context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System.Text.RegularExpressions;
using System.Diagnostics;
using System;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Collections;
using System.Drawing;
using Microsoft.VisualBasic;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
using WeifenLuo.WinFormsUI;
using Microsoft.Win32;
using WeifenLuo;
namespace SoftLogik.Win
{
namespace Reporting
{
[global::Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]public partial class SPReportFilterUI : System.Windows.Forms.UserControl
{
//UserControl overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]protected override void Dispose(bool disposing)
{
try
{
if (disposing && (components != null))
{
components.Dispose();
}
}
finally
{
base.Dispose(disposing);
}
}
//Required by the Windows Form Designer
private System.ComponentModel.Container components = null;
//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()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SPReportFilterUI));
this.TableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.FilterList = new System.Windows.Forms.DataGridView();
this.FieldDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewComboBoxColumn();
this.bsFields = new System.Windows.Forms.BindingSource(this.components);
this.OperationDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewComboBoxColumn();
this.bsOperators = new System.Windows.Forms.BindingSource(this.components);
this.ValueDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ValueField = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.FilterIDDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.bsFilterTable = new System.Windows.Forms.BindingSource(this.components);
this.DSFilters = new Win.DSFilters();
this.tbrMainOptions = new System.Windows.Forms.ToolStrip();
this.NewFilter = new System.Windows.Forms.ToolStripButton();
this.NewFilter.Click += new System.EventHandler(NewFilter_Click);
this.DeleteFilter = new System.Windows.Forms.ToolStripButton();
this.DeleteFilter.Click += new System.EventHandler(DeleteFilter_Click);
this.ToolStripButton3 = new System.Windows.Forms.ToolStripSeparator();
this.TableLayoutPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize) this.FilterList).BeginInit();
((System.ComponentModel.ISupportInitialize) this.bsFields).BeginInit();
((System.ComponentModel.ISupportInitialize) this.bsOperators).BeginInit();
((System.ComponentModel.ISupportInitialize) this.bsFilterTable).BeginInit();
((System.ComponentModel.ISupportInitialize) this.DSFilters).BeginInit();
this.tbrMainOptions.SuspendLayout();
this.SuspendLayout();
//
//TableLayoutPanel1
//
this.TableLayoutPanel1.ColumnCount = 2;
this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50.14577));
this.TableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 49.85423));
this.TableLayoutPanel1.Controls.Add(this.FilterList, 0, 1);
this.TableLayoutPanel1.Controls.Add(this.tbrMainOptions, 0, 0);
this.TableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.TableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.TableLayoutPanel1.Name = "TableLayoutPanel1";
this.TableLayoutPanel1.RowCount = 2;
this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 27.0));
this.TableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 55.0));
this.TableLayoutPanel1.Size = new System.Drawing.Size(343, 425);
this.TableLayoutPanel1.TabIndex = 1;
//
//FilterList
//
this.FilterList.AllowUserToOrderColumns = true;
this.FilterList.AutoGenerateColumns = false;
this.FilterList.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.DisplayedCells;
this.FilterList.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.DisplayedCells;
this.FilterList.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {this.FieldDataGridViewTextBoxColumn, this.OperationDataGridViewTextBoxColumn, this.ValueDataGridViewTextBoxColumn, this.ValueField, this.FilterIDDataGridViewTextBoxColumn});
this.TableLayoutPanel1.SetColumnSpan(this.FilterList, 2);
this.FilterList.DataSource = this.bsFilterTable;
this.FilterList.Dock = System.Windows.Forms.DockStyle.Fill;
this.FilterList.Location = new System.Drawing.Point(3, 30);
this.FilterList.MultiSelect = false;
this.FilterList.Name = "FilterList";
this.FilterList.RowHeadersVisible = false;
this.FilterList.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect;
this.FilterList.Size = new System.Drawing.Size(337, 392);
this.FilterList.TabIndex = 0;
this.FilterList.TabStop = false;
//
//FieldDataGridViewTextBoxColumn
//
this.FieldDataGridViewTextBoxColumn.DataPropertyName = "Field";
this.FieldDataGridViewTextBoxColumn.DataSource = this.bsFields;
this.FieldDataGridViewTextBoxColumn.Frozen = true;
this.FieldDataGridViewTextBoxColumn.HeaderText = "Field";
this.FieldDataGridViewTextBoxColumn.Name = "FieldDataGridViewTextBoxColumn";
this.FieldDataGridViewTextBoxColumn.Resizable = @System.Windows.Forms.DataGridViewTriState.True;
this.FieldDataGridViewTextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
this.FieldDataGridViewTextBoxColumn.Width = 54;
//
//OperationDataGridViewTextBoxColumn
//
this.OperationDataGridViewTextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.OperationDataGridViewTextBoxColumn.DataPropertyName = "Operation";
this.OperationDataGridViewTextBoxColumn.DataSource = this.bsOperators;
this.OperationDataGridViewTextBoxColumn.HeaderText = "Operation";
this.OperationDataGridViewTextBoxColumn.Name = "OperationDataGridViewTextBoxColumn";
this.OperationDataGridViewTextBoxColumn.Resizable = @System.Windows.Forms.DataGridViewTriState.True;
this.OperationDataGridViewTextBoxColumn.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
//
//ValueDataGridViewTextBoxColumn
//
this.ValueDataGridViewTextBoxColumn.DataPropertyName = "Value";
this.ValueDataGridViewTextBoxColumn.HeaderText = "Value";
this.ValueDataGridViewTextBoxColumn.Name = "ValueDataGridViewTextBoxColumn";
this.ValueDataGridViewTextBoxColumn.Visible = false;
this.ValueDataGridViewTextBoxColumn.Width = 59;
//
//ValueField
//
this.ValueField.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.ValueField.HeaderText = "Value";
this.ValueField.Name = "ValueField";
this.ValueField.ReadOnly = true;
//
//FilterIDDataGridViewTextBoxColumn
//
this.FilterIDDataGridViewTextBoxColumn.DataPropertyName = "FilterID";
this.FilterIDDataGridViewTextBoxColumn.HeaderText = "FilterID";
this.FilterIDDataGridViewTextBoxColumn.Name = "FilterIDDataGridViewTextBoxColumn";
this.FilterIDDataGridViewTextBoxColumn.Visible = false;
this.FilterIDDataGridViewTextBoxColumn.Width = 65;
//
//bsFilterTable
//
this.bsFilterTable.DataMember = "SPFilterTable";
this.bsFilterTable.DataSource = this.DSFilters;
//
//DSFilters
//
this.DSFilters.DataSetName = "DSFilters";
this.DSFilters.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
//tbrMainOptions
//
this.TableLayoutPanel1.SetColumnSpan(this.tbrMainOptions, 2);
this.tbrMainOptions.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.tbrMainOptions.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {this.NewFilter, this.DeleteFilter, this.ToolStripButton3});
this.tbrMainOptions.Location = new System.Drawing.Point(0, 0);
this.tbrMainOptions.Name = "tbrMainOptions";
this.tbrMainOptions.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional;
this.tbrMainOptions.Size = new System.Drawing.Size(343, 25);
this.tbrMainOptions.TabIndex = 5;
this.tbrMainOptions.Text = "ToolStrip1";
//
//NewFilter
//
this.NewFilter.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.NewFilter.Image = (System.Drawing.Image) (resources.GetObject("NewFilter.Image"));
this.NewFilter.Name = "NewFilter";
this.NewFilter.RightToLeftAutoMirrorImage = true;
this.NewFilter.Size = new System.Drawing.Size(23, 22);
this.NewFilter.Text = "Add new";
//
//DeleteFilter
//
this.DeleteFilter.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.DeleteFilter.Image = (System.Drawing.Image) (resources.GetObject("DeleteFilter.Image"));
this.DeleteFilter.Name = "DeleteFilter";
this.DeleteFilter.RightToLeftAutoMirrorImage = true;
this.DeleteFilter.Size = new System.Drawing.Size(23, 22);
this.DeleteFilter.Text = "Delete";
//
//ToolStripButton3
//
this.ToolStripButton3.Name = "ToolStripButton3";
this.ToolStripButton3.Size = new System.Drawing.Size(6, 25);
//
//SPReportFilterUI
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6.0, 13.0);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.TableLayoutPanel1);
this.Name = "SPReportFilterUI";
this.Size = new System.Drawing.Size(343, 425);
this.TableLayoutPanel1.ResumeLayout(false);
this.TableLayoutPanel1.PerformLayout();
((System.ComponentModel.ISupportInitialize) this.FilterList).EndInit();
((System.ComponentModel.ISupportInitialize) this.bsFields).EndInit();
((System.ComponentModel.ISupportInitialize) this.bsOperators).EndInit();
((System.ComponentModel.ISupportInitialize) this.bsFilterTable).EndInit();
((System.ComponentModel.ISupportInitialize) this.DSFilters).EndInit();
this.tbrMainOptions.ResumeLayout(false);
this.tbrMainOptions.PerformLayout();
this.ResumeLayout(false);
}
internal System.Windows.Forms.TableLayoutPanel TableLayoutPanel1;
internal System.Windows.Forms.DataGridView FilterList;
internal System.Windows.Forms.ToolStrip tbrMainOptions;
internal System.Windows.Forms.ToolStripButton NewFilter;
internal System.Windows.Forms.ToolStripButton DeleteFilter;
internal System.Windows.Forms.ToolStripSeparator ToolStripButton3;
internal System.Windows.Forms.BindingSource bsFilterTable;
internal SoftLogik.Win.DSFilters DSFilters;
internal System.Windows.Forms.BindingSource bsFields;
internal System.Windows.Forms.BindingSource bsOperators;
internal System.Windows.Forms.DataGridViewComboBoxColumn FieldDataGridViewTextBoxColumn;
internal System.Windows.Forms.DataGridViewComboBoxColumn OperationDataGridViewTextBoxColumn;
internal System.Windows.Forms.DataGridViewTextBoxColumn ValueDataGridViewTextBoxColumn;
internal System.Windows.Forms.DataGridViewTextBoxColumn ValueField;
internal System.Windows.Forms.DataGridViewTextBoxColumn FilterIDDataGridViewTextBoxColumn;
}
}
}
| |
#region Copyright (c) Roni Schuetz - All Rights Reserved
// * --------------------------------------------------------------------- *
// * Roni Schuetz *
// * Copyright (c) 2008 All Rights reserved *
// * *
// * Shared Cache high-performance, distributed caching and *
// * replicated caching system, generic in nature, but intended to *
// * speeding up dynamic web and / or win applications by alleviating *
// * database load. *
// * *
// * This Software is written by Roni Schuetz (schuetz AT gmail DOT com) *
// * *
// * This library is free software; you can redistribute it and/or *
// * modify it under the terms of the GNU Lesser General Public License *
// * as published by the Free Software Foundation; either version 2.1 *
// * of the License, or (at your option) any later version. *
// * *
// * This library is distributed in the hope that it will be useful, *
// * but WITHOUT ANY WARRANTY; without even the implied warranty of *
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
// * Lesser General Public License for more details. *
// * *
// * You should have received a copy of the GNU Lesser General Public *
// * License along with this library; if not, write to the Free *
// * Software Foundation, Inc., 59 Temple Place, Suite 330, *
// * Boston, MA 02111-1307 USA *
// * *
// * THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE. *
// * --------------------------------------------------------------------- *
#endregion
// *************************************************************************
//
// Name: Serialization.cs
//
// Created: 25-01-2007 SharedCache.com, rschuetz
// Modified: 25-01-2007 SharedCache.com, rschuetz : Creation
// Modified: 24-02-2008 SharedCache.com, rschuetz : updated logging part for tracking, instead of using appsetting we use precompiler definition #if TRACE
// Modified: 28-01-2010 SharedCache.com, chrisme : clean up code
// *************************************************************************
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Text;
namespace SharedCache.WinServiceCommon.Formatters
{
/// <summary>
/// <b>Serialization contains a set of Utils for various serilization by usage of Generics</b>
/// more information available at: <![CDATA[http://www.codeproject.com/soap/Coreweb03.asp]]>
/// <remarks>
/// with soap usage you need to add a reference to
/// System.Runtime.Serialization.Formatter.Soap assembly
/// </remarks>
/// </summary>
public static class Serialization
{
#region binary serialization
/// <summary>
/// Binaries the serialize.
/// </summary>
/// <param name="obj">The obj. A <see cref="T:System.Object"/> Object.</param>
/// <returns>A <see cref="T:System.Byte[]"/> Object.</returns>
[System.Diagnostics.DebuggerStepThrough]
public static byte[] BinarySerialize(Object obj)
{
#region Access Log
#if TRACE
{
Handler.LogHandler.Tracking("Access Method: " + typeof(Serialization).FullName + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
}
#endif
#endregion Access Log
var ms = new MemoryStream();
var b = new BinaryFormatter();
b.Serialize(ms, obj);
ms.Seek(0, 0);
byte[] serializedObject = ms.ToArray();
ms.Close();
return serializedObject;
}
/// <summary>
/// Desirializes the given type.
/// </summary>
/// <param name="serializedObject">The serialized object. A <see cref="T:System.Byte[]"/> Object.</param>
/// <returns>A <see cref="T:T"/> Object.</returns>
//[System.Diagnostics.DebuggerStepThrough]
public static T BinaryDeSerialize<T>(byte[] serializedObject)
{
#region Access Log
#if TRACE
{
Handler.LogHandler.Tracking("Access Method: " + typeof(Serialization).FullName + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
}
#endif
#endregion Access Log
try
{
var ms = new MemoryStream();
ms.Write(serializedObject, 0, serializedObject.Length);
ms.Seek(0, 0);
var b = new BinaryFormatter();
Object obj = b.Deserialize(ms);
ms.Close();
return (T)obj;
}
catch (Exception ex)
{
var ms = new MemoryStream();
ms.Write(serializedObject, 0, serializedObject.Length);
ms.Seek(0, 0);
var b = new BinaryFormatter();
Object obj = b.Deserialize(ms);
ms.Close();
var cex = (CacheException)obj;
if (cex != null)
{
// TODO: Shared Cache Exception
Handler.LogHandler.Error(cex.StackTrace, ex);
}
return (T)obj;
}
}
#endregion binary serialization
#region file binary serialization
/// <summary>
/// Serialize Files
/// </summary>
/// <param name="obj">The obj. A <see cref="T:System.Object"/> Object.</param>
/// <param name="filePath">The file path. A <see cref="T:System.String"/> Object.</param>
[System.Diagnostics.DebuggerStepThrough]
public static void FileSerialize(Object obj, string filePath)
{
#region Access Log
#if TRACE
{
Handler.LogHandler.Tracking("Access Method: " + typeof(Serialization).FullName + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
}
#endif
#endregion Access Log
FileStream fileStream = null;
try
{
fileStream = new FileStream(filePath, FileMode.Create);
BinaryFormatter b = new BinaryFormatter();
b.Serialize(fileStream, obj);
}
catch
{
throw;
}
finally
{
if (fileStream != null)
fileStream.Close();
}
}
/// <summary>
/// deserialize Files
/// </summary>
/// <param name="filePath">The file path. A <see cref="T:System.String"/> Object.</param>
/// <returns>A <see cref="T:T"/> Object.</returns>
[System.Diagnostics.DebuggerStepThrough]
public static T FileDeSerialize<T>(string filePath)
{
#region Access Log
#if TRACE
{
Handler.LogHandler.Tracking("Access Method: " + typeof(Serialization).FullName + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
}
#endif
#endregion Access Log
FileStream fileStream = null;
Object obj;
try
{
if (File.Exists(filePath) == false)
throw new FileNotFoundException("The file was not found.", filePath);
fileStream = new FileStream(filePath, FileMode.Open);
BinaryFormatter b = new BinaryFormatter();
obj = b.Deserialize(fileStream);
}
catch
{
throw;
}
finally
{
if (fileStream != null)
fileStream.Close();
}
return (T)obj;
}
#endregion file binary serialization
#region soap binary serialization
/// <summary>
/// SOAPs the memory stream serialization.
/// </summary>
/// <param name="obj">The obj. A <see cref="T:System.Object"/> Object.</param>
/// <param name="encodingType">Type of the encoding.</param>
/// <returns>A <see cref="T:System.String"/> Object.</returns>
[System.Diagnostics.DebuggerStepThrough]
public static string SoapMemoryStreamSerialization(object obj, Encoding encodingType)
{
#region Access Log
#if TRACE
{
Handler.LogHandler.Tracking("Access Method: " + typeof(Serialization).FullName + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
}
#endif
#endregion Access Log
string xmlResult;
using (Stream stream = new MemoryStream())
{
var sf = new SoapFormatter();
sf.Serialize(stream, obj);
stream.Position = 0;
var b = new byte[stream.Length];
stream.Read(b, 0, (int)stream.Length);
xmlResult = encodingType.GetString(b, 0, b.Length);
}
return xmlResult;
}
/// <summary>
/// SOAP deserailization.
/// </summary>
/// <param name="input">The input. A <see cref="T:System.String"/> Object.</param>
/// <param name="encodingType">Type of the encoding.</param>
/// <returns>A <see cref="T:T"/> Object.</returns>
[System.Diagnostics.DebuggerStepThrough]
public static T SoapDeserailization<T>(string input, System.Text.Encoding encodingType)
{
#region Access Log
#if TRACE
{
Handler.LogHandler.Tracking("Access Method: " + typeof(Serialization).FullName + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
}
#endif
#endregion Access Log
Object obj;
using (var sr = new StringReader(input))
{
byte[] b = encodingType.GetBytes(input);
Stream stream = new MemoryStream(b);
var sf = new SoapFormatter();
obj = sf.Deserialize(stream);
}
return (T)obj;
}
#endregion soap binary serialization
#region DataContract binary serialization
/// <summary>
/// A helper method to identify if the attribute of an object is
/// serializable
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
internal static bool IsSerializable(Type type)
{
return type.IsSerializable;
}
/// <summary>
/// Binaries the serialize.
/// </summary>
/// <param name="obj">The obj. A <see cref="T:System.Object"/> Object.</param>
/// <returns>A <see cref="T:System.Byte[]"/> Object.</returns>
// [System.Diagnostics.DebuggerStepThrough]
public static byte[] DataContractBinarySerialize(Object obj)
{
#region Access Log
#if TRACE
{
Handler.LogHandler.Tracking("Access Method: " + typeof(Serialization).FullName + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
}
#endif
#endregion Access Log
MemoryStream ms = new MemoryStream();
DataContractSerializer ser = new DataContractSerializer(obj.GetType());
ser.WriteObject(ms, obj);
byte[] data = ms.ToArray();
return data;
}
/// <summary>
/// Desirializes the given type.
/// </summary>
/// <param name="serializedObject">The serialized object. A <see cref="T:System.Byte[]"/> Object.</param>
/// <returns>A <see cref="T:T"/> Object.</returns>
//[System.Diagnostics.DebuggerStepThrough]
public static T DataContractBinaryDeSerialize<T>(byte[] serializedObject)
{
#region Access Log
#if TRACE
{
Handler.LogHandler.Tracking("Access Method: " + typeof(Serialization).FullName + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
}
#endif
#endregion Access Log
try
{
MemoryStream ms = new MemoryStream(serializedObject);
ms.Write(serializedObject, 0, serializedObject.Length);
ms.Seek(0, 0);
DataContractSerializer ser = new DataContractSerializer(typeof(T));
Object obj = ser.ReadObject(ms);
ms.Close();
return (T)obj;
}
catch (Exception ex)
{
MemoryStream ms = new MemoryStream();
ms.Write(serializedObject, 0, serializedObject.Length);
ms.Seek(0, 0);
BinaryFormatter b = new BinaryFormatter();
Object obj = b.Deserialize(ms);
ms.Close();
CacheException cex = (CacheException)obj;
if (cex != null)
{
// TODO: Shared Cache Exception
Handler.LogHandler.Error(cex.StackTrace, ex);
}
return (T)obj;
}
}
#endregion DataContract binary serialization
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.NetworkManagement.V1.Snippets
{
using Google.Api.Gax;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedReachabilityServiceClientSnippets
{
/// <summary>Snippet for ListConnectivityTests</summary>
public void ListConnectivityTestsRequestObject()
{
// Snippet: ListConnectivityTests(ListConnectivityTestsRequest, CallSettings)
// Create client
ReachabilityServiceClient reachabilityServiceClient = ReachabilityServiceClient.Create();
// Initialize request argument(s)
ListConnectivityTestsRequest request = new ListConnectivityTestsRequest
{
Parent = "",
Filter = "",
OrderBy = "",
};
// Make the request
PagedEnumerable<ListConnectivityTestsResponse, ConnectivityTest> response = reachabilityServiceClient.ListConnectivityTests(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (ConnectivityTest item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListConnectivityTestsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ConnectivityTest item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ConnectivityTest> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ConnectivityTest item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListConnectivityTestsAsync</summary>
public async Task ListConnectivityTestsRequestObjectAsync()
{
// Snippet: ListConnectivityTestsAsync(ListConnectivityTestsRequest, CallSettings)
// Create client
ReachabilityServiceClient reachabilityServiceClient = await ReachabilityServiceClient.CreateAsync();
// Initialize request argument(s)
ListConnectivityTestsRequest request = new ListConnectivityTestsRequest
{
Parent = "",
Filter = "",
OrderBy = "",
};
// Make the request
PagedAsyncEnumerable<ListConnectivityTestsResponse, ConnectivityTest> response = reachabilityServiceClient.ListConnectivityTestsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ConnectivityTest item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListConnectivityTestsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ConnectivityTest item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ConnectivityTest> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ConnectivityTest item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListConnectivityTests</summary>
public void ListConnectivityTests()
{
// Snippet: ListConnectivityTests(string, string, int?, CallSettings)
// Create client
ReachabilityServiceClient reachabilityServiceClient = ReachabilityServiceClient.Create();
// Initialize request argument(s)
string parent = "";
// Make the request
PagedEnumerable<ListConnectivityTestsResponse, ConnectivityTest> response = reachabilityServiceClient.ListConnectivityTests(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (ConnectivityTest item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListConnectivityTestsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ConnectivityTest item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ConnectivityTest> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ConnectivityTest item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListConnectivityTestsAsync</summary>
public async Task ListConnectivityTestsAsync()
{
// Snippet: ListConnectivityTestsAsync(string, string, int?, CallSettings)
// Create client
ReachabilityServiceClient reachabilityServiceClient = await ReachabilityServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "";
// Make the request
PagedAsyncEnumerable<ListConnectivityTestsResponse, ConnectivityTest> response = reachabilityServiceClient.ListConnectivityTestsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ConnectivityTest item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListConnectivityTestsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ConnectivityTest item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ConnectivityTest> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ConnectivityTest item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetConnectivityTest</summary>
public void GetConnectivityTestRequestObject()
{
// Snippet: GetConnectivityTest(GetConnectivityTestRequest, CallSettings)
// Create client
ReachabilityServiceClient reachabilityServiceClient = ReachabilityServiceClient.Create();
// Initialize request argument(s)
GetConnectivityTestRequest request = new GetConnectivityTestRequest { Name = "", };
// Make the request
ConnectivityTest response = reachabilityServiceClient.GetConnectivityTest(request);
// End snippet
}
/// <summary>Snippet for GetConnectivityTestAsync</summary>
public async Task GetConnectivityTestRequestObjectAsync()
{
// Snippet: GetConnectivityTestAsync(GetConnectivityTestRequest, CallSettings)
// Additional: GetConnectivityTestAsync(GetConnectivityTestRequest, CancellationToken)
// Create client
ReachabilityServiceClient reachabilityServiceClient = await ReachabilityServiceClient.CreateAsync();
// Initialize request argument(s)
GetConnectivityTestRequest request = new GetConnectivityTestRequest { Name = "", };
// Make the request
ConnectivityTest response = await reachabilityServiceClient.GetConnectivityTestAsync(request);
// End snippet
}
/// <summary>Snippet for GetConnectivityTest</summary>
public void GetConnectivityTest()
{
// Snippet: GetConnectivityTest(string, CallSettings)
// Create client
ReachabilityServiceClient reachabilityServiceClient = ReachabilityServiceClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
ConnectivityTest response = reachabilityServiceClient.GetConnectivityTest(name);
// End snippet
}
/// <summary>Snippet for GetConnectivityTestAsync</summary>
public async Task GetConnectivityTestAsync()
{
// Snippet: GetConnectivityTestAsync(string, CallSettings)
// Additional: GetConnectivityTestAsync(string, CancellationToken)
// Create client
ReachabilityServiceClient reachabilityServiceClient = await ReachabilityServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
ConnectivityTest response = await reachabilityServiceClient.GetConnectivityTestAsync(name);
// End snippet
}
/// <summary>Snippet for CreateConnectivityTest</summary>
public void CreateConnectivityTestRequestObject()
{
// Snippet: CreateConnectivityTest(CreateConnectivityTestRequest, CallSettings)
// Create client
ReachabilityServiceClient reachabilityServiceClient = ReachabilityServiceClient.Create();
// Initialize request argument(s)
CreateConnectivityTestRequest request = new CreateConnectivityTestRequest
{
Parent = "",
TestId = "",
Resource = new ConnectivityTest(),
};
// Make the request
Operation<ConnectivityTest, OperationMetadata> response = reachabilityServiceClient.CreateConnectivityTest(request);
// Poll until the returned long-running operation is complete
Operation<ConnectivityTest, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
ConnectivityTest result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ConnectivityTest, OperationMetadata> retrievedResponse = reachabilityServiceClient.PollOnceCreateConnectivityTest(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ConnectivityTest retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateConnectivityTestAsync</summary>
public async Task CreateConnectivityTestRequestObjectAsync()
{
// Snippet: CreateConnectivityTestAsync(CreateConnectivityTestRequest, CallSettings)
// Additional: CreateConnectivityTestAsync(CreateConnectivityTestRequest, CancellationToken)
// Create client
ReachabilityServiceClient reachabilityServiceClient = await ReachabilityServiceClient.CreateAsync();
// Initialize request argument(s)
CreateConnectivityTestRequest request = new CreateConnectivityTestRequest
{
Parent = "",
TestId = "",
Resource = new ConnectivityTest(),
};
// Make the request
Operation<ConnectivityTest, OperationMetadata> response = await reachabilityServiceClient.CreateConnectivityTestAsync(request);
// Poll until the returned long-running operation is complete
Operation<ConnectivityTest, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
ConnectivityTest result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ConnectivityTest, OperationMetadata> retrievedResponse = await reachabilityServiceClient.PollOnceCreateConnectivityTestAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ConnectivityTest retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateConnectivityTest</summary>
public void CreateConnectivityTest()
{
// Snippet: CreateConnectivityTest(string, string, ConnectivityTest, CallSettings)
// Create client
ReachabilityServiceClient reachabilityServiceClient = ReachabilityServiceClient.Create();
// Initialize request argument(s)
string parent = "";
string testId = "";
ConnectivityTest resource = new ConnectivityTest();
// Make the request
Operation<ConnectivityTest, OperationMetadata> response = reachabilityServiceClient.CreateConnectivityTest(parent, testId, resource);
// Poll until the returned long-running operation is complete
Operation<ConnectivityTest, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
ConnectivityTest result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ConnectivityTest, OperationMetadata> retrievedResponse = reachabilityServiceClient.PollOnceCreateConnectivityTest(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ConnectivityTest retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateConnectivityTestAsync</summary>
public async Task CreateConnectivityTestAsync()
{
// Snippet: CreateConnectivityTestAsync(string, string, ConnectivityTest, CallSettings)
// Additional: CreateConnectivityTestAsync(string, string, ConnectivityTest, CancellationToken)
// Create client
ReachabilityServiceClient reachabilityServiceClient = await ReachabilityServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "";
string testId = "";
ConnectivityTest resource = new ConnectivityTest();
// Make the request
Operation<ConnectivityTest, OperationMetadata> response = await reachabilityServiceClient.CreateConnectivityTestAsync(parent, testId, resource);
// Poll until the returned long-running operation is complete
Operation<ConnectivityTest, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
ConnectivityTest result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ConnectivityTest, OperationMetadata> retrievedResponse = await reachabilityServiceClient.PollOnceCreateConnectivityTestAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ConnectivityTest retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateConnectivityTest</summary>
public void UpdateConnectivityTestRequestObject()
{
// Snippet: UpdateConnectivityTest(UpdateConnectivityTestRequest, CallSettings)
// Create client
ReachabilityServiceClient reachabilityServiceClient = ReachabilityServiceClient.Create();
// Initialize request argument(s)
UpdateConnectivityTestRequest request = new UpdateConnectivityTestRequest
{
UpdateMask = new FieldMask(),
Resource = new ConnectivityTest(),
};
// Make the request
Operation<ConnectivityTest, OperationMetadata> response = reachabilityServiceClient.UpdateConnectivityTest(request);
// Poll until the returned long-running operation is complete
Operation<ConnectivityTest, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
ConnectivityTest result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ConnectivityTest, OperationMetadata> retrievedResponse = reachabilityServiceClient.PollOnceUpdateConnectivityTest(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ConnectivityTest retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateConnectivityTestAsync</summary>
public async Task UpdateConnectivityTestRequestObjectAsync()
{
// Snippet: UpdateConnectivityTestAsync(UpdateConnectivityTestRequest, CallSettings)
// Additional: UpdateConnectivityTestAsync(UpdateConnectivityTestRequest, CancellationToken)
// Create client
ReachabilityServiceClient reachabilityServiceClient = await ReachabilityServiceClient.CreateAsync();
// Initialize request argument(s)
UpdateConnectivityTestRequest request = new UpdateConnectivityTestRequest
{
UpdateMask = new FieldMask(),
Resource = new ConnectivityTest(),
};
// Make the request
Operation<ConnectivityTest, OperationMetadata> response = await reachabilityServiceClient.UpdateConnectivityTestAsync(request);
// Poll until the returned long-running operation is complete
Operation<ConnectivityTest, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
ConnectivityTest result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ConnectivityTest, OperationMetadata> retrievedResponse = await reachabilityServiceClient.PollOnceUpdateConnectivityTestAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ConnectivityTest retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateConnectivityTest</summary>
public void UpdateConnectivityTest()
{
// Snippet: UpdateConnectivityTest(FieldMask, ConnectivityTest, CallSettings)
// Create client
ReachabilityServiceClient reachabilityServiceClient = ReachabilityServiceClient.Create();
// Initialize request argument(s)
FieldMask updateMask = new FieldMask();
ConnectivityTest resource = new ConnectivityTest();
// Make the request
Operation<ConnectivityTest, OperationMetadata> response = reachabilityServiceClient.UpdateConnectivityTest(updateMask, resource);
// Poll until the returned long-running operation is complete
Operation<ConnectivityTest, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
ConnectivityTest result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ConnectivityTest, OperationMetadata> retrievedResponse = reachabilityServiceClient.PollOnceUpdateConnectivityTest(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ConnectivityTest retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateConnectivityTestAsync</summary>
public async Task UpdateConnectivityTestAsync()
{
// Snippet: UpdateConnectivityTestAsync(FieldMask, ConnectivityTest, CallSettings)
// Additional: UpdateConnectivityTestAsync(FieldMask, ConnectivityTest, CancellationToken)
// Create client
ReachabilityServiceClient reachabilityServiceClient = await ReachabilityServiceClient.CreateAsync();
// Initialize request argument(s)
FieldMask updateMask = new FieldMask();
ConnectivityTest resource = new ConnectivityTest();
// Make the request
Operation<ConnectivityTest, OperationMetadata> response = await reachabilityServiceClient.UpdateConnectivityTestAsync(updateMask, resource);
// Poll until the returned long-running operation is complete
Operation<ConnectivityTest, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
ConnectivityTest result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ConnectivityTest, OperationMetadata> retrievedResponse = await reachabilityServiceClient.PollOnceUpdateConnectivityTestAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ConnectivityTest retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for RerunConnectivityTest</summary>
public void RerunConnectivityTestRequestObject()
{
// Snippet: RerunConnectivityTest(RerunConnectivityTestRequest, CallSettings)
// Create client
ReachabilityServiceClient reachabilityServiceClient = ReachabilityServiceClient.Create();
// Initialize request argument(s)
RerunConnectivityTestRequest request = new RerunConnectivityTestRequest { Name = "", };
// Make the request
Operation<ConnectivityTest, OperationMetadata> response = reachabilityServiceClient.RerunConnectivityTest(request);
// Poll until the returned long-running operation is complete
Operation<ConnectivityTest, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
ConnectivityTest result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ConnectivityTest, OperationMetadata> retrievedResponse = reachabilityServiceClient.PollOnceRerunConnectivityTest(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ConnectivityTest retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for RerunConnectivityTestAsync</summary>
public async Task RerunConnectivityTestRequestObjectAsync()
{
// Snippet: RerunConnectivityTestAsync(RerunConnectivityTestRequest, CallSettings)
// Additional: RerunConnectivityTestAsync(RerunConnectivityTestRequest, CancellationToken)
// Create client
ReachabilityServiceClient reachabilityServiceClient = await ReachabilityServiceClient.CreateAsync();
// Initialize request argument(s)
RerunConnectivityTestRequest request = new RerunConnectivityTestRequest { Name = "", };
// Make the request
Operation<ConnectivityTest, OperationMetadata> response = await reachabilityServiceClient.RerunConnectivityTestAsync(request);
// Poll until the returned long-running operation is complete
Operation<ConnectivityTest, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
ConnectivityTest result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<ConnectivityTest, OperationMetadata> retrievedResponse = await reachabilityServiceClient.PollOnceRerunConnectivityTestAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
ConnectivityTest retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteConnectivityTest</summary>
public void DeleteConnectivityTestRequestObject()
{
// Snippet: DeleteConnectivityTest(DeleteConnectivityTestRequest, CallSettings)
// Create client
ReachabilityServiceClient reachabilityServiceClient = ReachabilityServiceClient.Create();
// Initialize request argument(s)
DeleteConnectivityTestRequest request = new DeleteConnectivityTestRequest { Name = "", };
// Make the request
Operation<Empty, OperationMetadata> response = reachabilityServiceClient.DeleteConnectivityTest(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = reachabilityServiceClient.PollOnceDeleteConnectivityTest(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteConnectivityTestAsync</summary>
public async Task DeleteConnectivityTestRequestObjectAsync()
{
// Snippet: DeleteConnectivityTestAsync(DeleteConnectivityTestRequest, CallSettings)
// Additional: DeleteConnectivityTestAsync(DeleteConnectivityTestRequest, CancellationToken)
// Create client
ReachabilityServiceClient reachabilityServiceClient = await ReachabilityServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteConnectivityTestRequest request = new DeleteConnectivityTestRequest { Name = "", };
// Make the request
Operation<Empty, OperationMetadata> response = await reachabilityServiceClient.DeleteConnectivityTestAsync(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await reachabilityServiceClient.PollOnceDeleteConnectivityTestAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteConnectivityTest</summary>
public void DeleteConnectivityTest()
{
// Snippet: DeleteConnectivityTest(string, CallSettings)
// Create client
ReachabilityServiceClient reachabilityServiceClient = ReachabilityServiceClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
Operation<Empty, OperationMetadata> response = reachabilityServiceClient.DeleteConnectivityTest(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = reachabilityServiceClient.PollOnceDeleteConnectivityTest(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteConnectivityTestAsync</summary>
public async Task DeleteConnectivityTestAsync()
{
// Snippet: DeleteConnectivityTestAsync(string, CallSettings)
// Additional: DeleteConnectivityTestAsync(string, CancellationToken)
// Create client
ReachabilityServiceClient reachabilityServiceClient = await ReachabilityServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
Operation<Empty, OperationMetadata> response = await reachabilityServiceClient.DeleteConnectivityTestAsync(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await reachabilityServiceClient.PollOnceDeleteConnectivityTestAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
}
}
| |
namespace SqlBulkCopyExample
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
/// <summary>
/// Object Data Reader from developerFusion
/// http://www.developerfusion.com/article/122498/using-sqlbulkcopy-for-high-performance-inserts/
/// </summary>
/// <typeparam name="TData"></typeparam>
public class ObjectDataReader<TData> : IDataReader
{
/// <summary>
/// The enumerator for the IEnumerable{TData} passed to the constructor for
/// this instance.
/// </summary>
private IEnumerator<TData> dataEnumerator;
/// <summary>
/// The lookup of accessor functions for the properties on the TData type.
/// </summary>
private Func<TData, object>[] accessors;
/// <summary>
/// The lookup of property names against their ordinal positions.
/// </summary>
private Dictionary<string, int> ordinalLookup;
/// <summary>
/// Initializes a new instance of the <see cref="ObjectDataReader<TData>"/> class.
/// </summary>
/// <param name="data">The data this instance should enumerate through.</param>
public ObjectDataReader(IEnumerable<TData> data)
{
this.dataEnumerator = data.GetEnumerator();
// Get all the readable properties for the class and
// compile an expression capable of reading it
var propertyAccessors = typeof(TData)
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(p => p.CanRead)
.Select((p, i) => new
{
Index = i,
Property = p,
Accessor = CreatePropertyAccessor(p)
})
.ToArray();
this.accessors = propertyAccessors.Select(p => p.Accessor).ToArray();
this.ordinalLookup = propertyAccessors.ToDictionary(
p => p.Property.Name,
p => p.Index,
StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Creates a property accessor for the given property information.
/// </summary>
/// <param name="p">The property information to generate the accessor for.</param>
/// <returns>The generated accessor function.</returns>
private Func<TData, object> CreatePropertyAccessor(PropertyInfo p)
{
// Define the parameter that will be passed - will be the current object
var parameter = Expression.Parameter(typeof(TData), "input");
// Define an expression to get the value from the property
var propertyAccess = Expression.Property(parameter, p.GetGetMethod());
// Make sure the result of the get method is cast as an object
var castAsObject = Expression.TypeAs(propertyAccess, typeof(object));
// Create a lambda expression for the property access and compile it
var lamda = Expression.Lambda<Func<TData, object>>(castAsObject, parameter);
return lamda.Compile();
}
#region IDataReader Members
public void Close()
{
this.Dispose();
}
public int Depth
{
get { return 1; }
}
public DataTable GetSchemaTable()
{
return null;
}
public bool IsClosed
{
get { return this.dataEnumerator == null; }
}
public bool NextResult()
{
return false;
}
public bool Read()
{
if (this.dataEnumerator == null)
{
throw new ObjectDisposedException("ObjectDataReader");
}
return this.dataEnumerator.MoveNext();
}
public int RecordsAffected
{
get { return -1; }
}
#endregion
#region IDisposable Members
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
if (disposing)
{
if (this.dataEnumerator != null)
{
this.dataEnumerator.Dispose();
this.dataEnumerator = null;
}
}
}
#endregion
#region IDataRecord Members
public int FieldCount
{
get { return this.accessors.Length; }
}
public bool GetBoolean(int i)
{
throw new NotImplementedException();
}
public byte GetByte(int i)
{
throw new NotImplementedException();
}
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
throw new NotImplementedException();
}
public char GetChar(int i)
{
throw new NotImplementedException();
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
throw new NotImplementedException();
}
public IDataReader GetData(int i)
{
throw new NotImplementedException();
}
public string GetDataTypeName(int i)
{
throw new NotImplementedException();
}
public DateTime GetDateTime(int i)
{
throw new NotImplementedException();
}
public decimal GetDecimal(int i)
{
throw new NotImplementedException();
}
public double GetDouble(int i)
{
throw new NotImplementedException();
}
public Type GetFieldType(int i)
{
throw new NotImplementedException();
}
public float GetFloat(int i)
{
throw new NotImplementedException();
}
public Guid GetGuid(int i)
{
throw new NotImplementedException();
}
public short GetInt16(int i)
{
throw new NotImplementedException();
}
public int GetInt32(int i)
{
throw new NotImplementedException();
}
public long GetInt64(int i)
{
throw new NotImplementedException();
}
public string GetName(int i)
{
throw new NotImplementedException();
}
public int GetOrdinal(string name)
{
int ordinal;
if (!this.ordinalLookup.TryGetValue(name, out ordinal))
{
throw new InvalidOperationException("Unknown parameter name " + name);
}
return ordinal;
}
public string GetString(int i)
{
throw new NotImplementedException();
}
public object GetValue(int i)
{
if (this.dataEnumerator == null)
{
throw new ObjectDisposedException("ObjectDataReader");
}
return this.accessors[i](this.dataEnumerator.Current);
}
public int GetValues(object[] values)
{
throw new NotImplementedException();
}
public bool IsDBNull(int i)
{
throw new NotImplementedException();
}
public object this[string name]
{
get { throw new NotImplementedException(); }
}
public object this[int i]
{
get { throw new NotImplementedException(); }
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsHttp
{
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for HttpSuccess.
/// </summary>
public static partial class HttpSuccessExtensions
{
/// <summary>
/// Return 200 status code if successful
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void Head200(this IHttpSuccess operations)
{
Task.Factory.StartNew(s => ((IHttpSuccess)s).Head200Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 200 status code if successful
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Head200Async(this IHttpSuccess operations, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Head200WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get 200 success
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static bool? Get200(this IHttpSuccess operations)
{
return Task.Factory.StartNew(s => ((IHttpSuccess)s).Get200Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get 200 success
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<bool?> Get200Async(this IHttpSuccess operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Get200WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put boolean value true returning 200 success
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Put200(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
Task.Factory.StartNew(s => ((IHttpSuccess)s).Put200Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put boolean value true returning 200 success
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Put200Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Put200WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Patch true Boolean value in request returning 200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Patch200(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
Task.Factory.StartNew(s => ((IHttpSuccess)s).Patch200Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Patch true Boolean value in request returning 200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Patch200Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Patch200WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Post bollean value true in request that returns a 200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Post200(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
Task.Factory.StartNew(s => ((IHttpSuccess)s).Post200Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Post bollean value true in request that returns a 200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Post200Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Post200WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Delete simple boolean value true returns 200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Delete200(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
Task.Factory.StartNew(s => ((IHttpSuccess)s).Delete200Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete simple boolean value true returns 200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Delete200Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Delete200WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Put true Boolean value in request returns 201
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Put201(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
Task.Factory.StartNew(s => ((IHttpSuccess)s).Put201Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put true Boolean value in request returns 201
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Put201Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Put201WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Post true Boolean value in request returns 201 (Created)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Post201(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
Task.Factory.StartNew(s => ((IHttpSuccess)s).Post201Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Post true Boolean value in request returns 201 (Created)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Post201Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Post201WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Put true Boolean value in request returns 202 (Accepted)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Put202(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
Task.Factory.StartNew(s => ((IHttpSuccess)s).Put202Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put true Boolean value in request returns 202 (Accepted)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Put202Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Put202WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Patch true Boolean value in request returns 202
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Patch202(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
Task.Factory.StartNew(s => ((IHttpSuccess)s).Patch202Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Patch true Boolean value in request returns 202
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Patch202Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Patch202WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Post true Boolean value in request returns 202 (Accepted)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Post202(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
Task.Factory.StartNew(s => ((IHttpSuccess)s).Post202Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Post true Boolean value in request returns 202 (Accepted)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Post202Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Post202WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Delete true Boolean value in request returns 202 (accepted)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Delete202(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
Task.Factory.StartNew(s => ((IHttpSuccess)s).Delete202Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete true Boolean value in request returns 202 (accepted)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Delete202Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Delete202WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Return 204 status code if successful
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void Head204(this IHttpSuccess operations)
{
Task.Factory.StartNew(s => ((IHttpSuccess)s).Head204Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 204 status code if successful
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Head204Async(this IHttpSuccess operations, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Head204WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Put true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Put204(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
Task.Factory.StartNew(s => ((IHttpSuccess)s).Put204Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Put204Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Put204WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Patch true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Patch204(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
Task.Factory.StartNew(s => ((IHttpSuccess)s).Patch204Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Patch true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Patch204Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Patch204WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Post true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Post204(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
Task.Factory.StartNew(s => ((IHttpSuccess)s).Post204Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Post true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Post204Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Post204WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Delete true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static void Delete204(this IHttpSuccess operations, bool? booleanValue = default(bool?))
{
Task.Factory.StartNew(s => ((IHttpSuccess)s).Delete204Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Delete204Async(this IHttpSuccess operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Delete204WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Return 404 status code
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void Head404(this IHttpSuccess operations)
{
Task.Factory.StartNew(s => ((IHttpSuccess)s).Head404Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 404 status code
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task Head404Async(this IHttpSuccess operations, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.Head404WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
}
}
}
| |
namespace AutoMapper
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Impl;
using Internal;
[DebuggerDisplay("{DestinationProperty.Name}")]
public class PropertyMap
{
private readonly LinkedList<IValueResolver> _sourceValueResolvers = new LinkedList<IValueResolver>();
private bool _ignored;
private int _mappingOrder;
private IValueResolver _customResolver;
private IValueResolver _customMemberResolver;
private bool _sealed;
private IValueResolver[] _cachedResolvers;
private Func<ResolutionContext, bool> _condition;
private Func<ResolutionContext, bool> _preCondition;
private MemberInfo _sourceMember;
public PropertyMap(IMemberAccessor destinationProperty)
{
UseDestinationValue = true;
DestinationProperty = destinationProperty;
}
public PropertyMap(PropertyMap inheritedMappedProperty)
: this(inheritedMappedProperty.DestinationProperty)
{
if (inheritedMappedProperty.IsIgnored())
Ignore();
else
{
foreach (var sourceValueResolver in inheritedMappedProperty.GetSourceValueResolvers())
{
ChainResolver(sourceValueResolver);
}
}
ApplyCondition(inheritedMappedProperty._condition);
SetNullSubstitute(inheritedMappedProperty.NullSubstitute);
SetMappingOrder(inheritedMappedProperty._mappingOrder);
CustomExpression = inheritedMappedProperty.CustomExpression;
}
public IMemberAccessor DestinationProperty { get; }
public Type DestinationPropertyType => DestinationProperty.MemberType;
public LambdaExpression CustomExpression { get; private set; }
public MemberInfo SourceMember
{
get
{
return _sourceMember ?? GetSourceValueResolvers().OfType<IMemberGetter>().LastOrDefault()?.MemberInfo;
}
internal set { _sourceMember = value; }
}
public bool CanBeSet => !(DestinationProperty is PropertyAccessor) ||
((PropertyAccessor) DestinationProperty).HasSetter;
public bool UseDestinationValue { get; set; }
internal bool HasCustomValueResolver { get; private set; }
public bool ExplicitExpansion { get; set; }
public object NullSubstitute { get; private set; }
public IEnumerable<IValueResolver> GetSourceValueResolvers()
{
if (_customMemberResolver != null)
yield return _customMemberResolver;
if (_customResolver != null)
yield return _customResolver;
foreach (var resolver in _sourceValueResolvers)
{
yield return resolver;
}
if (NullSubstitute != null)
yield return new NullReplacementMethod(NullSubstitute);
}
public void RemoveLastResolver()
{
_sourceValueResolvers.RemoveLast();
}
public ResolutionResult ResolveValue(ResolutionContext context)
{
Seal();
var result = new ResolutionResult(context);
return _cachedResolvers.Aggregate(result, (current, resolver) => resolver.Resolve(current));
}
internal void Seal()
{
if (_sealed)
{
return;
}
_cachedResolvers = GetSourceValueResolvers().ToArray();
_sealed = true;
}
public void ChainResolver(IValueResolver valueResolver)
{
_sourceValueResolvers.AddLast(valueResolver);
}
public void AssignCustomExpression(LambdaExpression customExpression)
{
CustomExpression = customExpression;
}
public void AssignCustomValueResolver(IValueResolver valueResolver)
{
_ignored = false;
_customResolver = valueResolver;
ResetSourceMemberChain();
HasCustomValueResolver = true;
}
public void ChainTypeMemberForResolver(IValueResolver valueResolver)
{
ResetSourceMemberChain();
_customMemberResolver = valueResolver;
}
public void ChainConstructorForResolver(IValueResolver valueResolver)
{
_customResolver = valueResolver;
}
public void Ignore()
{
_ignored = true;
}
public bool IsIgnored()
{
return _ignored;
}
public void SetMappingOrder(int mappingOrder)
{
_mappingOrder = mappingOrder;
}
public int GetMappingOrder()
{
return _mappingOrder;
}
public bool IsMapped()
{
return _sourceValueResolvers.Count > 0 || HasCustomValueResolver || _ignored;
}
public bool CanResolveValue()
{
return (_sourceValueResolvers.Count > 0 || HasCustomValueResolver) && !_ignored;
}
public void SetNullSubstitute(object nullSubstitute)
{
NullSubstitute = nullSubstitute;
}
private void ResetSourceMemberChain()
{
_sourceValueResolvers.Clear();
}
public bool Equals(PropertyMap other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.DestinationProperty, DestinationProperty);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (PropertyMap)) return false;
return Equals((PropertyMap) obj);
}
public override int GetHashCode()
{
return DestinationProperty.GetHashCode();
}
public void ApplyCondition(Func<ResolutionContext, bool> condition)
{
_condition = condition;
}
public void ApplyPreCondition(Func<ResolutionContext, bool> condition)
{
_preCondition = condition;
}
public bool ShouldAssignValue(ResolutionContext context)
{
return _condition == null || _condition(context);
}
public bool ShouldAssignValuePreResolving(ResolutionContext context)
{
return _preCondition == null || _preCondition(context);
}
public void SetCustomValueResolverExpression<TSource, TMember>(Expression<Func<TSource, TMember>> sourceMember)
{
var body = sourceMember.Body as MemberExpression;
if (body != null)
{
SourceMember = body.Member;
}
CustomExpression = sourceMember;
AssignCustomValueResolver(
new NullReferenceExceptionSwallowingResolver(
new DelegateBasedResolver<TSource, TMember>(sourceMember.Compile())
)
);
}
public object GetDestinationValue(object mappedObject)
{
return UseDestinationValue
? DestinationProperty.GetValue(mappedObject)
: null;
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Reflection;
namespace System.Security.Principal
{
public class IdentityReferenceCollection : ICollection<IdentityReference>
{
#region Private members
//
// Container enumerated by this collection
//
private readonly List<IdentityReference> _Identities;
#endregion
#region Constructors
//
// Creates an empty collection of default size
//
public IdentityReferenceCollection()
: this(0)
{
}
//
// Creates an empty collection of given initial size
//
public IdentityReferenceCollection(int capacity)
{
_Identities = new List<IdentityReference>(capacity);
}
#endregion
#region ICollection<IdentityReference> implementation
public void CopyTo(IdentityReference[] array, int offset)
{
_Identities.CopyTo(0, array, offset, Count);
}
public int Count
{
get
{
return _Identities.Count;
}
}
bool ICollection<IdentityReference>.IsReadOnly
{
get
{
return false;
}
}
public void Add(IdentityReference identity)
{
if (identity == null)
{
throw new ArgumentNullException("identity");
}
Contract.EndContractBlock();
_Identities.Add(identity);
}
public bool Remove(IdentityReference identity)
{
if (identity == null)
{
throw new ArgumentNullException("identity");
}
Contract.EndContractBlock();
if (Contains(identity))
{
return _Identities.Remove(identity);
}
return false;
}
public void Clear()
{
_Identities.Clear();
}
public bool Contains(IdentityReference identity)
{
if (identity == null)
{
throw new ArgumentNullException("identity");
}
Contract.EndContractBlock();
return _Identities.Contains(identity);
}
#endregion
#region IEnumerable<IdentityReference> implementation
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<IdentityReference> GetEnumerator()
{
return new IdentityReferenceEnumerator(this);
}
#endregion
#region Public methods
public IdentityReference this[int index]
{
get
{
return _Identities[index];
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
Contract.EndContractBlock();
_Identities[index] = value;
}
}
internal List<IdentityReference> Identities
{
get
{
return _Identities;
}
}
public IdentityReferenceCollection Translate(Type targetType)
{
return Translate(targetType, false);
}
public IdentityReferenceCollection Translate(Type targetType, bool forceSuccess)
{
if (targetType == null)
{
throw new ArgumentNullException("targetType");
}
//
// Target type must be a subclass of IdentityReference
//
if (!targetType.GetTypeInfo().IsSubclassOf(typeof(IdentityReference)))
{
throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, "targetType");
}
Contract.EndContractBlock();
//
// if the source collection is empty, just return an empty collection
//
if (Identities.Count == 0)
{
return new IdentityReferenceCollection();
}
int SourceSidsCount = 0;
int SourceNTAccountsCount = 0;
//
// First, see how many of each of the source types we have.
// The cases where source type == target type require no conversion.
//
for (int i = 0; i < Identities.Count; i++)
{
Type type = Identities[i].GetType();
if (type == targetType)
{
continue;
}
else if (type == typeof(SecurityIdentifier))
{
SourceSidsCount += 1;
}
else if (type == typeof(NTAccount))
{
SourceNTAccountsCount += 1;
}
else
{
//
// Rare case that we have defined a type of identity reference and not included it in the code logic above.
// To avoid this we do not allow IdentityReference to be subclassed outside of the BCL.
//
Debug.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic.");
throw new NotSupportedException();
}
}
bool Homogeneous = false;
IdentityReferenceCollection SourceSids = null;
IdentityReferenceCollection SourceNTAccounts = null;
if (SourceSidsCount == Count)
{
Homogeneous = true;
SourceSids = this;
}
else if (SourceSidsCount > 0)
{
SourceSids = new IdentityReferenceCollection(SourceSidsCount);
}
if (SourceNTAccountsCount == Count)
{
Homogeneous = true;
SourceNTAccounts = this;
}
else if (SourceNTAccountsCount > 0)
{
SourceNTAccounts = new IdentityReferenceCollection(SourceNTAccountsCount);
}
//
// Repackage only if the source is not homogeneous (contains different source types)
//
IdentityReferenceCollection Result = null;
if (!Homogeneous)
{
Result = new IdentityReferenceCollection(Identities.Count);
for (int i = 0; i < Identities.Count; i++)
{
IdentityReference id = this[i];
Type type = id.GetType();
if (type == targetType)
{
continue;
}
else if (type == typeof(SecurityIdentifier))
{
SourceSids.Add(id);
}
else if (type == typeof(NTAccount))
{
SourceNTAccounts.Add(id);
}
else
{
//
// Rare case that we have defined a type of identity reference and not included it in the code logic above.
// To avoid this we do not allow IdentityReference to be subclassed outside of the BCL.
//
Debug.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic.");
throw new NotSupportedException();
}
}
}
bool someFailed = false;
IdentityReferenceCollection TargetSids = null, TargetNTAccounts = null;
if (SourceSidsCount > 0)
{
TargetSids = SecurityIdentifier.Translate(SourceSids, targetType, out someFailed);
if (Homogeneous && !(forceSuccess && someFailed))
{
Result = TargetSids;
}
}
if (SourceNTAccountsCount > 0)
{
TargetNTAccounts = NTAccount.Translate(SourceNTAccounts, targetType, out someFailed);
if (Homogeneous && !(forceSuccess && someFailed))
{
Result = TargetNTAccounts;
}
}
if (forceSuccess && someFailed)
{
//
// Need to throw an exception here and provide information regarding
// which identity references could not be translated to the target type
//
Result = new IdentityReferenceCollection();
if (TargetSids != null)
{
foreach (IdentityReference id in TargetSids)
{
if (id.GetType() != targetType)
{
Result.Add(id);
}
}
}
if (TargetNTAccounts != null)
{
foreach (IdentityReference id in TargetNTAccounts)
{
if (id.GetType() != targetType)
{
Result.Add(id);
}
}
}
throw new IdentityNotMappedException(SR.IdentityReference_IdentityNotMapped, Result);
}
else if (!Homogeneous)
{
SourceSidsCount = 0;
SourceNTAccountsCount = 0;
Result = new IdentityReferenceCollection(Identities.Count);
for (int i = 0; i < Identities.Count; i++)
{
IdentityReference id = this[i];
Type type = id.GetType();
if (type == targetType)
{
Result.Add(id);
}
else if (type == typeof(SecurityIdentifier))
{
Result.Add(TargetSids[SourceSidsCount++]);
}
else if (type == typeof(NTAccount))
{
Result.Add(TargetNTAccounts[SourceNTAccountsCount++]);
}
else
{
//
// Rare case that we have defined a type of identity reference and not included it in the code logic above.
// To avoid this we do not allow IdentityReference to be subclassed outside of the BCL.
//
Debug.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic.");
throw new NotSupportedException();
}
}
}
return Result;
}
#endregion
}
internal class IdentityReferenceEnumerator : IEnumerator<IdentityReference>, IDisposable
{
#region Private members
//
// Current enumeration index
//
private int _current;
//
// Parent collection
//
private readonly IdentityReferenceCollection _collection;
#endregion
#region Constructors
internal IdentityReferenceEnumerator(IdentityReferenceCollection collection)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
Contract.EndContractBlock();
_collection = collection;
_current = -1;
}
#endregion
#region IEnumerator implementation
/// <internalonly/>
object IEnumerator.Current
{
get
{
return Current;
}
}
public IdentityReference Current
{
get
{
return _collection.Identities[_current];
}
}
public bool MoveNext()
{
_current++;
return (_current < _collection.Count);
}
public void Reset()
{
_current = -1;
}
public void Dispose()
{
}
#endregion
}
}
| |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <[email protected]>
using UnityEngine;
using UnityEditor;
using System;
namespace AmplifyShaderEditor
{
[Serializable]
[NodeAttributes( "Color", "Constants", "Color property", null, KeyCode.Alpha5 )]
public sealed class ColorNode : PropertyNode
{
[SerializeField]
private Color m_defaultValue = new Color( 0, 0, 0, 0 );
[SerializeField]
private Color m_materialValue = new Color( 0, 0, 0, 0 );
private ColorPickerHDRConfig m_dummyHdrConfig;
private GUIContent m_dummyContent;
private int m_cachedPropertyId = -1;
public ColorNode() : base() { }
public ColorNode( int uniqueId, float x, float y, float width, float height ) : base( uniqueId, x, y, width, height ) { }
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
m_insideSize.Set( 100, 50 );
m_dummyHdrConfig = new ColorPickerHDRConfig( float.MinValue, float.MinValue, float.MaxValue, float.MaxValue );
m_dummyContent = new GUIContent();
AddOutputColorPorts( "RGBA" );
m_drawPreview = false;
m_drawPreviewExpander = false;
m_canExpand = false;
m_selectedLocation = PreviewLocation.BottomCenter;
m_precisionString = UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, m_outputPorts[ 0 ].DataType );
m_previewShaderGUID = "6cf365ccc7ae776488ae8960d6d134c3";
}
public override void SetPreviewInputs()
{
base.SetPreviewInputs();
if ( m_cachedPropertyId == -1 )
m_cachedPropertyId = Shader.PropertyToID( "_InputColor" );
if ( m_materialMode && m_currentParameterType != PropertyType.Constant )
PreviewMaterial.SetColor( m_cachedPropertyId, m_materialValue );
else
PreviewMaterial.SetColor( m_cachedPropertyId, m_defaultValue );
}
public override void CopyDefaultsToMaterial()
{
m_materialValue = m_defaultValue;
}
public override void DrawSubProperties()
{
m_defaultValue = EditorGUILayoutColorField( Constants.DefaultValueLabel, m_defaultValue );
}
public override void DrawMaterialProperties()
{
if ( m_materialMode )
EditorGUI.BeginChangeCheck();
m_materialValue = EditorGUILayoutColorField( Constants.MaterialValueLabel, m_materialValue );
if ( m_materialMode && EditorGUI.EndChangeCheck() )
m_requireMaterialUpdate = true;
}
public override void Draw( DrawInfo drawInfo )
{
base.Draw( drawInfo );
if ( m_isVisible )
{
Rect newPos = m_globalPosition;
newPos.x = m_remainingBox.x;
newPos.y = m_remainingBox.y;
newPos.width = 80 * drawInfo.InvertedZoom;
newPos.height = m_remainingBox.height;
if ( m_materialMode && m_currentParameterType != PropertyType.Constant )
{
EditorGUI.BeginChangeCheck();
m_materialValue = EditorGUIColorField( newPos, m_dummyContent, m_materialValue, false, true, false, m_dummyHdrConfig );
if ( EditorGUI.EndChangeCheck() )
{
m_requireMaterialUpdate = true;
if ( m_currentParameterType != PropertyType.Constant )
{
BeginDelayedDirtyProperty();
}
}
}
else
{
EditorGUI.BeginChangeCheck();
m_defaultValue = EditorGUIColorField( newPos, m_dummyContent, m_defaultValue, false, true, false, m_dummyHdrConfig );
if ( EditorGUI.EndChangeCheck() )
{
BeginDelayedDirtyProperty();
}
}
}
}
public override void ConfigureLocalVariable( ref MasterNodeDataCollector dataCollector )
{
Color color = m_defaultValue;
dataCollector.AddLocalVariable( UniqueId, CreateLocalVarDec( color.r + "," + color.g + "," + color.b + "," + color.a ) );
m_outputPorts[ 0 ].SetLocalValue( m_propertyName );
m_outputPorts[ 1 ].SetLocalValue( m_propertyName + ".r" );
m_outputPorts[ 2 ].SetLocalValue( m_propertyName + ".g" );
m_outputPorts[ 3 ].SetLocalValue( m_propertyName + ".b" );
m_outputPorts[ 4 ].SetLocalValue( m_propertyName + ".a" );
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
base.GenerateShaderForOutput( outputId, ref dataCollector, ignoreLocalvar );
m_precisionString = UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, m_outputPorts[ 0 ].DataType );
if ( m_currentParameterType != PropertyType.Constant )
return GetOutputVectorItem( 0, outputId, PropertyData );
if ( m_outputPorts[ outputId ].IsLocalValue )
{
return m_outputPorts[ outputId ].LocalValue;
}
if ( CheckLocalVariable( ref dataCollector ) )
{
return m_outputPorts[ outputId ].LocalValue;
}
Color color = m_defaultValue;
string result = string.Empty;
switch ( outputId )
{
case 0:
{
result = m_precisionString + "(" + color.r + "," + color.g + "," + color.b + "," + color.a + ")";
}
break;
case 1:
{
result = color.r.ToString();
}
break;
case 2:
{
result = color.g.ToString();
}
break;
case 3:
{
result = color.b.ToString();
}
break;
case 4:
{
result = color.a.ToString();
}
break;
}
return result;
}
public override string GetPropertyValue()
{
return PropertyAttributes + m_propertyName + "(\"" + m_propertyInspectorName + "\", Color) = (" + m_defaultValue.r + "," + m_defaultValue.g + "," + m_defaultValue.b + "," + m_defaultValue.a + ")";
}
public override void UpdateMaterial( Material mat )
{
base.UpdateMaterial( mat );
if ( UIUtils.IsProperty( m_currentParameterType ) )
{
mat.SetColor( m_propertyName, m_materialValue );
}
}
public override void SetMaterialMode( Material mat , bool fetchMaterialValues )
{
base.SetMaterialMode( mat , fetchMaterialValues );
if ( m_materialMode && fetchMaterialValues )
{
m_materialValue = ( UIUtils.IsProperty( m_currentParameterType ) && mat.HasProperty( m_propertyName ) ) ? mat.GetColor( m_propertyName ) : m_defaultValue;
}
}
public override void ForceUpdateFromMaterial( Material material )
{
if ( UIUtils.IsProperty( m_currentParameterType ) && material.HasProperty( m_propertyName ) )
m_materialValue = material.GetColor( m_propertyName );
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
string[] colorChannels = GetCurrentParam( ref nodeParams ).Split( IOUtils.VECTOR_SEPARATOR );
if ( colorChannels.Length == 4 )
{
m_defaultValue.r = Convert.ToSingle( colorChannels[ 0 ] );
m_defaultValue.g = Convert.ToSingle( colorChannels[ 1 ] );
m_defaultValue.b = Convert.ToSingle( colorChannels[ 2 ] );
m_defaultValue.a = Convert.ToSingle( colorChannels[ 3 ] );
}
else
{
UIUtils.ShowMessage( "Incorrect number of color values", MessageSeverity.Error );
}
}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, m_defaultValue.r.ToString() + IOUtils.VECTOR_SEPARATOR + m_defaultValue.g.ToString() + IOUtils.VECTOR_SEPARATOR + m_defaultValue.b.ToString() + IOUtils.VECTOR_SEPARATOR + m_defaultValue.a.ToString() );
}
public override void ReadAdditionalClipboardData( ref string[] nodeParams )
{
base.ReadAdditionalClipboardData( ref nodeParams );
m_materialValue = IOUtils.StringToColor( GetCurrentParam( ref nodeParams ) );
}
public override void WriteAdditionalClipboardData( ref string nodeInfo )
{
base.WriteAdditionalClipboardData( ref nodeInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, IOUtils.ColorToString( m_materialValue ) );
}
public override string GetPropertyValStr()
{
return ( m_materialMode && m_currentParameterType != PropertyType.Constant ) ? m_materialValue.r.ToString( Constants.PropertyVectorFormatLabel ) + IOUtils.VECTOR_SEPARATOR +
m_materialValue.g.ToString( Constants.PropertyVectorFormatLabel ) + IOUtils.VECTOR_SEPARATOR +
m_materialValue.b.ToString( Constants.PropertyVectorFormatLabel ) + IOUtils.VECTOR_SEPARATOR +
m_materialValue.a.ToString( Constants.PropertyVectorFormatLabel ) :
m_defaultValue.r.ToString( Constants.PropertyVectorFormatLabel ) + IOUtils.VECTOR_SEPARATOR +
m_defaultValue.g.ToString( Constants.PropertyVectorFormatLabel ) + IOUtils.VECTOR_SEPARATOR +
m_defaultValue.b.ToString( Constants.PropertyVectorFormatLabel ) + IOUtils.VECTOR_SEPARATOR +
m_defaultValue.a.ToString( Constants.PropertyVectorFormatLabel );
}
public Color Value
{
get { return m_defaultValue; }
set { m_defaultValue = value; }
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace TaskManagement.Web.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using 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 Appoints.Api.Areas.HelpPage.ModelDescriptions;
using Appoints.Api.Areas.HelpPage.Models;
namespace Appoints.Api.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) 2021 Alachisoft
//
// 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.Net;
using Alachisoft.NCache.Caching;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.SocketServer.Statistics;
using System.Collections.Generic;
using System.Collections;
using Alachisoft.NCache.Common.Net;
using Alachisoft.NCache.Common.Monitoring;
using Alachisoft.NCache.Common.Util;
using Alachisoft.NCache.Common.Logger;
using Alachisoft.NCache.Management;
using Alachisoft.NCache.Common.CacheManagement;
using Alachisoft.NCache.Common.Topologies.Clustered;
using Alachisoft.NCache.Client;
using System.Runtime;
using Alachisoft.NCache.Common.Pooling.Stats;
using Alachisoft.NCache.Common.FeatureUsageData.Dom;
namespace Alachisoft.NCache.SocketServer
{
/// <summary>
/// An object of this class is called when NCache service starts and stops
/// as well as when NCache Bridge service starts and stops.
/// </summary>
public sealed class SocketServer : CacheRenderer
{
int _serverPort;
int _sendBuffer;
int _recieveBuffer;
decimal _clusterHealthDetectionInterval = 3;
int _managementServerPort;
string _managementServerIP;
public const int DEFAULT_SOCK_SERVER_PORT = 9800;
public const int DEFAULT_MANAGEMENT_PORT = 8250;
public const int DEFAULT_SOCK_BUFFER_SIZE = 32768;
//Size is specified in bytes (.net stream if grow more then 1.9GB will give memory exception that's why
//we send multiple responses each containing objects of specified size.
// 1 GB = 1 * 1024 * 1024 * 1024 = 1073741824
// 1 GB = 1 * MB * KB * Bytes = 1073741824
// If not specified in Service configuration then we will consider 1GB packeting
public static long CHUNK_SIZE_FOR_OBJECT = 35 * 1024;//1073741824;
static Logs _logger = new Logs();
static bool _enableCacheServerCounters = true;
#if !MONO
StatisticsCounter _perfStatsColl = null;
#endif
static LoggingInfo _serverLoggingInfo = new LoggingInfo();
/// <summary>
/// The garbage collection timer class.
/// </summary>
GarbageCollectionTimer gcTimer;
ConnectionManager _conManager;
LoggerNames _loggerName;
private static IConnectionManager _hostClientConnectionManager;
private string cacheName;
public string CacheName
{
set { cacheName = value; }
}
public static IConnectionManager HostClientConnectionManager
{
get { return _hostClientConnectionManager; }
}
/// <summary>
/// Initializes the socket server with the given port.
/// </summary>
/// <param name="port"></param>
/// <param name="sendBufferSize"></param>
/// <param name="recieveBufferSize"></param>
public SocketServer(int port, int sendBufferSize, int recieveBufferSize)
{
_serverPort = port;
_sendBuffer = sendBufferSize;
_recieveBuffer = recieveBufferSize;
if (ServiceConfiguration.ClusterHealthDetectionInterval != 3)
_clusterHealthDetectionInterval = ServiceConfiguration.ClusterHealthDetectionInterval;
}
/// <summary>
/// Gets the socket server port.
/// </summary>
public int ServerPort
{
get { return _serverPort; }
set { _serverPort = value < 0 ? DEFAULT_SOCK_SERVER_PORT : value; }
}
/// <summary>
/// Gets the send buffer size of connected client socket.
/// </summary>
public int SendBufferSize
{
get { return _sendBuffer; }
set { _sendBuffer = value < 0 ? DEFAULT_SOCK_BUFFER_SIZE : value; }
}
internal static Logs Logger
{
get { return _logger; }
}
/// <summary>
/// Gets the receive buffer size of connected client socket.
/// </summary>
public int ReceiveBufferSize
{
get { return _recieveBuffer; }
set { _recieveBuffer = value < 0 ? DEFAULT_SOCK_BUFFER_SIZE : value; }
}
/// <summary>
/// Gets a value indicating whether Cache Server counters are enabled or not.
/// </summary>
public static bool IsServerCounterEnabled
{
get { return _enableCacheServerCounters; }
set { _enableCacheServerCounters = value; }
}
public override int ManagementPort
{
get { return _managementServerPort; }
set { _managementServerPort = value; }
}
public override string ManagementIPAddress
{
get { return _managementServerIP; }
set { _managementServerIP = value; }
}
/// <summary>
/// Starts the socket server.It registers some types with compact Framework,
/// enables simple logs as well as DetailedLogs, then it checks Ncache licence information.
/// starts connection manager and perfmon counters.
/// </summary>
/// <param name="bindIP" ></param>
///
public void Start(IPAddress bindIP, LoggerNames loggerName, string perfStatColInstanceName, CommandManagerType cmdMgrType, ConnectionManagerType conMgrType)
{
if (loggerName == null)
_loggerName = LoggerNames.SocketServerLogs;
else
_loggerName = loggerName;
InitializeLogging();
if (ServiceConfiguration.PublishCountersToCacheHost)
_perfStatsColl = new CustomStatsCollector(cacheName, _serverPort);
else
_perfStatsColl = new PerfStatsCollector(cacheName, _serverPort);
_conManager = new ConnectionManager(_perfStatsColl);
_conManager.Start(bindIP, _serverPort, _sendBuffer, _recieveBuffer, _logger, cmdMgrType, conMgrType);
if (ConnectionManagerType.HostClient == conMgrType)
{
_hostClientConnectionManager = _conManager;
}
//We initialize PerfstatsCollector only for SocketServer's instance for client.
//Management socket server has just DUMMY stats collector.
if (conMgrType == ConnectionManagerType.HostClient)
_perfStatsColl.InitializePerfCounters();
}
/// <summary>
/// Initialize logging by reading setting from application configuration file
/// </summary>
public void InitializeLogging()
{
bool enable_logs = false;
bool detailed_logs = false;
try
{
enable_logs = ServiceConfiguration.EnableLogs;
detailed_logs = ServiceConfiguration.EnableDetailedLogs;
this.InitializeLogging(enable_logs, detailed_logs);
}
catch (Exception) { throw; }
}
/// <summary>
/// Initialize logging
/// </summary>
/// <param name="enable">Enable error logging only</param>
/// <param name="detailed">Enable detailed logging</param>
public void InitializeLogging(bool errorOnly, bool detailed)
{
try
{
if (errorOnly || detailed)
{
Logs localLogger = new Logs();
localLogger.NCacheLog = new NCacheLogger();
localLogger.NCacheLog.Initialize(LoggerNames.SocketServerLogs);
if (detailed)
{
localLogger.NCacheLog.SetLevel("all");
localLogger.IsErrorLogsEnabled = true;
}
else
{
localLogger.NCacheLog.SetLevel("info");
}
localLogger.NCacheLog.Info("SocketServer.Start", "server started successfully");
///Set logging status
if (errorOnly)
_serverLoggingInfo.SetStatus(LoggingInfo.LoggingType.Error, LoggingInfo.LogsStatus.Enable);
if (detailed)
_serverLoggingInfo.SetStatus(LoggingInfo.LoggingType.Detailed,
(detailed ? LoggingInfo.LogsStatus.Enable : LoggingInfo.LogsStatus.Disable));
localLogger.IsDetailedLogsEnabled = detailed;
localLogger.IsErrorLogsEnabled = errorOnly;
_logger = localLogger;
}
else
{
if (_logger.NCacheLog != null)
{
_logger.NCacheLog.Flush();
_logger.NCacheLog.SetLevel("OFF");
}
}
}
catch (Exception) { throw; }
}
/// <summary>
/// Stops the socket server. Stops connection manager.
/// </summary>
public void Stop()
{
if (_conManager != null)
{
_conManager.Stop();
}
}
public void StopListening()
{
if (_conManager != null)
_conManager.StopListening();
}
~SocketServer()
{
if (_conManager != null)
{
_conManager.Stop();
_conManager = null;
}
if (_perfStatsColl != null)
{
//_perfStatsColl.Dispose();
_perfStatsColl = null;
}
}
/// <summary>
/// Gets Server Port.
/// </summary>
public override int Port
{
get
{
return ServerPort;
}
}
/// <summary>
/// Converts server IpAddress string to IPAddress instance and return that.
/// </summary>
public override IPAddress IPAddress
{
get
{
try
{
return IPAddress.Parse(ConnectionManager.ServerIpAddress);
}
catch (Exception ex)
{
return null;
}
}
}
public override decimal ClusterHealthDetectionInterval
{
get
{
lock (this)
{
return this._clusterHealthDetectionInterval;
}
}
}
public override List<string> DeadClients => ConnectionManager.DeadClients();
/// <summary>
/// Get current logging status for specified type
/// </summary>
/// <param name="subsystem"></param>
/// <param name="type"></param>
/// <returns></returns>
public override LoggingInfo.LogsStatus GetLoggingStatus(LoggingInfo.LoggingSubsystem subsystem, LoggingInfo.LoggingType type)
{
switch (subsystem)
{
case LoggingInfo.LoggingSubsystem.Server:
lock (_serverLoggingInfo)
{
return _serverLoggingInfo.GetStatus(type);
}
case LoggingInfo.LoggingSubsystem.Client:
return ConnectionManager.GetClientLoggingInfo(type);
default:
return LoggingInfo.LogsStatus.Disable;
}
}
/// <summary>
/// Set and apply logging status
/// </summary>
/// <param name="subsystem"></param>
/// <param name="type"></param>
/// <param name="status"></param>
public override void SetLoggingStatus(LoggingInfo.LoggingSubsystem subsystem, LoggingInfo.LoggingType type, LoggingInfo.LogsStatus status)
{
if (subsystem == LoggingInfo.LoggingSubsystem.Client)
{
bool updateClient = false;
switch (type)
{
case LoggingInfo.LoggingType.Error:
case LoggingInfo.LoggingType.Detailed:
updateClient = ConnectionManager.SetClientLoggingInfo(type, status);
break;
case (LoggingInfo.LoggingType.Error | LoggingInfo.LoggingType.Detailed):
bool updateErrorLogs = ConnectionManager.SetClientLoggingInfo(LoggingInfo.LoggingType.Error, status);
bool updateDetailedLogs = ConnectionManager.SetClientLoggingInfo(LoggingInfo.LoggingType.Detailed, status);
updateClient = (updateErrorLogs || updateDetailedLogs);
break;
}
if (updateClient)
ConnectionManager.UpdateClients();
}
else if (subsystem == LoggingInfo.LoggingSubsystem.Server)
{
switch (status)
{
case LoggingInfo.LogsStatus.Disable:
///If error logs are disabled, then disable both
if (type == LoggingInfo.LoggingType.Error ||
type == (LoggingInfo.LoggingType.Error | LoggingInfo.LoggingType.Detailed))
{
this.InitializeLogging(false, false);
}
else if (type == LoggingInfo.LoggingType.Detailed)
{
this.InitializeLogging(Logger.IsErrorLogsEnabled, false);
}
break;
case LoggingInfo.LogsStatus.Enable:
bool error = Logger.IsErrorLogsEnabled;
bool detailed = Logger.IsDetailedLogsEnabled;
if (type == LoggingInfo.LoggingType.Error)
{
error = true;
detailed = false;
}
else if (type == LoggingInfo.LoggingType.Detailed |
type == (LoggingInfo.LoggingType.Error | LoggingInfo.LoggingType.Detailed))
{
error = true;
detailed = true;
}
this.InitializeLogging(error, detailed);
break;
}
}
}
/// <summary>
/// Start the gc timer to collect GEN#2 after specified intervals.
/// </summary>
/// <param name="dueTime">Time to wait (in minutes) before first collection.</param>
/// <param name="period">Time between two consecutive GEN#2 collections.</param>
public void StartGCTimer(int dueTime, int period)
{
try
{
}
catch (Exception e)
{
if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error("SocketServer.StartGCTimer", e.ToString());
}
}
public override List<Alachisoft.NCache.Common.Monitoring.ClientNode> GetClientList(string cacheId)
{
List<ClientNode> clients = new List<ClientNode>();
lock (ConnectionManager.ConnectionTable)
{
IDictionaryEnumerator ide = ConnectionManager.ConnectionTable.GetEnumerator();
while (ide.MoveNext())
{
ClientManager clientManager = ide.Value as ClientManager;
if (!clientManager.IsDisposed && clientManager.CmdExecuter != null && clientManager.CmdExecuter.ID.ToLower() == cacheId.ToLower())
{
ClientNode client = new ClientNode();
IPEndPoint endPoint = clientManager.ClientSocket.RemoteEndPoint as IPEndPoint;
client.Address = new Address(endPoint.Address, endPoint.Port);
client.ClientID = clientManager.ClientID;
if (clientManager.IsDotNetClient)
{
client.ClientContext = RtContextValue.NCACHE;
}
else
{
client.ClientContext = RtContextValue.JVCACHE;
}
clients.Add(client);
}
}
}
return clients;
}
//CLIENTSTATS : Add method in CacheRenderer as virtual
public override List<Alachisoft.NCache.Common.Monitoring.ClientProcessStats> GetClientProcessStats(string cacheId)
{
List<ClientProcessStats> clientProcessStats = new List<ClientProcessStats>();
lock (ConnectionManager.ConnectionTable)
{
IDictionaryEnumerator ide = ConnectionManager.ConnectionTable.GetEnumerator();
while (ide.MoveNext())
{
ClientManager clientManager = ide.Value as ClientManager;
if (clientManager.CmdExecuter != null && clientManager.CmdExecuter.ID.ToLower() == cacheId.ToLower())
{
IPEndPoint endPoint = clientManager.ClientSocket.RemoteEndPoint as IPEndPoint;
Address address = new Address(endPoint.Address, endPoint.Port);
ClientProcessStats cpStats = new ClientProcessStats(clientManager.ClientID, address, clientManager.ClientsBytesSent, clientManager.ClientsBytesRecieved, ConnectionManager.ServerIpAddress);
clientProcessStats.Add(cpStats);
}
}
}
return clientProcessStats;
}
public override Alachisoft.NCache.Common.DataStructures.RequestStatus GetRequestStatus(string clientId, long requestId, long commandId)
{
return _conManager.GetRequestStatus(clientId, requestId, commandId);
}
public override double GetCounterValue(string counterName)
{
double value = 0.0;
if (_perfStatsColl != null)
{
value = _perfStatsColl.GetCounterValue(counterName);
}
return value;
}
public override void RegisterOperationModeChangeEvent()
{
if (_conManager == null || _conManager.CommandManager == null) return;
_conManager.CommandManager.RegisterOperationModeChangeEvent();
}
public sealed override void InitializePools(bool createFakePools)
{
_conManager.CreatePools(createFakePools);
}
public sealed override PoolStats GetPoolStats(PoolStatsRequest request)
{
return _conManager.PoolManager?.GetStats(request);
}
public override ClientProfileDom GetClientProfile()
{
return _hostClientConnectionManager.GetClientProfile();
}
}
}
| |
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;
// <auto-generated />
namespace SAEON.Observations.Data
{
/// <summary>
/// Strongly-typed collection for the InstrumentSensor class.
/// </summary>
[Serializable]
public partial class InstrumentSensorCollection : ActiveList<InstrumentSensor, InstrumentSensorCollection>
{
public InstrumentSensorCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>InstrumentSensorCollection</returns>
public InstrumentSensorCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
InstrumentSensor 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 Instrument_Sensor table.
/// </summary>
[Serializable]
public partial class InstrumentSensor : ActiveRecord<InstrumentSensor>, IActiveRecord
{
#region .ctors and Default Settings
public InstrumentSensor()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public InstrumentSensor(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public InstrumentSensor(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public InstrumentSensor(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("Instrument_Sensor", TableType.Table, DataService.GetInstance("ObservationsDB"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema);
colvarId.ColumnName = "ID";
colvarId.DataType = DbType.Guid;
colvarId.MaxLength = 0;
colvarId.AutoIncrement = false;
colvarId.IsNullable = false;
colvarId.IsPrimaryKey = true;
colvarId.IsForeignKey = false;
colvarId.IsReadOnly = false;
colvarId.DefaultSetting = @"(newid())";
colvarId.ForeignKeyTableName = "";
schema.Columns.Add(colvarId);
TableSchema.TableColumn colvarInstrumentID = new TableSchema.TableColumn(schema);
colvarInstrumentID.ColumnName = "InstrumentID";
colvarInstrumentID.DataType = DbType.Guid;
colvarInstrumentID.MaxLength = 0;
colvarInstrumentID.AutoIncrement = false;
colvarInstrumentID.IsNullable = false;
colvarInstrumentID.IsPrimaryKey = false;
colvarInstrumentID.IsForeignKey = true;
colvarInstrumentID.IsReadOnly = false;
colvarInstrumentID.DefaultSetting = @"";
colvarInstrumentID.ForeignKeyTableName = "Instrument";
schema.Columns.Add(colvarInstrumentID);
TableSchema.TableColumn colvarSensorID = new TableSchema.TableColumn(schema);
colvarSensorID.ColumnName = "SensorID";
colvarSensorID.DataType = DbType.Guid;
colvarSensorID.MaxLength = 0;
colvarSensorID.AutoIncrement = false;
colvarSensorID.IsNullable = false;
colvarSensorID.IsPrimaryKey = false;
colvarSensorID.IsForeignKey = true;
colvarSensorID.IsReadOnly = false;
colvarSensorID.DefaultSetting = @"";
colvarSensorID.ForeignKeyTableName = "Sensor";
schema.Columns.Add(colvarSensorID);
TableSchema.TableColumn colvarStartDate = new TableSchema.TableColumn(schema);
colvarStartDate.ColumnName = "StartDate";
colvarStartDate.DataType = DbType.DateTime;
colvarStartDate.MaxLength = 0;
colvarStartDate.AutoIncrement = false;
colvarStartDate.IsNullable = true;
colvarStartDate.IsPrimaryKey = false;
colvarStartDate.IsForeignKey = false;
colvarStartDate.IsReadOnly = false;
colvarStartDate.DefaultSetting = @"";
colvarStartDate.ForeignKeyTableName = "";
schema.Columns.Add(colvarStartDate);
TableSchema.TableColumn colvarEndDate = new TableSchema.TableColumn(schema);
colvarEndDate.ColumnName = "EndDate";
colvarEndDate.DataType = DbType.DateTime;
colvarEndDate.MaxLength = 0;
colvarEndDate.AutoIncrement = false;
colvarEndDate.IsNullable = true;
colvarEndDate.IsPrimaryKey = false;
colvarEndDate.IsForeignKey = false;
colvarEndDate.IsReadOnly = false;
colvarEndDate.DefaultSetting = @"";
colvarEndDate.ForeignKeyTableName = "";
schema.Columns.Add(colvarEndDate);
TableSchema.TableColumn colvarLatitude = new TableSchema.TableColumn(schema);
colvarLatitude.ColumnName = "Latitude";
colvarLatitude.DataType = DbType.Double;
colvarLatitude.MaxLength = 0;
colvarLatitude.AutoIncrement = false;
colvarLatitude.IsNullable = true;
colvarLatitude.IsPrimaryKey = false;
colvarLatitude.IsForeignKey = false;
colvarLatitude.IsReadOnly = false;
colvarLatitude.DefaultSetting = @"";
colvarLatitude.ForeignKeyTableName = "";
schema.Columns.Add(colvarLatitude);
TableSchema.TableColumn colvarLongitude = new TableSchema.TableColumn(schema);
colvarLongitude.ColumnName = "Longitude";
colvarLongitude.DataType = DbType.Double;
colvarLongitude.MaxLength = 0;
colvarLongitude.AutoIncrement = false;
colvarLongitude.IsNullable = true;
colvarLongitude.IsPrimaryKey = false;
colvarLongitude.IsForeignKey = false;
colvarLongitude.IsReadOnly = false;
colvarLongitude.DefaultSetting = @"";
colvarLongitude.ForeignKeyTableName = "";
schema.Columns.Add(colvarLongitude);
TableSchema.TableColumn colvarElevation = new TableSchema.TableColumn(schema);
colvarElevation.ColumnName = "Elevation";
colvarElevation.DataType = DbType.Double;
colvarElevation.MaxLength = 0;
colvarElevation.AutoIncrement = false;
colvarElevation.IsNullable = true;
colvarElevation.IsPrimaryKey = false;
colvarElevation.IsForeignKey = false;
colvarElevation.IsReadOnly = false;
colvarElevation.DefaultSetting = @"";
colvarElevation.ForeignKeyTableName = "";
schema.Columns.Add(colvarElevation);
TableSchema.TableColumn colvarUserId = new TableSchema.TableColumn(schema);
colvarUserId.ColumnName = "UserId";
colvarUserId.DataType = DbType.Guid;
colvarUserId.MaxLength = 0;
colvarUserId.AutoIncrement = false;
colvarUserId.IsNullable = false;
colvarUserId.IsPrimaryKey = false;
colvarUserId.IsForeignKey = true;
colvarUserId.IsReadOnly = false;
colvarUserId.DefaultSetting = @"";
colvarUserId.ForeignKeyTableName = "aspnet_Users";
schema.Columns.Add(colvarUserId);
TableSchema.TableColumn colvarAddedAt = new TableSchema.TableColumn(schema);
colvarAddedAt.ColumnName = "AddedAt";
colvarAddedAt.DataType = DbType.DateTime;
colvarAddedAt.MaxLength = 0;
colvarAddedAt.AutoIncrement = false;
colvarAddedAt.IsNullable = true;
colvarAddedAt.IsPrimaryKey = false;
colvarAddedAt.IsForeignKey = false;
colvarAddedAt.IsReadOnly = false;
colvarAddedAt.DefaultSetting = @"(getdate())";
colvarAddedAt.ForeignKeyTableName = "";
schema.Columns.Add(colvarAddedAt);
TableSchema.TableColumn colvarUpdatedAt = new TableSchema.TableColumn(schema);
colvarUpdatedAt.ColumnName = "UpdatedAt";
colvarUpdatedAt.DataType = DbType.DateTime;
colvarUpdatedAt.MaxLength = 0;
colvarUpdatedAt.AutoIncrement = false;
colvarUpdatedAt.IsNullable = true;
colvarUpdatedAt.IsPrimaryKey = false;
colvarUpdatedAt.IsForeignKey = false;
colvarUpdatedAt.IsReadOnly = false;
colvarUpdatedAt.DefaultSetting = @"(getdate())";
colvarUpdatedAt.ForeignKeyTableName = "";
schema.Columns.Add(colvarUpdatedAt);
TableSchema.TableColumn colvarRowVersion = new TableSchema.TableColumn(schema);
colvarRowVersion.ColumnName = "RowVersion";
colvarRowVersion.DataType = DbType.Binary;
colvarRowVersion.MaxLength = 0;
colvarRowVersion.AutoIncrement = false;
colvarRowVersion.IsNullable = false;
colvarRowVersion.IsPrimaryKey = false;
colvarRowVersion.IsForeignKey = false;
colvarRowVersion.IsReadOnly = true;
colvarRowVersion.DefaultSetting = @"";
colvarRowVersion.ForeignKeyTableName = "";
schema.Columns.Add(colvarRowVersion);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["ObservationsDB"].AddSchema("Instrument_Sensor",schema);
}
}
#endregion
#region Props
[XmlAttribute("Id")]
[Bindable(true)]
public Guid Id
{
get { return GetColumnValue<Guid>(Columns.Id); }
set { SetColumnValue(Columns.Id, value); }
}
[XmlAttribute("InstrumentID")]
[Bindable(true)]
public Guid InstrumentID
{
get { return GetColumnValue<Guid>(Columns.InstrumentID); }
set { SetColumnValue(Columns.InstrumentID, value); }
}
[XmlAttribute("SensorID")]
[Bindable(true)]
public Guid SensorID
{
get { return GetColumnValue<Guid>(Columns.SensorID); }
set { SetColumnValue(Columns.SensorID, value); }
}
[XmlAttribute("StartDate")]
[Bindable(true)]
public DateTime? StartDate
{
get { return GetColumnValue<DateTime?>(Columns.StartDate); }
set { SetColumnValue(Columns.StartDate, value); }
}
[XmlAttribute("EndDate")]
[Bindable(true)]
public DateTime? EndDate
{
get { return GetColumnValue<DateTime?>(Columns.EndDate); }
set { SetColumnValue(Columns.EndDate, value); }
}
[XmlAttribute("Latitude")]
[Bindable(true)]
public double? Latitude
{
get { return GetColumnValue<double?>(Columns.Latitude); }
set { SetColumnValue(Columns.Latitude, value); }
}
[XmlAttribute("Longitude")]
[Bindable(true)]
public double? Longitude
{
get { return GetColumnValue<double?>(Columns.Longitude); }
set { SetColumnValue(Columns.Longitude, value); }
}
[XmlAttribute("Elevation")]
[Bindable(true)]
public double? Elevation
{
get { return GetColumnValue<double?>(Columns.Elevation); }
set { SetColumnValue(Columns.Elevation, value); }
}
[XmlAttribute("UserId")]
[Bindable(true)]
public Guid UserId
{
get { return GetColumnValue<Guid>(Columns.UserId); }
set { SetColumnValue(Columns.UserId, value); }
}
[XmlAttribute("AddedAt")]
[Bindable(true)]
public DateTime? AddedAt
{
get { return GetColumnValue<DateTime?>(Columns.AddedAt); }
set { SetColumnValue(Columns.AddedAt, value); }
}
[XmlAttribute("UpdatedAt")]
[Bindable(true)]
public DateTime? UpdatedAt
{
get { return GetColumnValue<DateTime?>(Columns.UpdatedAt); }
set { SetColumnValue(Columns.UpdatedAt, value); }
}
[XmlAttribute("RowVersion")]
[Bindable(true)]
public byte[] RowVersion
{
get { return GetColumnValue<byte[]>(Columns.RowVersion); }
set { SetColumnValue(Columns.RowVersion, value); }
}
#endregion
#region ForeignKey Properties
private SAEON.Observations.Data.AspnetUser _AspnetUser = null;
/// <summary>
/// Returns a AspnetUser ActiveRecord object related to this InstrumentSensor
///
/// </summary>
public SAEON.Observations.Data.AspnetUser AspnetUser
{
// get { return SAEON.Observations.Data.AspnetUser.FetchByID(this.UserId); }
get { return _AspnetUser ?? (_AspnetUser = SAEON.Observations.Data.AspnetUser.FetchByID(this.UserId)); }
set { SetColumnValue("UserId", value.UserId); }
}
private SAEON.Observations.Data.Instrument _Instrument = null;
/// <summary>
/// Returns a Instrument ActiveRecord object related to this InstrumentSensor
///
/// </summary>
public SAEON.Observations.Data.Instrument Instrument
{
// get { return SAEON.Observations.Data.Instrument.FetchByID(this.InstrumentID); }
get { return _Instrument ?? (_Instrument = SAEON.Observations.Data.Instrument.FetchByID(this.InstrumentID)); }
set { SetColumnValue("InstrumentID", value.Id); }
}
private SAEON.Observations.Data.Sensor _Sensor = null;
/// <summary>
/// Returns a Sensor ActiveRecord object related to this InstrumentSensor
///
/// </summary>
public SAEON.Observations.Data.Sensor Sensor
{
// get { return SAEON.Observations.Data.Sensor.FetchByID(this.SensorID); }
get { return _Sensor ?? (_Sensor = SAEON.Observations.Data.Sensor.FetchByID(this.SensorID)); }
set { SetColumnValue("SensorID", value.Id); }
}
#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(Guid varId,Guid varInstrumentID,Guid varSensorID,DateTime? varStartDate,DateTime? varEndDate,double? varLatitude,double? varLongitude,double? varElevation,Guid varUserId,DateTime? varAddedAt,DateTime? varUpdatedAt,byte[] varRowVersion)
{
InstrumentSensor item = new InstrumentSensor();
item.Id = varId;
item.InstrumentID = varInstrumentID;
item.SensorID = varSensorID;
item.StartDate = varStartDate;
item.EndDate = varEndDate;
item.Latitude = varLatitude;
item.Longitude = varLongitude;
item.Elevation = varElevation;
item.UserId = varUserId;
item.AddedAt = varAddedAt;
item.UpdatedAt = varUpdatedAt;
item.RowVersion = varRowVersion;
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(Guid varId,Guid varInstrumentID,Guid varSensorID,DateTime? varStartDate,DateTime? varEndDate,double? varLatitude,double? varLongitude,double? varElevation,Guid varUserId,DateTime? varAddedAt,DateTime? varUpdatedAt,byte[] varRowVersion)
{
InstrumentSensor item = new InstrumentSensor();
item.Id = varId;
item.InstrumentID = varInstrumentID;
item.SensorID = varSensorID;
item.StartDate = varStartDate;
item.EndDate = varEndDate;
item.Latitude = varLatitude;
item.Longitude = varLongitude;
item.Elevation = varElevation;
item.UserId = varUserId;
item.AddedAt = varAddedAt;
item.UpdatedAt = varUpdatedAt;
item.RowVersion = varRowVersion;
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 IdColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn InstrumentIDColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn SensorIDColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn StartDateColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn EndDateColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn LatitudeColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn LongitudeColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn ElevationColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn UserIdColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn AddedAtColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn UpdatedAtColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn RowVersionColumn
{
get { return Schema.Columns[11]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string Id = @"ID";
public static string InstrumentID = @"InstrumentID";
public static string SensorID = @"SensorID";
public static string StartDate = @"StartDate";
public static string EndDate = @"EndDate";
public static string Latitude = @"Latitude";
public static string Longitude = @"Longitude";
public static string Elevation = @"Elevation";
public static string UserId = @"UserId";
public static string AddedAt = @"AddedAt";
public static string UpdatedAt = @"UpdatedAt";
public static string RowVersion = @"RowVersion";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////////////////////////////////////////////////////////////////////////////
//
//
// Purpose: This class defines behaviors specific to a writing system.
// A writing system is the collection of scripts and
// orthographic rules required to represent a language as text.
//
//
////////////////////////////////////////////////////////////////////////////
using System;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
[System.Runtime.InteropServices.ComVisible(true)]
public class StringInfo
{
private String _str;
private int[] _indexes;
// Legacy constructor
public StringInfo() : this("") { }
// Primary, useful constructor
public StringInfo(String value)
{
this.String = value;
}
[System.Runtime.InteropServices.ComVisible(false)]
public override bool Equals(Object value)
{
StringInfo that = value as StringInfo;
if (that != null)
{
return (_str.Equals(that._str));
}
return (false);
}
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetHashCode()
{
return _str.GetHashCode();
}
// Our zero-based array of index values into the string. Initialize if
// our private array is not yet, in fact, initialized.
private int[] Indexes
{
get
{
if ((null == _indexes) && (0 < this.String.Length))
{
_indexes = StringInfo.ParseCombiningCharacters(this.String);
}
return (_indexes);
}
}
public String String
{
get
{
return (_str);
}
set
{
if (null == value)
{
throw new ArgumentNullException("String",
SR.ArgumentNull_String);
}
Contract.EndContractBlock();
_str = value;
_indexes = null;
}
}
public int LengthInTextElements
{
get
{
if (null == this.Indexes)
{
// Indexes not initialized, so assume length zero
return (0);
}
return (this.Indexes.Length);
}
}
public static String GetNextTextElement(String str)
{
return (GetNextTextElement(str, 0));
}
////////////////////////////////////////////////////////////////////////
//
// Get the code point count of the current text element.
//
// A combining class is defined as:
// A character/surrogate that has the following Unicode category:
// * NonSpacingMark (e.g. U+0300 COMBINING GRAVE ACCENT)
// * SpacingCombiningMark (e.g. U+ 0903 DEVANGARI SIGN VISARGA)
// * EnclosingMark (e.g. U+20DD COMBINING ENCLOSING CIRCLE)
//
// In the context of GetNextTextElement() and ParseCombiningCharacters(), a text element is defined as:
//
// 1. If a character/surrogate is in the following category, it is a text element.
// It can NOT further combine with characters in the combinging class to form a text element.
// * one of the Unicode category in the combinging class
// * UnicodeCategory.Format
// * UnicodeCateogry.Control
// * UnicodeCategory.OtherNotAssigned
// 2. Otherwise, the character/surrogate can be combined with characters in the combinging class to form a text element.
//
// Return:
// The length of the current text element
//
// Parameters:
// String str
// index The starting index
// len The total length of str (to define the upper boundary)
// ucCurrent The Unicode category pointed by Index. It will be updated to the uc of next character if this is not the last text element.
// currentCharCount The char count of an abstract char pointed by Index. It will be updated to the char count of next abstract character if this is not the last text element.
//
////////////////////////////////////////////////////////////////////////
internal static int GetCurrentTextElementLen(String str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount)
{
Contract.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
Contract.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
if (index + currentCharCount == len)
{
// This is the last character/surrogate in the string.
return (currentCharCount);
}
// Call an internal GetUnicodeCategory, which will tell us both the unicode category, and also tell us if it is a surrogate pair or not.
int nextCharCount;
UnicodeCategory ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index + currentCharCount, out nextCharCount);
if (CharUnicodeInfo.IsCombiningCategory(ucNext))
{
// The next element is a combining class.
// Check if the current text element to see if it is a valid base category (i.e. it should not be a combining category,
// not a format character, and not a control character).
if (CharUnicodeInfo.IsCombiningCategory(ucCurrent)
|| (ucCurrent == UnicodeCategory.Format)
|| (ucCurrent == UnicodeCategory.Control)
|| (ucCurrent == UnicodeCategory.OtherNotAssigned)
|| (ucCurrent == UnicodeCategory.Surrogate)) // An unpair high surrogate or low surrogate
{
// Will fall thru and return the currentCharCount
}
else
{
int startIndex = index; // Remember the current index.
// We have a valid base characters, and we have a character (or surrogate) that is combining.
// Check if there are more combining characters to follow.
// Check if the next character is a nonspacing character.
index += currentCharCount + nextCharCount;
while (index < len)
{
ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out nextCharCount);
if (!CharUnicodeInfo.IsCombiningCategory(ucNext))
{
ucCurrent = ucNext;
currentCharCount = nextCharCount;
break;
}
index += nextCharCount;
}
return (index - startIndex);
}
}
// The return value will be the currentCharCount.
int ret = currentCharCount;
ucCurrent = ucNext;
// Update currentCharCount.
currentCharCount = nextCharCount;
return (ret);
}
// Returns the str containing the next text element in str starting at
// index index. If index is not supplied, then it will start at the beginning
// of str. It recognizes a base character plus one or more combining
// characters or a properly formed surrogate pair as a text element. See also
// the ParseCombiningCharacters() and the ParseSurrogates() methods.
public static String GetNextTextElement(String str, int index)
{
//
// Validate parameters.
//
if (str == null)
{
throw new ArgumentNullException("str");
}
Contract.EndContractBlock();
int len = str.Length;
if (index < 0 || index >= len)
{
if (index == len)
{
return (String.Empty);
}
throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index);
}
int charLen;
UnicodeCategory uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen);
return (str.Substring(index, GetCurrentTextElementLen(str, index, len, ref uc, ref charLen)));
}
public static TextElementEnumerator GetTextElementEnumerator(String str)
{
return (GetTextElementEnumerator(str, 0));
}
public static TextElementEnumerator GetTextElementEnumerator(String str, int index)
{
//
// Validate parameters.
//
if (str == null)
{
throw new ArgumentNullException("str");
}
Contract.EndContractBlock();
int len = str.Length;
if (index < 0 || (index > len))
{
throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index);
}
return (new TextElementEnumerator(str, index, len));
}
/*
* Returns the indices of each base character or properly formed surrogate pair
* within the str. It recognizes a base character plus one or more combining
* characters or a properly formed surrogate pair as a text element and returns
* the index of the base character or high surrogate. Each index is the
* beginning of a text element within a str. The length of each element is
* easily computed as the difference between successive indices. The length of
* the array will always be less than or equal to the length of the str. For
* example, given the str \u4f00\u302a\ud800\udc00\u4f01, this method would
* return the indices: 0, 2, 4.
*/
public static int[] ParseCombiningCharacters(String str)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
Contract.EndContractBlock();
int len = str.Length;
int[] result = new int[len];
if (len == 0)
{
return (result);
}
int resultCount = 0;
int i = 0;
int currentCharLen;
UnicodeCategory currentCategory = CharUnicodeInfo.InternalGetUnicodeCategory(str, 0, out currentCharLen);
while (i < len)
{
result[resultCount++] = i;
i += GetCurrentTextElementLen(str, i, len, ref currentCategory, ref currentCharLen);
}
if (resultCount < len)
{
int[] returnArray = new int[resultCount];
Array.Copy(result, returnArray, resultCount);
return (returnArray);
}
return (result);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Automation
{
/// <summary>
/// Service operation for automation agent registration information. (see
/// http://aka.ms/azureautomationsdk/agentregistrationoperations for more
/// information)
/// </summary>
internal partial class AgentRegistrationOperation : IServiceOperations<AutomationManagementClient>, IAgentRegistrationOperation
{
/// <summary>
/// Initializes a new instance of the AgentRegistrationOperation class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal AgentRegistrationOperation(AutomationManagementClient client)
{
this._client = client;
}
private AutomationManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Automation.AutomationManagementClient.
/// </summary>
public AutomationManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Retrieve the automation agent registration information. (see
/// http://aka.ms/azureautomationsdk/agentregistrationoperations for
/// more information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get agent registration information
/// operation.
/// </returns>
public async Task<AgentRegistrationGetResponse> GetAsync(string resourceGroupName, string automationAccount, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/agentRegistrationInformation";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AgentRegistrationGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new AgentRegistrationGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
AgentRegistration agentRegistrationInstance = new AgentRegistration();
result.AgentRegistration = agentRegistrationInstance;
JToken dscMetaConfigurationValue = responseDoc["dscMetaConfiguration"];
if (dscMetaConfigurationValue != null && dscMetaConfigurationValue.Type != JTokenType.Null)
{
string dscMetaConfigurationInstance = ((string)dscMetaConfigurationValue);
agentRegistrationInstance.DscMetaConfiguration = dscMetaConfigurationInstance;
}
JToken endpointValue = responseDoc["endpoint"];
if (endpointValue != null && endpointValue.Type != JTokenType.Null)
{
string endpointInstance = ((string)endpointValue);
agentRegistrationInstance.Endpoint = endpointInstance;
}
JToken keysValue = responseDoc["keys"];
if (keysValue != null && keysValue.Type != JTokenType.Null)
{
AgentRegistrationKeys keysInstance = new AgentRegistrationKeys();
agentRegistrationInstance.Keys = keysInstance;
JToken primaryValue = keysValue["primary"];
if (primaryValue != null && primaryValue.Type != JTokenType.Null)
{
string primaryInstance = ((string)primaryValue);
keysInstance.Primary = primaryInstance;
}
JToken secondaryValue = keysValue["secondary"];
if (secondaryValue != null && secondaryValue.Type != JTokenType.Null)
{
string secondaryInstance = ((string)secondaryValue);
keysInstance.Secondary = secondaryInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Regenerate a primary or secondary agent registration key (see
/// http://aka.ms/azureautomationsdk/agentregistrationoperations for
/// more information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='keyName'>
/// Required. The name of the agent registration key to be regenerated
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the agent registration key regenerate
/// operation.
/// </returns>
public async Task<AgentRegistrationRegenerateKeyResponse> RegenerateKeyAsync(string resourceGroupName, string automationAccount, AgentRegistrationRegenerateKeyParameter keyName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (keyName == null)
{
throw new ArgumentNullException("keyName");
}
if (keyName.KeyName == null)
{
throw new ArgumentNullException("keyName.KeyName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("keyName", keyName);
TracingAdapter.Enter(invocationId, this, "RegenerateKeyAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/agentRegistrationInformation/regenerateKey";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject agentRegistrationRegenerateKeyParameterValue = new JObject();
requestDoc = agentRegistrationRegenerateKeyParameterValue;
agentRegistrationRegenerateKeyParameterValue["keyName"] = keyName.KeyName;
if (keyName.Name != null)
{
agentRegistrationRegenerateKeyParameterValue["name"] = keyName.Name;
}
if (keyName.Location != null)
{
agentRegistrationRegenerateKeyParameterValue["location"] = keyName.Location;
}
if (keyName.Tags != null)
{
JObject tagsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in keyName.Tags)
{
string tagsKey = pair.Key;
string tagsValue = pair.Value;
tagsDictionary[tagsKey] = tagsValue;
}
agentRegistrationRegenerateKeyParameterValue["tags"] = tagsDictionary;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AgentRegistrationRegenerateKeyResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new AgentRegistrationRegenerateKeyResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
AgentRegistration agentRegistrationInstance = new AgentRegistration();
result.AgentRegistration = agentRegistrationInstance;
JToken dscMetaConfigurationValue = responseDoc["dscMetaConfiguration"];
if (dscMetaConfigurationValue != null && dscMetaConfigurationValue.Type != JTokenType.Null)
{
string dscMetaConfigurationInstance = ((string)dscMetaConfigurationValue);
agentRegistrationInstance.DscMetaConfiguration = dscMetaConfigurationInstance;
}
JToken endpointValue = responseDoc["endpoint"];
if (endpointValue != null && endpointValue.Type != JTokenType.Null)
{
string endpointInstance = ((string)endpointValue);
agentRegistrationInstance.Endpoint = endpointInstance;
}
JToken keysValue = responseDoc["keys"];
if (keysValue != null && keysValue.Type != JTokenType.Null)
{
AgentRegistrationKeys keysInstance = new AgentRegistrationKeys();
agentRegistrationInstance.Keys = keysInstance;
JToken primaryValue = keysValue["primary"];
if (primaryValue != null && primaryValue.Type != JTokenType.Null)
{
string primaryInstance = ((string)primaryValue);
keysInstance.Primary = primaryInstance;
}
JToken secondaryValue = keysValue["secondary"];
if (secondaryValue != null && secondaryValue.Type != JTokenType.Null)
{
string secondaryInstance = ((string)secondaryValue);
keysInstance.Secondary = secondaryInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.XWPF.Extractor
{
using NPOI.XWPF.Extractor;
using NPOI.XWPF.UserModel;
using NUnit.Framework;
using System;
using System.Diagnostics;
using System.Text.RegularExpressions;
/**
* Tests for HXFWordExtractor
*/
[TestFixture]
public class TestXWPFWordExtractor
{
/**
* Get text out of the simple file
* @throws IOException
*/
[Test]
public void TestGetSimpleText()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("sample.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
String text = extractor.Text;
Assert.IsTrue(text.Length > 0);
// Check contents
Assert.IsTrue(text.StartsWith(
"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nunc at risus vel erat tempus posuere. Aenean non ante. Suspendisse vehicula dolor sit amet odio."
));
Assert.IsTrue(text.EndsWith(
"Phasellus ultricies mi nec leo. Sed tempus. In sit amet lorem at velit faucibus vestibulum.\n"
));
// Check number of paragraphs
int ps = 0;
char[] t = text.ToCharArray();
for (int i = 0; i < t.Length; i++)
{
if (t[i] == '\n')
{
ps++;
}
}
Assert.AreEqual(3, ps);
}
/**
* Tests Getting the text out of a complex file
* @throws IOException
*/
[Test]
public void TestGetComplexText()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("IllustrativeCases.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
String text = extractor.Text;
Assert.IsTrue(text.Length > 0);
char euro = '\u20ac';
Debug.WriteLine("'" + text.Substring(text.Length - 40) + "'");
//Check contents
Assert.IsTrue(text.StartsWith(
" \n(V) ILLUSTRATIVE CASES\n\n"
));
Assert.IsTrue(text.Contains(
"As well as gaining " + euro + "90 from child benefit increases, he will also receive the early childhood supplement of " + euro + "250 per quarter for Vincent for the full four quarters of the year.\n\n\n\n"// \n\n\n"
));
Assert.IsTrue(text.EndsWith(
"11.4%\t\t90\t\t\t\t\t250\t\t1,310\t\n\n \n\n\n"
));
// Check number of paragraphs
int ps = 0;
char[] t = text.ToCharArray();
for (int i = 0; i < t.Length; i++)
{
if (t[i] == '\n')
{
ps++;
}
}
Assert.AreEqual(134, ps);
}
[Test]
public void TestGetWithHyperlinks()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("TestDocument.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
// Now check contents
extractor.SetFetchHyperlinks(false);
Assert.AreEqual(
"This is a test document.\nThis bit is in bold and italic\n" +
"Back to normal\n" +
"This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.\n" +
"We have a hyperlink here, and another.\n",
extractor.Text
);
// One hyperlink is a real one, one is just to the top of page
extractor.SetFetchHyperlinks(true);
Assert.AreEqual(
"This is a test document.\nThis bit is in bold and italic\n" +
"Back to normal\n" +
"This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.\n" +
"We have a hyperlink <http://poi.apache.org/> here, and another.\n",
extractor.Text
);
}
[Test]
public void TestHeadersFooters()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("ThreeColHeadFoot.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
Assert.AreEqual(
"First header column!\tMid header\tRight header!\n" +
"This is a sample word document. It has two pages. It has a three column heading, and a three column footer\n" +
"\n" +
"HEADING TEXT\n" +
"\n" +
"More on page one\n" +
"\n\n" +
"End of page 1\n\n\n" +
"This is page two. It also has a three column heading, and a three column footer.\n" +
"Footer Left\tFooter Middle\tFooter Right\n",
extractor.Text
);
// Now another file, expect multiple headers
// and multiple footers
doc = XWPFTestDataSamples.OpenSampleDocument("DiffFirstPageHeadFoot.docx");
extractor = new XWPFWordExtractor(doc);
extractor =
new XWPFWordExtractor(doc);
//extractor.Text;
Assert.AreEqual(
"I am the header on the first page, and I" + '\u2019' + "m nice and simple\n" +
"First header column!\tMid header\tRight header!\n" +
"This is a sample word document. It has two pages. It has a simple header and footer, which is different to all the other pages.\n" +
"\n" +
"HEADING TEXT\n" +
"\n" +
"More on page one\n" +
"\n\n" +
"End of page 1\n\n\n" +
"This is page two. It also has a three column heading, and a three column footer.\n" +
"The footer of the first page\n" +
"Footer Left\tFooter Middle\tFooter Right\n",
extractor.Text
);
}
[Test]
public void TestFootnotes()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("footnotes.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
String text = extractor.Text;
Assert.IsTrue(extractor.Text.Contains("snoska"));
Assert.IsTrue(text.Contains("Eto ochen prostoy[footnoteRef:1] text so snoskoy"));
}
[Test]
public void TestTableFootnotes()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("table_footnotes.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
Assert.IsTrue(extractor.Text.Contains("snoska"));
}
[Test]
public void TestFormFootnotes()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("form_footnotes.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
String text = extractor.Text;
Assert.IsTrue(text.Contains("testdoc"), "Unable to find expected word in text\n" + text);
Assert.IsTrue(text.Contains("test phrase"), "Unable to find expected word in text\n" + text);
}
[Test]
public void TestEndnotes()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("endnotes.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
string text = extractor.Text;
Assert.IsTrue(text.Contains("XXX"));
Assert.IsTrue(text.Contains("tilaka [endnoteRef:2]or 'tika'"));
}
[Test]
public void TestInsertedDeletedText()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("delins.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
Assert.IsTrue(extractor.Text.Contains("pendant worn"));
Assert.IsTrue(extractor.Text.Contains("extremely well"));
}
[Test]
public void TestParagraphHeader()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("Headers.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
Assert.IsTrue(extractor.Text.Contains("Section 1"));
Assert.IsTrue(extractor.Text.Contains("Section 2"));
Assert.IsTrue(extractor.Text.Contains("Section 3"));
}
/**
* Test that we can open and process .docm
* (macro enabled) docx files (bug #45690)
* @throws IOException
*/
[Test]
public void TestDOCMFiles()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("45690.docm");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
Assert.IsTrue(extractor.Text.Contains("2004"));
Assert.IsTrue(extractor.Text.Contains("2008"));
Assert.IsTrue(extractor.Text.Contains("(120 "));
}
/**
* Test that we handle things like tabs and
* carriage returns properly in the text that
* we're extracting (bug #49189)
* @throws IOException
*/
[Test]
public void TestDocTabs()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("WithTabs.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
// Check bits
Assert.IsTrue(extractor.Text.Contains("a"));
Assert.IsTrue(extractor.Text.Contains("\t"));
Assert.IsTrue(extractor.Text.Contains("b"));
// Now check the first paragraph in total
Assert.IsTrue(extractor.Text.Contains("a\tb\n"));
}
/**
* The output should not contain field codes, e.g. those specified in the
* w:instrText tag (spec sec. 17.16.23)
* @throws IOException
*/
[Test]
public void TestNoFieldCodes()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("FieldCodes.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
String text = extractor.Text;
Assert.IsTrue(text.Length > 0);
Assert.IsFalse(text.Contains("AUTHOR"));
Assert.IsFalse(text.Contains("CREATEDATE"));
}
/**
* The output should contain the values of simple fields, those specified
* with the fldSimple element (spec sec. 17.16.19)
* @throws IOException
*/
[Test]
public void TestFldSimpleContent()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("FldSimple.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
String text = extractor.Text;
Assert.IsTrue(text.Length > 0);
Assert.IsTrue(text.Contains("FldSimple.docx"));
}
/**
* Test for parsing document with Drawings to prevent
* NoClassDefFoundError for CTAnchor in XWPFRun
*/
[Test]
public void TestDrawings()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("drawing.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
String text = extractor.Text;
Assert.IsTrue(text.Length > 0);
}
/**
* Test for basic extraction of SDT content
* @throws IOException
*/
[Test]
public void TestSimpleControlContent()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("Bug54849.docx");
String[] targs = new String[]{
"header_rich_text",
"rich_text",
"rich_text_pre_table\nrich_text_cell1\t\t\t\n\t\t\t\n\t\t\t\n\nrich_text_post_table",
"plain_text_no_newlines",
"plain_text_with_newlines1\nplain_text_with_newlines2\n",
"watermelon\n",
"dirt\n",
"4/16/2013\n",
"rich_text_in_cell",
"abc",
"rich_text_in_paragraph_in_cell",
"footer_rich_text",
"footnote_sdt",
"endnote_sdt"
};
XWPFWordExtractor ex = new XWPFWordExtractor(doc);
String s = ex.Text.ToLower();
int hits = 0;
foreach (String targ in targs)
{
bool hitted = false;
if (s.Contains(targ))
{
hitted = true;
hits++;
}
Assert.AreEqual(true, hitted, "controlled content loading-" + targ);
}
Assert.AreEqual(targs.Length, hits, "controlled content loading hit count");
ex.Close();
doc = XWPFTestDataSamples.OpenSampleDocument("Bug54771a.docx");
targs = new String[]{
"bb",
"test subtitle\n",
"test user\n",
};
ex = new XWPFWordExtractor(doc);
s = ex.Text.ToLower();
//At one point in development there were three copies of the text.
//This ensures that there is only one copy.
MatchCollection mc;
int hit;
foreach (String targ in targs)
{
mc = Regex.Matches(s, targ);
hit = 0;
foreach (Match m in mc)
{
if (m.Success)
hit++;
}
Assert.AreEqual(1, hit, "controlled content loading-" + targ);
}
//"test\n" appears twice: once as the "title" and once in the text.
//This also happens when you save this document as text from MSWord.
mc = Regex.Matches(s, "test\n");
hit = 0;
foreach (Match m in mc)
{
if (m.Success)
hit++;
}
Assert.AreEqual(2, hit, "test<N>");
ex.Close();
}
/** No Header or Footer in document */
[Test]
public void TestBug55733()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("55733.docx");
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
// Check it gives text without error
string text = extractor.Text;
extractor.Close();
}
[Test]
public void TestCheckboxes()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("checkboxes.docx");
Console.WriteLine(doc);
XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
Assert.AreEqual("This is a small test for checkboxes \nunchecked: |_| \n" +
"Or checked: |X|\n\n\n\n\n" +
"Test a checkbox within a textbox: |_| -> |X|\n\n\n" +
"In Table:\n|_|\t|X|\n\n\n" +
"In Sequence:\n|X||_||X|\n", extractor.Text);
extractor.Close();
}
}
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org/?p=license&r=2.4.
// ****************************************************************
using System;
using System.IO;
using System.Collections;
using NUnit.Framework;
namespace NUnit.Util.Tests
{
/// <summary>
/// Summary description for ProjectConfigTests.
/// </summary>
[TestFixture]
public class ProjectConfigTests
{
private ProjectConfig config;
private NUnitProject project;
[SetUp]
public void SetUp()
{
config = new ProjectConfig( "Debug" );
project = new NUnitProject( TestPath( "/test/myproject.nunit" ) );
project.Configs.Add( config );
}
/// <summary>
/// Take a valid Linux path and make a valid windows path out of it
/// if we are on Windows. Change slashes to backslashes and, if the
/// path starts with a slash, add C: in front of it.
/// </summary>
private string TestPath(string path)
{
if (Path.DirectorySeparatorChar != '/')
{
path = path.Replace('/', Path.DirectorySeparatorChar);
if (path[0] == Path.DirectorySeparatorChar)
path = "C:" + path;
}
return path;
}
[Test]
public void EmptyConfig()
{
Assert.AreEqual( "Debug", config.Name );
Assert.AreEqual( 0, config.Assemblies.Count );
}
[Test]
public void CanAddAssemblies()
{
string path1 = TestPath("/test/assembly1.dll");
string path2 = TestPath("/test/assembly2.dll");
config.Assemblies.Add(path1);
config.Assemblies.Add( path2 );
Assert.AreEqual( 2, config.Assemblies.Count );
Assert.AreEqual( path1, config.Assemblies[0] );
Assert.AreEqual( path2, config.Assemblies[1] );
}
[Test]
public void ToArray()
{
string path1 = TestPath("/test/assembly1.dll");
string path2 = TestPath("/test/assembly2.dll");
config.Assemblies.Add( path1 );
config.Assemblies.Add( path2 );
string[] files = config.Assemblies.ToArray();
Assert.AreEqual( path1, files[0] );
Assert.AreEqual( path2, files[1] );
}
[Test]
public void AddMarksProjectDirty()
{
config.Assemblies.Add( TestPath( "/test/bin/debug/assembly1.dll" ) );
Assert.IsTrue( project.IsDirty );
}
[Test]
public void RenameMarksProjectDirty()
{
config.Name = "Renamed";
Assert.IsTrue( project.IsDirty );
}
[Test]
public void RemoveMarksProjectDirty()
{
string path1 = TestPath("/test/bin/debug/assembly1.dll");
config.Assemblies.Add( path1 );
project.IsDirty = false;
config.Assemblies.Remove( path1 );
Assert.IsTrue( project.IsDirty );
}
[Test]
public void SettingApplicationBaseMarksProjectDirty()
{
config.BasePath = TestPath( "/junk" );
Assert.IsTrue( project.IsDirty );
}
[Test]
public void AbsoluteBasePath()
{
config.BasePath = TestPath("/junk");
string path1 = TestPath( "/junk/bin/debug/assembly1.dll" );
config.Assemblies.Add( path1 );
Assert.AreEqual( path1, config.Assemblies[0] );
}
[Test]
public void RelativeBasePath()
{
config.BasePath = @"junk";
string path1 = TestPath("/test/junk/bin/debug/assembly1.dll");
config.Assemblies.Add( path1 );
Assert.AreEqual( path1, config.Assemblies[0] );
}
[Test]
public void NoBasePathSet()
{
string path1 = TestPath( "/test/bin/debug/assembly1.dll" );
config.Assemblies.Add( path1 );
Assert.AreEqual( path1, config.Assemblies[0] );
}
[Test]
public void SettingConfigurationFileMarksProjectDirty()
{
config.ConfigurationFile = "MyProject.config";
Assert.IsTrue( project.IsDirty );
}
[Test]
public void DefaultConfigurationFile()
{
Assert.AreEqual( "myproject.config", config.ConfigurationFile );
Assert.AreEqual( TestPath( "/test/myproject.config" ), config.ConfigurationFilePath );
}
[Test]
public void AbsoluteConfigurationFile()
{
string path1 = TestPath("/configs/myconfig.config");
config.ConfigurationFile = path1;
Assert.AreEqual( path1, config.ConfigurationFilePath );
}
[Test]
public void RelativeConfigurationFile()
{
config.ConfigurationFile = "myconfig.config";
Assert.AreEqual( TestPath( "/test/myconfig.config" ), config.ConfigurationFilePath );
}
[Test]
public void SettingPrivateBinPathMarksProjectDirty()
{
config.PrivateBinPath = TestPath( "/junk" ) + Path.PathSeparator + TestPath( "/bin" );
Assert.IsTrue( project.IsDirty );
}
[Test]
public void SettingBinPathTypeMarksProjectDirty()
{
config.BinPathType = BinPathType.Manual;
Assert.IsTrue( project.IsDirty );
}
// TODO: Move to DomainManagerTests
// [Test]
// public void GetPrivateBinPath()
// {
// string path1 = TestPath("/test/bin/debug/test1.dll");
// string path2 = TestPath("/test/bin/debug/test2.dll");
// string path3 = TestPath("/test/utils/test3.dll");
// config.Assemblies.Add( path1 );
// config.Assemblies.Add(path2);
// config.Assemblies.Add(path3);
//
// Assert.AreEqual( TestPath( "bin/debug" ) + Path.PathSeparator + TestPath( "utils" ), config.PrivateBinPath );
// }
[Test]
public void NoPrivateBinPath()
{
config.Assemblies.Add( TestPath( "/bin/assembly1.dll" ) );
config.Assemblies.Add( TestPath( "/bin/assembly2.dll" ) );
config.BinPathType = BinPathType.None;
Assert.IsNull( config.PrivateBinPath );
}
[Test]
public void ManualPrivateBinPath()
{
config.Assemblies.Add( TestPath( "/test/bin/assembly1.dll" ) );
config.Assemblies.Add( TestPath( "/test/bin/assembly2.dll" ) );
config.BinPathType = BinPathType.Manual;
config.PrivateBinPath = TestPath( "/test" );
Assert.AreEqual( TestPath( "/test" ), config.PrivateBinPath );
}
// TODO: Move to DomainManagerTests
// [Test]
// public void AutoPrivateBinPath()
// {
// config.Assemblies.Add( TestPath( "/test/bin/assembly1.dll" ) );
// config.Assemblies.Add( TestPath( "/test/bin/assembly2.dll" ) );
// config.BinPathType = BinPathType.Auto;
// Assert.AreEqual( "bin", config.PrivateBinPath );
// }
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Markup;
using GodLesZ.Library.Win7.Controls;
using GodLesZ.Library.Win7.Dialogs.Controls;
using GodLesZ.Library.Win7.Shell;
using GodLesZ.Library.Win7.Shell.Resources;
using MS.WindowsAPICodePack.Internal;
namespace GodLesZ.Library.Win7.Dialogs {
/// <summary>
/// Defines the abstract base class for the common file dialogs.
/// </summary>
[ContentProperty("Controls")]
public abstract class CommonFileDialog : IDialogControlHost, IDisposable {
/// <summary>
/// The collection of names selected by the user.
/// </summary>
protected IEnumerable<string> FileNameCollection {
get {
foreach (string name in filenames) {
yield return name;
}
}
}
private Collection<string> filenames;
internal readonly Collection<IShellItem> items;
internal DialogShowState showState = DialogShowState.PreShow;
private IFileDialog nativeDialog;
private IFileDialogCustomize customize;
private NativeDialogEventSink nativeEventSink;
private bool? canceled;
private bool resetSelections;
private IntPtr parentWindow = IntPtr.Zero;
private bool filterSet; // filters can only be set once
#region Constructors
/// <summary>
/// Creates a new instance of this class.
/// </summary>
protected CommonFileDialog() {
if (!CoreHelpers.RunningOnVista) {
throw new PlatformNotSupportedException(LocalizedMessages.CommonFileDialogRequiresVista);
}
filenames = new Collection<string>();
filters = new CommonFileDialogFilterCollection();
items = new Collection<IShellItem>();
controls = new CommonFileDialogControlCollection<CommonFileDialogControl>(this);
}
/// <summary>
/// Creates a new instance of this class with the specified title.
/// </summary>
/// <param name="title">The title to display in the dialog.</param>
protected CommonFileDialog(string title)
: this() {
this.title = title;
}
#endregion
// Template method to allow derived dialog to create actual
// specific COM coclass (e.g. FileOpenDialog or FileSaveDialog).
internal abstract void InitializeNativeFileDialog();
internal abstract IFileDialog GetNativeFileDialog();
internal abstract void PopulateWithFileNames(Collection<string> names);
internal abstract void PopulateWithIShellItems(Collection<IShellItem> shellItems);
internal abstract void CleanUpNativeFileDialog();
internal abstract ShellNativeMethods.FileOpenOptions GetDerivedOptionFlags(ShellNativeMethods.FileOpenOptions flags);
#region Public API
// Events.
/// <summary>
/// Raised just before the dialog is about to return with a result. Occurs when the user clicks on the Open
/// or Save button on a file dialog box.
/// </summary>
public event CancelEventHandler FileOk;
/// <summary>
/// Raised just before the user navigates to a new folder.
/// </summary>
public event EventHandler<CommonFileDialogFolderChangeEventArgs> FolderChanging;
/// <summary>
/// Raised when the user navigates to a new folder.
/// </summary>
public event EventHandler FolderChanged;
/// <summary>
/// Raised when the user changes the selection in the dialog's view.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Raised when the dialog is opened to notify the application of the initial chosen filetype.
/// </summary>
public event EventHandler FileTypeChanged;
/// <summary>
/// Raised when the dialog is opening.
/// </summary>
public event EventHandler DialogOpening;
private CommonFileDialogControlCollection<CommonFileDialogControl> controls;
/// <summary>
/// Gets the collection of controls for the dialog.
/// </summary>
public CommonFileDialogControlCollection<CommonFileDialogControl> Controls {
get { return controls; }
}
private CommonFileDialogFilterCollection filters;
/// <summary>
/// Gets the filters used by the dialog.
/// </summary>
public CommonFileDialogFilterCollection Filters {
get { return filters; }
}
private string title;
/// <summary>
/// Gets or sets the dialog title.
/// </summary>
/// <value>A <see cref="System.String"/> object.</value>
public string Title {
get { return title; }
set {
title = value;
if (NativeDialogShowing) { nativeDialog.SetTitle(value); }
}
}
// This is the first of many properties that are backed by the FOS_*
// bitflag options set with IFileDialog.SetOptions().
// SetOptions() fails
// if called while dialog is showing (e.g. from a callback).
private bool ensureFileExists;
/// <summary>
/// Gets or sets a value that determines whether the file must exist beforehand.
/// </summary>
/// <value>A <see cref="System.Boolean"/> value. <b>true</b> if the file must exist.</value>
/// <exception cref="System.InvalidOperationException">This property cannot be set when the dialog is visible.</exception>
public bool EnsureFileExists {
get { return ensureFileExists; }
set {
ThrowIfDialogShowing(LocalizedMessages.EnsureFileExistsCannotBeChanged);
ensureFileExists = value;
}
}
private bool ensurePathExists;
/// <summary>
/// Gets or sets a value that specifies whether the returned file must be in an existing folder.
/// </summary>
/// <value>A <see cref="System.Boolean"/> value. <b>true</b> if the file must exist.</value>
/// <exception cref="System.InvalidOperationException">This property cannot be set when the dialog is visible.</exception>
public bool EnsurePathExists {
get { return ensurePathExists; }
set {
ThrowIfDialogShowing(LocalizedMessages.EnsurePathExistsCannotBeChanged);
ensurePathExists = value;
}
}
private bool ensureValidNames;
/// <summary>Gets or sets a value that determines whether to validate file names.
/// </summary>
///<value>A <see cref="System.Boolean"/> value. <b>true </b>to check for situations that would prevent an application from opening the selected file, such as sharing violations or access denied errors.</value>
/// <exception cref="System.InvalidOperationException">This property cannot be set when the dialog is visible.</exception>
///
public bool EnsureValidNames {
get { return ensureValidNames; }
set {
ThrowIfDialogShowing(LocalizedMessages.EnsureValidNamesCannotBeChanged);
ensureValidNames = value;
}
}
private bool ensureReadOnly;
/// <summary>
/// Gets or sets a value that determines whether read-only items are returned.
/// Default value for CommonOpenFileDialog is true (allow read-only files) and
/// CommonSaveFileDialog is false (don't allow read-only files).
/// </summary>
/// <value>A <see cref="System.Boolean"/> value. <b>true</b> includes read-only items.</value>
/// <exception cref="System.InvalidOperationException">This property cannot be set when the dialog is visible.</exception>
public bool EnsureReadOnly {
get { return ensureReadOnly; }
set {
ThrowIfDialogShowing(LocalizedMessages.EnsureReadonlyCannotBeChanged);
ensureReadOnly = value;
}
}
private bool restoreDirectory;
/// <summary>
/// Gets or sets a value that determines the restore directory.
/// </summary>
/// <remarks></remarks>
/// <exception cref="System.InvalidOperationException">This property cannot be set when the dialog is visible.</exception>
public bool RestoreDirectory {
get { return restoreDirectory; }
set {
ThrowIfDialogShowing(LocalizedMessages.RestoreDirectoryCannotBeChanged);
restoreDirectory = value;
}
}
private bool showPlacesList = true;
/// <summary>
/// Gets or sets a value that controls whether
/// to show or hide the list of pinned places that
/// the user can choose.
/// </summary>
/// <value>A <see cref="System.Boolean"/> value. <b>true</b> if the list is visible; otherwise <b>false</b>.</value>
/// <exception cref="System.InvalidOperationException">This property cannot be set when the dialog is visible.</exception>
public bool ShowPlacesList {
get { return showPlacesList; }
set {
ThrowIfDialogShowing(LocalizedMessages.ShowPlacesListCannotBeChanged);
showPlacesList = value;
}
}
private bool addToMruList = true;
/// <summary>
/// Gets or sets a value that controls whether to show or hide the list of places where the user has recently opened or saved items.
/// </summary>
/// <value>A <see cref="System.Boolean"/> value.</value>
/// <exception cref="System.InvalidOperationException">This property cannot be set when the dialog is visible.</exception>
public bool AddToMostRecentlyUsedList {
get { return addToMruList; }
set {
ThrowIfDialogShowing(LocalizedMessages.AddToMostRecentlyUsedListCannotBeChanged);
addToMruList = value;
}
}
private bool showHiddenItems;
///<summary>
/// Gets or sets a value that controls whether to show hidden items.
/// </summary>
/// <value>A <see cref="System.Boolean"/> value.<b>true</b> to show the items; otherwise <b>false</b>.</value>
/// <exception cref="System.InvalidOperationException">This property cannot be set when the dialog is visible.</exception>
public bool ShowHiddenItems {
get { return showHiddenItems; }
set {
ThrowIfDialogShowing(LocalizedMessages.ShowHiddenItemsCannotBeChanged);
showHiddenItems = value;
}
}
private bool allowPropertyEditing;
/// <summary>
/// Gets or sets a value that controls whether
/// properties can be edited.
/// </summary>
/// <value>A <see cref="System.Boolean"/> value. </value>
public bool AllowPropertyEditing {
get { return allowPropertyEditing; }
set { allowPropertyEditing = value; }
}
private bool navigateToShortcut = true;
///<summary>
/// Gets or sets a value that controls whether shortcuts should be treated as their target items, allowing an application to open a .lnk file.
/// </summary>
/// <value>A <see cref="System.Boolean"/> value. <b>true</b> indicates that shortcuts should be treated as their targets. </value>
/// <exception cref="System.InvalidOperationException">This property cannot be set when the dialog is visible.</exception>
public bool NavigateToShortcut {
get { return navigateToShortcut; }
set {
ThrowIfDialogShowing(LocalizedMessages.NavigateToShortcutCannotBeChanged);
navigateToShortcut = value;
}
}
/// <summary>
/// Gets or sets the default file extension to be added to file names. If the value is null
/// or string.Empty, the extension is not added to the file names.
/// </summary>
public string DefaultExtension { get; set; }
/// <summary>
/// Gets the index for the currently selected file type.
/// </summary>
public int SelectedFileTypeIndex {
get {
uint fileType;
if (nativeDialog != null) {
nativeDialog.GetFileTypeIndex(out fileType);
return (int)fileType;
}
return -1;
}
}
/// <summary>
/// Tries to set the File(s) Type Combo to match the value in
/// 'DefaultExtension'. Only doing this if 'this' is a Save dialog
/// as it makes no sense to do this if only Opening a file.
/// </summary>
///
/// <param name="dialog">The native/IFileDialog instance.</param>
///
private void SyncFileTypeComboToDefaultExtension(IFileDialog dialog) {
// make sure it's a Save dialog and that there is a default
// extension to sync to.
if (!(this is CommonSaveFileDialog) || DefaultExtension == null ||
filters.Count <= 0) {
return;
}
CommonFileDialogFilter filter = null;
for (uint filtersCounter = 0; filtersCounter < filters.Count; filtersCounter++) {
filter = (CommonFileDialogFilter)filters[(int)filtersCounter];
if (filter.Extensions.Contains(DefaultExtension)) {
// set the docType combo to match this
// extension. property is a 1-based index.
dialog.SetFileTypeIndex(filtersCounter + 1);
// we're done, exit for
break;
}
}
}
/// <summary>
/// Gets the selected filename.
/// </summary>
/// <value>A <see cref="System.String"/> object.</value>
/// <exception cref="System.InvalidOperationException">This property cannot be used when multiple files are selected.</exception>
public string FileName {
get {
CheckFileNamesAvailable();
if (filenames.Count > 1) {
throw new InvalidOperationException(LocalizedMessages.CommonFileDialogMultipleFiles);
}
string returnFilename = filenames[0];
// "If extension is a null reference (Nothing in Visual
// Basic), the returned string contains the specified
// path with its extension removed." Since we do not want
// to remove any existing extension, make sure the
// DefaultExtension property is NOT null.
// if we should, and there is one to set...
if (!string.IsNullOrEmpty(DefaultExtension)) {
returnFilename = System.IO.Path.ChangeExtension(returnFilename, DefaultExtension);
}
return returnFilename;
}
}
/// <summary>
/// Gets the selected item as a ShellObject.
/// </summary>
/// <value>A <see cref="GodLesZ.Library.Win7.Shell.ShellObject"></see> object.</value>
/// <exception cref="System.InvalidOperationException">This property cannot be used when multiple files
/// are selected.</exception>
public ShellObject FileAsShellObject {
get {
CheckFileItemsAvailable();
if (items.Count > 1) {
throw new InvalidOperationException(LocalizedMessages.CommonFileDialogMultipleItems);
}
if (items.Count == 0) { return null; }
return ShellObjectFactory.Create(items[0]);
}
}
/// <summary>
/// Adds a location, such as a folder, library, search connector, or known folder, to the list of
/// places available for a user to open or save items. This method actually adds an item
/// to the <b>Favorite Links</b> or <b>Places</b> section of the Open/Save dialog.
/// </summary>
/// <param name="place">The item to add to the places list.</param>
/// <param name="location">One of the enumeration values that indicates placement of the item in the list.</param>
public void AddPlace(ShellContainer place, FileDialogAddPlaceLocation location) {
if (place == null) {
throw new ArgumentNullException("place");
}
// Get our native dialog
if (nativeDialog == null) {
InitializeNativeFileDialog();
nativeDialog = GetNativeFileDialog();
}
// Add the shellitem to the places list
if (nativeDialog != null) {
nativeDialog.AddPlace(place.NativeShellItem, (ShellNativeMethods.FileDialogAddPlacement)location);
}
}
/// <summary>
/// Adds a location (folder, library, search connector, known folder) to the list of
/// places available for the user to open or save items. This method actually adds an item
/// to the <b>Favorite Links</b> or <b>Places</b> section of the Open/Save dialog. Overload method
/// takes in a string for the path.
/// </summary>
/// <param name="path">The item to add to the places list.</param>
/// <param name="location">One of the enumeration values that indicates placement of the item in the list.</param>
public void AddPlace(string path, FileDialogAddPlaceLocation location) {
if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path"); }
// Get our native dialog
if (nativeDialog == null) {
InitializeNativeFileDialog();
nativeDialog = GetNativeFileDialog();
}
// Create a native shellitem from our path
IShellItem2 nativeShellItem;
Guid guid = new Guid(ShellIIDGuid.IShellItem2);
int retCode = ShellNativeMethods.SHCreateItemFromParsingName(path, IntPtr.Zero, ref guid, out nativeShellItem);
if (!CoreErrorHelper.Succeeded(retCode)) {
throw new CommonControlException(LocalizedMessages.CommonFileDialogCannotCreateShellItem, Marshal.GetExceptionForHR(retCode));
}
// Add the shellitem to the places list
if (nativeDialog != null) {
nativeDialog.AddPlace(nativeShellItem, (ShellNativeMethods.FileDialogAddPlacement)location);
}
}
// Null = use default directory.
private string initialDirectory;
/// <summary>
/// Gets or sets the initial directory displayed when the dialog is shown.
/// A null or empty string indicates that the dialog is using the default directory.
/// </summary>
/// <value>A <see cref="System.String"/> object.</value>
public string InitialDirectory {
get { return initialDirectory; }
set { initialDirectory = value; }
}
private ShellContainer initialDirectoryShellContainer;
/// <summary>
/// Gets or sets a location that is always selected when the dialog is opened,
/// regardless of previous user action. A null value implies that the dialog is using
/// the default location.
/// </summary>
public ShellContainer InitialDirectoryShellContainer {
get { return initialDirectoryShellContainer; }
set { initialDirectoryShellContainer = value; }
}
private string defaultDirectory;
/// <summary>
/// Sets the folder and path used as a default if there is not a recently used folder value available.
/// </summary>
public string DefaultDirectory {
get { return defaultDirectory; }
set { defaultDirectory = value; }
}
private ShellContainer defaultDirectoryShellContainer;
/// <summary>
/// Sets the location (<see cref="GodLesZ.Library.Win7.Shell.ShellContainer">ShellContainer</see>
/// used as a default if there is not a recently used folder value available.
/// </summary>
public ShellContainer DefaultDirectoryShellContainer {
get { return defaultDirectoryShellContainer; }
set { defaultDirectoryShellContainer = value; }
}
// Null = use default identifier.
private Guid cookieIdentifier;
/// <summary>
/// Gets or sets a value that enables a calling application
/// to associate a GUID with a dialog's persisted state.
/// </summary>
public Guid CookieIdentifier {
get { return cookieIdentifier; }
set { cookieIdentifier = value; }
}
/// <summary>
/// Displays the dialog.
/// </summary>
/// <param name="ownerWindowHandle">Window handle of any top-level window that will own the modal dialog box.</param>
/// <returns>A <see cref="CommonFileDialogResult"/> object.</returns>
public CommonFileDialogResult ShowDialog(IntPtr ownerWindowHandle) {
if (ownerWindowHandle == IntPtr.Zero) {
throw new ArgumentException(LocalizedMessages.CommonFileDialogInvalidHandle, "ownerWindowHandle");
}
// Set the parent / owner window
parentWindow = ownerWindowHandle;
// Show the modal dialog
return ShowDialog();
}
/// <summary>
/// Displays the dialog.
/// </summary>
/// <param name="window">Top-level WPF window that will own the modal dialog box.</param>
/// <returns>A <see cref="CommonFileDialogResult"/> object.</returns>
public CommonFileDialogResult ShowDialog(Window window) {
if (window == null) {
throw new ArgumentNullException("window");
}
// Set the parent / owner window
parentWindow = (new WindowInteropHelper(window)).Handle;
// Show the modal dialog
return ShowDialog();
}
/// <summary>
/// Displays the dialog.
/// </summary>
/// <returns>A <see cref="CommonFileDialogResult"/> object.</returns>
public CommonFileDialogResult ShowDialog() {
CommonFileDialogResult result;
// Fetch derived native dialog (i.e. Save or Open).
InitializeNativeFileDialog();
nativeDialog = GetNativeFileDialog();
// Apply outer properties to native dialog instance.
ApplyNativeSettings(nativeDialog);
InitializeEventSink(nativeDialog);
// Clear user data if Reset has been called
// since the last show.
if (resetSelections) {
resetSelections = false;
}
// Show dialog.
showState = DialogShowState.Showing;
int hresult = nativeDialog.Show(parentWindow);
showState = DialogShowState.Closed;
// Create return information.
if (CoreErrorHelper.Matches(hresult, (int)HResult.Win32ErrorCanceled)) {
canceled = true;
result = CommonFileDialogResult.Cancel;
filenames.Clear();
} else {
canceled = false;
result = CommonFileDialogResult.Ok;
// Populate filenames if user didn't cancel.
PopulateWithFileNames(filenames);
// Populate the actual IShellItems
PopulateWithIShellItems(items);
}
return result;
}
/// <summary>
/// Removes the current selection.
/// </summary>
public void ResetUserSelections() {
resetSelections = true;
}
/// <summary>
/// Default file name.
/// </summary>
public string DefaultFileName { get; set; }
#endregion
#region Configuration
private void InitializeEventSink(IFileDialog nativeDlg) {
// Check if we even need to have a sink.
if (FileOk != null
|| FolderChanging != null
|| FolderChanged != null
|| SelectionChanged != null
|| FileTypeChanged != null
|| DialogOpening != null
|| (controls != null && controls.Count > 0)) {
uint cookie;
nativeEventSink = new NativeDialogEventSink(this);
nativeDlg.Advise(nativeEventSink, out cookie);
nativeEventSink.Cookie = cookie;
}
}
private void ApplyNativeSettings(IFileDialog dialog) {
Debug.Assert(dialog != null, "No dialog instance to configure");
if (parentWindow == IntPtr.Zero) {
if (System.Windows.Application.Current != null && System.Windows.Application.Current.MainWindow != null) {
parentWindow = (new WindowInteropHelper(System.Windows.Application.Current.MainWindow)).Handle;
} else if (System.Windows.Forms.Application.OpenForms.Count > 0) {
parentWindow = System.Windows.Forms.Application.OpenForms[0].Handle;
}
}
Guid guid = new Guid(ShellIIDGuid.IShellItem2);
// Apply option bitflags.
dialog.SetOptions(CalculateNativeDialogOptionFlags());
// Other property sets.
if (title != null) { dialog.SetTitle(title); }
if (initialDirectoryShellContainer != null) {
dialog.SetFolder(((ShellObject)initialDirectoryShellContainer).NativeShellItem);
}
if (defaultDirectoryShellContainer != null) {
dialog.SetDefaultFolder(((ShellObject)defaultDirectoryShellContainer).NativeShellItem);
}
if (!string.IsNullOrEmpty(initialDirectory)) {
// Create a native shellitem from our path
IShellItem2 initialDirectoryShellItem;
ShellNativeMethods.SHCreateItemFromParsingName(initialDirectory, IntPtr.Zero, ref guid, out initialDirectoryShellItem);
// If we get a real shell item back,
// then use that as the initial folder - otherwise,
// we'll allow the dialog to revert to the default folder.
// (OR should we fail loudly?)
if (initialDirectoryShellItem != null)
dialog.SetFolder(initialDirectoryShellItem);
}
if (!string.IsNullOrEmpty(defaultDirectory)) {
// Create a native shellitem from our path
IShellItem2 defaultDirectoryShellItem;
ShellNativeMethods.SHCreateItemFromParsingName(defaultDirectory, IntPtr.Zero, ref guid, out defaultDirectoryShellItem);
// If we get a real shell item back,
// then use that as the initial folder - otherwise,
// we'll allow the dialog to revert to the default folder.
// (OR should we fail loudly?)
if (defaultDirectoryShellItem != null) {
dialog.SetDefaultFolder(defaultDirectoryShellItem);
}
}
// Apply file type filters, if available.
if (filters.Count > 0 && !filterSet) {
dialog.SetFileTypes(
(uint)filters.Count,
filters.GetAllFilterSpecs());
filterSet = true;
SyncFileTypeComboToDefaultExtension(dialog);
}
if (cookieIdentifier != Guid.Empty) {
dialog.SetClientGuid(ref cookieIdentifier);
}
// Set the default extension
if (!string.IsNullOrEmpty(DefaultExtension)) {
dialog.SetDefaultExtension(DefaultExtension);
}
// Set the default filename
dialog.SetFileName(DefaultFileName);
}
private ShellNativeMethods.FileOpenOptions CalculateNativeDialogOptionFlags() {
// We start with only a few flags set by default,
// then go from there based on the current state
// of the managed dialog's property values.
ShellNativeMethods.FileOpenOptions flags = ShellNativeMethods.FileOpenOptions.NoTestFileCreate;
// Call to derived (concrete) dialog to
// set dialog-specific flags.
flags = GetDerivedOptionFlags(flags);
// Apply other optional flags.
if (ensureFileExists) {
flags |= ShellNativeMethods.FileOpenOptions.FileMustExist;
}
if (ensurePathExists) {
flags |= ShellNativeMethods.FileOpenOptions.PathMustExist;
}
if (!ensureValidNames) {
flags |= ShellNativeMethods.FileOpenOptions.NoValidate;
}
if (!EnsureReadOnly) {
flags |= ShellNativeMethods.FileOpenOptions.NoReadOnlyReturn;
}
if (restoreDirectory) {
flags |= ShellNativeMethods.FileOpenOptions.NoChangeDirectory;
}
if (!showPlacesList) {
flags |= ShellNativeMethods.FileOpenOptions.HidePinnedPlaces;
}
if (!addToMruList) {
flags |= ShellNativeMethods.FileOpenOptions.DontAddToRecent;
}
if (showHiddenItems) {
flags |= ShellNativeMethods.FileOpenOptions.ForceShowHidden;
}
if (!navigateToShortcut) {
flags |= ShellNativeMethods.FileOpenOptions.NoDereferenceLinks;
}
return flags;
}
#endregion
#region IDialogControlHost Members
private static void GenerateNotImplementedException() {
throw new NotImplementedException(LocalizedMessages.NotImplementedException);
}
/// <summary>
/// Returns if change to the colleciton is allowed.
/// </summary>
/// <returns>true if collection change is allowed.</returns>
public virtual bool IsCollectionChangeAllowed() {
return true;
}
/// <summary>
/// Applies changes to the collection.
/// </summary>
public virtual void ApplyCollectionChanged() {
// Query IFileDialogCustomize interface before adding controls
GetCustomizedFileDialog();
// Populate all the custom controls and add them to the dialog
foreach (CommonFileDialogControl control in controls) {
if (!control.IsAdded) {
control.HostingDialog = this;
control.Attach(customize);
control.IsAdded = true;
}
}
}
/// <summary>
/// Determines if changes to a specific property are allowed.
/// </summary>
/// <param name="propertyName">The name of the property.</param>
/// <param name="control">The control propertyName applies to.</param>
/// <returns>true if the property change is allowed.</returns>
public virtual bool IsControlPropertyChangeAllowed(string propertyName, DialogControl control) {
CommonFileDialog.GenerateNotImplementedException();
return false;
}
/// <summary>
/// Called when a control currently in the collection
/// has a property changed.
/// </summary>
/// <param name="propertyName">The name of the property changed.</param>
/// <param name="control">The control whose property has changed.</param>
public virtual void ApplyControlPropertyChange(string propertyName, DialogControl control) {
if (control == null) {
throw new ArgumentNullException("control");
}
CommonFileDialogControl dialogControl = null;
if (propertyName == "Text") {
CommonFileDialogTextBox textBox = control as CommonFileDialogTextBox;
if (textBox != null) {
customize.SetEditBoxText(control.Id, textBox.Text);
} else {
customize.SetControlLabel(control.Id, textBox.Text);
}
} else if (propertyName == "Visible" && (dialogControl = control as CommonFileDialogControl) != null) {
ShellNativeMethods.ControlState state;
customize.GetControlState(control.Id, out state);
if (dialogControl.Visible == true) {
state |= ShellNativeMethods.ControlState.Visible;
} else if (dialogControl.Visible == false) {
state &= ~ShellNativeMethods.ControlState.Visible;
}
customize.SetControlState(control.Id, state);
} else if (propertyName == "Enabled" && dialogControl != null) {
ShellNativeMethods.ControlState state;
customize.GetControlState(control.Id, out state);
if (dialogControl.Enabled == true) {
state |= ShellNativeMethods.ControlState.Enable;
} else if (dialogControl.Enabled == false) {
state &= ~ShellNativeMethods.ControlState.Enable;
}
customize.SetControlState(control.Id, state);
} else if (propertyName == "SelectedIndex") {
CommonFileDialogRadioButtonList list;
CommonFileDialogComboBox box;
if ((list = control as CommonFileDialogRadioButtonList) != null) {
customize.SetSelectedControlItem(list.Id, list.SelectedIndex);
} else if ((box = control as CommonFileDialogComboBox) != null) {
customize.SetSelectedControlItem(box.Id, box.SelectedIndex);
}
} else if (propertyName == "IsChecked") {
CommonFileDialogCheckBox checkBox = control as CommonFileDialogCheckBox;
if (checkBox != null) {
customize.SetCheckButtonState(checkBox.Id, checkBox.IsChecked);
}
}
}
#endregion
#region Helpers
/// <summary>
/// Ensures that the user has selected one or more files.
/// </summary>
/// <permission cref="System.InvalidOperationException">
/// The dialog has not been dismissed yet or the dialog was cancelled.
/// </permission>
protected void CheckFileNamesAvailable() {
if (showState != DialogShowState.Closed) {
throw new InvalidOperationException(LocalizedMessages.CommonFileDialogNotClosed);
}
if (canceled.GetValueOrDefault()) {
throw new InvalidOperationException(LocalizedMessages.CommonFileDialogCanceled);
}
Debug.Assert(filenames.Count != 0,
"FileNames empty - shouldn't happen unless dialog canceled or not yet shown.");
}
/// <summary>
/// Ensures that the user has selected one or more files.
/// </summary>
/// <permission cref="System.InvalidOperationException">
/// The dialog has not been dismissed yet or the dialog was cancelled.
/// </permission>
protected void CheckFileItemsAvailable() {
if (showState != DialogShowState.Closed) {
throw new InvalidOperationException(LocalizedMessages.CommonFileDialogNotClosed);
}
if (canceled.GetValueOrDefault()) {
throw new InvalidOperationException(LocalizedMessages.CommonFileDialogCanceled);
}
Debug.Assert(items.Count != 0,
"Items list empty - shouldn't happen unless dialog canceled or not yet shown.");
}
private bool NativeDialogShowing {
get {
return (nativeDialog != null)
&& (showState == DialogShowState.Showing || showState == DialogShowState.Closing);
}
}
internal static string GetFileNameFromShellItem(IShellItem item) {
string filename = null;
IntPtr pszString = IntPtr.Zero;
HResult hr = item.GetDisplayName(ShellNativeMethods.ShellItemDesignNameOptions.DesktopAbsoluteParsing, out pszString);
if (hr == HResult.Ok && pszString != IntPtr.Zero) {
filename = Marshal.PtrToStringAuto(pszString);
Marshal.FreeCoTaskMem(pszString);
}
return filename;
}
internal static IShellItem GetShellItemAt(IShellItemArray array, int i) {
IShellItem result;
uint index = (uint)i;
array.GetItemAt(index, out result);
return result;
}
/// <summary>
/// Throws an exception when the dialog is showing preventing
/// a requested change to a property or the visible set of controls.
/// </summary>
/// <param name="message">The message to include in the exception.</param>
/// <permission cref="System.InvalidOperationException"> The dialog is in an
/// invalid state to perform the requested operation.</permission>
protected void ThrowIfDialogShowing(string message) {
if (NativeDialogShowing) {
throw new InvalidOperationException(message);
}
}
/// <summary>
/// Get the IFileDialogCustomize interface, preparing to add controls.
/// </summary>
private void GetCustomizedFileDialog() {
if (customize == null) {
if (nativeDialog == null) {
InitializeNativeFileDialog();
nativeDialog = GetNativeFileDialog();
}
customize = (IFileDialogCustomize)nativeDialog;
}
}
#endregion
#region CheckChanged handling members
/// <summary>
/// Raises the <see cref="CommonFileDialog.FileOk"/> event just before the dialog is about to return with a result.
/// </summary>
/// <param name="e">The event data.</param>
protected virtual void OnFileOk(CancelEventArgs e) {
CancelEventHandler handler = FileOk;
if (handler != null) {
handler(this, e);
}
}
/// <summary>
/// Raises the <see cref="FolderChanging"/> to stop navigation to a particular location.
/// </summary>
/// <param name="e">Cancelable event arguments.</param>
protected virtual void OnFolderChanging(CommonFileDialogFolderChangeEventArgs e) {
EventHandler<CommonFileDialogFolderChangeEventArgs> handler = FolderChanging;
if (handler != null) {
handler(this, e);
}
}
/// <summary>
/// Raises the <see cref="CommonFileDialog.FolderChanged"/> event when the user navigates to a new folder.
/// </summary>
/// <param name="e">The event data.</param>
protected virtual void OnFolderChanged(EventArgs e) {
EventHandler handler = FolderChanged;
if (handler != null) {
handler(this, e);
}
}
/// <summary>
/// Raises the <see cref="CommonFileDialog.SelectionChanged"/> event when the user changes the selection in the dialog's view.
/// </summary>
/// <param name="e">The event data.</param>
protected virtual void OnSelectionChanged(EventArgs e) {
EventHandler handler = SelectionChanged;
if (handler != null) {
handler(this, e);
}
}
/// <summary>
/// Raises the <see cref="CommonFileDialog.FileTypeChanged"/> event when the dialog is opened to notify the
/// application of the initial chosen filetype.
/// </summary>
/// <param name="e">The event data.</param>
protected virtual void OnFileTypeChanged(EventArgs e) {
EventHandler handler = FileTypeChanged;
if (handler != null) {
handler(this, e);
}
}
/// <summary>
/// Raises the <see cref="CommonFileDialog.DialogOpening"/> event when the dialog is opened.
/// </summary>
/// <param name="e">The event data.</param>
protected virtual void OnOpening(EventArgs e) {
EventHandler handler = DialogOpening;
if (handler != null) {
handler(this, e);
}
}
#endregion
#region NativeDialogEventSink Nested Class
private class NativeDialogEventSink : IFileDialogEvents, IFileDialogControlEvents {
private CommonFileDialog parent;
private bool firstFolderChanged = true;
public NativeDialogEventSink(CommonFileDialog commonDialog) {
this.parent = commonDialog;
}
public uint Cookie { get; set; }
public HResult OnFileOk(IFileDialog pfd) {
CancelEventArgs args = new CancelEventArgs();
parent.OnFileOk(args);
if (!args.Cancel) {
// Make sure all custom properties are sync'ed
if (parent.Controls != null) {
foreach (CommonFileDialogControl control in parent.Controls) {
CommonFileDialogTextBox textBox;
CommonFileDialogGroupBox groupBox;
;
if ((textBox = control as CommonFileDialogTextBox) != null) {
textBox.SyncValue();
textBox.Closed = true;
}
// Also check subcontrols
else if ((groupBox = control as CommonFileDialogGroupBox) != null) {
foreach (CommonFileDialogControl subcontrol in groupBox.Items) {
CommonFileDialogTextBox textbox = subcontrol as CommonFileDialogTextBox;
if (textbox != null) {
textbox.SyncValue();
textbox.Closed = true;
}
}
}
}
}
}
return (args.Cancel ? HResult.False : HResult.Ok);
}
public HResult OnFolderChanging(IFileDialog pfd, IShellItem psiFolder) {
CommonFileDialogFolderChangeEventArgs args = new CommonFileDialogFolderChangeEventArgs(
CommonFileDialog.GetFileNameFromShellItem(psiFolder));
if (!firstFolderChanged) { parent.OnFolderChanging(args); }
return (args.Cancel ? HResult.False : HResult.Ok);
}
public void OnFolderChange(IFileDialog pfd) {
if (firstFolderChanged) {
firstFolderChanged = false;
parent.OnOpening(EventArgs.Empty);
} else {
parent.OnFolderChanged(EventArgs.Empty);
}
}
public void OnSelectionChange(IFileDialog pfd) {
parent.OnSelectionChanged(EventArgs.Empty);
}
public void OnShareViolation(
IFileDialog pfd,
IShellItem psi,
out ShellNativeMethods.FileDialogEventShareViolationResponse pResponse) {
// Do nothing: we will ignore share violations,
// and don't register
// for them, so this method should never be called.
pResponse = ShellNativeMethods.FileDialogEventShareViolationResponse.Accept;
}
public void OnTypeChange(IFileDialog pfd) {
parent.OnFileTypeChanged(EventArgs.Empty);
}
public void OnOverwrite(IFileDialog pfd, IShellItem psi, out ShellNativeMethods.FileDialogEventOverwriteResponse pResponse) {
// Don't accept or reject the dialog, keep default settings
pResponse = ShellNativeMethods.FileDialogEventOverwriteResponse.Default;
}
public void OnItemSelected(IFileDialogCustomize pfdc, int dwIDCtl, int dwIDItem) {
// Find control
DialogControl control = this.parent.controls.GetControlbyId(dwIDCtl);
ICommonFileDialogIndexedControls controlInterface;
CommonFileDialogMenu menu;
// Process ComboBox and/or RadioButtonList
if ((controlInterface = control as ICommonFileDialogIndexedControls) != null) {
// Update selected item and raise SelectedIndexChanged event
controlInterface.SelectedIndex = dwIDItem;
controlInterface.RaiseSelectedIndexChangedEvent();
}
// Process Menu
else if ((menu = control as CommonFileDialogMenu) != null) {
// Find the menu item that was clicked and invoke it's click event
foreach (CommonFileDialogMenuItem item in menu.Items) {
if (item.Id == dwIDItem) {
item.RaiseClickEvent();
break;
}
}
}
}
public void OnButtonClicked(IFileDialogCustomize pfdc, int dwIDCtl) {
// Find control
DialogControl control = this.parent.controls.GetControlbyId(dwIDCtl);
CommonFileDialogButton button = control as CommonFileDialogButton;
// Call corresponding event
if (button != null) {
button.RaiseClickEvent();
}
}
public void OnCheckButtonToggled(IFileDialogCustomize pfdc, int dwIDCtl, bool bChecked) {
// Find control
DialogControl control = this.parent.controls.GetControlbyId(dwIDCtl);
CommonFileDialogCheckBox box = control as CommonFileDialogCheckBox;
// Update control and call corresponding event
if (box != null) {
box.IsChecked = bChecked;
box.RaiseCheckedChangedEvent();
}
}
public void OnControlActivating(IFileDialogCustomize pfdc, int dwIDCtl) {
}
}
#endregion
#region IDisposable Members
/// <summary>
/// Releases the unmanaged resources used by the CommonFileDialog class and optionally
/// releases the managed resources.
/// </summary>
/// <param name="disposing"><b>true</b> to release both managed and unmanaged resources;
/// <b>false</b> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing) {
if (disposing) {
CleanUpNativeFileDialog();
}
}
/// <summary>
/// Releases the resources used by the current instance of the CommonFileDialog class.
/// </summary>
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
/// <summary>
/// Indicates whether this feature is supported on the current platform.
/// </summary>
public static bool IsPlatformSupported {
get {
// We need Windows Vista onwards ...
return CoreHelpers.RunningOnVista;
}
}
}
}
| |
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using CompoundFileDirectory = Lucene.Net.Store.CompoundFileDirectory;
using Directory = Lucene.Net.Store.Directory;
namespace Lucene.Net.Codecs.Lucene3x
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IndexFormatTooNewException = Lucene.Net.Index.IndexFormatTooNewException;
using IndexFormatTooOldException = Lucene.Net.Index.IndexFormatTooOldException;
using IndexInput = Lucene.Net.Store.IndexInput;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using SegmentCommitInfo = Lucene.Net.Index.SegmentCommitInfo;
using SegmentInfo = Lucene.Net.Index.SegmentInfo;
using SegmentInfos = Lucene.Net.Index.SegmentInfos;
/// <summary>
/// Lucene 3x implementation of <see cref="SegmentInfoReader"/>.
/// <para/>
/// @lucene.experimental
/// </summary>
[Obsolete("Only for reading existing 3.x indexes")]
public class Lucene3xSegmentInfoReader : SegmentInfoReader
{
public static void ReadLegacyInfos(SegmentInfos infos, Directory directory, IndexInput input, int format)
{
infos.Version = input.ReadInt64(); // read version
infos.Counter = input.ReadInt32(); // read counter
Lucene3xSegmentInfoReader reader = new Lucene3xSegmentInfoReader();
for (int i = input.ReadInt32(); i > 0; i--) // read segmentInfos
{
SegmentCommitInfo siPerCommit = reader.ReadLegacySegmentInfo(directory, format, input);
SegmentInfo si = siPerCommit.Info;
if (si.Version == null)
{
// Could be a 3.0 - try to open the doc stores - if it fails, it's a
// 2.x segment, and an IndexFormatTooOldException will be thrown,
// which is what we want.
Directory dir = directory;
if (Lucene3xSegmentInfoFormat.GetDocStoreOffset(si) != -1)
{
if (Lucene3xSegmentInfoFormat.GetDocStoreIsCompoundFile(si))
{
dir = new CompoundFileDirectory(dir, IndexFileNames.SegmentFileName(Lucene3xSegmentInfoFormat.GetDocStoreSegment(si), "", Lucene3xCodec.COMPOUND_FILE_STORE_EXTENSION), IOContext.READ_ONCE, false);
}
}
else if (si.UseCompoundFile)
{
dir = new CompoundFileDirectory(dir, IndexFileNames.SegmentFileName(si.Name, "", IndexFileNames.COMPOUND_FILE_EXTENSION), IOContext.READ_ONCE, false);
}
try
{
Lucene3xStoredFieldsReader.CheckCodeVersion(dir, Lucene3xSegmentInfoFormat.GetDocStoreSegment(si));
}
finally
{
// If we opened the directory, close it
if (dir != directory)
{
dir.Dispose();
}
}
// Above call succeeded, so it's a 3.0 segment. Upgrade it so the next
// time the segment is read, its version won't be null and we won't
// need to open FieldsReader every time for each such segment.
si.Version = "3.0";
}
else if (si.Version.Equals("2.x", StringComparison.Ordinal))
{
// If it's a 3x index touched by 3.1+ code, then segments record their
// version, whether they are 2.x ones or not. We detect that and throw
// appropriate exception.
throw new IndexFormatTooOldException("segment " + si.Name + " in resource " + input, si.Version);
}
infos.Add(siPerCommit);
}
infos.UserData = input.ReadStringStringMap();
}
public override SegmentInfo Read(Directory directory, string segmentName, IOContext context)
{
// NOTE: this is NOT how 3.x is really written...
string fileName = IndexFileNames.SegmentFileName(segmentName, "", Lucene3xSegmentInfoFormat.UPGRADED_SI_EXTENSION);
bool success = false;
IndexInput input = directory.OpenInput(fileName, context);
try
{
SegmentInfo si = ReadUpgradedSegmentInfo(segmentName, directory, input);
success = true;
return si;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(input);
}
else
{
input.Dispose();
}
}
}
private static void AddIfExists(Directory dir, ISet<string> files, string fileName)
{
if (dir.FileExists(fileName))
{
files.Add(fileName);
}
}
/// <summary>
/// Reads from legacy 3.x segments_N. </summary>
private SegmentCommitInfo ReadLegacySegmentInfo(Directory dir, int format, IndexInput input)
{
// check that it is a format we can understand
if (format > Lucene3xSegmentInfoFormat.FORMAT_DIAGNOSTICS)
{
throw new IndexFormatTooOldException(input, format, Lucene3xSegmentInfoFormat.FORMAT_DIAGNOSTICS, Lucene3xSegmentInfoFormat.FORMAT_3_1);
}
if (format < Lucene3xSegmentInfoFormat.FORMAT_3_1)
{
throw new IndexFormatTooNewException(input, format, Lucene3xSegmentInfoFormat.FORMAT_DIAGNOSTICS, Lucene3xSegmentInfoFormat.FORMAT_3_1);
}
string version;
if (format <= Lucene3xSegmentInfoFormat.FORMAT_3_1)
{
version = input.ReadString();
}
else
{
version = null;
}
string name = input.ReadString();
int docCount = input.ReadInt32();
long delGen = input.ReadInt64();
int docStoreOffset = input.ReadInt32();
IDictionary<string, string> attributes = new Dictionary<string, string>();
// parse the docstore stuff and shove it into attributes
string docStoreSegment;
bool docStoreIsCompoundFile;
if (docStoreOffset != -1)
{
docStoreSegment = input.ReadString();
docStoreIsCompoundFile = input.ReadByte() == SegmentInfo.YES;
attributes[Lucene3xSegmentInfoFormat.DS_OFFSET_KEY] = Convert.ToString(docStoreOffset, CultureInfo.InvariantCulture);
attributes[Lucene3xSegmentInfoFormat.DS_NAME_KEY] = docStoreSegment;
attributes[Lucene3xSegmentInfoFormat.DS_COMPOUND_KEY] = Convert.ToString(docStoreIsCompoundFile, CultureInfo.InvariantCulture);
}
else
{
docStoreSegment = name;
docStoreIsCompoundFile = false;
}
// pre-4.0 indexes write a byte if there is a single norms file
byte b = input.ReadByte();
//System.out.println("version=" + version + " name=" + name + " docCount=" + docCount + " delGen=" + delGen + " dso=" + docStoreOffset + " dss=" + docStoreSegment + " dssCFs=" + docStoreIsCompoundFile + " b=" + b + " format=" + format);
Debug.Assert(1 == b, "expected 1 but was: " + b + " format: " + format);
int numNormGen = input.ReadInt32();
IDictionary<int, long> normGen;
if (numNormGen == SegmentInfo.NO)
{
normGen = null;
}
else
{
normGen = new Dictionary<int, long>();
for (int j = 0; j < numNormGen; j++)
{
normGen[j] = input.ReadInt64();
}
}
bool isCompoundFile = input.ReadByte() == SegmentInfo.YES;
int delCount = input.ReadInt32();
Debug.Assert(delCount <= docCount);
bool hasProx = input.ReadByte() == 1;
IDictionary<string, string> diagnostics = input.ReadStringStringMap();
if (format <= Lucene3xSegmentInfoFormat.FORMAT_HAS_VECTORS)
{
// NOTE: unused
int hasVectors = input.ReadByte();
}
// Replicate logic from 3.x's SegmentInfo.files():
ISet<string> files = new HashSet<string>();
if (isCompoundFile)
{
files.Add(IndexFileNames.SegmentFileName(name, "", IndexFileNames.COMPOUND_FILE_EXTENSION));
}
else
{
AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xFieldInfosReader.FIELD_INFOS_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xPostingsFormat.FREQ_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xPostingsFormat.PROX_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xPostingsFormat.TERMS_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xPostingsFormat.TERMS_INDEX_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xNormsProducer.NORMS_EXTENSION));
}
if (docStoreOffset != -1)
{
if (docStoreIsCompoundFile)
{
files.Add(IndexFileNames.SegmentFileName(docStoreSegment, "", Lucene3xCodec.COMPOUND_FILE_STORE_EXTENSION));
}
else
{
files.Add(IndexFileNames.SegmentFileName(docStoreSegment, "", Lucene3xStoredFieldsReader.FIELDS_INDEX_EXTENSION));
files.Add(IndexFileNames.SegmentFileName(docStoreSegment, "", Lucene3xStoredFieldsReader.FIELDS_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(docStoreSegment, "", Lucene3xTermVectorsReader.VECTORS_INDEX_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(docStoreSegment, "", Lucene3xTermVectorsReader.VECTORS_FIELDS_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(docStoreSegment, "", Lucene3xTermVectorsReader.VECTORS_DOCUMENTS_EXTENSION));
}
}
else if (!isCompoundFile)
{
files.Add(IndexFileNames.SegmentFileName(name, "", Lucene3xStoredFieldsReader.FIELDS_INDEX_EXTENSION));
files.Add(IndexFileNames.SegmentFileName(name, "", Lucene3xStoredFieldsReader.FIELDS_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xTermVectorsReader.VECTORS_INDEX_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xTermVectorsReader.VECTORS_FIELDS_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xTermVectorsReader.VECTORS_DOCUMENTS_EXTENSION));
}
// parse the normgen stuff and shove it into attributes
if (normGen != null)
{
attributes[Lucene3xSegmentInfoFormat.NORMGEN_KEY] = Convert.ToString(numNormGen, CultureInfo.InvariantCulture);
foreach (KeyValuePair<int, long> ent in normGen)
{
long gen = ent.Value;
if (gen >= SegmentInfo.YES)
{
// Definitely a separate norm file, with generation:
files.Add(IndexFileNames.FileNameFromGeneration(name, "s" + ent.Key, gen));
attributes[Lucene3xSegmentInfoFormat.NORMGEN_PREFIX + ent.Key] = Convert.ToString(gen, CultureInfo.InvariantCulture);
}
else if (gen == SegmentInfo.NO)
{
// No separate norm
}
else
{
// We should have already hit indexformat too old exception
Debug.Assert(false);
}
}
}
SegmentInfo info = new SegmentInfo(dir, version, name, docCount, isCompoundFile, null, diagnostics, Collections.UnmodifiableMap(attributes));
info.SetFiles(files);
SegmentCommitInfo infoPerCommit = new SegmentCommitInfo(info, delCount, delGen, -1);
return infoPerCommit;
}
private SegmentInfo ReadUpgradedSegmentInfo(string name, Directory dir, IndexInput input)
{
CodecUtil.CheckHeader(input, Lucene3xSegmentInfoFormat.UPGRADED_SI_CODEC_NAME, Lucene3xSegmentInfoFormat.UPGRADED_SI_VERSION_START, Lucene3xSegmentInfoFormat.UPGRADED_SI_VERSION_CURRENT);
string version = input.ReadString();
int docCount = input.ReadInt32();
IDictionary<string, string> attributes = input.ReadStringStringMap();
bool isCompoundFile = input.ReadByte() == SegmentInfo.YES;
IDictionary<string, string> diagnostics = input.ReadStringStringMap();
ISet<string> files = input.ReadStringSet();
SegmentInfo info = new SegmentInfo(dir, version, name, docCount, isCompoundFile, null, diagnostics, Collections.UnmodifiableMap(attributes));
info.SetFiles(files);
return info;
}
}
}
| |
/*
* 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 OpenMetaverse;
using System;
using System.Collections.Generic;
namespace OpenSim.Region.ScriptEngine.Shared.Api.Plugins
{
public class Timer
{
public AsyncCommandManager m_CmdManager;
private object TimerListLock = new object();
private Dictionary<string, TimerInfo> Timers = new Dictionary<string, TimerInfo>();
public Timer(AsyncCommandManager CmdManager)
{
m_CmdManager = CmdManager;
}
public int TimersCount
{
get
{
lock (TimerListLock)
return Timers.Count;
}
}
public void CheckTimerEvents()
{
// Nothing to do here?
if (Timers.Count == 0)
return;
lock (TimerListLock)
{
// Go through all timers
Dictionary<string, TimerInfo>.ValueCollection tvals = Timers.Values;
foreach (TimerInfo ts in tvals)
{
// Time has passed?
if (ts.next < DateTime.Now.Ticks)
{
//m_log.Debug("Time has passed: Now: " + DateTime.Now.Ticks + ", Passed: " + ts.next);
// Add it to queue
m_CmdManager.m_ScriptEngine.PostScriptEvent(ts.itemID,
new EventParams("timer", new Object[0],
new DetectParams[0]));
// set next interval
//ts.next = DateTime.Now.ToUniversalTime().AddSeconds(ts.interval);
ts.next = DateTime.Now.Ticks + ts.interval;
}
}
}
}
public void CreateFromData(uint localID, UUID itemID, UUID objectID,
Object[] data)
{
int idx = 0;
while (idx < data.Length)
{
TimerInfo ts = new TimerInfo();
ts.localID = localID;
ts.itemID = itemID;
ts.interval = (long)data[idx];
ts.next = DateTime.Now.Ticks + (long)data[idx + 1];
idx += 2;
lock (TimerListLock)
{
Timers.Add(MakeTimerKey(localID, itemID), ts);
}
}
}
public Object[] GetSerializationData(UUID itemID)
{
List<Object> data = new List<Object>();
lock (TimerListLock)
{
Dictionary<string, TimerInfo>.ValueCollection tvals = Timers.Values;
foreach (TimerInfo ts in tvals)
{
if (ts.itemID == itemID)
{
data.Add(ts.interval);
data.Add(ts.next - DateTime.Now.Ticks);
}
}
}
return data.ToArray();
}
public List<TimerInfo> GetTimersInfo()
{
List<TimerInfo> retList = new List<TimerInfo>();
lock (TimerListLock)
{
foreach (TimerInfo i in Timers.Values)
retList.Add(i.Clone());
}
return retList;
}
public void SetTimerEvent(uint m_localID, UUID m_itemID, double sec)
{
if (sec == 0) // Disabling timer
{
UnSetTimerEvents(m_localID, m_itemID);
return;
}
// Add to timer
TimerInfo ts = new TimerInfo();
ts.localID = m_localID;
ts.itemID = m_itemID;
ts.interval = Convert.ToInt64(sec * 10000000); // How many 100 nanoseconds (ticks) should we wait
// 2193386136332921 ticks
// 219338613 seconds
//ts.next = DateTime.Now.ToUniversalTime().AddSeconds(ts.interval);
ts.next = DateTime.Now.Ticks + ts.interval;
string key = MakeTimerKey(m_localID, m_itemID);
lock (TimerListLock)
{
// Adds if timer doesn't exist, otherwise replaces with new timer
Timers[key] = ts;
}
}
public void UnSetTimerEvents(uint m_localID, UUID m_itemID)
{
// Remove from timer
string key = MakeTimerKey(m_localID, m_itemID);
lock (TimerListLock)
{
if (Timers.ContainsKey(key))
{
Timers.Remove(key);
}
}
}
//
// TIMER
//
static private string MakeTimerKey(uint localID, UUID itemID)
{
return localID.ToString() + itemID.ToString();
}
public class TimerInfo
{
//public double interval;
public long interval;
public UUID itemID;
public uint localID;
//public DateTime next;
public long next;
public TimerInfo Clone()
{
return (TimerInfo)this.MemberwiseClone();
}
}
}
}
| |
/*
* 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.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Text;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Client.VWoHTTP.ClientStack
{
class VWHClientView : IClientAPI
{
private Scene m_scene;
public bool ProcessInMsg(OSHttpRequest req, OSHttpResponse resp)
{
// 0 1 2 3
// http://simulator.com:9000/vwohttp/sessionid/methodname/param
string[] urlparts = req.UrlParts;
UUID sessionID;
// Check for session
if (!UUID.TryParse(urlparts[1], out sessionID))
return false;
// Check we match session
if (sessionID != SessionId)
return false;
string method = urlparts[2];
string param = String.Empty;
if (urlparts.Length > 3)
param = urlparts[3];
bool found;
switch (method.ToLower())
{
case "textures":
found = ProcessTextureRequest(param, resp);
break;
default:
found = false;
break;
}
return found;
}
private bool ProcessTextureRequest(string param, OSHttpResponse resp)
{
UUID assetID;
if (!UUID.TryParse(param, out assetID))
return false;
AssetBase asset = m_scene.AssetService.Get(assetID.ToString());
if (asset == null)
return false;
ManagedImage tmp;
Image imgData;
byte[] jpegdata;
OpenJPEG.DecodeToImage(asset.Data, out tmp, out imgData);
using (MemoryStream ms = new MemoryStream())
{
imgData.Save(ms, ImageFormat.Jpeg);
jpegdata = ms.GetBuffer();
}
resp.ContentType = "image/jpeg";
resp.ContentLength = jpegdata.Length;
resp.StatusCode = 200;
resp.Body.Write(jpegdata, 0, jpegdata.Length);
return true;
}
public VWHClientView(UUID sessionID, UUID agentID, string agentName, Scene scene)
{
m_scene = scene;
}
#region Implementation of IClientAPI
public Vector3 StartPos
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
public UUID AgentId
{
get { throw new System.NotImplementedException(); }
}
public UUID SessionId
{
get { throw new System.NotImplementedException(); }
}
public UUID SecureSessionId
{
get { throw new System.NotImplementedException(); }
}
public UUID ActiveGroupId
{
get { throw new System.NotImplementedException(); }
}
public string ActiveGroupName
{
get { throw new System.NotImplementedException(); }
}
public ulong ActiveGroupPowers
{
get { throw new System.NotImplementedException(); }
}
public ulong GetGroupPowers(UUID groupID)
{
throw new System.NotImplementedException();
}
public bool IsGroupMember(UUID GroupID)
{
throw new System.NotImplementedException();
}
public string FirstName
{
get { throw new System.NotImplementedException(); }
}
public string LastName
{
get { throw new System.NotImplementedException(); }
}
public IScene Scene
{
get { throw new System.NotImplementedException(); }
}
public int NextAnimationSequenceNumber
{
get { throw new System.NotImplementedException(); }
}
public string Name
{
get { throw new System.NotImplementedException(); }
}
public bool IsActive
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
public bool SendLogoutPacketWhenClosing
{
set { throw new System.NotImplementedException(); }
}
public uint CircuitCode
{
get { throw new System.NotImplementedException(); }
}
public IPEndPoint RemoteEndPoint
{
get { throw new System.NotImplementedException(); }
}
public event GenericMessage OnGenericMessage = delegate { };
public event ImprovedInstantMessage OnInstantMessage = delegate { };
public event ChatMessage OnChatFromClient = delegate { };
public event TextureRequest OnRequestTexture = delegate { };
public event RezObject OnRezObject = delegate { };
public event ModifyTerrain OnModifyTerrain = delegate { };
public event BakeTerrain OnBakeTerrain = delegate { };
public event EstateChangeInfo OnEstateChangeInfo = delegate { };
public event SetAppearance OnSetAppearance = delegate { };
public event AvatarNowWearing OnAvatarNowWearing = delegate { };
public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv = delegate { return new UUID(); };
public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv = delegate { };
public event UUIDNameRequest OnDetachAttachmentIntoInv = delegate { };
public event ObjectAttach OnObjectAttach = delegate { };
public event ObjectDeselect OnObjectDetach = delegate { };
public event ObjectDrop OnObjectDrop = delegate { };
public event StartAnim OnStartAnim = delegate { };
public event StopAnim OnStopAnim = delegate { };
public event LinkObjects OnLinkObjects = delegate { };
public event DelinkObjects OnDelinkObjects = delegate { };
public event RequestMapBlocks OnRequestMapBlocks = delegate { };
public event RequestMapName OnMapNameRequest = delegate { };
public event TeleportLocationRequest OnTeleportLocationRequest = delegate { };
public event DisconnectUser OnDisconnectUser = delegate { };
public event RequestAvatarProperties OnRequestAvatarProperties = delegate { };
public event SetAlwaysRun OnSetAlwaysRun = delegate { };
public event TeleportLandmarkRequest OnTeleportLandmarkRequest = delegate { };
public event DeRezObject OnDeRezObject = delegate { };
public event Action<IClientAPI> OnRegionHandShakeReply = delegate { };
public event GenericCall2 OnRequestWearables = delegate { };
public event GenericCall2 OnCompleteMovementToRegion = delegate { };
public event UpdateAgent OnAgentUpdate = delegate { };
public event AgentRequestSit OnAgentRequestSit = delegate { };
public event AgentSit OnAgentSit = delegate { };
public event AvatarPickerRequest OnAvatarPickerRequest = delegate { };
public event Action<IClientAPI> OnRequestAvatarsData = delegate { };
public event AddNewPrim OnAddPrim = delegate { };
public event FetchInventory OnAgentDataUpdateRequest = delegate { };
public event TeleportLocationRequest OnSetStartLocationRequest = delegate { };
public event RequestGodlikePowers OnRequestGodlikePowers = delegate { };
public event GodKickUser OnGodKickUser = delegate { };
public event ObjectDuplicate OnObjectDuplicate = delegate { };
public event ObjectDuplicateOnRay OnObjectDuplicateOnRay = delegate { };
public event GrabObject OnGrabObject = delegate { };
public event DeGrabObject OnDeGrabObject = delegate { };
public event MoveObject OnGrabUpdate = delegate { };
public event SpinStart OnSpinStart = delegate { };
public event SpinObject OnSpinUpdate = delegate { };
public event SpinStop OnSpinStop = delegate { };
public event UpdateShape OnUpdatePrimShape = delegate { };
public event ObjectExtraParams OnUpdateExtraParams = delegate { };
public event ObjectRequest OnObjectRequest = delegate { };
public event ObjectSelect OnObjectSelect = delegate { };
public event ObjectDeselect OnObjectDeselect = delegate { };
public event GenericCall7 OnObjectDescription = delegate { };
public event GenericCall7 OnObjectName = delegate { };
public event GenericCall7 OnObjectClickAction = delegate { };
public event GenericCall7 OnObjectMaterial = delegate { };
public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily = delegate { };
public event UpdatePrimFlags OnUpdatePrimFlags = delegate { };
public event UpdatePrimTexture OnUpdatePrimTexture = delegate { };
public event UpdateVector OnUpdatePrimGroupPosition = delegate { };
public event UpdateVector OnUpdatePrimSinglePosition = delegate { };
public event UpdatePrimRotation OnUpdatePrimGroupRotation = delegate { };
public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation = delegate { };
public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition = delegate { };
public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation = delegate { };
public event UpdateVector OnUpdatePrimScale = delegate { };
public event UpdateVector OnUpdatePrimGroupScale = delegate { };
public event StatusChange OnChildAgentStatus = delegate { };
public event GenericCall2 OnStopMovement = delegate { };
public event Action<UUID> OnRemoveAvatar = delegate { };
public event ObjectPermissions OnObjectPermissions = delegate { };
public event CreateNewInventoryItem OnCreateNewInventoryItem = delegate { };
public event CreateInventoryFolder OnCreateNewInventoryFolder = delegate { };
public event UpdateInventoryFolder OnUpdateInventoryFolder = delegate { };
public event MoveInventoryFolder OnMoveInventoryFolder = delegate { };
public event FetchInventoryDescendents OnFetchInventoryDescendents = delegate { };
public event PurgeInventoryDescendents OnPurgeInventoryDescendents = delegate { };
public event FetchInventory OnFetchInventory = delegate { };
public event RequestTaskInventory OnRequestTaskInventory = delegate { };
public event UpdateInventoryItem OnUpdateInventoryItem = delegate { };
public event CopyInventoryItem OnCopyInventoryItem = delegate { };
public event MoveInventoryItem OnMoveInventoryItem = delegate { };
public event RemoveInventoryFolder OnRemoveInventoryFolder = delegate { };
public event RemoveInventoryItem OnRemoveInventoryItem = delegate { };
public event UDPAssetUploadRequest OnAssetUploadRequest = delegate { };
public event XferReceive OnXferReceive = delegate { };
public event RequestXfer OnRequestXfer = delegate { };
public event ConfirmXfer OnConfirmXfer = delegate { };
public event AbortXfer OnAbortXfer = delegate { };
public event RezScript OnRezScript = delegate { };
public event UpdateTaskInventory OnUpdateTaskInventory = delegate { };
public event MoveTaskInventory OnMoveTaskItem = delegate { };
public event RemoveTaskInventory OnRemoveTaskItem = delegate { };
public event RequestAsset OnRequestAsset = delegate { };
public event UUIDNameRequest OnNameFromUUIDRequest = delegate { };
public event ParcelAccessListRequest OnParcelAccessListRequest = delegate { };
public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest = delegate { };
public event ParcelPropertiesRequest OnParcelPropertiesRequest = delegate { };
public event ParcelDivideRequest OnParcelDivideRequest = delegate { };
public event ParcelJoinRequest OnParcelJoinRequest = delegate { };
public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest = delegate { };
public event ParcelSelectObjects OnParcelSelectObjects = delegate { };
public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest = delegate { };
public event ParcelAbandonRequest OnParcelAbandonRequest = delegate { };
public event ParcelGodForceOwner OnParcelGodForceOwner = delegate { };
public event ParcelReclaim OnParcelReclaim = delegate { };
public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest = delegate { };
public event ParcelDeedToGroup OnParcelDeedToGroup = delegate { };
public event RegionInfoRequest OnRegionInfoRequest = delegate { };
public event EstateCovenantRequest OnEstateCovenantRequest = delegate { };
public event FriendActionDelegate OnApproveFriendRequest = delegate { };
public event FriendActionDelegate OnDenyFriendRequest = delegate { };
public event FriendshipTermination OnTerminateFriendship = delegate { };
public event GrantUserFriendRights OnGrantUserRights = delegate { };
public event MoneyTransferRequest OnMoneyTransferRequest = delegate { };
public event EconomyDataRequest OnEconomyDataRequest = delegate { };
public event MoneyBalanceRequest OnMoneyBalanceRequest = delegate { };
public event UpdateAvatarProperties OnUpdateAvatarProperties = delegate { };
public event ParcelBuy OnParcelBuy = delegate { };
public event RequestPayPrice OnRequestPayPrice = delegate { };
public event ObjectSaleInfo OnObjectSaleInfo = delegate { };
public event ObjectBuy OnObjectBuy = delegate { };
public event BuyObjectInventory OnBuyObjectInventory = delegate { };
public event RequestTerrain OnRequestTerrain = delegate { };
public event RequestTerrain OnUploadTerrain = delegate { };
public event ObjectIncludeInSearch OnObjectIncludeInSearch = delegate { };
public event UUIDNameRequest OnTeleportHomeRequest = delegate { };
public event ScriptAnswer OnScriptAnswer = delegate { };
public event AgentSit OnUndo = delegate { };
public event AgentSit OnRedo = delegate { };
public event LandUndo OnLandUndo = delegate { };
public event ForceReleaseControls OnForceReleaseControls = delegate { };
public event GodLandStatRequest OnLandStatRequest = delegate { };
public event DetailedEstateDataRequest OnDetailedEstateDataRequest = delegate { };
public event SetEstateFlagsRequest OnSetEstateFlagsRequest = delegate { };
public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture = delegate { };
public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture = delegate { };
public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights = delegate { };
public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest = delegate { };
public event SetRegionTerrainSettings OnSetRegionTerrainSettings = delegate { };
public event EstateRestartSimRequest OnEstateRestartSimRequest = delegate { };
public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest = delegate { };
public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest = delegate { };
public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest = delegate { };
public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest = delegate { };
public event EstateDebugRegionRequest OnEstateDebugRegionRequest = delegate { };
public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest = delegate { };
public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest = delegate { };
public event UUIDNameRequest OnUUIDGroupNameRequest = delegate { };
public event RegionHandleRequest OnRegionHandleRequest = delegate { };
public event ParcelInfoRequest OnParcelInfoRequest = delegate { };
public event RequestObjectPropertiesFamily OnObjectGroupRequest = delegate { };
public event ScriptReset OnScriptReset = delegate { };
public event GetScriptRunning OnGetScriptRunning = delegate { };
public event SetScriptRunning OnSetScriptRunning = delegate { };
public event UpdateVector OnAutoPilotGo = delegate { };
public event TerrainUnacked OnUnackedTerrain = delegate { };
public event ActivateGesture OnActivateGesture = delegate { };
public event DeactivateGesture OnDeactivateGesture = delegate { };
public event ObjectOwner OnObjectOwner = delegate { };
public event DirPlacesQuery OnDirPlacesQuery = delegate { };
public event DirFindQuery OnDirFindQuery = delegate { };
public event DirLandQuery OnDirLandQuery = delegate { };
public event DirPopularQuery OnDirPopularQuery = delegate { };
public event DirClassifiedQuery OnDirClassifiedQuery = delegate { };
public event EventInfoRequest OnEventInfoRequest = delegate { };
public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime = delegate { };
public event MapItemRequest OnMapItemRequest = delegate { };
public event OfferCallingCard OnOfferCallingCard = delegate { };
public event AcceptCallingCard OnAcceptCallingCard = delegate { };
public event DeclineCallingCard OnDeclineCallingCard = delegate { };
public event SoundTrigger OnSoundTrigger = delegate { };
public event StartLure OnStartLure = delegate { };
public event TeleportLureRequest OnTeleportLureRequest = delegate { };
public event NetworkStats OnNetworkStatsUpdate = delegate { };
public event ClassifiedInfoRequest OnClassifiedInfoRequest = delegate { };
public event ClassifiedInfoUpdate OnClassifiedInfoUpdate = delegate { };
public event ClassifiedDelete OnClassifiedDelete = delegate { };
public event ClassifiedDelete OnClassifiedGodDelete = delegate { };
public event EventNotificationAddRequest OnEventNotificationAddRequest = delegate { };
public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest = delegate { };
public event EventGodDelete OnEventGodDelete = delegate { };
public event ParcelDwellRequest OnParcelDwellRequest = delegate { };
public event UserInfoRequest OnUserInfoRequest = delegate { };
public event UpdateUserInfo OnUpdateUserInfo = delegate { };
public event RetrieveInstantMessages OnRetrieveInstantMessages = delegate { };
public event PickDelete OnPickDelete = delegate { };
public event PickGodDelete OnPickGodDelete = delegate { };
public event PickInfoUpdate OnPickInfoUpdate = delegate { };
public event AvatarNotesUpdate OnAvatarNotesUpdate = delegate { };
public event MuteListRequest OnMuteListRequest = delegate { };
public event AvatarInterestUpdate OnAvatarInterestUpdate = delegate { };
public event PlacesQuery OnPlacesQuery = delegate { };
public event FindAgentUpdate OnFindAgent = delegate { };
public event TrackAgentUpdate OnTrackAgent = delegate { };
public event NewUserReport OnUserReport = delegate { };
public event SaveStateHandler OnSaveState = delegate { };
public event GroupAccountSummaryRequest OnGroupAccountSummaryRequest = delegate { };
public event GroupAccountDetailsRequest OnGroupAccountDetailsRequest = delegate { };
public event GroupAccountTransactionsRequest OnGroupAccountTransactionsRequest = delegate { };
public event FreezeUserUpdate OnParcelFreezeUser = delegate { };
public event EjectUserUpdate OnParcelEjectUser = delegate { };
public event ParcelBuyPass OnParcelBuyPass = delegate { };
public event ParcelGodMark OnParcelGodMark = delegate { };
public event GroupActiveProposalsRequest OnGroupActiveProposalsRequest = delegate { };
public event GroupVoteHistoryRequest OnGroupVoteHistoryRequest = delegate { };
public event SimWideDeletesDelegate OnSimWideDeletes = delegate { };
public event SendPostcard OnSendPostcard = delegate { };
public event MuteListEntryUpdate OnUpdateMuteListEntry = delegate { };
public event MuteListEntryRemove OnRemoveMuteListEntry = delegate { };
public event GodlikeMessage onGodlikeMessage = delegate { };
public event GodUpdateRegionInfoUpdate OnGodUpdateRegionInfoUpdate = delegate { };
public void SetDebugPacketLevel(int newDebug)
{
throw new System.NotImplementedException();
}
public void InPacket(object NewPack)
{
throw new System.NotImplementedException();
}
public void ProcessInPacket(Packet NewPack)
{
throw new System.NotImplementedException();
}
public void Close()
{
throw new System.NotImplementedException();
}
public void Kick(string message)
{
throw new System.NotImplementedException();
}
public void Start()
{
throw new System.NotImplementedException();
}
public void Stop()
{
throw new System.NotImplementedException();
}
public void SendWearables(AvatarWearable[] wearables, int serial)
{
throw new System.NotImplementedException();
}
public void SendAppearance(UUID agentID, byte[] visualParams, byte[] textureEntry)
{
throw new System.NotImplementedException();
}
public void SendStartPingCheck(byte seq)
{
throw new System.NotImplementedException();
}
public void SendKillObject(ulong regionHandle, uint localID)
{
throw new System.NotImplementedException();
}
public void SendAnimations(UUID[] animID, int[] seqs, UUID sourceAgentId, UUID[] objectIDs)
{
throw new System.NotImplementedException();
}
public void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args)
{
throw new System.NotImplementedException();
}
public void SendChatMessage(string message, byte type, Vector3 fromPos, string fromName, UUID fromAgentID, byte source, byte audible)
{
throw new System.NotImplementedException();
}
public void SendInstantMessage(GridInstantMessage im)
{
throw new System.NotImplementedException();
}
public void SendGenericMessage(string method, List<string> message)
{
throw new System.NotImplementedException();
}
public void SendLayerData(float[] map)
{
throw new System.NotImplementedException();
}
public void SendLayerData(int px, int py, float[] map)
{
throw new System.NotImplementedException();
}
public void SendWindData(Vector2[] windSpeeds)
{
throw new System.NotImplementedException();
}
public void SendCloudData(float[] cloudCover)
{
throw new System.NotImplementedException();
}
public void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look)
{
throw new System.NotImplementedException();
}
public void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint)
{
throw new System.NotImplementedException();
}
public AgentCircuitData RequestClientInfo()
{
throw new System.NotImplementedException();
}
public void CrossRegion(ulong newRegionHandle, Vector3 pos, Vector3 lookAt, IPEndPoint newRegionExternalEndPoint, string capsURL)
{
throw new System.NotImplementedException();
}
public void SendMapBlock(List<MapBlockData> mapBlocks, uint flag)
{
throw new System.NotImplementedException();
}
public void SendLocalTeleport(Vector3 position, Vector3 lookAt, uint flags)
{
throw new System.NotImplementedException();
}
public void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, uint flags, string capsURL)
{
throw new System.NotImplementedException();
}
public void SendTeleportFailed(string reason)
{
throw new System.NotImplementedException();
}
public void SendTeleportLocationStart()
{
throw new System.NotImplementedException();
}
public void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance)
{
throw new System.NotImplementedException();
}
public void SendPayPrice(UUID objectID, int[] payPrice)
{
throw new System.NotImplementedException();
}
public void SendAvatarData(SendAvatarData data)
{
throw new System.NotImplementedException();
}
public void SendAvatarTerseUpdate(SendAvatarTerseData data)
{
throw new System.NotImplementedException();
}
public void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations)
{
throw new System.NotImplementedException();
}
public void AttachObject(uint localID, Quaternion rotation, byte attachPoint, UUID ownerID)
{
throw new System.NotImplementedException();
}
public void SetChildAgentThrottle(byte[] throttle)
{
throw new System.NotImplementedException();
}
public void SendPrimitiveToClient(SendPrimitiveData data)
{
throw new System.NotImplementedException();
}
public void SendPrimTerseUpdate(SendPrimitiveTerseData data)
{
throw new System.NotImplementedException();
}
public void ReprioritizeUpdates(StateUpdateTypes type, UpdatePriorityHandler handler)
{
throw new System.NotImplementedException();
}
public void FlushPrimUpdates()
{
throw new System.NotImplementedException();
}
public void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List<InventoryItemBase> items, List<InventoryFolderBase> folders, int version, bool fetchFolders, bool fetchItems)
{
throw new System.NotImplementedException();
}
public void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item)
{
throw new System.NotImplementedException();
}
public void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackId)
{
throw new System.NotImplementedException();
}
public void SendRemoveInventoryItem(UUID itemID)
{
throw new System.NotImplementedException();
}
public void SendTakeControls(int controls, bool passToAgent, bool TakeControls)
{
throw new System.NotImplementedException();
}
public void SendTaskInventory(UUID taskID, short serial, byte[] fileName)
{
throw new System.NotImplementedException();
}
public void SendBulkUpdateInventory(InventoryNodeBase node)
{
throw new System.NotImplementedException();
}
public void SendXferPacket(ulong xferID, uint packet, byte[] data)
{
throw new System.NotImplementedException();
}
public 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)
{
throw new System.NotImplementedException();
}
public void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data)
{
throw new System.NotImplementedException();
}
public void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle)
{
throw new System.NotImplementedException();
}
public void SendPreLoadSound(UUID objectID, UUID ownerID, UUID soundID)
{
throw new System.NotImplementedException();
}
public void SendPlayAttachedSound(UUID soundID, UUID objectID, UUID ownerID, float gain, byte flags)
{
throw new System.NotImplementedException();
}
public void SendTriggeredSound(UUID soundID, UUID ownerID, UUID objectID, UUID parentID, ulong handle, Vector3 position, float gain)
{
throw new System.NotImplementedException();
}
public void SendAttachedSoundGainChange(UUID objectID, float gain)
{
throw new System.NotImplementedException();
}
public void SendNameReply(UUID profileId, string firstname, string lastname)
{
throw new System.NotImplementedException();
}
public void SendAlertMessage(string message)
{
throw new System.NotImplementedException();
}
public void SendAgentAlertMessage(string message, bool modal)
{
throw new System.NotImplementedException();
}
public void SendLoadURL(string objectname, UUID objectID, UUID ownerID, bool groupOwned, string message, string url)
{
throw new System.NotImplementedException();
}
public void SendDialog(string objectname, UUID objectID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels)
{
throw new System.NotImplementedException();
}
public bool AddMoney(int debit)
{
throw new System.NotImplementedException();
}
public void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong CurrentTime, uint SecondsPerSunCycle, uint SecondsPerYear, float OrbitalPosition)
{
throw new System.NotImplementedException();
}
public void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks)
{
throw new System.NotImplementedException();
}
public void SendViewerTime(int phase)
{
throw new System.NotImplementedException();
}
public UUID GetDefaultAnimation(string name)
{
throw new System.NotImplementedException();
}
public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, byte[] charterMember, string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL, UUID partnerID)
{
throw new System.NotImplementedException();
}
public void SendScriptQuestion(UUID taskID, string taskName, string ownerName, UUID itemID, int question)
{
throw new System.NotImplementedException();
}
public void SendHealth(float health)
{
throw new System.NotImplementedException();
}
public void SendEstateList(UUID invoice, int code, UUID[] Data, uint estateID)
{
throw new System.NotImplementedException();
}
public void SendBannedUserList(UUID invoice, EstateBan[] banlist, uint estateID)
{
throw new System.NotImplementedException();
}
public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args)
{
throw new System.NotImplementedException();
}
public void SendEstateCovenantInformation(UUID covenant)
{
throw new System.NotImplementedException();
}
public void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, string abuseEmail, UUID estateOwner)
{
throw new System.NotImplementedException();
}
public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, LandData landData, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags)
{
throw new System.NotImplementedException();
}
public void SendLandAccessListData(List<UUID> avatars, uint accessFlag, int localLandID)
{
throw new System.NotImplementedException();
}
public void SendForceClientSelectObjects(List<uint> objectIDs)
{
throw new System.NotImplementedException();
}
public void SendCameraConstraint(Vector4 ConstraintPlane)
{
}
public void SendLandObjectOwners(LandData land, List<UUID> groups, Dictionary<UUID, int> ownersAndCount)
{
throw new System.NotImplementedException();
}
public void SendLandParcelOverlay(byte[] data, int sequence_id)
{
throw new System.NotImplementedException();
}
public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time)
{
throw new System.NotImplementedException();
}
public void SendParcelMediaUpdate(string mediaUrl, UUID mediaTextureID, byte autoScale, string mediaType, string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop)
{
throw new System.NotImplementedException();
}
public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID)
{
throw new System.NotImplementedException();
}
public void SendConfirmXfer(ulong xferID, uint PacketID)
{
throw new System.NotImplementedException();
}
public void SendXferRequest(ulong XferID, short AssetType, UUID vFileID, byte FilePath, byte[] FileName)
{
throw new System.NotImplementedException();
}
public void SendInitiateDownload(string simFileName, string clientFileName)
{
throw new System.NotImplementedException();
}
public void SendImageFirstPart(ushort numParts, UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec)
{
throw new System.NotImplementedException();
}
public void SendImageNextPart(ushort partNumber, UUID imageUuid, byte[] imageData)
{
throw new System.NotImplementedException();
}
public void SendImageNotFound(UUID imageid)
{
throw new System.NotImplementedException();
}
public void SendShutdownConnectionNotice()
{
throw new System.NotImplementedException();
}
public void SendSimStats(SimStats stats)
{
throw new System.NotImplementedException();
}
public void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID, uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, uint NextOwnerMask, int OwnershipCost, byte SaleType, int SalePrice, uint Category, UUID LastOwnerID, string ObjectName, string Description)
{
throw new System.NotImplementedException();
}
public void SendObjectPropertiesReply(UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, UUID FromTaskUUID, UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID, UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, uint BaseMask, byte saleType, int salePrice)
{
throw new System.NotImplementedException();
}
public void SendAgentOffline(UUID[] agentIDs)
{
throw new System.NotImplementedException();
}
public void SendAgentOnline(UUID[] agentIDs)
{
throw new System.NotImplementedException();
}
public void SendSitResponse(UUID TargetID, Vector3 OffsetPos, Quaternion SitOrientation, bool autopilot, Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook)
{
throw new System.NotImplementedException();
}
public void SendAdminResponse(UUID Token, uint AdminLevel)
{
throw new System.NotImplementedException();
}
public void SendGroupMembership(GroupMembershipData[] GroupMembership)
{
throw new System.NotImplementedException();
}
public void SendGroupNameReply(UUID groupLLUID, string GroupName)
{
throw new System.NotImplementedException();
}
public void SendJoinGroupReply(UUID groupID, bool success)
{
throw new System.NotImplementedException();
}
public void SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool success)
{
throw new System.NotImplementedException();
}
public void SendLeaveGroupReply(UUID groupID, bool success)
{
throw new System.NotImplementedException();
}
public void SendCreateGroupReply(UUID groupID, bool success, string message)
{
throw new System.NotImplementedException();
}
public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, LandStatReportItem[] lsrpia)
{
throw new System.NotImplementedException();
}
public void SendScriptRunningReply(UUID objectID, UUID itemID, bool running)
{
throw new System.NotImplementedException();
}
public void SendAsset(AssetRequestToClient req)
{
throw new System.NotImplementedException();
}
public void SendTexture(AssetBase TextureAsset)
{
throw new System.NotImplementedException();
}
public byte[] GetThrottlesPacked(float multiplier)
{
throw new System.NotImplementedException();
}
public event ViewerEffectEventHandler OnViewerEffect;
public event Action<IClientAPI> OnLogout;
public event Action<IClientAPI> OnConnectionClosed;
public void SendBlueBoxMessage(UUID FromAvatarID, string FromAvatarName, string Message)
{
throw new System.NotImplementedException();
}
public void SendLogoutPacket()
{
throw new System.NotImplementedException();
}
public EndPoint GetClientEP()
{
return null;
}
public ClientInfo GetClientInfo()
{
throw new System.NotImplementedException();
}
public void SetClientInfo(ClientInfo info)
{
throw new System.NotImplementedException();
}
public void SetClientOption(string option, string value)
{
throw new System.NotImplementedException();
}
public string GetClientOption(string option)
{
throw new System.NotImplementedException();
}
public void Terminate()
{
throw new System.NotImplementedException();
}
public void SendSetFollowCamProperties(UUID objectID, SortedDictionary<int, float> parameters)
{
throw new System.NotImplementedException();
}
public void SendClearFollowCamProperties(UUID objectID)
{
throw new System.NotImplementedException();
}
public void SendRegionHandle(UUID regoinID, ulong handle)
{
throw new System.NotImplementedException();
}
public void SendParcelInfo(RegionInfo info, LandData land, UUID parcelID, uint x, uint y)
{
throw new System.NotImplementedException();
}
public void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt)
{
throw new System.NotImplementedException();
}
public void SendDirPlacesReply(UUID queryID, DirPlacesReplyData[] data)
{
throw new System.NotImplementedException();
}
public void SendDirPeopleReply(UUID queryID, DirPeopleReplyData[] data)
{
throw new System.NotImplementedException();
}
public void SendDirEventsReply(UUID queryID, DirEventsReplyData[] data)
{
throw new System.NotImplementedException();
}
public void SendDirGroupsReply(UUID queryID, DirGroupsReplyData[] data)
{
throw new System.NotImplementedException();
}
public void SendDirClassifiedReply(UUID queryID, DirClassifiedReplyData[] data)
{
throw new System.NotImplementedException();
}
public void SendDirLandReply(UUID queryID, DirLandReplyData[] data)
{
throw new System.NotImplementedException();
}
public void SendDirPopularReply(UUID queryID, DirPopularReplyData[] data)
{
throw new System.NotImplementedException();
}
public void SendEventInfoReply(EventData info)
{
throw new System.NotImplementedException();
}
public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags)
{
throw new System.NotImplementedException();
}
public void SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data)
{
throw new System.NotImplementedException();
}
public void SendOfferCallingCard(UUID srcID, UUID transactionID)
{
throw new System.NotImplementedException();
}
public void SendAcceptCallingCard(UUID transactionID)
{
throw new System.NotImplementedException();
}
public void SendDeclineCallingCard(UUID transactionID)
{
throw new System.NotImplementedException();
}
public void SendTerminateFriend(UUID exFriendID)
{
throw new System.NotImplementedException();
}
public void SendAvatarClassifiedReply(UUID targetID, UUID[] classifiedID, string[] name)
{
throw new System.NotImplementedException();
}
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)
{
throw new System.NotImplementedException();
}
public void SendAgentDropGroup(UUID groupID)
{
throw new System.NotImplementedException();
}
public void RefreshGroupMembership()
{
throw new System.NotImplementedException();
}
public void SendAvatarNotesReply(UUID targetID, string text)
{
throw new System.NotImplementedException();
}
public void SendAvatarPicksReply(UUID targetID, Dictionary<UUID, string> picks)
{
throw new System.NotImplementedException();
}
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)
{
throw new System.NotImplementedException();
}
public void SendAvatarClassifiedReply(UUID targetID, Dictionary<UUID, string> classifieds)
{
throw new System.NotImplementedException();
}
public void SendAvatarInterestUpdate(IClientAPI client, uint wantmask, string wanttext, uint skillsmask, string skillstext, string languages)
{
throw new System.NotImplementedException();
}
public void SendParcelDwellReply(int localID, UUID parcelID, float dwell)
{
throw new System.NotImplementedException();
}
public void SendUserInfoReply(bool imViaEmail, bool visible, string email)
{
throw new System.NotImplementedException();
}
public void SendUseCachedMuteList()
{
throw new System.NotImplementedException();
}
public void SendMuteListUpdate(string filename)
{
throw new System.NotImplementedException();
}
public void KillEndDone()
{
throw new System.NotImplementedException();
}
public bool AddGenericPacketHandler(string MethodName, GenericMessage handler)
{
throw new System.NotImplementedException();
}
#endregion
public void SendRebakeAvatarTextures(UUID 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 SendTextBoxRequest(string message, int chatChannel, string objectname, string ownerFirstName, string ownerLastName, UUID objectId)
{
}
}
}
| |
//
// Copyright (c) 2004-2018 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.
//
namespace NLog
{
using System;
using System.ComponentModel;
using JetBrains.Annotations;
/// <summary>
/// Logger with only generic methods (passing 'LogLevel' to methods) and core properties.
/// </summary>
public partial interface ILoggerBase
{
/// <summary>
/// Occurs when logger configuration changes.
/// </summary>
event EventHandler<EventArgs> LoggerReconfigured;
/// <summary>
/// Gets the name of the logger.
/// </summary>
string Name
{
get;
}
/// <summary>
/// Gets the factory that created this logger.
/// </summary>
LogFactory Factory
{
get;
}
/// <summary>
/// Gets a value indicating whether logging is enabled for the specified level.
/// </summary>
/// <param name="level">Log level to be checked.</param>
/// <returns>A value of <see langword="true" /> if logging is enabled for the specified level, otherwise it returns <see langword="false" />.</returns>
bool IsEnabled(LogLevel level);
#region Log() overloads
/// <summary>
/// Writes the specified diagnostic message.
/// </summary>
/// <param name="logEvent">Log event.</param>
void Log(LogEventInfo logEvent);
/// <summary>
/// Writes the specified diagnostic message.
/// </summary>
/// <param name="wrapperType">The name of the type that wraps Logger.</param>
/// <param name="logEvent">Log event.</param>
void Log(Type wrapperType, LogEventInfo logEvent);
/// <overloads>
/// Writes the diagnostic message at the specified level using the specified format provider and format parameters.
/// </overloads>
/// <summary>
/// Writes the diagnostic message at the specified level.
/// </summary>
/// <typeparam name="T">Type of the value.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="value">The value to be written.</param>
void Log<T>(LogLevel level, T value);
/// <summary>
/// Writes the diagnostic message at the specified level.
/// </summary>
/// <typeparam name="T">Type of the value.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="value">The value to be written.</param>
void Log<T>(LogLevel level, IFormatProvider formatProvider, T value);
/// <summary>
/// Writes the diagnostic message at the specified level.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param>
void Log(LogLevel level, LogMessageGenerator messageFunc);
/// <summary>
/// Writes the diagnostic message and exception at the specified level.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> to be written.</param>
/// <param name="exception">An exception to be logged.</param>
/// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks>
[Obsolete("Use Log(LogLevel level, Exception exception, [Localizable(false)] string message, params object[] args) instead. Marked obsolete before v4.3.11")]
void LogException(LogLevel level, [Localizable(false)] string message, Exception exception);
/// <summary>
/// Writes the diagnostic message and exception at the specified level.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> to be written.</param>
/// <param name="args">Arguments to format.</param>
/// <param name="exception">An exception to be logged.</param>
[MessageTemplateFormatMethod("message")]
void Log(LogLevel level, Exception exception, [Localizable(false)] string message, params object[] args);
/// <summary>
/// Writes the diagnostic message and exception at the specified level.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> to be written.</param>
/// <param name="args">Arguments to format.</param>
/// <param name="exception">An exception to be logged.</param>
[MessageTemplateFormatMethod("message")]
void Log(LogLevel level, Exception exception, IFormatProvider formatProvider, [Localizable(false)] string message, params object[] args);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified parameters and formatting them with the supplied format provider.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing format items.</param>
/// <param name="args">Arguments to format.</param>
[MessageTemplateFormatMethod("message")]
void Log(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message, params object[] args);
/// <summary>
/// Writes the diagnostic message at the specified level.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">Log message.</param>
void Log(LogLevel level, [Localizable(false)] string message);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified parameters.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing format items.</param>
/// <param name="args">Arguments to format.</param>
[MessageTemplateFormatMethod("message")]
void Log(LogLevel level, [Localizable(false)] string message, params object[] args);
/// <summary>
/// Writes the diagnostic message and exception at the specified level.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> to be written.</param>
/// <param name="exception">An exception to be logged.</param>
/// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks>
[Obsolete("Use Log(LogLevel level, Exception exception, [Localizable(false)] string message, params object[] args) instead. Marked obsolete before v4.3.11")]
void Log(LogLevel level, [Localizable(false)] string message, Exception exception);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified parameter and formatting it with the supplied format provider.
/// </summary>
/// <typeparam name="TArgument">The type of the argument.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[MessageTemplateFormatMethod("message")]
void Log<TArgument>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message, TArgument argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified parameter.
/// </summary>
/// <typeparam name="TArgument">The type of the argument.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[MessageTemplateFormatMethod("message")]
void Log<TArgument>(LogLevel level, [Localizable(false)] string message, TArgument argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified arguments formatting it with the supplied format provider.
/// </summary>
/// <typeparam name="TArgument1">The type of the first argument.</typeparam>
/// <typeparam name="TArgument2">The type of the second argument.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument1">The first argument to format.</param>
/// <param name="argument2">The second argument to format.</param>
[MessageTemplateFormatMethod("message")]
void Log<TArgument1, TArgument2>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message, TArgument1 argument1, TArgument2 argument2);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified parameters.
/// </summary>
/// <typeparam name="TArgument1">The type of the first argument.</typeparam>
/// <typeparam name="TArgument2">The type of the second argument.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument1">The first argument to format.</param>
/// <param name="argument2">The second argument to format.</param>
[MessageTemplateFormatMethod("message")]
void Log<TArgument1, TArgument2>(LogLevel level, [Localizable(false)] string message, TArgument1 argument1, TArgument2 argument2);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified arguments formatting it with the supplied format provider.
/// </summary>
/// <typeparam name="TArgument1">The type of the first argument.</typeparam>
/// <typeparam name="TArgument2">The type of the second argument.</typeparam>
/// <typeparam name="TArgument3">The type of the third argument.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument1">The first argument to format.</param>
/// <param name="argument2">The second argument to format.</param>
/// <param name="argument3">The third argument to format.</param>
[MessageTemplateFormatMethod("message")]
void Log<TArgument1, TArgument2, TArgument3>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified parameters.
/// </summary>
/// <typeparam name="TArgument1">The type of the first argument.</typeparam>
/// <typeparam name="TArgument2">The type of the second argument.</typeparam>
/// <typeparam name="TArgument3">The type of the third argument.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument1">The first argument to format.</param>
/// <param name="argument2">The second argument to format.</param>
/// <param name="argument3">The third argument to format.</param>
[MessageTemplateFormatMethod("message")]
void Log<TArgument1, TArgument2, TArgument3>(LogLevel level, [Localizable(false)] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3);
#endregion
}
}
| |
#region Header
// ---------------------------------------------------------------------------
// Sepura - Commercially Confidential.
//
// ArrayTypeDefinition.cs
// Implementation of the Class ArrayTypeDefinition
//
// Copyright (c) 2010 Sepura Plc
// All Rights reserved.
//
// Original author: robinsond
//
// $Id:$
// ---------------------------------------------------------------------------
#endregion
namespace Sepura.DataDictionary
{
using System;
using System.Text;
using System.Xml;
using System.Xml.Linq;
/// <summary>
/// Class holding a definition of an array type
/// </summary>
public class ArrayTypeDefinition : TypeDefinition
{
/// <summary>
/// Gets the number of elements in the array
/// UpperBound [0] is the left-most dimension (slowest varying) so int[a][b][c] would have
/// UpperBound [0] = a, UpperBound [1] = b, UpperBound [2] = c,
/// Arrays may also be dynamically allocated so UpperBound [] is zero-length
/// </summary>
public int[] UpperBound
{
get;
private set;
}
/// <summary>
/// Gets the name of the variable that defines the upper bound
/// May be empty if unused
/// </summary>
public string UpperBoundVariable
{
get;
private set;
}
/// <summary>
/// Gets the rank of the array - how many dimensions
/// </summary>
public int Rank
{
get { return UpperBound.Length; }
}
/// <summary>
/// Gets the reference to the type of each element that this array holds.If the initial type is a
/// typedef then this holds a reference to the aliased type
/// </summary>
public TypeDefinition ElementType
{
get;
private set;
}
/// <summary>
/// Gets the name of the type of each element that this array holds. If the initial type is a
/// typedef then this holds the name of the typedef, not the aliased type
/// </summary>
public string ElementTypeName
{
get;
private set;
}
/// <summary>
/// Initializes a new instance of the ArrayTypeDefinition class
/// </summary>
/// <param name="theNode"></param>
public ArrayTypeDefinition(XElement theNode)
: base(theNode, TypeId.ArrayType)
{
}
/// <summary>
/// Finishes construction of the object by populating properties of the object from
/// the XML node
/// </summary>
/// <param name="theNode"></param>
/// <param name="theManager"></param>
public override void FinishConstruction(XElement theNode, DictionaryManager theManager)
{
try
{
// Find out what type this holds and use this to form the name of the type
TypeDefinition theType = theManager.GetElementType(theNode.Element("Type").Value);
// Set the type name before following any typedefs
ElementTypeName = theType.Name;
// Follow aliases of typedefs so that the underlying type is stored
while (theType is TypedefDefinition)
{
theType = ((TypedefDefinition)theType).AliasedType;
}
ElementType = theType;
if (theNode.Element("UpperBound") != null && !string.IsNullOrEmpty(theNode.Element("UpperBound").Value))
{
// Read the size of the array
int thisUpperBound = 0;
if (Sepura.Utilities.Formatting.TryGetInt(theNode.Element("UpperBound").Value, out thisUpperBound))
{
// Handle nested (multi-dimensional) arrays
if (theType.GetType() == typeof(ArrayTypeDefinition))
{
ArrayTypeDefinition nestedArray = theType as ArrayTypeDefinition;
// Propagate the name of the underlying type (determined before following typedefs)
ElementTypeName = nestedArray.ElementTypeName;
ElementType = nestedArray.ElementType;
UpperBound = new int[nestedArray.UpperBound.Length + 1];
for (int i = 0; i < nestedArray.UpperBound.Length; i++)
{
UpperBound[i + 1] = nestedArray.UpperBound[i];
}
UpperBound[0] = thisUpperBound;
}
else
{
UpperBound = new int[1];
UpperBound[0] = thisUpperBound;
}
// Finally set the name for the type
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0} ", ElementTypeName);
for (int i = 0; i < UpperBound.Length; i++)
{
sb.AppendFormat("[{0}]", UpperBound[i]);
}
Name = sb.ToString();
}
else
{
UpperBoundVariable = theNode.Element("UpperBound").Value;
// Length of the array is defined at run-time
UpperBound = new int[0];
Name = string.Format("{0} []", ElementTypeName);
}
}
else
{
// Length of the array is undefined - this gets treated as a list whose length is determined at run-time
UpperBound = new int[0];
Name = string.Format("{0} []", ElementTypeName);
}
}
catch (DataDictionaryException ex)
{
throw new DataDictionaryException("Error constructing definition for Array. XML:\n{0}\nException: {1}", theNode, ex.Message);
}
catch (XmlException ex)
{
throw new DataDictionaryException("Error constructing definition for Array. XML:\n{0}\nException: {1}", theNode, ex.Message);
}
}
/// <summary>
/// Return a string describing the object
/// </summary>
/// <returns>String describing the object</returns>
public override string ToString()
{
return String.Format("Array type {0}", Name);
}
/// <summary>
/// Creates a new Value object, deriving the value by decoding the specified bytes.
/// Each derived class creates its corresponding value type
/// </summary>
/// <param name="theBytes">The collection of bytes containing the value to be
/// decoded</param>
/// <param name="parent"></param>
/// <returns>
/// The decoded value object
/// </returns>
public override Value Decode(ByteStore theBytes, Value parent)
{
return new ArrayTypeValue(this, theBytes, parent);
}
/// <summary>
/// Create a new instance of the type populated with default values.
/// </summary>
/// <param name="parent"></param>
/// <returns>
/// New instance of the type populated with default values
/// </returns>
public override Value Instantiate(Value parent)
{
return new ArrayTypeValue(this, parent);
}
}
}
| |
#region [R# naming]
// ReSharper disable ArrangeTypeModifiers
// ReSharper disable UnusedMember.Local
// ReSharper disable FieldCanBeMadeReadOnly.Local
// ReSharper disable ArrangeTypeMemberModifiers
// ReSharper disable InconsistentNaming
#endregion
using System;
using NUnit.Framework;
using FluentAssertions;
namespace NSpectator.Specs.Running
{
[TestFixture]
public class Describe_abstract_class_execution_order : When_running_specs
{
abstract class Class1 : Spec
{
public string beforeExecutionOrder = "", actExecutionOrder = "", afterExecutionOrder = "", allExecutions = "";
public void LogBefore(string classId)
{
beforeExecutionOrder += classId;
allExecutions += "b" + classId;
}
public void LogAct(string classId)
{
actExecutionOrder += classId;
allExecutions += "ac" + classId;
}
public void LogAfter(string classId)
{
afterExecutionOrder += classId;
allExecutions += "af" + classId;
}
public void LogExample(string classId)
{
allExecutions += "i" + classId;
}
void abstract1_example()
{
It["abstract1 tests nothing", "example_in_abtract_class"] = () => LogExample(classId: "1");
}
void before_each()
{
LogBefore(classId: "1");
}
void act_each()
{
LogAct(classId: "1");
}
void after_each()
{
LogAfter(classId: "1");
}
}
class Class2 : Class1
{
void concrete2_example()
{
It["concrete2 tests nothing", "example_in_concrete_class_that_inherits_abstract"] = () => LogExample(classId: "2");
}
void before_each()
{
LogBefore(classId: "2");
}
void act_each()
{
LogAct(classId: "2");
}
void after_each()
{
LogAfter(classId: "2");
}
}
abstract class Class3 : Class2
{
void abstract3_example()
{
It["abstract3 tests nothing", "example_in_abstract_class_that_directly_inherits_from_concrete_class"] = () => LogExample(classId: "3");
}
void before_each()
{
LogBefore(classId: "3");
}
void act_each()
{
LogAct(classId: "3");
}
void after_each()
{
LogAfter(classId: "3");
}
}
abstract class Class4 : Class3
{
void abstract4_example()
{
It["abstract4 tests nothing", "example_in_abstract_class_that_inherits_another_abstract_class"] = () => LogExample(classId: "4");
}
void before_each()
{
LogBefore(classId: "4");
}
void act_each()
{
LogAct(classId: "4");
}
void after_each()
{
LogAfter(classId: "4");
}
}
class Class5 : Class4
{
void concrete5_example()
{
It["concrete5 tests nothing", "example_in_concrete_class_that_inherits_an_abstract_class_with_deep_inheritance_chain"] = () => LogExample(classId: "5");
}
void before_each()
{
LogBefore(classId: "5");
}
void act_each()
{
LogAct(classId: "5");
}
void after_each()
{
LogAfter(classId: "5");
}
}
[Test(Description = "before_each() in concrete classes affects base abstracts"),
TestCase(typeof(Class2), "example_in_abtract_class", "12"),
TestCase(typeof(Class2), "example_in_concrete_class_that_inherits_abstract", "12"),
TestCase(typeof(Class5), "example_in_abstract_class_that_directly_inherits_from_concrete_class", "12345"),
TestCase(typeof(Class5), "example_in_abstract_class_that_inherits_another_abstract_class", "12345"),
TestCase(typeof(Class5), "example_in_concrete_class_that_inherits_an_abstract_class_with_deep_inheritance_chain", "12345")]
public void before_eaches_should_run_in_the_correct_order(Type withRespectToContext, string tags, string beforeExecutionLog)
{
this.tags = tags;
Run(withRespectToContext);
var specInstance = classContext.GetInstance() as Class1;
specInstance.beforeExecutionOrder.Should().Be(beforeExecutionLog);
}
[Test(Description = "act_each() in concrete classes affects base abstracts"),
TestCase(typeof(Class2), "example_in_abtract_class", "12"),
TestCase(typeof(Class2), "example_in_concrete_class_that_inherits_abstract", "12"),
TestCase(typeof(Class5), "example_in_abstract_class_that_directly_inherits_from_concrete_class", "12345"),
TestCase(typeof(Class5), "example_in_abstract_class_that_inherits_another_abstract_class", "12345"),
TestCase(typeof(Class5), "example_in_concrete_class_that_inherits_an_abstract_class_with_deep_inheritance_chain", "12345")]
public void act_eaches_should_run_in_the_correct_order(Type withRespectToContext, string tags, string actExecutionLog)
{
this.tags = tags;
Run(withRespectToContext);
var specInstance = classContext.GetInstance() as Class1;
specInstance.actExecutionOrder.Should().Be(actExecutionLog);
}
[Test(Description = "after_each() in concrete classes affects base abstracts"),
TestCase(typeof(Class2), "example_in_abtract_class", "21"),
TestCase(typeof(Class2), "example_in_concrete_class_that_inherits_abstract", "21"),
TestCase(typeof(Class5), "example_in_abstract_class_that_directly_inherits_from_concrete_class", "54321"),
TestCase(typeof(Class5), "example_in_abstract_class_that_inherits_another_abstract_class", "54321"),
TestCase(typeof(Class5), "example_in_concrete_class_that_inherits_an_abstract_class_with_deep_inheritance_chain", "54321")]
public void after_eaches_should_run_in_the_correct_order(Type withRespectToContext, string tags, string afterExecutionLog)
{
this.tags = tags;
Run(withRespectToContext);
var specInstance = classContext.GetInstance() as Class1;
specInstance.afterExecutionOrder.Should().Be(afterExecutionLog);
}
[Test,
TestCase(typeof(Class2), "example_in_abtract_class", "b1b2ac1ac2i1af2af1"),
TestCase(typeof(Class2), "example_in_concrete_class_that_inherits_abstract", "b1b2ac1ac2i2af2af1"),
TestCase(typeof(Class5), "example_in_abstract_class_that_directly_inherits_from_concrete_class", "b1b2b3b4b5ac1ac2ac3ac4ac5i3af5af4af3af2af1"),
TestCase(typeof(Class5), "example_in_abstract_class_that_inherits_another_abstract_class", "b1b2b3b4b5ac1ac2ac3ac4ac5i4af5af4af3af2af1"),
TestCase(typeof(Class5), "example_in_concrete_class_that_inherits_an_abstract_class_with_deep_inheritance_chain", "b1b2b3b4b5ac1ac2ac3ac4ac5i5af5af4af3af2af1")]
public void execution_should_run_in_the_correct_order(Type withRespectToContext, string tags, string fullExecutionLog)
{
this.tags = tags;
Run(withRespectToContext);
var specInstance = classContext.GetInstance() as Class1;
specInstance.allExecutions.Should().Be(fullExecutionLog);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Compute.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedNetworkEndpointGroupsClientTest
{
[xunit::FactAttribute]
public void GetRequestObject()
{
moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetNetworkEndpointGroupRequest request = new GetNetworkEndpointGroupRequest
{
Zone = "zone255f4ea8",
Project = "projectaa6ff846",
NetworkEndpointGroup = "network_endpoint_groupdf1fb34e",
};
NetworkEndpointGroup expectedResponse = new NetworkEndpointGroup
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Size = -1218396681,
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
CloudRun = new NetworkEndpointGroupCloudRun(),
Annotations =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
NetworkEndpointType = NetworkEndpointGroup.Types.NetworkEndpointType.InternetFqdnPort,
Region = "regionedb20d96",
Network = "networkd22ce091",
Subnetwork = "subnetworkf55bf572",
AppEngine = new NetworkEndpointGroupAppEngine(),
Description = "description2cf9da67",
DefaultPort = 4850952,
SelfLink = "self_link7e87f12d",
CloudFunction = new NetworkEndpointGroupCloudFunction(),
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NetworkEndpointGroupsClient client = new NetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null);
NetworkEndpointGroup response = client.Get(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRequestObjectAsync()
{
moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetNetworkEndpointGroupRequest request = new GetNetworkEndpointGroupRequest
{
Zone = "zone255f4ea8",
Project = "projectaa6ff846",
NetworkEndpointGroup = "network_endpoint_groupdf1fb34e",
};
NetworkEndpointGroup expectedResponse = new NetworkEndpointGroup
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Size = -1218396681,
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
CloudRun = new NetworkEndpointGroupCloudRun(),
Annotations =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
NetworkEndpointType = NetworkEndpointGroup.Types.NetworkEndpointType.InternetFqdnPort,
Region = "regionedb20d96",
Network = "networkd22ce091",
Subnetwork = "subnetworkf55bf572",
AppEngine = new NetworkEndpointGroupAppEngine(),
Description = "description2cf9da67",
DefaultPort = 4850952,
SelfLink = "self_link7e87f12d",
CloudFunction = new NetworkEndpointGroupCloudFunction(),
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<NetworkEndpointGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NetworkEndpointGroupsClient client = new NetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null);
NetworkEndpointGroup responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
NetworkEndpointGroup responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Get()
{
moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetNetworkEndpointGroupRequest request = new GetNetworkEndpointGroupRequest
{
Zone = "zone255f4ea8",
Project = "projectaa6ff846",
NetworkEndpointGroup = "network_endpoint_groupdf1fb34e",
};
NetworkEndpointGroup expectedResponse = new NetworkEndpointGroup
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Size = -1218396681,
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
CloudRun = new NetworkEndpointGroupCloudRun(),
Annotations =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
NetworkEndpointType = NetworkEndpointGroup.Types.NetworkEndpointType.InternetFqdnPort,
Region = "regionedb20d96",
Network = "networkd22ce091",
Subnetwork = "subnetworkf55bf572",
AppEngine = new NetworkEndpointGroupAppEngine(),
Description = "description2cf9da67",
DefaultPort = 4850952,
SelfLink = "self_link7e87f12d",
CloudFunction = new NetworkEndpointGroupCloudFunction(),
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NetworkEndpointGroupsClient client = new NetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null);
NetworkEndpointGroup response = client.Get(request.Project, request.Zone, request.NetworkEndpointGroup);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAsync()
{
moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetNetworkEndpointGroupRequest request = new GetNetworkEndpointGroupRequest
{
Zone = "zone255f4ea8",
Project = "projectaa6ff846",
NetworkEndpointGroup = "network_endpoint_groupdf1fb34e",
};
NetworkEndpointGroup expectedResponse = new NetworkEndpointGroup
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Size = -1218396681,
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
CloudRun = new NetworkEndpointGroupCloudRun(),
Annotations =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
NetworkEndpointType = NetworkEndpointGroup.Types.NetworkEndpointType.InternetFqdnPort,
Region = "regionedb20d96",
Network = "networkd22ce091",
Subnetwork = "subnetworkf55bf572",
AppEngine = new NetworkEndpointGroupAppEngine(),
Description = "description2cf9da67",
DefaultPort = 4850952,
SelfLink = "self_link7e87f12d",
CloudFunction = new NetworkEndpointGroupCloudFunction(),
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<NetworkEndpointGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NetworkEndpointGroupsClient client = new NetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null);
NetworkEndpointGroup responseCallSettings = await client.GetAsync(request.Project, request.Zone, request.NetworkEndpointGroup, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
NetworkEndpointGroup responseCancellationToken = await client.GetAsync(request.Project, request.Zone, request.NetworkEndpointGroup, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissionsRequestObject()
{
moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsNetworkEndpointGroupRequest request = new TestIamPermissionsNetworkEndpointGroupRequest
{
Zone = "zone255f4ea8",
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NetworkEndpointGroupsClient client = new NetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse response = client.TestIamPermissions(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsRequestObjectAsync()
{
moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsNetworkEndpointGroupRequest request = new TestIamPermissionsNetworkEndpointGroupRequest
{
Zone = "zone255f4ea8",
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NetworkEndpointGroupsClient client = new NetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissions()
{
moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsNetworkEndpointGroupRequest request = new TestIamPermissionsNetworkEndpointGroupRequest
{
Zone = "zone255f4ea8",
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
NetworkEndpointGroupsClient client = new NetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse response = client.TestIamPermissions(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsAsync()
{
moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TestIamPermissionsNetworkEndpointGroupRequest request = new TestIamPermissionsNetworkEndpointGroupRequest
{
Zone = "zone255f4ea8",
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
NetworkEndpointGroupsClient client = new NetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using ModernHttpClient.CoreFoundation;
using ModernHttpClient.Foundation;
#if UNIFIED
using Foundation;
#else
using MonoTouch.Foundation;
using System.Globalization;
#endif
namespace ModernHttpClient
{
class InflightOperation
{
public HttpRequestMessage Request { get; set; }
public TaskCompletionSource<HttpResponseMessage> FutureResponse { get; set; }
public ProgressDelegate Progress { get; set; }
public ByteArrayListStream ResponseBody { get; set; }
public CancellationToken CancellationToken { get; set; }
public bool IsCompleted { get; set; }
public NetworkCredential PresentedCredential { get; set; }
}
public class NativeMessageHandler : HttpClientHandler
{
readonly NSUrlSession session;
readonly Dictionary<NSUrlSessionTask, InflightOperation> inflightRequests =
new Dictionary<NSUrlSessionTask, InflightOperation>();
readonly Dictionary<HttpRequestMessage, ProgressDelegate> registeredProgressCallbacks =
new Dictionary<HttpRequestMessage, ProgressDelegate>();
readonly Dictionary<string, string> headerSeparators =
new Dictionary<string, string>(){
{"User-Agent", " "}
};
readonly bool throwOnCaptiveNetwork;
readonly bool customSSLVerification;
public bool DisableCaching { get; set; }
public NativeMessageHandler(): this(false, false) { }
public NativeMessageHandler(bool throwOnCaptiveNetwork, bool customSSLVerification, NativeCookieHandler cookieHandler = null)
{
var config = NSUrlSessionConfiguration.DefaultSessionConfiguration;
config.TimeoutIntervalForRequest = 1000;
config.TimeoutIntervalForResource = 1000;
config.URLCache = new NSUrlCache (0, 0, "HttpClientCache");
session = NSUrlSession.FromConfiguration(
config,
new DataTaskDelegate(this), null);
this.throwOnCaptiveNetwork = throwOnCaptiveNetwork;
this.customSSLVerification = customSSLVerification;
this.DisableCaching = false;
}
string getHeaderSeparator(string name)
{
if (headerSeparators.ContainsKey(name)) {
return headerSeparators[name];
}
return ",";
}
public void RegisterForProgress(HttpRequestMessage request, ProgressDelegate callback)
{
if (callback == null && registeredProgressCallbacks.ContainsKey(request)) {
registeredProgressCallbacks.Remove(request);
return;
}
registeredProgressCallbacks[request] = callback;
}
ProgressDelegate getAndRemoveCallbackFromRegister(HttpRequestMessage request)
{
ProgressDelegate emptyDelegate = delegate { };
lock (registeredProgressCallbacks) {
if (!registeredProgressCallbacks.ContainsKey(request)) return emptyDelegate;
var callback = registeredProgressCallbacks[request];
registeredProgressCallbacks.Remove(request);
return callback;
}
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var headers = request.Headers as IEnumerable<KeyValuePair<string, IEnumerable<string>>>;
var ms = new MemoryStream();
if (request.Content != null) {
await request.Content.CopyToAsync(ms).ConfigureAwait(false);
headers = headers.Union(request.Content.Headers).ToArray();
}
var rq = new NSMutableUrlRequest() {
AllowsCellularAccess = true,
Body = NSData.FromArray(ms.ToArray()),
CachePolicy = (!this.DisableCaching ? NSUrlRequestCachePolicy.UseProtocolCachePolicy : NSUrlRequestCachePolicy.ReloadIgnoringCacheData),
Headers = headers.Aggregate(new NSMutableDictionary(), (acc, x) => {
acc.Add(new NSString(x.Key), new NSString(String.Join(getHeaderSeparator(x.Key), x.Value)));
return acc;
}),
HttpMethod = request.Method.ToString().ToUpperInvariant(),
Url = NSUrl.FromString(request.RequestUri.AbsoluteUri),
};
var op = session.CreateDataTask(rq);
cancellationToken.ThrowIfCancellationRequested();
var ret = new TaskCompletionSource<HttpResponseMessage>();
cancellationToken.Register(() => {
op.Cancel();
ret.TrySetCanceled();
});
lock (inflightRequests) {
inflightRequests[op] = new InflightOperation() {
FutureResponse = ret,
Request = request,
Progress = getAndRemoveCallbackFromRegister(request),
ResponseBody = new ByteArrayListStream(),
CancellationToken = cancellationToken,
};
}
op.Resume();
return await ret.Task.ConfigureAwait(false);
}
class DataTaskDelegate : NSUrlSessionDataDelegate
{
NativeMessageHandler This { get; set; }
public DataTaskDelegate(NativeMessageHandler that)
{
this.This = that;
}
public override void DidReceiveResponse(NSUrlSession session, NSUrlSessionDataTask dataTask, NSUrlResponse response, Action<NSUrlSessionResponseDisposition> completionHandler)
{
var data = getResponseForTask(dataTask);
try {
if (data.CancellationToken.IsCancellationRequested) {
dataTask.Cancel();
}
var resp = (NSHttpUrlResponse)response;
var req = data.Request;
if (This.throwOnCaptiveNetwork && req.RequestUri.Host != resp.Url.Host) {
throw new CaptiveNetworkException(req.RequestUri, new Uri(resp.Url.ToString()));
}
var content = new CancellableStreamContent(data.ResponseBody, () => {
if (!data.IsCompleted) {
dataTask.Cancel();
}
data.IsCompleted = true;
data.ResponseBody.SetException(new OperationCanceledException());
});
content.Progress = data.Progress;
// NB: The double cast is because of a Xamarin compiler bug
int status = (int)resp.StatusCode;
var ret = new HttpResponseMessage((HttpStatusCode)status) {
Content = content,
RequestMessage = data.Request,
};
ret.RequestMessage.RequestUri = new Uri(resp.Url.AbsoluteString);
foreach(var v in resp.AllHeaderFields) {
// NB: Cocoa trolling us so hard by giving us back dummy
// dictionary entries
if (v.Key == null || v.Value == null) continue;
ret.Headers.TryAddWithoutValidation(v.Key.ToString(), v.Value.ToString());
ret.Content.Headers.TryAddWithoutValidation(v.Key.ToString(), v.Value.ToString());
}
// NB: The awaiting code can synchronously call read, which will block, and we'll
// never get a didReceiveData, because we have not returned from DidReceiveResponse.
Task.Run (() => { data.FutureResponse.TrySetResult(ret); });
} catch (Exception ex) {
data.FutureResponse.TrySetException(ex);
}
completionHandler(NSUrlSessionResponseDisposition.Allow);
}
public override void DidCompleteWithError (NSUrlSession session, NSUrlSessionTask task, NSError error)
{
var data = getResponseForTask(task);
data.IsCompleted = true;
if (error != null) {
var ex = createExceptionForNSError(error);
// Pass the exception to the response
data.FutureResponse.TrySetException(ex);
data.ResponseBody.SetException(ex);
return;
}
data.ResponseBody.Complete();
lock (This.inflightRequests) {
This.inflightRequests.Remove(task);
}
}
public override void DidReceiveData (NSUrlSession session, NSUrlSessionDataTask dataTask, NSData byteData)
{
var data = getResponseForTask(dataTask);
var bytes = byteData.ToArray();
// NB: If we're cancelled, we still might have one more chunk
// of data that attempts to be delivered
if (data.IsCompleted) return;
data.ResponseBody.AddByteArray(bytes);
}
InflightOperation getResponseForTask(NSUrlSessionTask task)
{
lock (This.inflightRequests) {
return This.inflightRequests[task];
}
}
static readonly Regex cnRegex = new Regex(@"CN\s*=\s*([^,]*)", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Singleline);
public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
{
if (!This.customSSLVerification) {
goto doDefault;
}
if (challenge.ProtectionSpace.AuthenticationMethod != "NSURLAuthenticationMethodServerTrust") {
goto doDefault;
}
if (ServicePointManager.ServerCertificateValidationCallback == null) {
goto doDefault;
}
// Convert Mono Certificates to .NET certificates and build cert
// chain from root certificate
var serverCertChain = challenge.ProtectionSpace.ServerSecTrust;
var chain = new X509Chain();
X509Certificate2 root = null;
var errors = SslPolicyErrors.None;
if (serverCertChain == null || serverCertChain.Count == 0) {
errors = SslPolicyErrors.RemoteCertificateNotAvailable;
goto sslErrorVerify;
}
if (serverCertChain.Count == 1) {
errors = SslPolicyErrors.RemoteCertificateChainErrors;
goto sslErrorVerify;
}
var netCerts = Enumerable.Range(0, serverCertChain.Count)
.Select(x => serverCertChain[x].ToX509Certificate2())
.ToArray();
for (int i = 1; i < netCerts.Length; i++) {
chain.ChainPolicy.ExtraStore.Add(netCerts[i]);
}
root = netCerts[0];
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
if (!chain.Build(root)) {
errors = SslPolicyErrors.RemoteCertificateChainErrors;
goto sslErrorVerify;
}
var subject = root.Subject;
var subjectCn = cnRegex.Match(subject).Groups[1].Value;
if (String.IsNullOrWhiteSpace(subjectCn) || !Utility.MatchHostnameToPattern(task.CurrentRequest.Url.Host, subjectCn)) {
errors = SslPolicyErrors.RemoteCertificateNameMismatch;
goto sslErrorVerify;
}
sslErrorVerify:
// NachoCove: Add this to make it look like other HTTP client
var url = task.CurrentRequest.Url.ToString ();
var request = new HttpWebRequest (new Uri (url));
// End of NachoCove
bool result = ServicePointManager.ServerCertificateValidationCallback(request, root, chain, errors);
if (result) {
completionHandler(
NSUrlSessionAuthChallengeDisposition.UseCredential,
NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust));
} else {
completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
}
return;
doDefault:
if (null != This.Credentials) {
var authenticationType = AuthenticationTypeFromAuthenticationMethod(challenge.ProtectionSpace.AuthenticationMethod);
var uri = UriFromNSUrlProtectionSpace(challenge.ProtectionSpace);
if (null != authenticationType && null != uri) {
var specifedCredential = This.Credentials.GetCredential(uri, authenticationType);
var state = getResponseForTask (task);
if (null != specifedCredential &&
null != specifedCredential.UserName && null != specifedCredential.Password) {
if (specifedCredential == state.PresentedCredential) {
completionHandler (NSUrlSessionAuthChallengeDisposition.UseCredential, null);
} else {
state.PresentedCredential = specifedCredential;
var credential = new NSUrlCredential (
specifedCredential.UserName,
specifedCredential.Password,
NSUrlCredentialPersistence.ForSession);
completionHandler (NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
}
return;
}
}
}
completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
return;
}
Uri UriFromNSUrlProtectionSpace (NSUrlProtectionSpace pSpace)
{
var builder = new UriBuilder(pSpace.Protocol, pSpace.Host);
builder.Port = (int)pSpace.Port;
Uri retval;
try {
retval = builder.Uri;
} catch (UriFormatException) {
retval = null;
}
return retval;
}
string AuthenticationTypeFromAuthenticationMethod (string method)
{
if (NSUrlProtectionSpace.AuthenticationMethodDefault == method ||
NSUrlProtectionSpace.AuthenticationMethodHTTPBasic == method ||
NSUrlProtectionSpace.AuthenticationMethodNTLM == method ||
NSUrlProtectionSpace.AuthenticationMethodHTTPDigest == method) {
// Use Basic as a way to get the user+pass cred out.
return "Basic";
} else {
return null;
}
}
public override void WillPerformHttpRedirection(NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action<NSUrlRequest> completionHandler)
{
NSUrlRequest nextRequest = (This.AllowAutoRedirect ? newRequest : null);
completionHandler(nextRequest);
}
static Exception createExceptionForNSError(NSError error)
{
var ret = default(Exception);
var webExceptionStatus = WebExceptionStatus.UnknownError;
var innerException = new NSErrorException(error);
if (error.Domain == NSError.NSUrlErrorDomain) {
// Convert the error code into an enumeration (this is future
// proof, rather than just casting integer)
NSUrlErrorExtended urlError;
if (!Enum.TryParse<NSUrlErrorExtended>(error.Code.ToString(), out urlError)) urlError = NSUrlErrorExtended.Unknown;
// Parse the enum into a web exception status or exception. Some
// of these values don't necessarily translate completely to
// what WebExceptionStatus supports, so made some best guesses
// here. For your reading pleasure, compare these:
//
// Apple docs: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/index.html#//apple_ref/doc/constant_group/URL_Loading_System_Error_Codes
// .NET docs: http://msdn.microsoft.com/en-us/library/system.net.webexceptionstatus(v=vs.110).aspx
switch (urlError) {
case NSUrlErrorExtended.Cancelled:
case NSUrlErrorExtended.UserCancelledAuthentication:
// No more processing is required so just return.
return new OperationCanceledException(error.LocalizedDescription, innerException);
case NSUrlErrorExtended.BadURL:
case NSUrlErrorExtended.UnsupportedURL:
case NSUrlErrorExtended.CannotConnectToHost:
case NSUrlErrorExtended.ResourceUnavailable:
case NSUrlErrorExtended.NotConnectedToInternet:
case NSUrlErrorExtended.UserAuthenticationRequired:
case NSUrlErrorExtended.InternationalRoamingOff:
case NSUrlErrorExtended.CallIsActive:
case NSUrlErrorExtended.DataNotAllowed:
webExceptionStatus = WebExceptionStatus.ConnectFailure;
break;
case NSUrlErrorExtended.TimedOut:
webExceptionStatus = WebExceptionStatus.Timeout;
break;
case NSUrlErrorExtended.CannotFindHost:
case NSUrlErrorExtended.DNSLookupFailed:
webExceptionStatus = WebExceptionStatus.NameResolutionFailure;
break;
case NSUrlErrorExtended.DataLengthExceedsMaximum:
webExceptionStatus = WebExceptionStatus.MessageLengthLimitExceeded;
break;
case NSUrlErrorExtended.NetworkConnectionLost:
webExceptionStatus = WebExceptionStatus.ConnectionClosed;
break;
case NSUrlErrorExtended.HTTPTooManyRedirects:
case NSUrlErrorExtended.RedirectToNonExistentLocation:
webExceptionStatus = WebExceptionStatus.ProtocolError;
break;
case NSUrlErrorExtended.RequestBodyStreamExhausted:
webExceptionStatus = WebExceptionStatus.SendFailure;
break;
case NSUrlErrorExtended.BadServerResponse:
case NSUrlErrorExtended.ZeroByteResource:
case NSUrlErrorExtended.CannotDecodeRawData:
case NSUrlErrorExtended.CannotDecodeContentData:
case NSUrlErrorExtended.CannotParseResponse:
case NSUrlErrorExtended.FileDoesNotExist:
case NSUrlErrorExtended.FileIsDirectory:
case NSUrlErrorExtended.NoPermissionsToReadFile:
case NSUrlErrorExtended.CannotLoadFromNetwork:
case NSUrlErrorExtended.CannotCreateFile:
case NSUrlErrorExtended.CannotOpenFile:
case NSUrlErrorExtended.CannotCloseFile:
case NSUrlErrorExtended.CannotWriteToFile:
case NSUrlErrorExtended.CannotRemoveFile:
case NSUrlErrorExtended.CannotMoveFile:
case NSUrlErrorExtended.DownloadDecodingFailedMidStream:
case NSUrlErrorExtended.DownloadDecodingFailedToComplete:
webExceptionStatus = WebExceptionStatus.ReceiveFailure;
break;
case NSUrlErrorExtended.SecureConnectionFailed:
webExceptionStatus = WebExceptionStatus.SecureChannelFailure;
break;
case NSUrlErrorExtended.ServerCertificateHasBadDate:
case NSUrlErrorExtended.ServerCertificateHasUnknownRoot:
case NSUrlErrorExtended.ServerCertificateNotYetValid:
case NSUrlErrorExtended.ServerCertificateUntrusted:
case NSUrlErrorExtended.ClientCertificateRejected:
case NSUrlErrorExtended.ClientCertificateRequired:
webExceptionStatus = WebExceptionStatus.TrustFailure;
break;
}
goto done;
}
if (error.Domain == CFNetworkError.ErrorDomain) {
// Convert the error code into an enumeration (this is future
// proof, rather than just casting integer)
CFNetworkErrors networkError;
if (!Enum.TryParse<CFNetworkErrors>(error.Code.ToString(), out networkError)) {
networkError = CFNetworkErrors.CFHostErrorUnknown;
}
// Parse the enum into a web exception status or exception. Some
// of these values don't necessarily translate completely to
// what WebExceptionStatus supports, so made some best guesses
// here. For your reading pleasure, compare these:
//
// Apple docs: https://developer.apple.com/library/ios/documentation/Networking/Reference/CFNetworkErrors/#//apple_ref/c/tdef/CFNetworkErrors
// .NET docs: http://msdn.microsoft.com/en-us/library/system.net.webexceptionstatus(v=vs.110).aspx
switch (networkError) {
case CFNetworkErrors.CFURLErrorCancelled:
case CFNetworkErrors.CFURLErrorUserCancelledAuthentication:
case CFNetworkErrors.CFNetServiceErrorCancel:
// No more processing is required so just return.
return new OperationCanceledException(error.LocalizedDescription, innerException);
case CFNetworkErrors.CFSOCKS5ErrorBadCredentials:
case CFNetworkErrors.CFSOCKS5ErrorUnsupportedNegotiationMethod:
case CFNetworkErrors.CFSOCKS5ErrorNoAcceptableMethod:
case CFNetworkErrors.CFErrorHttpAuthenticationTypeUnsupported:
case CFNetworkErrors.CFErrorHttpBadCredentials:
case CFNetworkErrors.CFErrorHttpBadURL:
case CFNetworkErrors.CFURLErrorBadURL:
case CFNetworkErrors.CFURLErrorUnsupportedURL:
case CFNetworkErrors.CFURLErrorCannotConnectToHost:
case CFNetworkErrors.CFURLErrorResourceUnavailable:
case CFNetworkErrors.CFURLErrorNotConnectedToInternet:
case CFNetworkErrors.CFURLErrorUserAuthenticationRequired:
case CFNetworkErrors.CFURLErrorInternationalRoamingOff:
case CFNetworkErrors.CFURLErrorCallIsActive:
case CFNetworkErrors.CFURLErrorDataNotAllowed:
webExceptionStatus = WebExceptionStatus.ConnectFailure;
break;
case CFNetworkErrors.CFURLErrorTimedOut:
case CFNetworkErrors.CFNetServiceErrorTimeout:
webExceptionStatus = WebExceptionStatus.Timeout;
break;
case CFNetworkErrors.CFHostErrorHostNotFound:
case CFNetworkErrors.CFURLErrorCannotFindHost:
case CFNetworkErrors.CFURLErrorDNSLookupFailed:
case CFNetworkErrors.CFNetServiceErrorDNSServiceFailure:
webExceptionStatus = WebExceptionStatus.NameResolutionFailure;
break;
case CFNetworkErrors.CFURLErrorDataLengthExceedsMaximum:
webExceptionStatus = WebExceptionStatus.MessageLengthLimitExceeded;
break;
case CFNetworkErrors.CFErrorHttpConnectionLost:
case CFNetworkErrors.CFURLErrorNetworkConnectionLost:
webExceptionStatus = WebExceptionStatus.ConnectionClosed;
break;
case CFNetworkErrors.CFErrorHttpRedirectionLoopDetected:
case CFNetworkErrors.CFURLErrorHTTPTooManyRedirects:
case CFNetworkErrors.CFURLErrorRedirectToNonExistentLocation:
webExceptionStatus = WebExceptionStatus.ProtocolError;
break;
case CFNetworkErrors.CFSOCKSErrorUnknownClientVersion:
case CFNetworkErrors.CFSOCKSErrorUnsupportedServerVersion:
case CFNetworkErrors.CFErrorHttpParseFailure:
case CFNetworkErrors.CFURLErrorRequestBodyStreamExhausted:
webExceptionStatus = WebExceptionStatus.SendFailure;
break;
case CFNetworkErrors.CFSOCKS4ErrorRequestFailed:
case CFNetworkErrors.CFSOCKS4ErrorIdentdFailed:
case CFNetworkErrors.CFSOCKS4ErrorIdConflict:
case CFNetworkErrors.CFSOCKS4ErrorUnknownStatusCode:
case CFNetworkErrors.CFSOCKS5ErrorBadState:
case CFNetworkErrors.CFSOCKS5ErrorBadResponseAddr:
case CFNetworkErrors.CFURLErrorBadServerResponse:
case CFNetworkErrors.CFURLErrorZeroByteResource:
case CFNetworkErrors.CFURLErrorCannotDecodeRawData:
case CFNetworkErrors.CFURLErrorCannotDecodeContentData:
case CFNetworkErrors.CFURLErrorCannotParseResponse:
case CFNetworkErrors.CFURLErrorFileDoesNotExist:
case CFNetworkErrors.CFURLErrorFileIsDirectory:
case CFNetworkErrors.CFURLErrorNoPermissionsToReadFile:
case CFNetworkErrors.CFURLErrorCannotLoadFromNetwork:
case CFNetworkErrors.CFURLErrorCannotCreateFile:
case CFNetworkErrors.CFURLErrorCannotOpenFile:
case CFNetworkErrors.CFURLErrorCannotCloseFile:
case CFNetworkErrors.CFURLErrorCannotWriteToFile:
case CFNetworkErrors.CFURLErrorCannotRemoveFile:
case CFNetworkErrors.CFURLErrorCannotMoveFile:
case CFNetworkErrors.CFURLErrorDownloadDecodingFailedMidStream:
case CFNetworkErrors.CFURLErrorDownloadDecodingFailedToComplete:
case CFNetworkErrors.CFHTTPCookieCannotParseCookieFile:
case CFNetworkErrors.CFNetServiceErrorUnknown:
case CFNetworkErrors.CFNetServiceErrorCollision:
case CFNetworkErrors.CFNetServiceErrorNotFound:
case CFNetworkErrors.CFNetServiceErrorInProgress:
case CFNetworkErrors.CFNetServiceErrorBadArgument:
case CFNetworkErrors.CFNetServiceErrorInvalid:
webExceptionStatus = WebExceptionStatus.ReceiveFailure;
break;
case CFNetworkErrors.CFURLErrorServerCertificateHasBadDate:
case CFNetworkErrors.CFURLErrorServerCertificateUntrusted:
case CFNetworkErrors.CFURLErrorServerCertificateHasUnknownRoot:
case CFNetworkErrors.CFURLErrorServerCertificateNotYetValid:
case CFNetworkErrors.CFURLErrorClientCertificateRejected:
case CFNetworkErrors.CFURLErrorClientCertificateRequired:
webExceptionStatus = WebExceptionStatus.TrustFailure;
break;
case CFNetworkErrors.CFURLErrorSecureConnectionFailed:
webExceptionStatus = WebExceptionStatus.SecureChannelFailure;
break;
case CFNetworkErrors.CFErrorHttpProxyConnectionFailure:
case CFNetworkErrors.CFErrorHttpBadProxyCredentials:
case CFNetworkErrors.CFErrorPACFileError:
case CFNetworkErrors.CFErrorPACFileAuth:
case CFNetworkErrors.CFErrorHttpsProxyConnectionFailure:
case CFNetworkErrors.CFStreamErrorHttpsProxyFailureUnexpectedResponseToConnectMethod:
webExceptionStatus = WebExceptionStatus.RequestProhibitedByProxy;
break;
}
goto done;
}
done:
// Always create a WebException so that it can be handled by the client.
ret = new WebException(error.LocalizedDescription, innerException, webExceptionStatus, response: null);
return ret;
}
}
}
class ByteArrayListStream : Stream
{
Exception exception;
IDisposable lockRelease;
readonly AsyncLock readStreamLock;
readonly List<byte[]> bytes = new List<byte[]>();
bool isCompleted;
long maxLength = 0;
long position = 0;
int offsetInCurrentBuffer = 0;
public ByteArrayListStream()
{
// Initially we have nothing to read so Reads should be parked
readStreamLock = AsyncLock.CreateLocked(out lockRelease);
}
public override bool CanRead { get { return true; } }
public override bool CanWrite { get { return false; } }
public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); }
public override void WriteByte(byte value) { throw new NotSupportedException(); }
public override bool CanSeek { get { return false; } }
public override bool CanTimeout { get { return false; } }
public override void SetLength(long value) { throw new NotSupportedException(); }
public override void Flush() { }
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override long Position {
get { return position; }
set {
throw new NotSupportedException();
}
}
public override long Length {
get {
return maxLength;
}
}
public override int Read(byte[] buffer, int offset, int count)
{
return this.ReadAsync(buffer, offset, count).Result;
}
/* OMG THIS CODE IS COMPLICATED
*
* Here's the core idea. We want to create a ReadAsync function that
* reads from our list of byte arrays **until it gets to the end of
* our current list**.
*
* If we're not there yet, we keep returning data, serializing access
* to the underlying position pointer (i.e. we definitely don't want
* people concurrently moving position along). If we try to read past
* the end, we return the section of data we could read and complete
* it.
*
* Here's where the tricky part comes in. If we're not Completed (i.e.
* the caller still wants to add more byte arrays in the future) and
* we're at the end of the current stream, we want to *block* the read
* (not blocking, but async blocking whatever you know what I mean),
* until somebody adds another byte[] to chew through, or if someone
* rewinds the position.
*
* If we *are* completed, we should return zero to simply complete the
* read, signalling we're at the end of the stream */
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
retry:
int bytesRead = 0;
int buffersToRemove = 0;
if (isCompleted && position == maxLength) {
return 0;
}
if (exception != null) throw exception;
using (await readStreamLock.LockAsync().ConfigureAwait(false)) {
lock (bytes) {
foreach (var buf in bytes) {
cancellationToken.ThrowIfCancellationRequested();
if (exception != null) throw exception;
int toCopy = Math.Min(count, buf.Length - offsetInCurrentBuffer);
Array.ConstrainedCopy(buf, offsetInCurrentBuffer, buffer, offset, toCopy);
count -= toCopy;
offset += toCopy;
bytesRead += toCopy;
offsetInCurrentBuffer += toCopy;
if (offsetInCurrentBuffer >= buf.Length) {
offsetInCurrentBuffer = 0;
buffersToRemove++;
}
if (count <= 0) break;
}
// Remove buffers that we read in this operation
bytes.RemoveRange(0, buffersToRemove);
position += bytesRead;
}
}
// If we're at the end of the stream and it's not done, prepare
// the next read to park itself unless AddByteArray or Complete
// posts
if (position >= maxLength && !isCompleted) {
lockRelease = await readStreamLock.LockAsync().ConfigureAwait(false);
}
if (bytesRead == 0 && !isCompleted) {
// NB: There are certain race conditions where we somehow acquire
// the lock yet are at the end of the stream, and we're not completed
// yet. We should try again so that we can get stuck in the lock.
goto retry;
}
if (cancellationToken.IsCancellationRequested) {
Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose();
cancellationToken.ThrowIfCancellationRequested();
}
if (exception != null) {
Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose();
throw exception;
}
if (isCompleted && position < maxLength) {
// NB: This solves a rare deadlock
//
// 1. ReadAsync called (waiting for lock release)
// 2. AddByteArray called (release lock)
// 3. AddByteArray called (release lock)
// 4. Complete called (release lock the last time)
// 5. ReadAsync called (lock released at this point, the method completed successfully)
// 6. ReadAsync called (deadlock on LockAsync(), because the lock is block, and there is no way to release it)
//
// Current condition forces the lock to be released in the end of 5th point
Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose();
}
return bytesRead;
}
public void AddByteArray(byte[] arrayToAdd)
{
if (exception != null) throw exception;
if (isCompleted) throw new InvalidOperationException("Can't add byte arrays once Complete() is called");
lock (bytes) {
maxLength += arrayToAdd.Length;
bytes.Add(arrayToAdd);
//Console.WriteLine("Added a new byte array, {0}: max = {1}", arrayToAdd.Length, maxLength);
}
Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose();
}
public void Complete()
{
isCompleted = true;
Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose();
}
public void SetException(Exception ex)
{
exception = ex;
Complete();
}
}
sealed class CancellableStreamContent : ProgressStreamContent
{
Action onDispose;
public CancellableStreamContent(Stream source, Action onDispose) : base(source, CancellationToken.None)
{
this.onDispose = onDispose;
}
protected override void Dispose(bool disposing)
{
var disp = Interlocked.Exchange(ref onDispose, null);
if (disp != null) disp();
// EVIL HAX: We have to let at least one ReadAsync of the underlying
// stream fail with OperationCancelledException before we can dispose
// the base, or else the exception coming out of the ReadAsync will
// be an ObjectDisposedException from an internal MemoryStream. This isn't
// the Ideal way to fix this, but #yolo.
Task.Run(() => base.Dispose(disposing));
}
}
sealed class EmptyDisposable : IDisposable
{
static readonly IDisposable instance = new EmptyDisposable();
public static IDisposable Instance { get { return instance; } }
EmptyDisposable() { }
public void Dispose() { }
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using PCSComUtils.Common;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
namespace PCSComSale.Order.DS
{
public class SO_ReturnedGoodsDetailDS
{
public SO_ReturnedGoodsDetailDS()
{
}
private const string THIS = "PCSComSale.Order.DS.SO_ReturnedGoodsDetailDS";
//**************************************************************************
/// <Description>
/// Get the total received quantity
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
///
/// </Authors>
/// <History>
/// Tuesday, February 01, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public decimal GetTotalReceivedQuantity(int pintSaleOrderMasterID, int pintProductID, string pstrLot, string pstrSerial)
{
const string METHOD_NAME = THIS + ".GetTotalReceivedQuantity()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
const string VIEW_NAME = "v_TotalReturnedGoods";
try
{
string strSql = String.Empty;
strSql = "SELECT "
+ SO_ReturnedGoodsDetailTable.RECEIVEQUANTITY_FLD
+ " FROM " + VIEW_NAME
+ " WHERE " + SO_ReturnedGoodsMasterTable.SALEORDERMASTERID_FLD + "=" + pintSaleOrderMasterID
+ " AND " + SO_ReturnedGoodsDetailTable.PRODUCTID_FLD + "=" + pintProductID;
if (pstrLot != String.Empty)
{
strSql += " AND " + SO_ReturnedGoodsDetailTable.LOT_FLD + "='" + pstrLot.Replace("'", "''") + "'";
}
if (pstrSerial != String.Empty)
{
strSql += " AND " + SO_ReturnedGoodsDetailTable.SERIAL_FLD + "='" + pstrSerial.Replace("'", "''") + "'";
}
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
object objResult = ocmdPCS.ExecuteScalar();
if (objResult == null || objResult == DBNull.Value)
{
return 0;
}
else
{
if (objResult.ToString() == String.Empty)
{
return 0;
}
else
{
return decimal.Parse(objResult.ToString());
}
}
}
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();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get max Line number in the Detail
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
///
/// </Authors>
/// <History>
/// Tuesday, February 01, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public int GetMaxReturnedGoodsDetailLine(int pintReturnedGoodsMasterID)
{
const string METHOD_NAME = THIS + ".GetMaxReturnedGoodsDetailLine()";
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT max ("
+ SO_ReturnedGoodsDetailTable.LINE_FLD + ")"
+ " FROM " + SO_ReturnedGoodsDetailTable.TABLE_NAME
+ " WHERE " + SO_ReturnedGoodsDetailTable.RETURNEDGOODSMASTERID_FLD + "=" + pintReturnedGoodsMasterID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
string strResult = ocmdPCS.ExecuteScalar().ToString();
int intResult;
try
{
intResult = int.Parse(strResult);
}
catch
{
intResult = 0;
}
return intResult;
}
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();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to add data to SO_ReturnedGoodsDetail
/// </Description>
/// <Inputs>
/// SO_ReturnedGoodsDetailVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, February 22, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
SO_ReturnedGoodsDetailVO objObject = (SO_ReturnedGoodsDetailVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql = "INSERT INTO SO_ReturnedGoodsDetail("
+ SO_ReturnedGoodsDetailTable.RECEIVEQUANTITY_FLD + ","
+ SO_ReturnedGoodsDetailTable.UNITID_FLD + ","
+ SO_ReturnedGoodsDetailTable.PRODUCTID_FLD + ","
+ SO_ReturnedGoodsDetailTable.UNITPRICE_FLD + ","
+ SO_ReturnedGoodsDetailTable.RETURNEDGOODSMASTERID_FLD + ","
+ SO_ReturnedGoodsDetailTable.BINID_FLD + ","
+ SO_ReturnedGoodsDetailTable.LOCATIONID_FLD + ","
+ SO_ReturnedGoodsDetailTable.MASTERLOCATIONID_FLD + ","
+ SO_ReturnedGoodsDetailTable.QASTATUS_FLD + ","
+ SO_ReturnedGoodsDetailTable.LOT_FLD + ","
+ SO_ReturnedGoodsDetailTable.LINE_FLD + ","
+ SO_ReturnedGoodsDetailTable.SERIAL_FLD + ")"
+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.RECEIVEQUANTITY_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.RECEIVEQUANTITY_FLD].Value = objObject.ReceiveQuantity;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.UNITID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.UNITID_FLD].Value = objObject.UnitID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.PRODUCTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.PRODUCTID_FLD].Value = objObject.ProductID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.UNITPRICE_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.UNITPRICE_FLD].Value = objObject.UnitPrice;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.RETURNEDGOODSMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.RETURNEDGOODSMASTERID_FLD].Value = objObject.ReturnedGoodsMasterID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.BINID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.BINID_FLD].Value = objObject.BinID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.LOCATIONID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.LOCATIONID_FLD].Value = objObject.LocationID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.MASTERLOCATIONID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.QASTATUS_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.QASTATUS_FLD].Value = objObject.QAStatus;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.LOT_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.LOT_FLD].Value = objObject.Lot;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.LINE_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.LINE_FLD].Value = objObject.Line;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.SERIAL_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.SERIAL_FLD].Value = objObject.Serial;
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();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from SO_ReturnedGoodsDetail
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql = "DELETE " + SO_ReturnedGoodsDetailTable.TABLE_NAME + " WHERE " + "ReturnedGoodsDetailID" + "=" + 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();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from SO_ReturnedGoodsDetail
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void DeleteAllReturnedGoodsDetail(int pintReturnedGoodsMasterID)
{
const string METHOD_NAME = THIS + ".DeleteAllReturnedGoodsDetail()";
string strSql = String.Empty;
strSql = "DELETE " + SO_ReturnedGoodsDetailTable.TABLE_NAME + " WHERE " + SO_ReturnedGoodsDetailTable.RETURNEDGOODSMASTERID_FLD + "=" + pintReturnedGoodsMasterID.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();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from SO_ReturnedGoodsDetail
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// SO_ReturnedGoodsDetailVO
/// </Outputs>
/// <Returns>
/// SO_ReturnedGoodsDetailVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, February 22, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
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 "
+ SO_ReturnedGoodsDetailTable.RETURNEDGOODSDETAILID_FLD + ","
+ SO_ReturnedGoodsDetailTable.RECEIVEQUANTITY_FLD + ","
+ SO_ReturnedGoodsDetailTable.UNITID_FLD + ","
+ SO_ReturnedGoodsDetailTable.PRODUCTID_FLD + ","
+ SO_ReturnedGoodsDetailTable.UNITPRICE_FLD + ","
+ SO_ReturnedGoodsDetailTable.RETURNEDGOODSMASTERID_FLD + ","
+ SO_ReturnedGoodsDetailTable.BINID_FLD + ","
+ SO_ReturnedGoodsDetailTable.LOCATIONID_FLD + ","
+ SO_ReturnedGoodsDetailTable.MASTERLOCATIONID_FLD + ","
+ SO_ReturnedGoodsDetailTable.QASTATUS_FLD + ","
+ SO_ReturnedGoodsDetailTable.LOT_FLD + ","
+ SO_ReturnedGoodsDetailTable.LINE_FLD + ","
+ SO_ReturnedGoodsDetailTable.SERIAL_FLD
+ " FROM " + SO_ReturnedGoodsDetailTable.TABLE_NAME
+ " WHERE " + SO_ReturnedGoodsDetailTable.RETURNEDGOODSDETAILID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
SO_ReturnedGoodsDetailVO objObject = new SO_ReturnedGoodsDetailVO();
while (odrPCS.Read())
{
objObject.ReturnedGoodsDetailID = int.Parse(odrPCS[SO_ReturnedGoodsDetailTable.RETURNEDGOODSDETAILID_FLD].ToString().Trim());
objObject.ReceiveQuantity = Decimal.Parse(odrPCS[SO_ReturnedGoodsDetailTable.RECEIVEQUANTITY_FLD].ToString().Trim());
objObject.UnitID = int.Parse(odrPCS[SO_ReturnedGoodsDetailTable.UNITID_FLD].ToString().Trim());
objObject.ProductID = int.Parse(odrPCS[SO_ReturnedGoodsDetailTable.PRODUCTID_FLD].ToString().Trim());
objObject.UnitPrice = Decimal.Parse(odrPCS[SO_ReturnedGoodsDetailTable.UNITPRICE_FLD].ToString().Trim());
objObject.ReturnedGoodsMasterID = int.Parse(odrPCS[SO_ReturnedGoodsDetailTable.RETURNEDGOODSMASTERID_FLD].ToString().Trim());
objObject.BinID = int.Parse(odrPCS[SO_ReturnedGoodsDetailTable.BINID_FLD].ToString().Trim());
objObject.LocationID = int.Parse(odrPCS[SO_ReturnedGoodsDetailTable.LOCATIONID_FLD].ToString().Trim());
objObject.MasterLocationID = int.Parse(odrPCS[SO_ReturnedGoodsDetailTable.MASTERLOCATIONID_FLD].ToString().Trim());
objObject.QAStatus = int.Parse(odrPCS[SO_ReturnedGoodsDetailTable.QASTATUS_FLD].ToString().Trim());
objObject.Lot = odrPCS[SO_ReturnedGoodsDetailTable.LOT_FLD].ToString().Trim();
objObject.Line = int.Parse(odrPCS[SO_ReturnedGoodsDetailTable.LINE_FLD].ToString().Trim());
objObject.Serial = odrPCS[SO_ReturnedGoodsDetailTable.SERIAL_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();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to SO_ReturnedGoodsDetail
/// </Description>
/// <Inputs>
/// SO_ReturnedGoodsDetailVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
SO_ReturnedGoodsDetailVO objObject = (SO_ReturnedGoodsDetailVO) 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 SO_ReturnedGoodsDetail SET "
+ SO_ReturnedGoodsDetailTable.RECEIVEQUANTITY_FLD + "= ?" + ","
+ SO_ReturnedGoodsDetailTable.UNITID_FLD + "= ?" + ","
+ SO_ReturnedGoodsDetailTable.PRODUCTID_FLD + "= ?" + ","
+ SO_ReturnedGoodsDetailTable.UNITPRICE_FLD + "= ?" + ","
+ SO_ReturnedGoodsDetailTable.RETURNEDGOODSMASTERID_FLD + "= ?" + ","
+ SO_ReturnedGoodsDetailTable.BINID_FLD + "= ?" + ","
+ SO_ReturnedGoodsDetailTable.LOCATIONID_FLD + "= ?" + ","
+ SO_ReturnedGoodsDetailTable.MASTERLOCATIONID_FLD + "= ?" + ","
+ SO_ReturnedGoodsDetailTable.QASTATUS_FLD + "= ?" + ","
+ SO_ReturnedGoodsDetailTable.LOT_FLD + "= ?" + ","
+ SO_ReturnedGoodsDetailTable.LINE_FLD + "= ?" + ","
+ SO_ReturnedGoodsDetailTable.SERIAL_FLD + "= ?"
+ " WHERE " + SO_ReturnedGoodsDetailTable.RETURNEDGOODSDETAILID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.RECEIVEQUANTITY_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.RECEIVEQUANTITY_FLD].Value = objObject.ReceiveQuantity;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.UNITID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.UNITID_FLD].Value = objObject.UnitID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.PRODUCTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.PRODUCTID_FLD].Value = objObject.ProductID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.UNITPRICE_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.UNITPRICE_FLD].Value = objObject.UnitPrice;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.RETURNEDGOODSMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.RETURNEDGOODSMASTERID_FLD].Value = objObject.ReturnedGoodsMasterID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.BINID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.BINID_FLD].Value = objObject.BinID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.LOCATIONID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.LOCATIONID_FLD].Value = objObject.LocationID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.MASTERLOCATIONID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.QASTATUS_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.QASTATUS_FLD].Value = objObject.QAStatus;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.LOT_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.LOT_FLD].Value = objObject.Lot;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.LINE_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.LINE_FLD].Value = objObject.Line;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.SERIAL_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.SERIAL_FLD].Value = objObject.Serial;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ReturnedGoodsDetailTable.RETURNEDGOODSDETAILID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ReturnedGoodsDetailTable.RETURNEDGOODSDETAILID_FLD].Value = objObject.ReturnedGoodsDetailID;
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();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from SO_ReturnedGoodsDetail
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Monday, February 14, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet ListReturnedGoodsDetail(int pintReturnedGoodsID)
{
const string METHOD_NAME = THIS + ".ListReturnedGoodsDetail()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
//+ "'' BalanceQty,"
strSql = "SELECT "
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.RETURNEDGOODSDETAILID_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.LINE_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.PRODUCTID_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.CONFIRMSHIPMASTERID_FLD + ","
+ "COM." + SO_ConfirmShipMasterTable.CONFIRMSHIPNO_FLD + ","
+ ITM_ProductTable.TABLE_NAME + "." + ITM_ProductTable.CODE_FLD + ","
+ ITM_ProductTable.TABLE_NAME + "." + ITM_ProductTable.DESCRIPTION_FLD + ","
+ ITM_ProductTable.TABLE_NAME + "." + ITM_ProductTable.REVISION_FLD + ","
+ ITM_ProductTable.TABLE_NAME + "." + ITM_ProductTable.STOCKUMID_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.UNITID_FLD + ","
+ "(SELECT " + MST_UnitOfMeasureTable.CODE_FLD + " FROM " + MST_UnitOfMeasureTable.TABLE_NAME + " WHERE " + MST_UnitOfMeasureTable.UNITOFMEASUREID_FLD + "=" + SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.UNITID_FLD + ") as MST_UnitOfMeasureCode,"
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.RECEIVEQUANTITY_FLD + ","
// edited by dungla, fix bug for NgaHT
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.BALANCEQTY_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.UNITPRICE_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.RETURNEDGOODSMASTERID_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.MASTERLOCATIONID_FLD + ","
+ MST_MasterLocationTable.TABLE_NAME + "." + MST_MasterLocationTable.CODE_FLD + " as MST_MasterLocationCode ,"
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.LOCATIONID_FLD + ","
+ MST_LocationTable.TABLE_NAME + "." + MST_LocationTable.CODE_FLD + " as MST_LocationCode ,"
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.BINID_FLD + ","
+ MST_BINTable.TABLE_NAME + "." + MST_BINTable.CODE_FLD + " as MST_BinCode ,"
+ MST_LocationTable.TABLE_NAME + "." + MST_LocationTable.BIN_FLD + " as MST_LocationBin,"
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.QASTATUS_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.LOT_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.SALEORDERDETAILID_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.QUANTITYOFSELLING_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.SERIAL_FLD
+ " FROM " + SO_ReturnedGoodsDetailTable.TABLE_NAME
+ " Inner join " + ITM_ProductTable.TABLE_NAME + " ON " + SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.PRODUCTID_FLD + "=" + ITM_ProductTable.TABLE_NAME + "." + ITM_ProductTable.PRODUCTID_FLD
+ " left join " + MST_MasterLocationTable.TABLE_NAME + " ON " + SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.MASTERLOCATIONID_FLD + "=" + MST_MasterLocationTable.TABLE_NAME + "." + MST_MasterLocationTable.MASTERLOCATIONID_FLD
+ " left join " + MST_LocationTable.TABLE_NAME + " ON " + SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.LOCATIONID_FLD + "=" + MST_LocationTable.TABLE_NAME + "." + MST_LocationTable.LOCATIONID_FLD
+ " left join " + MST_BINTable.TABLE_NAME + " ON " + SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.BINID_FLD + "=" + MST_BINTable.TABLE_NAME + "." + MST_BINTable.BINID_FLD
+ " left join " + SO_ConfirmShipMasterTable.TABLE_NAME + " COM ON " + SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.CONFIRMSHIPMASTERID_FLD + " = COM." + SO_ConfirmShipMasterTable.CONFIRMSHIPMASTERID_FLD
+ " WHERE " + SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.RETURNEDGOODSMASTERID_FLD + "=" + pintReturnedGoodsID;
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, SO_ReturnedGoodsDetailTable.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();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from SO_ReturnedGoodsDetail
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, February 22, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
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 "
+ SO_ReturnedGoodsDetailTable.RETURNEDGOODSDETAILID_FLD + ","
+ SO_ReturnedGoodsDetailTable.RECEIVEQUANTITY_FLD + ","
+ SO_ReturnedGoodsDetailTable.UNITID_FLD + ","
+ SO_ReturnedGoodsDetailTable.PRODUCTID_FLD + ","
+ SO_ReturnedGoodsDetailTable.UNITPRICE_FLD + ","
+ SO_ReturnedGoodsDetailTable.RETURNEDGOODSMASTERID_FLD + ","
+ SO_ReturnedGoodsDetailTable.BINID_FLD + ","
+ SO_ReturnedGoodsDetailTable.LOCATIONID_FLD + ","
+ SO_ReturnedGoodsDetailTable.MASTERLOCATIONID_FLD + ","
+ SO_ReturnedGoodsDetailTable.QASTATUS_FLD + ","
+ SO_ReturnedGoodsDetailTable.LOT_FLD + ","
+ SO_ReturnedGoodsDetailTable.LINE_FLD + ","
+ SO_ReturnedGoodsDetailTable.SERIAL_FLD
+ " FROM " + SO_ReturnedGoodsDetailTable.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, SO_ReturnedGoodsDetailTable.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();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, February 22, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS = null;
OleDbCommandBuilder odcbPCS;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql = "SELECT "
+ SO_ReturnedGoodsDetailTable.RETURNEDGOODSDETAILID_FLD + ","
+ SO_ReturnedGoodsDetailTable.RECEIVEQUANTITY_FLD + ","
+ SO_ReturnedGoodsDetailTable.UNITID_FLD + ","
+ SO_ReturnedGoodsDetailTable.PRODUCTID_FLD + ","
+ SO_ReturnedGoodsDetailTable.UNITPRICE_FLD + ","
+ SO_ReturnedGoodsDetailTable.RETURNEDGOODSMASTERID_FLD + ","
+ SO_ReturnedGoodsDetailTable.BINID_FLD + ","
+ SO_ReturnedGoodsDetailTable.LOCATIONID_FLD + ","
+ SO_ReturnedGoodsDetailTable.MASTERLOCATIONID_FLD + ","
+ SO_ReturnedGoodsDetailTable.QASTATUS_FLD + ","
+ SO_ReturnedGoodsDetailTable.LOT_FLD + ","
+ SO_ReturnedGoodsDetailTable.LINE_FLD + ","
+ SO_ReturnedGoodsDetailTable.SERIAL_FLD
+ " FROM " + SO_ReturnedGoodsDetailTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData, SO_ReturnedGoodsDetailTable.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();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, February 22, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSetReturnedGoodsDetail(DataSet pData, int pintReturnedGoodsMasterID)
{
const string METHOD_NAME = THIS + ".UpdateDataSetReturnedGoodsDetail()";
string strSql;
OleDbConnection oconPCS = null;
OleDbCommandBuilder odcbPCS;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql = "SELECT "
+ SO_ReturnedGoodsDetailTable.SALEORDERDETAILID_FLD + ","
+ SO_ReturnedGoodsDetailTable.CONFIRMSHIPMASTERID_FLD + ","
+ SO_ReturnedGoodsDetailTable.RETURNEDGOODSDETAILID_FLD + ","
+ SO_ReturnedGoodsDetailTable.RECEIVEQUANTITY_FLD + ","
+ SO_ReturnedGoodsDetailTable.UNITID_FLD + ","
+ SO_ReturnedGoodsDetailTable.PRODUCTID_FLD + ","
+ SO_ReturnedGoodsDetailTable.UNITPRICE_FLD + ","
+ SO_ReturnedGoodsDetailTable.RETURNEDGOODSMASTERID_FLD + ","
+ SO_ReturnedGoodsDetailTable.BINID_FLD + ","
+ SO_ReturnedGoodsDetailTable.LOCATIONID_FLD + ","
+ SO_ReturnedGoodsDetailTable.MASTERLOCATIONID_FLD + ","
+ SO_ReturnedGoodsDetailTable.QASTATUS_FLD + ","
+ SO_ReturnedGoodsDetailTable.LOT_FLD + ","
+ SO_ReturnedGoodsDetailTable.LINE_FLD + ","
+ SO_ReturnedGoodsDetailTable.QUANTITYOFSELLING_FLD + ","
+ SO_ReturnedGoodsDetailTable.BALANCEQTY_FLD + ","
+ SO_ReturnedGoodsDetailTable.SERIAL_FLD
+ " FROM " + SO_ReturnedGoodsDetailTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData, SO_ReturnedGoodsDetailTable.TABLE_NAME);
//Reload data from database
strSql = "SELECT "
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.RETURNEDGOODSDETAILID_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.LINE_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.CONFIRMSHIPMASTERID_FLD + ","
+ "COM." + SO_ConfirmShipMasterTable.CONFIRMSHIPNO_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.PRODUCTID_FLD + ","
+ ITM_ProductTable.TABLE_NAME + "." + ITM_ProductTable.DESCRIPTION_FLD + ","
+ ITM_ProductTable.TABLE_NAME + "." + ITM_ProductTable.REVISION_FLD + ","
+ ITM_ProductTable.TABLE_NAME + "." + ITM_ProductTable.STOCKUMID_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.UNITID_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.RECEIVEQUANTITY_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.BALANCEQTY_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.UNITPRICE_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.RETURNEDGOODSMASTERID_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.MASTERLOCATIONID_FLD + ","
+ MST_MasterLocationTable.TABLE_NAME + "." + MST_MasterLocationTable.CODE_FLD + " as MasterLocationCode ,"
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.LOCATIONID_FLD + ","
+ MST_LocationTable.TABLE_NAME + "." + MST_LocationTable.CODE_FLD + " as LocationCode ,"
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.BINID_FLD + ","
+ MST_BINTable.TABLE_NAME + "." + MST_BINTable.CODE_FLD + " as BinCode ,"
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.QASTATUS_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.LOT_FLD + ","
+ SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.SERIAL_FLD
+ " FROM " + SO_ReturnedGoodsDetailTable.TABLE_NAME
+ " Inner join " + ITM_ProductTable.TABLE_NAME + " ON " + SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.PRODUCTID_FLD + "=" + ITM_ProductTable.TABLE_NAME + "." + ITM_ProductTable.PRODUCTID_FLD
+ " left join " + MST_MasterLocationTable.TABLE_NAME + " ON " + SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.MASTERLOCATIONID_FLD + "=" + MST_MasterLocationTable.TABLE_NAME + "." + MST_MasterLocationTable.MASTERLOCATIONID_FLD
+ " left join " + MST_LocationTable.TABLE_NAME + " ON " + SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.LOCATIONID_FLD + "=" + MST_LocationTable.TABLE_NAME + "." + MST_LocationTable.LOCATIONID_FLD
+ " left join " + MST_BINTable.TABLE_NAME + " ON " + SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.BINID_FLD + "=" + MST_BINTable.TABLE_NAME + "." + MST_BINTable.BINID_FLD
+ " left join " + SO_ConfirmShipMasterTable.TABLE_NAME + " COM ON " + SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.CONFIRMSHIPMASTERID_FLD + "= COM." + SO_ConfirmShipMasterTable.CONFIRMSHIPMASTERID_FLD
+ " WHERE " + SO_ReturnedGoodsDetailTable.TABLE_NAME + "." + SO_ReturnedGoodsDetailTable.RETURNEDGOODSMASTERID_FLD + "=" + pintReturnedGoodsMasterID;
pData.Clear();
odadPCS.SelectCommand.CommandText = strSql;
odadPCS.SelectCommand.CommandType = CommandType.Text;
odadPCS.Fill(pData, SO_ReturnedGoodsDetailTable.TABLE_NAME);
pData.AcceptChanges();
}
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 if (ex.Errors[1].NativeError == ErrorCode.SQLDBNULL_VIALATION_KEYCODE)
{
throw new PCSDBException(ErrorCode.DBNULL_VIALATION, 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 UnityEngine;
namespace Codes.Linus.IntVectors
{
[Serializable]
public struct Vector2i
{
// Fields
public int x;
public int y;
// Indexer
public int this [int index]
{
get
{
switch (index)
{
case X_INDEX:
return this.x;
case Y_INDEX:
return this.y;
default:
throw new IndexOutOfRangeException ("Invalid Vector2i index!");
}
}
set
{
switch (index)
{
case X_INDEX:
this.x = value;
break;
case Y_INDEX:
this.y = value;
break;
default:
throw new IndexOutOfRangeException ("Invalid Vector2i index!");
}
}
}
// Constructors
public Vector2i (int x, int y)
{
this.x = x;
this.y = y;
}
// Properties
public float sqrMagnitude
{
get { return (float)x * x + (float)y * y; }
}
public float magnitude
{
get { return Mathf.Sqrt (sqrMagnitude); }
}
public bool IsWithinBounds (Vector2i from, Vector2i to)
{
return this.x >= from.x && this.x < to.x &&
this.y >= from.y && this.y < to.y;
}
// Set
public void Set (int new_x, int new_y)
{
this.x = new_x;
this.y = new_y;
}
// Scaling
public void Scale (Vector2i scale)
{
x *= scale.x;
y *= scale.y;
}
public static Vector2i Scale (Vector2i a, Vector2i b)
{
return new Vector2i (
a.x * b.x,
a.y * b.y
);
}
// Rotations
public void RotateCW()
{
int old_x = x;
x = y;
y = -old_x;
}
public void RotateCCW()
{
int old_x = x;
x = -y;
y = old_x;
}
public static Vector2i RotateCW(Vector2i a)
{
return new Vector2i(a.y, -a.x);
}
public static Vector2i RotateCCW(Vector2i a)
{
return new Vector2i(-a.y, a.x);
}
// Loops
public static void RectLoop (Vector2i from, Vector2i to, Action<Vector2i> body)
{
if (body == null)
{
throw new ArgumentNullException("body");
}
Vector2i iterator = Vector2i.zero;
for (iterator.x = from.x; iterator.x < to.x; iterator.x++)
{
for (iterator.y = from.y; iterator.y < to.y; iterator.y++)
{
body (iterator);
}
}
}
// ToString
public override string ToString ()
{
return string.Format ("({0}, {1})", x ,y);
}
// Operators
public static Vector2i operator + (Vector2i a, Vector2i b)
{
return new Vector2i (
a.x + b.x,
a.y + b.y
);
}
public static Vector2i operator - (Vector2i a) {
return new Vector2i (
-a.x,
-a.y
);
}
public static Vector2i operator - (Vector2i a, Vector2i b)
{
return a + (-b);
}
public static Vector2i operator * (int d, Vector2i a)
{
return new Vector2i(
d * a.x,
d * a.y
);
}
public static Vector2i operator * (Vector2i a, int d)
{
return d * a;
}
public static Vector2i operator / (Vector2i a, int d)
{
return new Vector2i(
a.x / d,
a.y / d
);
}
// Equality
public static bool operator == (Vector2i lhs, Vector2i rhs)
{
return lhs.x == rhs.x && lhs.y == rhs.y;
}
public static bool operator != (Vector2i lhs, Vector2i rhs)
{
return !(lhs == rhs);
}
public override bool Equals (object other)
{
if (!(other is Vector2i))
{
return false;
}
return this == (Vector2i)other;
}
public bool Equals (Vector2i other)
{
return this == other;
}
public override int GetHashCode ()
{
return (x.GetHashCode() << 6) ^ y.GetHashCode();
}
// Static methods
public static float Distance (Vector2i a, Vector2i b)
{
return (a - b).magnitude;
}
public static Vector2i Min(Vector2i lhs, Vector2i rhs)
{
return new Vector2i (
Mathf.Min (lhs.x, rhs.x),
Mathf.Min (lhs.y, rhs.y)
);
}
public static Vector2i Max(Vector2i a, Vector2i b)
{
return new Vector2i (
Mathf.Max (a.x, b.x),
Mathf.Max (a.y, b.y)
);
}
public static int Dot (Vector2i lhs, Vector2i rhs)
{
return lhs.x * rhs.x +
lhs.y * rhs.y;
}
public static float Magnitude(Vector2i a)
{
return a.magnitude;
}
public static float SqrMagnitude(Vector2i a)
{
return a.sqrMagnitude;
}
// Default values
public static Vector2i down
{
get { return new Vector2i (0,-1); }
}
public static Vector2i up
{
get { return new Vector2i (0,+1); }
}
public static Vector2i left
{
get { return new Vector2i (-1,0); }
}
public static Vector2i right
{
get { return new Vector2i (+1,0); }
}
public static Vector2i one
{
get { return new Vector2i (+1,+1); }
}
public static Vector2i zero
{
get { return new Vector2i (0,0); }
}
// Conversions
public static explicit operator Vector2i (Vector2 source)
{
return new Vector2i ((int)source.x, (int)source.y);
}
public static implicit operator Vector2 (Vector2i source)
{
return new Vector2 (source.x, source.y);
}
public static explicit operator Vector2i (Vector3 source)
{
return new Vector2i ((int)source.x, (int)source.y);
}
public static implicit operator Vector3 (Vector2i source)
{
return new Vector3 (source.x, source.y, 0);
}
// Constants
public const int X_INDEX = 0;
public const int Y_INDEX = 1;
}
}
| |
using Plugin.Calendars.Abstractions;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using EventKit;
using Foundation;
#nullable enable
namespace Plugin.Calendars
{
/// <summary>
/// Implementation for Calendars
/// </summary>
public class CalendarsImplementation : ICalendars
{
#region Constants
// iOS SDK provides this constant, but I'm not seeing it be exposed through Xamarin..
private const string _ekErrorDomain = "EKErrorDomain";
#endregion
#region Fields
private readonly EKEventStore _eventStore = new();
#endregion
#region ICalendars Implementation
/// <summary>
/// Gets a list of all calendars on the device.
/// </summary>
/// <returns>Calendars</returns>
/// <exception cref="System.UnauthorizedAccessException">Calendar access denied</exception>
/// <exception cref="Plugin.Calendars.Abstractions.PlatformException">Unexpected platform-specific error</exception>
public async Task<IList<Calendar>> GetCalendarsAsync()
{
await RequestCalendarAccess().ConfigureAwait(false);
var calendars = _eventStore.GetCalendars(EKEntityType.Event);
return calendars.Select(c => c.ToCalendar()).ToList();
}
/// <summary>
/// Gets a single calendar by platform-specific ID.
/// </summary>
/// <param name="externalId">Platform-specific calendar identifier</param>
/// <returns>The corresponding calendar, or null if not found</returns>
/// <exception cref="System.UnauthorizedAccessException">Calendar access denied</exception>
/// <exception cref="Plugin.Calendars.Abstractions.PlatformException">Unexpected platform-specific error</exception>
public async Task<Calendar?> GetCalendarByIdAsync(string externalId)
{
if (string.IsNullOrWhiteSpace(externalId))
{
return null;
}
await RequestCalendarAccess().ConfigureAwait(false);
var calendar = _eventStore.GetCalendar(externalId);
return calendar?.ToCalendar();
}
/// <summary>
/// Gets all events for a calendar within the specified time range.
/// </summary>
/// <param name="calendar">Calendar containing events</param>
/// <param name="start">Start of event range</param>
/// <param name="end">End of event range</param>
/// <returns>Calendar events</returns>
/// <exception cref="System.ArgumentException">Calendar does not exist on device</exception>
/// <exception cref="System.UnauthorizedAccessException">Calendar access denied</exception>
/// <exception cref="Plugin.Calendars.Abstractions.PlatformException">Unexpected platform-specific error</exception>
public async Task<IList<CalendarEvent>> GetEventsAsync(Calendar calendar, DateTime start, DateTime end)
{
if (calendar.ExternalID == null)
{
throw new ArgumentNullException("calendar.ExternalID cannot be null");
}
await RequestCalendarAccess().ConfigureAwait(false);
var deviceCalendar = _eventStore.GetCalendar(calendar.ExternalID)
?? throw new ArgumentException("Specified calendar not found on device");
var query = _eventStore.PredicateForEvents(start.ToNSDate(), end.ToNSDate(), new EKCalendar[] { deviceCalendar });
var events = await Task.Run(() =>
{
var iosEvents = _eventStore.EventsMatching(query);
return iosEvents.Select(e => e.ToCalendarEvent()).ToList();
}).ConfigureAwait(false);
return events;
}
/// <summary>
/// Gets a single calendar event by platform-specific ID.
/// </summary>
/// <param name="externalId">Platform-specific calendar event identifier</param>
/// <returns>The corresponding calendar event, or null if not found</returns>
/// <exception cref="System.UnauthorizedAccessException">Calendar access denied</exception>
/// <exception cref="Plugin.Calendars.Abstractions.PlatformException">Unexpected platform-specific error</exception>
public async Task<CalendarEvent?> GetEventByIdAsync(string externalId)
{
if (string.IsNullOrWhiteSpace(externalId))
{
return null;
}
await RequestCalendarAccess().ConfigureAwait(false);
var iosEvent = _eventStore.EventFromIdentifier(externalId);
return iosEvent?.ToCalendarEvent();
}
/// <summary>
/// Creates a new calendar or updates the name and color of an existing one.
/// If a new calendar was created, the ExternalID property will be set on the Calendar object,
/// to support future queries/updates.
/// </summary>
/// <param name="calendar">The calendar to create/update</param>
/// <exception cref="System.ArgumentException">Calendar does not exist on device or is read-only</exception>
/// <exception cref="System.UnauthorizedAccessException">Calendar access denied</exception>
/// <exception cref="System.InvalidOperationException">No active calendar sources available to create calendar on.</exception>
/// <exception cref="Plugin.Calendars.Abstractions.PlatformException">Unexpected platform-specific error</exception>
public async Task AddOrUpdateCalendarAsync(Calendar calendar)
{
if (calendar.Name == null)
{
throw new ArgumentNullException("calendar.Name cannot be null");
}
await RequestCalendarAccess().ConfigureAwait(false);
EKCalendar? deviceCalendar = null;
// TODO: Remove redundant null check after migrating to .net6
if (calendar.ExternalID != null && !string.IsNullOrEmpty(calendar.ExternalID))
{
deviceCalendar = _eventStore.GetCalendar(calendar.ExternalID)
?? throw new ArgumentException("Specified calendar does not exist on device", nameof(calendar));
}
if (deviceCalendar == null)
{
deviceCalendar = CreateEKCalendar(calendar.Name, calendar.Color);
calendar.ExternalID = deviceCalendar.CalendarIdentifier;
calendar.Color = ColorConversion.ToHexColor(deviceCalendar.CGColor);
}
else
{
deviceCalendar.Title = calendar.Name;
// TODO: Remove redundant null check after migrating to .net6
if (calendar.Color != null && !string.IsNullOrEmpty(calendar.Color))
{
deviceCalendar.CGColor = ColorConversion.ToCGColor(calendar.Color) ?? throw new ArgumentException("Invalid color");
}
if (!_eventStore.SaveCalendar(deviceCalendar, true, out NSError error))
{
// Without this, the eventStore will continue to return the "updated"
// calendar even though the save failed!
// (this obviously also resets any other changes, but since we own the eventStore
// we can be pretty confident that won't be an issue)
//
_eventStore.Reset();
if (error.Domain == _ekErrorDomain && error.Code == (int)EKErrorCode.CalendarIsImmutable)
{
throw new ArgumentException(error.LocalizedDescription, new NSErrorException(error));
}
else
{
throw new PlatformException(error.LocalizedDescription, new NSErrorException(error));
}
}
}
}
/// <summary>
/// Add new event to a calendar or update an existing event.
/// If a new event was added, the ExternalID property will be set on the CalendarEvent object,
/// to support future queries/updates.
/// Throws if Calendar ID is empty, calendar does not exist, or calendar is read-only.
/// </summary>
/// <param name="calendar">Destination calendar</param>
/// <param name="calendarEvent">Event to add or update</param>
/// <exception cref="System.ArgumentException">Calendar is not specified, does not exist on device, or is read-only</exception>
/// <exception cref="System.UnauthorizedAccessException">Calendar access denied</exception>
/// <exception cref="System.InvalidOperationException">Editing recurring events is not supported</exception>
/// <exception cref="Plugin.Calendars.Abstractions.PlatformException">Unexpected platform-specific error</exception>
public async Task AddOrUpdateEventAsync(Calendar calendar, CalendarEvent calendarEvent)
{
await RequestCalendarAccess().ConfigureAwait(false);
EKCalendar? deviceCalendar = null;
// TODO: Remove redundant null check after migrating to .net6
if (calendar.ExternalID == null || string.IsNullOrEmpty(calendar.ExternalID))
{
throw new ArgumentException("Missing calendar identifier", nameof(calendar));
}
else
{
deviceCalendar = _eventStore.GetCalendar(calendar.ExternalID);
if (deviceCalendar == null)
{
throw new ArgumentException("Specified calendar not found on device");
}
}
EKEvent? iosEvent = null;
// If Event already corresponds to an existing EKEvent in the target
// Calendar, then edit that instead of creating a new one.
//
// TODO: Remove redundant null check after migrating to .net6
if (calendarEvent.ExternalID != null && !string.IsNullOrEmpty(calendarEvent.ExternalID))
{
var existingEvent = _eventStore.EventFromIdentifier(calendarEvent.ExternalID);
if (existingEvent?.HasRecurrenceRules == true)
{
throw new InvalidOperationException("Editing recurring events is not supported");
}
if (existingEvent?.Calendar?.CalendarIdentifier == deviceCalendar.CalendarIdentifier)
{
iosEvent = existingEvent;
}
}
if (iosEvent == null)
{
iosEvent = EKEvent.FromStore(_eventStore);
}
iosEvent.Title = calendarEvent.Name;
iosEvent.Notes = calendarEvent.Description;
iosEvent.AllDay = calendarEvent.AllDay;
iosEvent.Location = calendarEvent.Location ?? string.Empty;
iosEvent.StartDate = calendarEvent.Start.ToNSDate();
// If set to AllDay and given an EndDate of 12am the next day, EventKit
// assumes that the event consumes two full days.
// (whereas WinPhone/Android consider that one day, and thus so do we)
//
iosEvent.EndDate = calendarEvent.AllDay ? calendarEvent.End.AddMilliseconds(-1).ToNSDate() : calendarEvent.End.ToNSDate();
iosEvent.Calendar = deviceCalendar;
// If the provided reminders are different from the existing alarms, replace them
//
if (calendarEvent.Reminders != null &&
!(calendarEvent.Reminders.SequenceEqual(iosEvent.Alarms?.Select(alarm => alarm.ToCalendarEventReminder()) ?? Enumerable.Empty<CalendarEventReminder>()) == true))
{
iosEvent.Alarms = calendarEvent.Reminders.Select(reminder => reminder.ToEKAlarm()).ToArray();
}
if (!_eventStore.SaveEvent(iosEvent, EKSpan.ThisEvent, out NSError error))
{
// Without this, the eventStore will continue to return the "updated"
// event even though the save failed!
// (this obviously also resets any other changes, but since we own the eventStore
// we can be pretty confident that won't be an issue)
//
_eventStore.Reset();
// Technically, probably any ekerrordomain error would be an ArgumentException?
// - but we don't necessarily know *which* argument (at least not without the code)
// - for now, just focusing on the start > end scenario and translating the rest to PlatformException. Can always add more later.
if (error.Domain == _ekErrorDomain && error.Code == (int)EKErrorCode.DatesInverted)
{
throw new ArgumentException(error.LocalizedDescription, new NSErrorException(error));
}
else
{
throw new PlatformException(error.LocalizedDescription, new NSErrorException(error));
}
}
calendarEvent.ExternalID = iosEvent.EventIdentifier;
}
/// <summary>
/// Adds an event reminder to specified calendar event
/// </summary>
/// <param name="calendarEvent">Event to add the reminder to</param>
/// <param name="reminder">The reminder</param>
/// <exception cref="ArgumentException">Calendar event is not created or not valid</exception>
/// <exception cref="System.InvalidOperationException">Editing recurring events is not supported</exception>
/// <exception cref="Plugin.Calendars.Abstractions.PlatformException">Unexpected platform-specific error</exception>
public async Task AddEventReminderAsync(CalendarEvent calendarEvent, CalendarEventReminder reminder)
{
// TODO: Remove redundant null check after migrating to .net6
if (calendarEvent.ExternalID == null || string.IsNullOrEmpty(calendarEvent.ExternalID))
{
throw new ArgumentException("Missing calendar event identifier", nameof(calendarEvent));
}
await RequestCalendarAccess().ConfigureAwait(false);
//Grab current event
var existingEvent = _eventStore.EventFromIdentifier(calendarEvent.ExternalID);
if (existingEvent == null)
{
throw new ArgumentException("Specified calendar event not found on device");
}
if (existingEvent.HasRecurrenceRules)
{
throw new InvalidOperationException("Editing recurring events is not supported");
}
existingEvent.AddAlarm(reminder.ToEKAlarm());
if (!_eventStore.SaveEvent(existingEvent, EKSpan.ThisEvent, out NSError error))
{
// Without this, the eventStore will continue to return the "updated"
// event even though the save failed!
// (this obviously also resets any other changes, but since we own the eventStore
// we can be pretty confident that won't be an issue)
//
_eventStore.Reset();
throw new ArgumentException(error.LocalizedDescription, nameof(reminder), new NSErrorException(error));
}
}
/// <summary>
/// Removes a calendar and all its events from the system.
/// </summary>
/// <param name="calendar">Calendar to delete</param>
/// <returns>True if successfully removed</returns>
/// <exception cref="System.ArgumentException">Calendar is read-only</exception>
/// <exception cref="System.UnauthorizedAccessException">Calendar access denied</exception>
/// <exception cref="Plugin.Calendars.Abstractions.PlatformException">Unexpected platform-specific error</exception>
public async Task<bool> DeleteCalendarAsync(Calendar calendar)
{
// TODO: Remove redundant null check after migrating to .net6
if (calendar.ExternalID == null || string.IsNullOrEmpty(calendar.ExternalID))
{
return false;
}
await RequestCalendarAccess().ConfigureAwait(false);
var deviceCalendar = _eventStore.GetCalendar(calendar.ExternalID);
if (deviceCalendar == null)
{
return false;
}
if (!_eventStore.RemoveCalendar(deviceCalendar, true, out NSError error))
{
// Without this, the eventStore may act like the remove succeeded.
// (this obviously also resets any other changes, but since we own the eventStore
// we can be pretty confident that won't be an issue)
//
_eventStore.Reset();
throw new ArgumentException(error.LocalizedDescription, nameof(calendar), new NSErrorException(error));
}
return true;
}
/// <summary>
/// Removes an event from the specified calendar.
/// </summary>
/// <param name="calendar">Calendar to remove event from</param>
/// <param name="calendarEvent">Event to remove</param>
/// <returns>True if successfully removed</returns>
/// <exception cref="System.ArgumentException">Calendar is read-only</exception>
/// <exception cref="System.UnauthorizedAccessException">Calendar access denied</exception>
/// <exception cref="System.InvalidOperationException">Editing recurring events is not supported</exception>
/// <exception cref="Plugin.Calendars.Abstractions.PlatformException">Unexpected platform-specific error</exception>
public async Task<bool> DeleteEventAsync(Calendar calendar, CalendarEvent calendarEvent)
{
// TODO: Remove redundant null check after migrating to .net6
if (calendar.ExternalID == null || string.IsNullOrEmpty(calendar.ExternalID)
|| calendarEvent.ExternalID == null || string.IsNullOrEmpty(calendarEvent.ExternalID))
{
return false;
}
await RequestCalendarAccess().ConfigureAwait(false);
var deviceCalendar = _eventStore.GetCalendar(calendar.ExternalID);
if (deviceCalendar == null)
{
return false;
}
var iosEvent = _eventStore.EventFromIdentifier(calendarEvent.ExternalID);
if (iosEvent?.Calendar == null || iosEvent.Calendar.CalendarIdentifier != deviceCalendar.CalendarIdentifier)
{
return false;
}
if (iosEvent.HasRecurrenceRules)
{
throw new InvalidOperationException("Editing recurring events is not supported");
}
if (!_eventStore.RemoveEvent(iosEvent, EKSpan.ThisEvent, true, out NSError error))
{
// Without this, the eventStore may act like the remove succeeded.
// (this obviously also resets any other changes, but since we own the eventStore
// we can be pretty confident that won't be an issue)
//
_eventStore.Reset();
if (error.Domain == _ekErrorDomain && error.Code == (int)EKErrorCode.CalendarReadOnly)
{
throw new ArgumentException(error.LocalizedDescription, nameof(calendar), new NSErrorException(error));
}
else
{
throw new PlatformException(error.LocalizedDescription, new NSErrorException(error));
}
}
return true;
}
#endregion
#region Private Methods
private async Task RequestCalendarAccess()
{
if (EKEventStore.GetAuthorizationStatus(EKEntityType.Event) != EKAuthorizationStatus.Authorized)
{
var accessResult = await _eventStore.RequestAccessAsync(EKEntityType.Event).ConfigureAwait(false);
bool hasAccess = accessResult.Item1;
NSError error = accessResult.Item2;
if (!hasAccess)
{
// This is the same exception WinPhone would throw
throw new UnauthorizedAccessException("Calendar access denied", error != null ? new NSErrorException(error) : null);
}
}
}
/// <summary>
/// Tries to create a new calendar with the specified source/name/color.
/// May fail depending on source.
/// </summary>
/// <remarks>
/// This is only intended as a helper method for CreateEKCalendar,
/// not to be called independently.
/// </remarks>
/// <returns>The created native calendar, or null on failure</returns>
/// <param name="source">Calendar source (e.g. iCloud vs local vs gmail)</param>
/// <param name="calendarName">Calendar name.</param>
/// <param name="color">Calendar color.</param>
private EKCalendar? SaveEKCalendar(EKSource source, string calendarName, string? color = null)
{
var calendar = EKCalendar.Create(EKEntityType.Event, _eventStore);
// Setup calendar to be inserted
//
calendar.Title = calendarName;
// TODO: Remove redundant null check after migrating to .net6
if (color != null && !string.IsNullOrEmpty(color))
{
calendar.CGColor = ColorConversion.ToCGColor(color) ?? throw new InvalidOperationException("Invalid color");
}
calendar.Source = source;
if (_eventStore.SaveCalendar(calendar, true, out NSError _))
{
Console.WriteLine($"Successfully saved calendar with source {source.Title}");
// TODO: Should we try calling GetCalendars to make sure that
// the calendar isn't hidden??
//
return calendar;
}
else
{
Console.WriteLine($"Tried and failed to save calendar with source {source.Title}");
}
_eventStore.Reset();
return null;
}
/// <summary>
/// Tries creating the specified calendar with each provided source in sequence,
/// returning the first successfully-created calendar (or null on failure).
/// </summary>
/// <returns>The created native calendar, or null on failure.</returns>
/// <param name="sources">Possible calendar sources to try</param>
/// <param name="calendarName">Calendar name.</param>
/// <param name="color">Calendar color.</param>
/// <param name="allowEmptySources">Whether to include empty sources (sources that currently lack calendars).</param>
private EKCalendar? SaveEKCalendar(IEnumerable<EKSource> sources, string calendarName,
string? color = null, bool allowEmptySources = false)
{
return sources
.Where(source => allowEmptySources || source.GetCalendars(EKEntityType.Event).Any())
.Select(source => SaveEKCalendar(source, calendarName, color))
.FirstOrDefault(cal => cal != null);
}
/// <summary>
/// Creates a new calendar.
/// </summary>
/// <remarks>
/// This crazy series of loops and save attempts is necessary because it is difficult
/// to determine which EKSource we should use for a new calendar.
/// 1. If iCloud calendars are enabled, then local device calendars will be hidden from
/// the user (and from our own GetCalendars requests), even though they still exist on device.
/// Therefore we must create new calendars with the iCloud source.
/// 2. If iCloud calendars are *not* enabled, then the opposite is true and we should go local.
/// 3. It is difficult to identify the iCloud EKSource(s?) and to even determine if iCloud
/// is enabled.
/// a. By default, the name is "iCloud." Most of the time, that will be unchanged and
/// should be an effective way to locate an/the iCloud source.
/// b. However, it *might* have changed. iOS previously allowed the user to rename it in
/// Settings. They removed that setting, but users may have already changed it.
/// Additionally, some users have discovered elaborate workarounds to change it in
/// newer versions. Because, you know, Apple took away their setting and they wanted it back.
/// So, if we don't find any "iCloud" sources, we fall back to searching for any
/// CalDav sources.
/// - This does mean that we may try storing calendars to non-iCloud CalDav sources,
/// such as Gmail. Gmail is expected to fail, which is fine and we just keep searching.
/// Uncertain if there are other possible CalDav sources that could *succeed* and
/// that we would want to avoid.
/// c. Also, the mere existence of the iCloud source does not necessarily prove that
/// iCloud calendar sync is currently enabled. Turning iCloud calendars on and off
/// may leave the source in the event store even though it's disabled. So we also
/// check that there exists at least one calendar for that source.
/// d. We do not know if we can save to a calendar source until we actually try to do
/// so. Hence the repeated save attempts.
///
/// Full lengthy discussion at https://github.com/TheAlmightyBob/Calendars/issues/10
/// </remarks>
/// <returns>The new native calendar.</returns>
/// <param name="calendarName">Calendar name.</param>
/// <param name="color">Calendar color.</param>
/// <exception cref="System.InvalidOperationException">No active calendar sources available to create calendar on.</exception>
private EKCalendar CreateEKCalendar(string calendarName, string? color = null)
{
// Log the available sources
//
Console.WriteLine("Sources:");
foreach (var source in _eventStore.Sources)
{
Console.WriteLine($"{source.Title}, {source.SourceType}");
}
// first attempt to find any and all iCloud sources
//
var iCloudSources = _eventStore.Sources.Where(s => s.SourceType == EKSourceType.CalDav &&
s.Title.Equals("icloud", StringComparison.InvariantCultureIgnoreCase));
var cal = SaveEKCalendar(iCloudSources, calendarName, color);
if (cal != null)
{
return cal;
}
// other sources that we didn't try before that are CalDav
// (may be renamed iCloud)
//
var otherSources = _eventStore.Sources.Where(s => s.SourceType == EKSourceType.CalDav &&
!s.Title.Equals("icloud", StringComparison.InvariantCultureIgnoreCase));
cal = SaveEKCalendar(otherSources, calendarName, color);
if (cal != null)
{
return cal;
}
// finally attempt just local sources
//
var localSources = _eventStore.Sources.Where(s => s.SourceType == EKSourceType.Local);
cal = SaveEKCalendar(localSources, calendarName, color, true);
if (cal != null)
{
return cal;
}
throw new InvalidOperationException("No active calendar sources available to create calendar on.");
}
#endregion
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoad.Business.ERLevel
{
/// <summary>
/// C04_SubContinent (editable child object).<br/>
/// This is a generated base class of <see cref="C04_SubContinent"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="C05_CountryObjects"/> of type <see cref="C05_CountryColl"/> (1:M relation to <see cref="C06_Country"/>)<br/>
/// This class is an item of <see cref="C03_SubContinentColl"/> collection.
/// </remarks>
[Serializable]
public partial class C04_SubContinent : BusinessBase<C04_SubContinent>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="SubContinent_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> SubContinent_IDProperty = RegisterProperty<int>(p => p.SubContinent_ID, "SubContinents ID");
/// <summary>
/// Gets the SubContinents ID.
/// </summary>
/// <value>The SubContinents ID.</value>
public int SubContinent_ID
{
get { return GetProperty(SubContinent_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="SubContinent_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> SubContinent_NameProperty = RegisterProperty<string>(p => p.SubContinent_Name, "SubContinents Name");
/// <summary>
/// Gets or sets the SubContinents Name.
/// </summary>
/// <value>The SubContinents Name.</value>
public string SubContinent_Name
{
get { return GetProperty(SubContinent_NameProperty); }
set { SetProperty(SubContinent_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="C05_SubContinent_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<C05_SubContinent_Child> C05_SubContinent_SingleObjectProperty = RegisterProperty<C05_SubContinent_Child>(p => p.C05_SubContinent_SingleObject, "C05 SubContinent Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the C05 Sub Continent Single Object ("self load" child property).
/// </summary>
/// <value>The C05 Sub Continent Single Object.</value>
public C05_SubContinent_Child C05_SubContinent_SingleObject
{
get { return GetProperty(C05_SubContinent_SingleObjectProperty); }
private set { LoadProperty(C05_SubContinent_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="C05_SubContinent_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<C05_SubContinent_ReChild> C05_SubContinent_ASingleObjectProperty = RegisterProperty<C05_SubContinent_ReChild>(p => p.C05_SubContinent_ASingleObject, "C05 SubContinent ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the C05 Sub Continent ASingle Object ("self load" child property).
/// </summary>
/// <value>The C05 Sub Continent ASingle Object.</value>
public C05_SubContinent_ReChild C05_SubContinent_ASingleObject
{
get { return GetProperty(C05_SubContinent_ASingleObjectProperty); }
private set { LoadProperty(C05_SubContinent_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="C05_CountryObjects"/> property.
/// </summary>
public static readonly PropertyInfo<C05_CountryColl> C05_CountryObjectsProperty = RegisterProperty<C05_CountryColl>(p => p.C05_CountryObjects, "C05 Country Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the C05 Country Objects ("self load" child property).
/// </summary>
/// <value>The C05 Country Objects.</value>
public C05_CountryColl C05_CountryObjects
{
get { return GetProperty(C05_CountryObjectsProperty); }
private set { LoadProperty(C05_CountryObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="C04_SubContinent"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="C04_SubContinent"/> object.</returns>
internal static C04_SubContinent NewC04_SubContinent()
{
return DataPortal.CreateChild<C04_SubContinent>();
}
/// <summary>
/// Factory method. Loads a <see cref="C04_SubContinent"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="C04_SubContinent"/> object.</returns>
internal static C04_SubContinent GetC04_SubContinent(SafeDataReader dr)
{
C04_SubContinent obj = new C04_SubContinent();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="C04_SubContinent"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public C04_SubContinent()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="C04_SubContinent"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(SubContinent_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(C05_SubContinent_SingleObjectProperty, DataPortal.CreateChild<C05_SubContinent_Child>());
LoadProperty(C05_SubContinent_ASingleObjectProperty, DataPortal.CreateChild<C05_SubContinent_ReChild>());
LoadProperty(C05_CountryObjectsProperty, DataPortal.CreateChild<C05_CountryColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="C04_SubContinent"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(SubContinent_IDProperty, dr.GetInt32("SubContinent_ID"));
LoadProperty(SubContinent_NameProperty, dr.GetString("SubContinent_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
internal void FetchChildren()
{
LoadProperty(C05_SubContinent_SingleObjectProperty, C05_SubContinent_Child.GetC05_SubContinent_Child(SubContinent_ID));
LoadProperty(C05_SubContinent_ASingleObjectProperty, C05_SubContinent_ReChild.GetC05_SubContinent_ReChild(SubContinent_ID));
LoadProperty(C05_CountryObjectsProperty, C05_CountryColl.GetC05_CountryColl(SubContinent_ID));
}
/// <summary>
/// Inserts a new <see cref="C04_SubContinent"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(C02_Continent parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddC04_SubContinent", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Parent_Continent_ID", parent.Continent_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@SubContinent_ID", ReadProperty(SubContinent_IDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@SubContinent_Name", ReadProperty(SubContinent_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(SubContinent_IDProperty, (int) cmd.Parameters["@SubContinent_ID"].Value);
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="C04_SubContinent"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateC04_SubContinent", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SubContinent_ID", ReadProperty(SubContinent_IDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@SubContinent_Name", ReadProperty(SubContinent_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="C04_SubContinent"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
// flushes all pending data operations
FieldManager.UpdateChildren(this);
using (var cmd = new SqlCommand("DeleteC04_SubContinent", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SubContinent_ID", ReadProperty(SubContinent_IDProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
// removes all previous references to children
LoadProperty(C05_SubContinent_SingleObjectProperty, DataPortal.CreateChild<C05_SubContinent_Child>());
LoadProperty(C05_SubContinent_ASingleObjectProperty, DataPortal.CreateChild<C05_SubContinent_ReChild>());
LoadProperty(C05_CountryObjectsProperty, DataPortal.CreateChild<C05_CountryColl>());
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// 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.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics.Contracts;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.IO.Compression;
using Microsoft.Research.DataStructures;
using Microsoft.Research.Cloudot.Common;
namespace Microsoft.Research.CodeAnalysis
{
public static class FileTransfer
{
#region AnalysisPackageInfo struct
public struct AnalysisPackageInfo
{
public string PackageFileNameLocal; // The package locally
public string PackageFileNameServer; // The location of the package on the server
public string[] ClousotOptions; // Original options
public string[] ExpandedClousotOptions; // Options with the response file inlined
public string[] ExpandedClousotOptionsNormalized; // options with the response file inlined and paths to UNC format. It may be null if we failed
public string[] AssembliesToAnalyze; // The Assembly to analyze
}
#endregion
#region Statics and constants
const string CloudotInstructionsFileName = @"cloudotPackageInfo.txt";
const string CloudotOptionsMarkerBegin = "((((";
const string CloudotOptionsMarkerEnd = "))))";
#endregion
#region Public surface
public static bool TryProcessPathsAndCreateAnalysisPackage(string outputDir, string[] originalClousotOptions, bool createThePackage, out AnalysisPackageInfo clousotOptions)
{
Contract.Requires(!string.IsNullOrEmpty(outputDir));
Contract.Requires(originalClousotOptions != null);
Contract.Ensures(!createThePackage || !Contract.Result<bool>() || Contract.ValueAtReturn(out clousotOptions).PackageFileNameLocal != null);
clousotOptions = new AnalysisPackageInfo();
clousotOptions.ClousotOptions = originalClousotOptions;
try
{
// Step 0: make sure the output dir exists
DirectoryInfo outputDirInfo;
if (Directory.Exists(outputDir))
{
outputDirInfo = new DirectoryInfo(outputDir);
}
else
{
outputDirInfo = Directory.CreateDirectory(outputDir);
}
// Step 1: Expand the response file, set the field
if (!FlattenClousotOptions(originalClousotOptions, out clousotOptions.ExpandedClousotOptions))
{
return false;
}
Contract.Assert(clousotOptions.ExpandedClousotOptions != null);
var pathsInTheExpandedCommandLine = ExtractPathsAndUpdateThePackageInfo(ref clousotOptions);
if (createThePackage)
{
// Step 2: Create the analysis package --- Go over all the directories and files, compress them, and save it in outputDirInfo
clousotOptions.PackageFileNameLocal = CreateAnalysisPackage(outputDirInfo, pathsInTheExpandedCommandLine, clousotOptions.ExpandedClousotOptions);
return (clousotOptions.PackageFileNameLocal != null);
}
else
{
return true;
}
}
catch (Exception)
{
// Something went wrong, we just abort
return false;
}
}
[Pure] // Even if we change the file system...
public static bool TrySendTheFile(string fromFileName, string serverOutDirName, out string packageFullNameOnTheServer)
{
Contract.Requires(!string.IsNullOrEmpty(fromFileName));
Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out packageFullNameOnTheServer) != null);
var start = DateTime.Now;
Console.WriteLine("Copying the file {0} to the server {1}".PrefixWithCurrentTime(), fromFileName, serverOutDirName);
packageFullNameOnTheServer = null;
try
{
packageFullNameOnTheServer = string.Format(@"{0}\{1}", serverOutDirName, Path.GetFileName(fromFileName));
File.Copy(fromFileName, packageFullNameOnTheServer);
}
catch (Exception e)
{
Console.WriteLine("Error in sending the file to the server. Aborting.{0}Exception{1}".PrefixWithCurrentTime(), Environment.NewLine, e.ToString());
return false;
}
Console.WriteLine("Time to copy {0}".PrefixWithCurrentTime(), DateTime.Now - start);
return true;
}
[Pure] // Even if we change the file system...
public static bool TryRestoreAnalysisPackage(string packageFileName, string outputDir, out string[] clousotNormalizedParameters)
{
Contract.Requires(packageFileName != null);
Contract.Requires(!string.IsNullOrEmpty(outputDir));
Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out clousotNormalizedParameters) != null);
clousotNormalizedParameters = null;
try
{
// Step 0: make sure the directory exists
DirectoryInfo outputDirInfo;
if (Directory.Exists(outputDir))
{
outputDirInfo = new DirectoryInfo(outputDir);
}
else
{
outputDirInfo = Directory.CreateDirectory(outputDir);
}
if(TryRestorePackage(packageFileName, outputDir))
{
clousotNormalizedParameters = ForgeClousotCommandLineFromOutputFile(outputDir);
return clousotNormalizedParameters != null;
}
return false;
}
catch(Exception e)
{
CloudotLogging.WriteLine("Something went wrong in restoring the package (exception of type {0}). Aborting.", e.GetType());
CloudotLogging.WriteLine("Exception: {0}", e);
return false;
}
}
#endregion
#region Private implementation and various helpers
[Pure] // Even if we change the file system...
private static string CreateAnalysisPackage(DirectoryInfo outputDir, List<Tuple<int, string>> paths, string[] commandLine)
{
Contract.Requires(commandLine != null);
var start = DateTime.Now;
string zipFileName;
try
{
Console.WriteLine("Creating the package".PrefixWithCurrentTime());
var mapping = new List<Tuple<string, string>>();
zipFileName = string.Format(@"{0}\{1}.{2}", outputDir.FullName, Path.GetRandomFileName(), "zip");
// Create the stream
using(var zipFile = new FileStream(zipFileName, FileMode.CreateNew))
{
// Create the archive
using(var zipArchive = new ZipArchive(zipFile, ZipArchiveMode.Create))
{
var added = new List<string>();
// TODO TODO TODO: Be smarter and avoid adding common reference assemblies, files we already uploaded, etc.
// Add all files and dirs
foreach(var path in paths)
{
// It seems that the .zip format allows to insert the same format twice.
// But we want to avoid it
if(added.Contains(path.Item2))
{
continue;
}
// We are not sure that all the paths in the options really exists in the path, so we'd better make sure it is the case
if (File.Exists(path.Item2))
{
// We should normalize with RemoveColomns as there is a bug in Windows Explorer unzip!!!
zipArchive.CreateEntryFromFile(path.Item2, RemoveColons(path.Item2), CompressionLevel.Fastest);
added.Add(path.Item2);
}
else if (Directory.Exists(path.Item2))
{
foreach (var fileInDir in Directory.GetFiles(path.Item2))
{
if(added.Contains(fileInDir))
{
continue;
}
// By some simple benchmark, it seems the Faster option is the better: it creates a slighter larger .zip but in less time that is not regained by coping things around the network
// Benchmarks:
// Build Size cp to CloudotServer
// NoCompression 1.0s 114M 11.00s
// Fastest 2.1s 26M 2.70 s
// Optimal 4.0s 21M 2.25s
// We should normalize with RemoveColomns as there is a bug in Windows Explorer unzip!!!
zipArchive.CreateEntryFromFile(fileInDir, RemoveColons(fileInDir), CompressionLevel.Fastest);
added.Add(fileInDir);
}
}
}
// Add a text file with the analysis options
// Probably we should use an xml file for that, but I love text files so much...
var readme = zipArchive.CreateEntry(CloudotInstructionsFileName);
using(var writer = new StreamWriter(readme.Open()))
{
writer.WriteLine("** Cloudot analysis package **");
writer.WriteLine("Created on {0} (Creation time {1})", start, DateTime.Now - start);
writer.WriteLine("Original command line (length {0}):", commandLine.Length);
writer.WriteLine(CloudotOptionsMarkerBegin);
foreach (var entry in commandLine)
{
writer.WriteLine(entry);
}
writer.WriteLine(CloudotOptionsMarkerEnd);
}
}
}
}
catch(Exception e)
{
Console.WriteLine("Error while creating the package. Exception of type {0}", e.GetType());
return null;
}
Console.WriteLine("[Debug] Package {0} created in {1}", zipFileName, DateTime.Now - start);
return zipFileName;
}
[Pure]
private static bool TryRestorePackage(string fileName, string outputDir)
{
var start = DateTime.Now;
try
{
CloudotLogging.WriteLine("Restoring the analysis package {0} in {1}", fileName, outputDir);
using (var zipArchive = ZipFile.OpenRead(fileName))
{
foreach(var entry in zipArchive.Entries)
{
var destinationFileName = MakeOutputFileName(outputDir, entry.FullName);
// If the file was already unzipped, skip it
if(File.Exists(destinationFileName))
{
continue; // Skip the file
}
// Make sure the destination directory exists
var dir = Path.GetDirectoryName(destinationFileName);
if(!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
entry.ExtractToFile(destinationFileName);
}
}
}
catch(Exception e)
{
CloudotLogging.WriteLine("Something went wrong in restoring the file {0} (got exception of type {1}). Aborting.", fileName, e.GetType());
return false;
}
CloudotLogging.WriteLine("Done Restoring the analysis package ({0} elapsed)", DateTime.Now - start);
return true;
}
/// <returns>May return null if something wrong happened</returns>
[Pure]
private static string[] ForgeClousotCommandLineFromOutputFile(string outputDir)
{
try
{
var lines = File.ReadAllLines(Path.Combine(outputDir, CloudotInstructionsFileName));
var result = new List<string>();
var optionsWithPaths = GeneralOptions.GetClousotOptionsWithPaths().ToArray();
var optionsBounds = FindOptions(lines);
for (var i = optionsBounds.Item1; i < optionsBounds.Item2; i++)
{
var line = lines[i];
if (line.Length > 0)
{
var subLine = line.Substring(1);
if (optionsWithPaths.Any(optionName => subLine.StartsWith(optionName)))
{
line = ReplaceVolumesWithLocalRootPath(outputDir, line);
}
else if(IsPath(line))
{
line = ReplaceVolumesWithLocalRootPath(outputDir, line);
}
}
result.Add(line);
}
return result.ToArray();
}
catch (Exception)
{
CloudotLogging.WriteLine("Something went wrong while getting the cmd line from dir {0}", outputDir);
return null;
}
}
[Pure]
private static string ReplaceVolumesWithLocalRootPath(string localRootPath, string stringToUpdate)
{
var result = stringToUpdate;
foreach (var drive in GetDrives(stringToUpdate))
{
var driveId = drive + @":\";
Contract.Assume(driveId.Length > 0);
var newPrefixReplacingDriveId = Path.Combine(localRootPath, drive + @"\");
result = stringToUpdate.Replace(driveId, newPrefixReplacingDriveId);
}
return result;
}
[Pure]
private static Tuple<int, int> FindOptions(string[] lines)
{
Contract.Ensures(Contract.Result<Tuple<int, int>>().Item1 <= Contract.Result<Tuple<int, int>>().Item2);
var begin = 0;
var end = lines.Length;
// Forward search for the begin
for(var i = 0; i < lines.Length; i++)
{
if(lines[i].Equals(CloudotOptionsMarkerBegin))
{
begin = i+1;
break;
}
}
// Backwards search for the end
for (var i = lines.Length - 1; i >= begin; i--)
{
if(lines[i].Equals(CloudotOptionsMarkerEnd))
{
end = i;
break;
}
}
return new Tuple<int, int>(begin, end);
}
[Pure]
private static char[] GetDrives(string subline)
{
var result = new List<char>();
// Search for x:\ occurrences
for(var i = 1; i < subline.Length -1 ; i++)
{
if (subline[i] == ':' && subline[i + 1] == '\\')
{
var drive = subline[i - 1];
// Add the index and the x:\ string
result.Add(drive);
}
}
return result.Distinct().ToArray();
}
[Pure]
private static string MakeOutputFileName(string outputDir, string fileName)
{
return Path.Combine(outputDir, fileName);
}
private static List<Tuple<int, string>> ExtractPathsAndUpdateThePackageInfo(ref AnalysisPackageInfo packageInfo)
{
Contract.Requires(packageInfo.ExpandedClousotOptions != null);
Contract.Ensures(packageInfo.AssembliesToAnalyze != null);
Contract.Ensures(packageInfo.ExpandedClousotOptions == Contract.OldValue(packageInfo.ExpandedClousotOptions));
var result = new List<Tuple<int, string>>();
var assembliesToAnalyse = new List<string>();
string[] expandedClousotOptions = packageInfo.ExpandedClousotOptions;
// Very stuping parsing algorithm, to be improved?
// Step 0: get the clousot options that contain paths
var clousotOptionsForPaths = GeneralOptions.GetClousotOptionsWithPaths().ToArray(); // Use ToArray to speed up the look ups
// Step 1: go all over the clousot options to find those fields, or the dirs we are interested in
for (var i = 0; i < expandedClousotOptions.Length; i++)
{
var option = expandedClousotOptions[i];
var pathsInTheOptions = GetPaths(option);
// Step 1a : Is the current option a path?
if(pathsInTheOptions.Count == 1)
{
// PrintPaths(pathsInTheOptions, "Found an assembly to analyze:");
AddIntoResult(result, i, pathsInTheOptions);
// Executed only once because of the test above
foreach (var match in pathsInTheOptions)
{
assembliesToAnalyse.Add(match.ToString());
}
}
// Step 1b : search inside the option
else
{
option = option.Substring(1); // Remove the first char
var tryFind = clousotOptionsForPaths.Where(t => option.StartsWith(t));
// Found a match
if(tryFind.Any())
{
foreach (var candidatePath in option.Split(';'))
{
var matches = GetPaths(candidatePath);
// PrintPaths(matches, "Found path(s) for option in position " + i);
AddIntoResult(result, i, matches);
}
}
}
}
// Step 2: create the normalized command line
var clonedCommandLine = packageInfo.ExpandedClousotOptions.Clone() as string[];
Contract.Assume(clonedCommandLine != null);
foreach(var pair in result)
{
string unc;
if(FileSystemAbstractions.TryGetUniversalName(Path.GetFullPath(pair.Item2), out unc))
{
clonedCommandLine[pair.Item1] = clonedCommandLine[pair.Item1].AssumeNotNull().Replace(pair.Item2, unc);
}
else
{
clonedCommandLine = null;
break;
}
}
packageInfo.AssembliesToAnalyze = assembliesToAnalyse.ToArray();
packageInfo.ExpandedClousotOptionsNormalized = clonedCommandLine;
return result;
}
private static void AddIntoResult(List<Tuple<int, string>> result, int position, MatchCollection matches)
{
Contract.Requires(result != null);
foreach(var match in matches)
{
result.Add(new Tuple<int, string>(position, match.ToString()));
}
}
[Conditional("DEBUG")]
[Pure]
private static void PrintPaths(MatchCollection pathsInTheOptions, string optionalHeadMsg = "")
{
// DEBUG code
if(!String.IsNullOrEmpty(optionalHeadMsg))
{
Console.WriteLine(optionalHeadMsg);
}
foreach (var match in pathsInTheOptions)
{
Console.WriteLine("{0}", match);
}
}
[Pure]
private static MatchCollection GetPaths(string s)
{
var regularExpression = @"(([a-z]:|\\\\[a-z0-9_.$]+\\[a-z0-9_.$]+)?(\\?(?:[^\\/:*?""<>|\r\n]+\\)+)[^\\/:*?""<>|\r\n]+)";
var regExp = new Regex(regularExpression, RegexOptions.IgnoreCase | RegexOptions.Singleline);
var matches = regExp.Matches(s);
return matches;
}
[Pure]
private static bool IsPath(string s)
{
return GetPaths(s).Count == 1;
}
[Pure]
private static bool IsDirectory(string path)
{
var attr = File.GetAttributes(path);
return ((attr & FileAttributes.Directory) == FileAttributes.Directory);
}
[Pure]
public static bool FlattenClousotOptions(string[] clousotOptions, out string[] resultOptions)
{
Contract.Requires(clousotOptions != null);
Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out resultOptions) != null);
var result = new List<string>();
for(var i = 0; i< clousotOptions.Length; i++)
{
var str = clousotOptions[i];
if(str != null && str.Length > 0 && str[0] == '@')
{
var fileName = str.Substring(1);
if (File.Exists(fileName))
{
var allText = File.ReadAllLines(fileName);
for(var j = 0; j < allText.Length; j++)
{
var line = allText[j];
if (string.IsNullOrEmpty(line))
{
continue;
}
if (line[0] == '#')
{
// It's a comment, let's skip it
continue;
}
if (ContainsQuote(line))
{
var splittedLine = SplitLineWithQuotes(line);
if (splittedLine == null)
{
goto failed;
}
result.AddRange(splittedLine);
}
else
{
// simple splitting
result.AddRange(line.Split(' '));
}
}
}
else
{
goto failed;
}
}
else
{
result.Add(str);
}
}
resultOptions = result.ToArray();
return true;
failed:
resultOptions = null;
return false;
}
#endregion
#region Helpers for parsing the response file and manipulating strings
[Pure]
private static string RemoveColons(string p)
{
return p.Replace(":", "");
}
[Pure]
static private bool ContainsQuote(string line)
{
Contract.Requires(line != null);
return (line.IndexOf('"') >= 0) || (line.IndexOf('\'') >= 0);
}
[Pure]
// Method adapted from OptionParsing.cs
// TODO: Merge the two implementations (passing a delegate for the action to perform?)
static private string[] SplitLineWithQuotes(string line)
{
Contract.Requires(line != null);
var start = 0;
var args = new List<string>();
bool inDoubleQuotes = false;
int escaping = 0; // number of escape characters in sequence
var currentArg = new StringBuilder();
for (var index = 0; index < line.Length; index++)
{
var current = line[index];
if (current == '\\')
{
// escape character
escaping++;
// swallow the escape character for now
// grab everything prior to prior escape character
if (index > start)
{
currentArg.Append(line.Substring(start, index - start));
}
start = index + 1;
continue;
}
if (escaping > 0)
{
if (current == '"')
{
var backslashes = escaping / 2;
for (int i = 0; i < backslashes; i++) { currentArg.Append('\\'); }
if (escaping % 2 == 1)
{
// escapes the "
currentArg.Append('"');
escaping = 0;
start = index + 1;
continue;
}
}
else
{
var backslashes = escaping;
for (int i = 0; i < backslashes; i++) { currentArg.Append('\\'); }
}
escaping = 0;
}
if (inDoubleQuotes)
{
if (current == '"')
{
// ending argument
FinishArgument(line, start, args, currentArg, index, true);
start = index + 1;
inDoubleQuotes = false;
continue;
}
}
else // not in quotes
{
if (Char.IsWhiteSpace(current))
{
// end previous, start new
FinishArgument(line, start, args, currentArg, index, false);
start = index + 1;
continue;
}
if (current == '"')
{
// starting double quote
if (index != start)
{
return null; // ERROR!!!!
}
start = index + 1;
inDoubleQuotes = true;
continue;
}
}
}
// add outstanding escape characters
while (escaping > 0) { currentArg.Append('\\'); escaping--; }
FinishArgument(line, start, args, currentArg, line.Length, inDoubleQuotes);
return args.ToArray();
}
[Pure]
static private void FinishArgument(string line, int start, List<string> args, StringBuilder currentArg, int index, bool includeEmpty)
{
Contract.Requires(args != null);
currentArg.Append(line.Substring(start, index - start));
if (includeEmpty || currentArg.Length > 0)
{
args.Add(currentArg.ToString());
currentArg.Length = 0;
}
}
#endregion
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// RouteFilterRulesOperations operations.
/// </summary>
public partial interface IRouteFilterRulesOperations
{
/// <summary>
/// Deletes the specified rule from a route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified rule from a route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RouteFilterRule>> GetWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a route in the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the create or update route filter rule
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RouteFilterRule>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates a route in the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the update route filter rule operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RouteFilterRule>> UpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, PatchRouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all RouteFilterRules in a route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<RouteFilterRule>>> ListByRouteFilterWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified rule from a route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a route in the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the create or update route filter rule
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RouteFilterRule>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates a route in the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the update route filter rule operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RouteFilterRule>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, PatchRouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all RouteFilterRules in a route filter.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<RouteFilterRule>>> ListByRouteFilterNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// 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.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace System.Data.SqlTypes
{
// Options that are used in comparison
[Flags]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public enum SqlCompareOptions
{
None = 0x00000000,
IgnoreCase = 0x00000001,
IgnoreNonSpace = 0x00000002,
IgnoreKanaType = 0x00000008, // ignore kanatype
IgnoreWidth = 0x00000010, // ignore width
BinarySort = 0x00008000, // binary sorting
BinarySort2 = 0x00004000, // binary sorting 2
}
/// <summary>
/// Represents a variable-length stream of characters to be stored in or retrieved from the database.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[XmlSchemaProvider("GetXsdType")]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct SqlString : INullable, IComparable, IXmlSerializable
{
private string m_value; // Do not rename (binary serialization)
private CompareInfo m_cmpInfo; // Do not rename (binary serialization)
private readonly int m_lcid; // Locale Id. Do not rename (binary serialization)
private readonly SqlCompareOptions m_flag; // Compare flags. Do not rename (binary serialization)
private bool m_fNotNull; // false if null. Do not rename (binary serialization)
/// <summary>
/// Represents a null value that can be assigned to the <see cref='System.Data.SqlTypes.SqlString.Value'/> property of an instance of
/// the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </summary>
public static readonly SqlString Null = new SqlString(true);
internal static readonly UnicodeEncoding s_unicodeEncoding = new UnicodeEncoding();
/// <summary>
/// </summary>
public static readonly int IgnoreCase = 0x1;
/// <summary>
/// </summary>
public static readonly int IgnoreWidth = 0x10;
/// <summary>
/// </summary>
public static readonly int IgnoreNonSpace = 0x2;
/// <summary>
/// </summary>
public static readonly int IgnoreKanaType = 0x8;
/// <summary>
/// </summary>
public static readonly int BinarySort = 0x8000;
/// <summary>
/// </summary>
public static readonly int BinarySort2 = 0x4000;
private const SqlCompareOptions s_iDefaultFlag =
SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType |
SqlCompareOptions.IgnoreWidth;
private const CompareOptions s_iValidCompareOptionMask =
CompareOptions.IgnoreCase | CompareOptions.IgnoreWidth |
CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreKanaType;
internal const SqlCompareOptions s_iValidSqlCompareOptionMask =
SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreWidth |
SqlCompareOptions.IgnoreNonSpace | SqlCompareOptions.IgnoreKanaType |
SqlCompareOptions.BinarySort | SqlCompareOptions.BinarySort2;
internal const int s_lcidUSEnglish = 0x00000409;
private const int s_lcidBinary = 0x00008200;
// constructor
// construct a Null
private SqlString(bool fNull)
{
m_value = null;
m_cmpInfo = null;
m_lcid = 0;
m_flag = SqlCompareOptions.None;
m_fNotNull = false;
}
// Constructor: Construct from both Unicode and NonUnicode data, according to fUnicode
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </summary>
public SqlString(int lcid, SqlCompareOptions compareOptions, byte[] data, int index, int count, bool fUnicode)
{
m_lcid = lcid;
ValidateSqlCompareOptions(compareOptions);
m_flag = compareOptions;
if (data == null)
{
m_fNotNull = false;
m_value = null;
m_cmpInfo = null;
}
else
{
m_fNotNull = true;
// m_cmpInfo is set lazily, so that we don't need to pay the cost
// unless the string is used in comparison.
m_cmpInfo = null;
if (fUnicode)
{
m_value = s_unicodeEncoding.GetString(data, index, count);
}
else
{
CultureInfo culInfo = new CultureInfo(m_lcid);
Encoding cpe = System.Text.Encoding.GetEncoding(culInfo.TextInfo.ANSICodePage);
m_value = cpe.GetString(data, index, count);
}
}
}
// Constructor: Construct from both Unicode and NonUnicode data, according to fUnicode
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </summary>
public SqlString(int lcid, SqlCompareOptions compareOptions, byte[] data, bool fUnicode)
: this(lcid, compareOptions, data, 0, data.Length, fUnicode)
{
}
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </summary>
public SqlString(int lcid, SqlCompareOptions compareOptions, byte[] data, int index, int count)
: this(lcid, compareOptions, data, index, count, true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </summary>
public SqlString(int lcid, SqlCompareOptions compareOptions, byte[] data)
: this(lcid, compareOptions, data, 0, data.Length, true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </summary>
public SqlString(string data, int lcid, SqlCompareOptions compareOptions)
{
m_lcid = lcid;
ValidateSqlCompareOptions(compareOptions);
m_flag = compareOptions;
m_cmpInfo = null;
if (data == null)
{
m_fNotNull = false;
m_value = null;
}
else
{
m_fNotNull = true;
m_value = data; // PERF: do not String.Copy
}
}
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </summary>
public SqlString(string data, int lcid) : this(data, lcid, s_iDefaultFlag)
{
}
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </summary>
public SqlString(string data) : this(data, System.Globalization.CultureInfo.CurrentCulture.LCID, s_iDefaultFlag)
{
}
private SqlString(int lcid, SqlCompareOptions compareOptions, string data, CompareInfo cmpInfo)
{
m_lcid = lcid;
ValidateSqlCompareOptions(compareOptions);
m_flag = compareOptions;
if (data == null)
{
m_fNotNull = false;
m_value = null;
m_cmpInfo = null;
}
else
{
m_value = data;
m_cmpInfo = cmpInfo;
m_fNotNull = true;
}
}
// INullable
/// <summary>
/// Gets whether the <see cref='System.Data.SqlTypes.SqlString.Value'/> of the <see cref='System.Data.SqlTypes.SqlString'/> is <see cref='System.Data.SqlTypes.SqlString.Null'/>.
/// </summary>
public bool IsNull
{
get { return !m_fNotNull; }
}
// property: Value
/// <summary>
/// Gets the string that is to be stored.
/// </summary>
public string Value
{
get
{
if (!IsNull)
return m_value;
else
throw new SqlNullValueException();
}
}
public int LCID
{
get
{
if (!IsNull)
return m_lcid;
else
throw new SqlNullValueException();
}
}
public CultureInfo CultureInfo
{
get
{
if (!IsNull)
return CultureInfo.GetCultureInfo(m_lcid);
else
throw new SqlNullValueException();
}
}
private void SetCompareInfo()
{
Debug.Assert(!IsNull);
if (m_cmpInfo == null)
m_cmpInfo = (CultureInfo.GetCultureInfo(m_lcid)).CompareInfo;
}
public CompareInfo CompareInfo
{
get
{
if (!IsNull)
{
SetCompareInfo();
return m_cmpInfo;
}
else
throw new SqlNullValueException();
}
}
public SqlCompareOptions SqlCompareOptions
{
get
{
if (!IsNull)
return m_flag;
else
throw new SqlNullValueException();
}
}
// Implicit conversion from String to SqlString
public static implicit operator SqlString(string x)
{
return new SqlString(x);
}
// Explicit conversion from SqlString to String. Throw exception if x is Null.
public static explicit operator string(SqlString x)
{
return x.Value;
}
/// <summary>
/// Converts a <see cref='System.Data.SqlTypes.SqlString'/> object to a string.
/// </summary>
public override string ToString()
{
return IsNull ? SQLResource.NullString : m_value;
}
public byte[] GetUnicodeBytes()
{
if (IsNull)
return null;
return s_unicodeEncoding.GetBytes(m_value);
}
public byte[] GetNonUnicodeBytes()
{
if (IsNull)
return null;
// Get the CultureInfo
CultureInfo culInfo = new CultureInfo(m_lcid);
Encoding cpe = System.Text.Encoding.GetEncoding(culInfo.TextInfo.ANSICodePage);
return cpe.GetBytes(m_value);
}
/*
internal int GetSQLCID() {
if (IsNull)
throw new SqlNullValueException();
return MAKECID(m_lcid, m_flag);
}
*/
// Binary operators
// Concatenation
public static SqlString operator +(SqlString x, SqlString y)
{
if (x.IsNull || y.IsNull)
return SqlString.Null;
if (x.m_lcid != y.m_lcid || x.m_flag != y.m_flag)
throw new SqlTypeException(SQLResource.ConcatDiffCollationMessage);
return new SqlString(x.m_lcid, x.m_flag, x.m_value + y.m_value,
(x.m_cmpInfo == null) ? y.m_cmpInfo : x.m_cmpInfo);
}
// StringCompare: Common compare function which is used by Compare and CompareTo
// In the case of Compare (used by comparison operators) the int result needs to be converted to SqlBoolean type
// while CompareTo needs the result in int type
// Pre-requisite: the null condition of the both string needs to be checked and handled by the caller of this function
private static int StringCompare(SqlString x, SqlString y)
{
Debug.Assert(!x.IsNull && !y.IsNull,
"!x.IsNull && !y.IsNull", "Null condition should be handled by the caller of StringCompare method");
if (x.m_lcid != y.m_lcid || x.m_flag != y.m_flag)
throw new SqlTypeException(SQLResource.CompareDiffCollationMessage);
x.SetCompareInfo();
y.SetCompareInfo();
Debug.Assert(x.FBinarySort() || (x.m_cmpInfo != null && y.m_cmpInfo != null),
"x.FBinarySort() || (x.m_cmpInfo != null && y.m_cmpInfo != null)", "");
int iCmpResult;
if ((x.m_flag & SqlCompareOptions.BinarySort) != 0)
iCmpResult = CompareBinary(x, y);
else if ((x.m_flag & SqlCompareOptions.BinarySort2) != 0)
iCmpResult = CompareBinary2(x, y);
else
{
// SqlString can be padded with spaces (Padding is turn on by default in SQL Server 2008
// Trim the trailing space for comparison
// Avoid using String.TrimEnd function to avoid extra string allocations
string rgchX = x.m_value;
string rgchY = y.m_value;
int cwchX = rgchX.Length;
int cwchY = rgchY.Length;
while (cwchX > 0 && rgchX[cwchX - 1] == ' ')
cwchX--;
while (cwchY > 0 && rgchY[cwchY - 1] == ' ')
cwchY--;
CompareOptions options = CompareOptionsFromSqlCompareOptions(x.m_flag);
iCmpResult = x.m_cmpInfo.Compare(x.m_value, 0, cwchX, y.m_value, 0, cwchY, options);
}
return iCmpResult;
}
// Comparison operators
private static SqlBoolean Compare(SqlString x, SqlString y, EComparison ecExpectedResult)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
int iCmpResult = StringCompare(x, y);
bool fResult = false;
switch (ecExpectedResult)
{
case EComparison.EQ:
fResult = (iCmpResult == 0);
break;
case EComparison.LT:
fResult = (iCmpResult < 0);
break;
case EComparison.LE:
fResult = (iCmpResult <= 0);
break;
case EComparison.GT:
fResult = (iCmpResult > 0);
break;
case EComparison.GE:
fResult = (iCmpResult >= 0);
break;
default:
Debug.Fail("Invalid ecExpectedResult");
return SqlBoolean.Null;
}
return new SqlBoolean(fResult);
}
// Implicit conversions
// Explicit conversions
// Explicit conversion from SqlBoolean to SqlString
public static explicit operator SqlString(SqlBoolean x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString());
}
// Explicit conversion from SqlByte to SqlString
public static explicit operator SqlString(SqlByte x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlInt16 to SqlString
public static explicit operator SqlString(SqlInt16 x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlInt32 to SqlString
public static explicit operator SqlString(SqlInt32 x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlInt64 to SqlString
public static explicit operator SqlString(SqlInt64 x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlSingle to SqlString
public static explicit operator SqlString(SqlSingle x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlDouble to SqlString
public static explicit operator SqlString(SqlDouble x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlDecimal to SqlString
public static explicit operator SqlString(SqlDecimal x)
{
return x.IsNull ? Null : new SqlString(x.ToString());
}
// Explicit conversion from SqlMoney to SqlString
public static explicit operator SqlString(SqlMoney x)
{
return x.IsNull ? Null : new SqlString(x.ToString());
}
// Explicit conversion from SqlDateTime to SqlString
public static explicit operator SqlString(SqlDateTime x)
{
return x.IsNull ? Null : new SqlString(x.ToString());
}
// Explicit conversion from SqlGuid to SqlString
public static explicit operator SqlString(SqlGuid x)
{
return x.IsNull ? Null : new SqlString(x.ToString());
}
public SqlString Clone()
{
if (IsNull)
return new SqlString(true);
else
{
SqlString ret = new SqlString(m_value, m_lcid, m_flag);
return ret;
}
}
// Overloading comparison operators
public static SqlBoolean operator ==(SqlString x, SqlString y)
{
return Compare(x, y, EComparison.EQ);
}
public static SqlBoolean operator !=(SqlString x, SqlString y)
{
return !(x == y);
}
public static SqlBoolean operator <(SqlString x, SqlString y)
{
return Compare(x, y, EComparison.LT);
}
public static SqlBoolean operator >(SqlString x, SqlString y)
{
return Compare(x, y, EComparison.GT);
}
public static SqlBoolean operator <=(SqlString x, SqlString y)
{
return Compare(x, y, EComparison.LE);
}
public static SqlBoolean operator >=(SqlString x, SqlString y)
{
return Compare(x, y, EComparison.GE);
}
//--------------------------------------------------
// Alternative methods for overloaded operators
//--------------------------------------------------
// Alternative method for operator +
public static SqlString Concat(SqlString x, SqlString y)
{
return x + y;
}
public static SqlString Add(SqlString x, SqlString y)
{
return x + y;
}
// Alternative method for operator ==
public static SqlBoolean Equals(SqlString x, SqlString y)
{
return (x == y);
}
// Alternative method for operator !=
public static SqlBoolean NotEquals(SqlString x, SqlString y)
{
return (x != y);
}
// Alternative method for operator <
public static SqlBoolean LessThan(SqlString x, SqlString y)
{
return (x < y);
}
// Alternative method for operator >
public static SqlBoolean GreaterThan(SqlString x, SqlString y)
{
return (x > y);
}
// Alternative method for operator <=
public static SqlBoolean LessThanOrEqual(SqlString x, SqlString y)
{
return (x <= y);
}
// Alternative method for operator >=
public static SqlBoolean GreaterThanOrEqual(SqlString x, SqlString y)
{
return (x >= y);
}
// Alternative method for conversions.
public SqlBoolean ToSqlBoolean()
{
return (SqlBoolean)this;
}
public SqlByte ToSqlByte()
{
return (SqlByte)this;
}
public SqlDateTime ToSqlDateTime()
{
return (SqlDateTime)this;
}
public SqlDouble ToSqlDouble()
{
return (SqlDouble)this;
}
public SqlInt16 ToSqlInt16()
{
return (SqlInt16)this;
}
public SqlInt32 ToSqlInt32()
{
return (SqlInt32)this;
}
public SqlInt64 ToSqlInt64()
{
return (SqlInt64)this;
}
public SqlMoney ToSqlMoney()
{
return (SqlMoney)this;
}
public SqlDecimal ToSqlDecimal()
{
return (SqlDecimal)this;
}
public SqlSingle ToSqlSingle()
{
return (SqlSingle)this;
}
public SqlGuid ToSqlGuid()
{
return (SqlGuid)this;
}
// Utility functions and constants
private static void ValidateSqlCompareOptions(SqlCompareOptions compareOptions)
{
if ((compareOptions & s_iValidSqlCompareOptionMask) != compareOptions)
throw new ArgumentOutOfRangeException(nameof(compareOptions));
}
public static CompareOptions CompareOptionsFromSqlCompareOptions(SqlCompareOptions compareOptions)
{
CompareOptions options = CompareOptions.None;
ValidateSqlCompareOptions(compareOptions);
if ((compareOptions & (SqlCompareOptions.BinarySort | SqlCompareOptions.BinarySort2)) != 0)
throw ADP.ArgumentOutOfRange(nameof(compareOptions));
else
{
if ((compareOptions & SqlCompareOptions.IgnoreCase) != 0)
options |= CompareOptions.IgnoreCase;
if ((compareOptions & SqlCompareOptions.IgnoreNonSpace) != 0)
options |= CompareOptions.IgnoreNonSpace;
if ((compareOptions & SqlCompareOptions.IgnoreKanaType) != 0)
options |= CompareOptions.IgnoreKanaType;
if ((compareOptions & SqlCompareOptions.IgnoreWidth) != 0)
options |= CompareOptions.IgnoreWidth;
}
return options;
}
private bool FBinarySort()
{
return (!IsNull && (m_flag & (SqlCompareOptions.BinarySort | SqlCompareOptions.BinarySort2)) != 0);
}
// Wide-character string comparison for Binary Unicode Collation
// Return values:
// -1 : wstr1 < wstr2
// 0 : wstr1 = wstr2
// 1 : wstr1 > wstr2
//
// Does a memory comparison.
private static int CompareBinary(SqlString x, SqlString y)
{
byte[] rgDataX = s_unicodeEncoding.GetBytes(x.m_value);
byte[] rgDataY = s_unicodeEncoding.GetBytes(y.m_value);
int cbX = rgDataX.Length;
int cbY = rgDataY.Length;
int cbMin = cbX < cbY ? cbX : cbY;
int i;
Debug.Assert(cbX % 2 == 0);
Debug.Assert(cbY % 2 == 0);
for (i = 0; i < cbMin; i++)
{
if (rgDataX[i] < rgDataY[i])
return -1;
else if (rgDataX[i] > rgDataY[i])
return 1;
}
i = cbMin;
int iCh;
int iSpace = ' ';
if (cbX < cbY)
{
for (; i < cbY; i += 2)
{
iCh = rgDataY[i + 1] << 8 + rgDataY[i];
if (iCh != iSpace)
return (iSpace > iCh) ? 1 : -1;
}
}
else
{
for (; i < cbX; i += 2)
{
iCh = rgDataX[i + 1] << 8 + rgDataX[i];
if (iCh != iSpace)
return (iCh > iSpace) ? 1 : -1;
}
}
return 0;
}
// Wide-character string comparison for Binary2 Unicode Collation
// Return values:
// -1 : wstr1 < wstr2
// 0 : wstr1 = wstr2
// 1 : wstr1 > wstr2
//
// Does a wchar comparison (different from memcmp of BinarySort).
private static int CompareBinary2(SqlString x, SqlString y)
{
Debug.Assert(!x.IsNull && !y.IsNull);
string rgDataX = x.m_value;
string rgDataY = y.m_value;
int cwchX = rgDataX.Length;
int cwchY = rgDataY.Length;
int cwchMin = cwchX < cwchY ? cwchX : cwchY;
int i;
for (i = 0; i < cwchMin; i++)
{
if (rgDataX[i] < rgDataY[i])
return -1;
else if (rgDataX[i] > rgDataY[i])
return 1;
}
// If compares equal up to one of the string terminates,
// pad it with spaces and compare with the rest of the other one.
//
char chSpace = ' ';
if (cwchX < cwchY)
{
for (i = cwchMin; i < cwchY; i++)
{
if (rgDataY[i] != chSpace)
return (chSpace > rgDataY[i]) ? 1 : -1;
}
}
else
{
for (i = cwchMin; i < cwchX; i++)
{
if (rgDataX[i] != chSpace)
return (rgDataX[i] > chSpace) ? 1 : -1;
}
}
return 0;
}
/*
private void Print() {
Debug.WriteLine("SqlString - ");
Debug.WriteLine("\tlcid = " + m_lcid.ToString());
Debug.Write("\t");
if ((m_flag & SqlCompareOptions.IgnoreCase) != 0)
Debug.Write("IgnoreCase, ");
if ((m_flag & SqlCompareOptions.IgnoreNonSpace) != 0)
Debug.Write("IgnoreNonSpace, ");
if ((m_flag & SqlCompareOptions.IgnoreKanaType) != 0)
Debug.Write("IgnoreKanaType, ");
if ((m_flag & SqlCompareOptions.IgnoreWidth) != 0)
Debug.Write("IgnoreWidth, ");
Debug.WriteLine("");
Debug.WriteLine("\tvalue = " + m_value);
Debug.WriteLine("\tcmpinfo = " + m_cmpInfo);
}
*/
// IComparable
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this < object, zero if this = object,
// or a value greater than zero if this > object.
// null is considered to be less than any instance.
// If object is not of same type, this method throws an ArgumentException.
public int CompareTo(object value)
{
if (value is SqlString)
{
SqlString i = (SqlString)value;
return CompareTo(i);
}
throw ADP.WrongType(value.GetType(), typeof(SqlString));
}
public int CompareTo(SqlString value)
{
// If both Null, consider them equal.
// Otherwise, Null is less than anything.
if (IsNull)
return value.IsNull ? 0 : -1;
else if (value.IsNull)
return 1;
int returnValue = StringCompare(this, value);
// Conver the result into -1, 0, or 1 as this method never returned any other values
// This is to ensure the backcompat
if (returnValue < 0)
{
return -1;
}
if (returnValue > 0)
{
return 1;
}
return 0;
}
// Compares this instance with a specified object
public override bool Equals(object value)
{
if (!(value is SqlString))
{
return false;
}
SqlString i = (SqlString)value;
if (i.IsNull || IsNull)
return (i.IsNull && IsNull);
else
return (this == i).Value;
}
// For hashing purpose
public override int GetHashCode()
{
if (IsNull)
return 0;
byte[] rgbSortKey;
if (FBinarySort())
rgbSortKey = s_unicodeEncoding.GetBytes(m_value.TrimEnd());
else
{
// GetHashCode should not throw just because this instance has an invalid LCID or compare options.
CompareInfo cmpInfo;
CompareOptions options;
try
{
SetCompareInfo();
cmpInfo = m_cmpInfo;
options = CompareOptionsFromSqlCompareOptions(m_flag);
}
catch (ArgumentException)
{
// SetCompareInfo throws this when instance's LCID is unsupported
// CompareOptionsFromSqlCompareOptions throws this when instance's options are invalid
cmpInfo = CultureInfo.InvariantCulture.CompareInfo;
options = CompareOptions.None;
}
rgbSortKey = cmpInfo.GetSortKey(m_value.TrimEnd(), options).KeyData;
}
return SqlBinary.HashByteArray(rgbSortKey, rgbSortKey.Length);
}
XmlSchema IXmlSerializable.GetSchema() { return null; }
void IXmlSerializable.ReadXml(XmlReader reader)
{
string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace);
if (isNull != null && XmlConvert.ToBoolean(isNull))
{
// Read the next value.
reader.ReadElementString();
m_fNotNull = false;
}
else
{
m_value = reader.ReadElementString();
m_fNotNull = true;
}
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
if (IsNull)
{
writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true");
}
else
{
writer.WriteString(m_value);
}
}
public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet)
{
return new XmlQualifiedName("string", XmlSchema.Namespace);
}
} // SqlString
/*
internal struct SLocaleMapItem {
public int lcid; // the primary key, not nullable
public String name; // unique, nullable
public int idCodePage; // the ANSI default code page of the locale
public SLocaleMapItem(int lid, String str, int cpid) {
lcid = lid;
name = str;
idCodePage = cpid;
}
}
// Struct to map lcid to ordinal
internal struct SLcidOrdMapItem {
internal int lcid;
internal int uiOrd;
};
// Class to store map of lcids to ordinal
internal class CBuildLcidOrdMap {
internal SLcidOrdMapItem[] m_rgLcidOrdMap;
internal int m_cValidLocales;
internal int m_uiPosEnglish; // Start binary searches here - this is index in array, not ordinal
// Constructor builds the array sorted by lcid
// We use a simple n**2 sort because the array is mostly sorted anyway
// and objects of this class will be const, hence this will be called
// only by VC compiler
public CBuildLcidOrdMap() {
int i,j;
m_rgLcidOrdMap = new SLcidOrdMapItem[SqlString.x_cLocales];
// Compact the array
for (i=0,j=0; i < SqlString.x_cLocales; i++) {
if (SqlString.x_rgLocaleMap[i].lcid != SqlString.x_lcidUnused) {
m_rgLcidOrdMap[j].lcid = SqlString.x_rgLocaleMap[i].lcid;
m_rgLcidOrdMap[j].uiOrd = i;
j++;
}
}
m_cValidLocales = j;
// Set the rest to invalid
while (j < SqlString.x_cLocales) {
m_rgLcidOrdMap[j].lcid = SqlString.x_lcidUnused;
m_rgLcidOrdMap[j].uiOrd = 0;
j++;
}
// Now sort in place
// Algo:
// Start from 1, assume list before i is sorted, if next item
// violates this assumption, exchange with prev items until the
// item is in its correct place
for (i=1; i<m_cValidLocales; i++) {
for (j=i; j>0 &&
m_rgLcidOrdMap[j].lcid < m_rgLcidOrdMap[j-1].lcid; j--) {
// Swap with prev element
int lcidTemp = m_rgLcidOrdMap[j-1].lcid;
int uiOrdTemp = m_rgLcidOrdMap[j-1].uiOrd;
m_rgLcidOrdMap[j-1].lcid = m_rgLcidOrdMap[j].lcid;
m_rgLcidOrdMap[j-1].uiOrd = m_rgLcidOrdMap[j].uiOrd;
m_rgLcidOrdMap[j].lcid = lcidTemp;
m_rgLcidOrdMap[j].uiOrd = uiOrdTemp;
}
}
// Set the position of the US_English LCID (Latin1_General)
for (i=0; i<m_cValidLocales && m_rgLcidOrdMap[i].lcid != SqlString.x_lcidUSEnglish; i++)
; // Deliberately empty
Debug.Assert(i<m_cValidLocales); // Latin1_General better be present
m_uiPosEnglish = i; // This is index in array, not ordinal
}
} // CBuildLcidOrdMap
*/
} // namespace System.Data.SqlTypes
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Xunit;
public class ReadAndWrite
{
[Fact]
public static void WriteOverloads()
{
TextWriter savedStandardOutput = Console.Out;
try
{
using (MemoryStream memStream = new MemoryStream())
{
using (StreamWriter sw = new StreamWriter(memStream))
{
Console.SetOut(sw);
WriteCore();
}
}
}
finally
{
Console.SetOut(savedStandardOutput);
}
}
[Fact]
public static void WriteToOutputStream_EmptyArray()
{
Stream outStream = Console.OpenStandardOutput();
outStream.Write(new byte[] { }, 0, 0);
}
[Fact]
[OuterLoop]
public static void WriteOverloadsToRealConsole()
{
WriteCore();
}
[Fact]
public static void WriteLineOverloads()
{
TextWriter savedStandardOutput = Console.Out;
try
{
using (MemoryStream memStream = new MemoryStream())
{
using (StreamWriter sw = new StreamWriter(memStream))
{
Console.SetOut(sw);
WriteLineCore();
}
}
}
finally
{
Console.SetOut(savedStandardOutput);
}
}
[Fact]
[OuterLoop]
public static void WriteLineOverloadsToRealConsole()
{
WriteLineCore();
}
private static void WriteCore()
{
// We just want to ensure none of these throw exceptions, we don't actually validate
// what was written.
Console.Write("{0}", 32);
Console.Write("{0}", null);
Console.Write("{0} {1}", 32, "Hello");
Console.Write("{0}", null, null);
Console.Write("{0} {1} {2}", 32, "Hello", (uint)50);
Console.Write("{0}", null, null, null);
Console.Write("{0} {1} {2} {3}", 32, "Hello", (uint)50, (ulong)5);
Console.Write("{0}", null, null, null, null);
Console.Write("{0} {1} {2} {3} {4}", 32, "Hello", (uint)50, (ulong)5, 'a');
Console.Write("{0}", null, null, null, null, null);
Console.Write(true);
Console.Write('a');
Console.Write(new char[] { 'a', 'b', 'c', 'd', });
Console.Write(new char[] { 'a', 'b', 'c', 'd', }, 1, 2);
Console.Write(1.23d);
Console.Write(123.456M);
Console.Write(1.234f);
Console.Write(39);
Console.Write(50u);
Console.Write(50L);
Console.Write(50UL);
Console.Write(new object());
Console.Write("Hello World");
}
private static void WriteLineCore()
{
Assert.Equal(Environment.NewLine, Console.Out.NewLine);
Console.Out.NewLine = "abcd";
Assert.Equal("abcd", Console.Out.NewLine);
Console.Out.NewLine = Environment.NewLine;
// We just want to ensure none of these throw exceptions, we don't actually validate
// what was written.
Console.WriteLine();
Console.WriteLine("{0}", 32);
Console.WriteLine("{0}", null);
Console.WriteLine("{0} {1}", 32, "Hello");
Console.WriteLine("{0}", null, null);
Console.WriteLine("{0} {1} {2}", 32, "Hello", (uint)50);
Console.WriteLine("{0}", null, null, null);
Console.WriteLine("{0} {1} {2} {3}", 32, "Hello", (uint)50, (ulong)5);
Console.WriteLine("{0}", null, null, null, null);
Console.WriteLine("{0} {1} {2} {3} {4}", 32, "Hello", (uint)50, (ulong)5, 'a');
Console.WriteLine("{0}", null, null, null, null, null);
Console.WriteLine(true);
Console.WriteLine('a');
Console.WriteLine(new char[] { 'a', 'b', 'c', 'd', });
Console.WriteLine(new char[] { 'a', 'b', 'c', 'd', }, 1, 2);
Console.WriteLine(1.23);
Console.WriteLine(123.456M);
Console.WriteLine(1.234f);
Console.WriteLine(39);
Console.WriteLine(50u);
Console.WriteLine(50L);
Console.WriteLine(50UL);
Console.WriteLine(new object());
Console.WriteLine("Hello World");
}
[Fact]
public static async Task OutWriteAndWriteLineOverloads()
{
TextWriter savedStandardOutput = Console.Out;
try
{
using (var sw = new StreamWriter(new MemoryStream()))
{
Console.SetOut(sw);
TextWriter writer = Console.Out;
Assert.NotNull(writer);
Assert.NotEqual(writer, sw); // the writer we provide gets wrapped
// We just want to ensure none of these throw exceptions, we don't actually validate
// what was written.
writer.Write("{0}", 32);
writer.Write("{0} {1}", 32, "Hello");
writer.Write("{0} {1} {2}", 32, "Hello", (uint)50);
writer.Write("{0} {1} {2} {3}", 32, "Hello", (uint)50, (ulong)5);
writer.Write("{0} {1} {2} {3} {4}", 32, "Hello", (uint)50, (ulong)5, 'a');
writer.Write(true);
writer.Write('a');
writer.Write(new char[] { 'a', 'b', 'c', 'd', });
writer.Write(new char[] { 'a', 'b', 'c', 'd', }, 1, 2);
writer.Write(1.23d);
writer.Write(123.456M);
writer.Write(1.234f);
writer.Write(39);
writer.Write(50u);
writer.Write(50L);
writer.Write(50UL);
writer.Write(new object());
writer.Write("Hello World");
writer.Flush();
await writer.WriteAsync('c');
await writer.WriteAsync(new char[] { 'a', 'b', 'c', 'd' });
await writer.WriteAsync(new char[] { 'a', 'b', 'c', 'd' }, 1, 2);
await writer.WriteAsync("Hello World");
await writer.WriteLineAsync('c');
await writer.WriteLineAsync(new char[] { 'a', 'b', 'c', 'd' });
await writer.WriteLineAsync(new char[] { 'a', 'b', 'c', 'd' }, 1, 2);
await writer.WriteLineAsync("Hello World");
await writer.FlushAsync();
}
}
finally
{
Console.SetOut(savedStandardOutput);
}
}
public static unsafe void ValidateConsoleEncoding(Encoding encoding)
{
Assert.NotNull(encoding);
// The primary purpose of ConsoleEncoding is to return an empty preamble.
Assert.Equal(Array.Empty<byte>(), encoding.GetPreamble());
// There's not much validation we can do, but we can at least invoke members
// to ensure they don't throw exceptions as they delegate to the underlying
// encoding wrapped by ConsoleEncoding.
Assert.False(string.IsNullOrWhiteSpace(encoding.EncodingName));
Assert.False(string.IsNullOrWhiteSpace(encoding.WebName));
Assert.True(encoding.CodePage >= 0);
bool ignored = encoding.IsSingleByte;
// And we can validate that the encoding is self-consistent by roundtripping
// data between chars and bytes.
string str = "This is the input string.";
char[] strAsChars = str.ToCharArray();
byte[] strAsBytes = encoding.GetBytes(str);
Assert.Equal(strAsBytes.Length, encoding.GetByteCount(str));
Assert.True(encoding.GetMaxByteCount(str.Length) >= strAsBytes.Length);
Assert.Equal(str, encoding.GetString(strAsBytes));
Assert.Equal(str, encoding.GetString(strAsBytes, 0, strAsBytes.Length));
Assert.Equal(str, new string(encoding.GetChars(strAsBytes)));
Assert.Equal(str, new string(encoding.GetChars(strAsBytes, 0, strAsBytes.Length)));
fixed (byte* bytesPtr = strAsBytes)
{
char[] outputArr = new char[encoding.GetMaxCharCount(strAsBytes.Length)];
int len = encoding.GetChars(strAsBytes, 0, strAsBytes.Length, outputArr, 0);
Assert.Equal(str, new string(outputArr, 0, len));
Assert.Equal(len, encoding.GetCharCount(strAsBytes));
Assert.Equal(len, encoding.GetCharCount(strAsBytes, 0, strAsBytes.Length));
fixed (char* charsPtr = outputArr)
{
len = encoding.GetChars(bytesPtr, strAsBytes.Length, charsPtr, outputArr.Length);
Assert.Equal(str, new string(charsPtr, 0, len));
Assert.Equal(len, encoding.GetCharCount(bytesPtr, strAsBytes.Length));
}
Assert.Equal(str, encoding.GetString(bytesPtr, strAsBytes.Length));
}
Assert.Equal(strAsBytes, encoding.GetBytes(strAsChars));
Assert.Equal(strAsBytes, encoding.GetBytes(strAsChars, 0, strAsChars.Length));
Assert.Equal(strAsBytes.Length, encoding.GetByteCount(strAsChars));
Assert.Equal(strAsBytes.Length, encoding.GetByteCount(strAsChars, 0, strAsChars.Length));
fixed (char* charsPtr = strAsChars)
{
Assert.Equal(strAsBytes.Length, encoding.GetByteCount(charsPtr, strAsChars.Length));
byte[] outputArr = new byte[encoding.GetMaxByteCount(strAsChars.Length)];
Assert.Equal(strAsBytes.Length, encoding.GetBytes(strAsChars, 0, strAsChars.Length, outputArr, 0));
fixed (byte* bytesPtr = outputArr)
{
Assert.Equal(strAsBytes.Length, encoding.GetBytes(charsPtr, strAsChars.Length, bytesPtr, outputArr.Length));
}
Assert.Equal(strAsBytes.Length, encoding.GetBytes(str, 0, str.Length, outputArr, 0));
}
}
[Fact]
public static unsafe void OutputEncoding()
{
Encoding curEncoding = Console.OutputEncoding;
try
{
Assert.Same(Console.Out, Console.Out);
Encoding encoding = Console.Out.Encoding;
Assert.NotNull(encoding);
Assert.Same(encoding, Console.Out.Encoding);
ValidateConsoleEncoding(encoding);
// Try setting the ConsoleEncoding to something else and see if it works.
Console.OutputEncoding = Encoding.Unicode;
Assert.Equal(Console.OutputEncoding.CodePage, Encoding.Unicode.CodePage);
ValidateConsoleEncoding(Console.Out.Encoding);
}
finally
{
Console.OutputEncoding = curEncoding;
}
}
static readonly string[] s_testLines = new string[] {
"3232 Hello32 Hello 5032 Hello 50 532 Hello 50 5 aTrueaabcdbc1.23123.4561.23439505050System.ObjectHello World",
"32",
"",
"32 Hello",
"",
"32 Hello 50",
"",
"32 Hello 50 5",
"",
"32 Hello 50 5 a",
"",
"True",
"a",
"abcd",
"bc",
"1.23",
"123.456",
"1.234",
"39",
"50",
"50",
"50",
"System.Object",
"Hello World",
};
[Fact]
public static void ReadAndReadLine()
{
TextWriter savedStandardOutput = Console.Out;
TextReader savedStandardInput = Console.In;
try
{
using (MemoryStream memStream = new MemoryStream())
{
using (StreamWriter sw = new StreamWriter(memStream))
{
sw.WriteLine(string.Join(Environment.NewLine, s_testLines));
sw.Flush();
memStream.Seek(0, SeekOrigin.Begin);
using (StreamReader sr = new StreamReader(memStream))
{
Console.SetIn(sr);
for (int i = 0; i < s_testLines[0].Length; i++)
{
Assert.Equal(s_testLines[0][i], Console.Read());
}
// Read the newline at the end of the first line.
Assert.Equal("", Console.ReadLine());
for (int i = 1; i < s_testLines.Length; i++)
{
Assert.Equal(s_testLines[i], sr.ReadLine());
}
// We should be at EOF now.
Assert.Equal(-1, Console.Read());
}
}
}
}
finally
{
Console.SetOut(savedStandardOutput);
Console.SetIn(savedStandardInput);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Compute.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedLicenseCodesClientTest
{
[xunit::FactAttribute]
public void GetRequestObject()
{
moq::Mock<LicenseCodes.LicenseCodesClient> mockGrpcClient = new moq::Mock<LicenseCodes.LicenseCodesClient>(moq::MockBehavior.Strict);
GetLicenseCodeRequest request = new GetLicenseCodeRequest
{
LicenseCode = "license_code196a50c0",
Project = "projectaa6ff846",
};
LicenseCode expectedResponse = new LicenseCode
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Transferable = false,
CreationTimestamp = "creation_timestamp235e59a1",
LicenseAlias =
{
new LicenseCodeLicenseAlias(),
},
State = LicenseCode.Types.State.UndefinedState,
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
LicenseCodesClient client = new LicenseCodesClientImpl(mockGrpcClient.Object, null);
LicenseCode response = client.Get(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRequestObjectAsync()
{
moq::Mock<LicenseCodes.LicenseCodesClient> mockGrpcClient = new moq::Mock<LicenseCodes.LicenseCodesClient>(moq::MockBehavior.Strict);
GetLicenseCodeRequest request = new GetLicenseCodeRequest
{
LicenseCode = "license_code196a50c0",
Project = "projectaa6ff846",
};
LicenseCode expectedResponse = new LicenseCode
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Transferable = false,
CreationTimestamp = "creation_timestamp235e59a1",
LicenseAlias =
{
new LicenseCodeLicenseAlias(),
},
State = LicenseCode.Types.State.UndefinedState,
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<LicenseCode>(stt::Task.FromResult(expectedResponse), null, null, null, null));
LicenseCodesClient client = new LicenseCodesClientImpl(mockGrpcClient.Object, null);
LicenseCode responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
LicenseCode responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Get()
{
moq::Mock<LicenseCodes.LicenseCodesClient> mockGrpcClient = new moq::Mock<LicenseCodes.LicenseCodesClient>(moq::MockBehavior.Strict);
GetLicenseCodeRequest request = new GetLicenseCodeRequest
{
LicenseCode = "license_code196a50c0",
Project = "projectaa6ff846",
};
LicenseCode expectedResponse = new LicenseCode
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Transferable = false,
CreationTimestamp = "creation_timestamp235e59a1",
LicenseAlias =
{
new LicenseCodeLicenseAlias(),
},
State = LicenseCode.Types.State.UndefinedState,
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
LicenseCodesClient client = new LicenseCodesClientImpl(mockGrpcClient.Object, null);
LicenseCode response = client.Get(request.Project, request.LicenseCode);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAsync()
{
moq::Mock<LicenseCodes.LicenseCodesClient> mockGrpcClient = new moq::Mock<LicenseCodes.LicenseCodesClient>(moq::MockBehavior.Strict);
GetLicenseCodeRequest request = new GetLicenseCodeRequest
{
LicenseCode = "license_code196a50c0",
Project = "projectaa6ff846",
};
LicenseCode expectedResponse = new LicenseCode
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Transferable = false,
CreationTimestamp = "creation_timestamp235e59a1",
LicenseAlias =
{
new LicenseCodeLicenseAlias(),
},
State = LicenseCode.Types.State.UndefinedState,
Description = "description2cf9da67",
SelfLink = "self_link7e87f12d",
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<LicenseCode>(stt::Task.FromResult(expectedResponse), null, null, null, null));
LicenseCodesClient client = new LicenseCodesClientImpl(mockGrpcClient.Object, null);
LicenseCode responseCallSettings = await client.GetAsync(request.Project, request.LicenseCode, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
LicenseCode responseCancellationToken = await client.GetAsync(request.Project, request.LicenseCode, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissionsRequestObject()
{
moq::Mock<LicenseCodes.LicenseCodesClient> mockGrpcClient = new moq::Mock<LicenseCodes.LicenseCodesClient>(moq::MockBehavior.Strict);
TestIamPermissionsLicenseCodeRequest request = new TestIamPermissionsLicenseCodeRequest
{
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
LicenseCodesClient client = new LicenseCodesClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse response = client.TestIamPermissions(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsRequestObjectAsync()
{
moq::Mock<LicenseCodes.LicenseCodesClient> mockGrpcClient = new moq::Mock<LicenseCodes.LicenseCodesClient>(moq::MockBehavior.Strict);
TestIamPermissionsLicenseCodeRequest request = new TestIamPermissionsLicenseCodeRequest
{
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
LicenseCodesClient client = new LicenseCodesClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissions()
{
moq::Mock<LicenseCodes.LicenseCodesClient> mockGrpcClient = new moq::Mock<LicenseCodes.LicenseCodesClient>(moq::MockBehavior.Strict);
TestIamPermissionsLicenseCodeRequest request = new TestIamPermissionsLicenseCodeRequest
{
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
LicenseCodesClient client = new LicenseCodesClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse response = client.TestIamPermissions(request.Project, request.Resource, request.TestPermissionsRequestResource);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsAsync()
{
moq::Mock<LicenseCodes.LicenseCodesClient> mockGrpcClient = new moq::Mock<LicenseCodes.LicenseCodesClient>(moq::MockBehavior.Strict);
TestIamPermissionsLicenseCodeRequest request = new TestIamPermissionsLicenseCodeRequest
{
Resource = "resource164eab96",
Project = "projectaa6ff846",
TestPermissionsRequestResource = new TestPermissionsRequest(),
};
TestPermissionsResponse expectedResponse = new TestPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
LicenseCodesClient client = new LicenseCodesClientImpl(mockGrpcClient.Object, null);
TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Project, request.Resource, request.TestPermissionsRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Project, request.Resource, request.TestPermissionsRequestResource, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Globalization;
using Moq;
using Xunit;
namespace System.ComponentModel.Tests
{
public partial class TypeDescriptorTests
{
[Fact]
public void AddProvider_InvokeObject_GetProviderReturnsExpected()
{
var instance = new object();
var mockProvider1 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider1
.Setup(p => p.IsSupportedType(typeof(int)))
.Returns(true)
.Verifiable();
var mockProvider2 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider2
.Setup(p => p.IsSupportedType(typeof(int)))
.Returns(true)
.Verifiable();
mockProvider2
.Setup(p => p.GetCache(instance))
.Returns(new Dictionary<int, string>());
TypeDescriptor.AddProvider(mockProvider1.Object, instance);
TypeDescriptionProvider actualProvider1 = TypeDescriptor.GetProvider(instance);
Assert.NotSame(actualProvider1, mockProvider1.Object);
actualProvider1.IsSupportedType(typeof(int));
mockProvider1.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
mockProvider2.Verify(p => p.IsSupportedType(typeof(int)), Times.Never());
// Add another.
TypeDescriptor.AddProvider(mockProvider2.Object, instance);
TypeDescriptionProvider actualProvider2 = TypeDescriptor.GetProvider(instance);
Assert.NotSame(actualProvider1, actualProvider2);
actualProvider2.IsSupportedType(typeof(int));
mockProvider1.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
mockProvider2.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
}
[Fact]
public void AddProvider_InvokeObjectMultipleTimes_Refreshes()
{
var instance = new object();
var mockProvider1 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider1
.Setup(p => p.GetCache(instance))
.Returns(new Dictionary<int, string>())
.Verifiable();
var mockProvider2 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider2
.Setup(p => p.GetCache(instance))
.Returns(new Dictionary<int, string>())
.Verifiable();
int callCount = 0;
RefreshEventHandler handler = (e) =>
{
if (e.ComponentChanged == instance)
{
callCount++;
}
};
TypeDescriptor.Refreshed += handler;
try
{
TypeDescriptor.AddProvider(mockProvider1.Object, instance);
Assert.Equal(0, callCount);
mockProvider1.Verify(p => p.GetCache(instance), Times.Never());
mockProvider2.Verify(p => p.GetCache(instance), Times.Never());
// Add again.
TypeDescriptor.AddProvider(mockProvider1.Object, instance);
Assert.Equal(1, callCount);
mockProvider1.Verify(p => p.GetCache(instance), Times.Once());
mockProvider2.Verify(p => p.GetCache(instance), Times.Never());
// Add different.
TypeDescriptor.AddProvider(mockProvider2.Object, instance);
Assert.Equal(2, callCount);
mockProvider1.Verify(p => p.GetCache(instance), Times.Once());
mockProvider2.Verify(p => p.GetCache(instance), Times.Once());
}
finally
{
TypeDescriptor.Refreshed -= handler;
}
}
[Fact]
public void AddProvider_InvokeType_GetProviderReturnsExpected()
{
Type type = typeof(AddProvider_InvokeType_GetProviderReturnsExpectedType);
var mockProvider1 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider1
.Setup(p => p.IsSupportedType(typeof(int)))
.Returns(true)
.Verifiable();
var mockProvider2 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider2
.Setup(p => p.IsSupportedType(typeof(int)))
.Returns(true)
.Verifiable();
mockProvider2
.Setup(p => p.GetCache(type))
.Returns(new Dictionary<int, string>());
TypeDescriptor.AddProvider(mockProvider1.Object, type);
TypeDescriptionProvider actualProvider1 = TypeDescriptor.GetProvider(type);
Assert.NotSame(actualProvider1, mockProvider1.Object);
actualProvider1.IsSupportedType(typeof(int));
mockProvider1.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
mockProvider2.Verify(p => p.IsSupportedType(typeof(int)), Times.Never());
// Add another.
TypeDescriptor.AddProvider(mockProvider2.Object, type);
TypeDescriptionProvider actualProvider2 = TypeDescriptor.GetProvider(type);
Assert.NotSame(actualProvider1, actualProvider2);
actualProvider2.IsSupportedType(typeof(int));
mockProvider1.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
mockProvider2.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
}
private class AddProvider_InvokeType_GetProviderReturnsExpectedType { }
[Fact]
public void AddProvider_InvokeTypeMultipleTimes_Refreshes()
{
var type = typeof(AddProvider_InvokeTypeMultipleTimes_RefreshesType);
var mockProvider1 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider1
.Setup(p => p.GetCache(type))
.Returns(new Dictionary<int, string>())
.Verifiable();
var mockProvider2 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider2
.Setup(p => p.GetCache(type))
.Returns(new Dictionary<int, string>())
.Verifiable();
int callCount = 0;
RefreshEventHandler handler = (e) =>
{
if (e.TypeChanged == type)
{
callCount++;
}
};
TypeDescriptor.Refreshed += handler;
try
{
TypeDescriptor.AddProvider(mockProvider1.Object, type);
Assert.Equal(1, callCount);
mockProvider1.Verify(p => p.GetCache(type), Times.Never());
mockProvider2.Verify(p => p.GetCache(type), Times.Never());
// Add again.
TypeDescriptor.AddProvider(mockProvider1.Object, type);
Assert.Equal(2, callCount);
mockProvider1.Verify(p => p.GetCache(type), Times.Never());
mockProvider2.Verify(p => p.GetCache(type), Times.Never());
// Add different.
TypeDescriptor.AddProvider(mockProvider2.Object, type);
Assert.Equal(3, callCount);
mockProvider1.Verify(p => p.GetCache(type), Times.Never());
mockProvider2.Verify(p => p.GetCache(type), Times.Never());
}
finally
{
TypeDescriptor.Refreshed -= handler;
}
}
private class AddProvider_InvokeTypeMultipleTimes_RefreshesType { }
[Fact]
public void AddProvider_NullProvider_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("provider", () => TypeDescriptor.AddProvider(null, new object()));
Assert.Throws<ArgumentNullException>("provider", () => TypeDescriptor.AddProvider(null, typeof(int)));
}
[Fact]
public void AddProvider_NullInstance_ThrowsArgumentNullException()
{
var mockProvider = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
Assert.Throws<ArgumentNullException>("instance", () => TypeDescriptor.AddProvider(mockProvider.Object, (object)null));
}
[Fact]
public void AddProvider_NullType_ThrowsArgumentNullException()
{
var mockProvider = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
Assert.Throws<ArgumentNullException>("type", () => TypeDescriptor.AddProvider(mockProvider.Object, null));
}
[Fact]
public void AddProviderTransparent_InvokeObject_GetProviderReturnsExpected()
{
var instance = new object();
var mockProvider1 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider1
.Setup(p => p.IsSupportedType(typeof(int)))
.Returns(true)
.Verifiable();
var mockProvider2 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider2
.Setup(p => p.IsSupportedType(typeof(int)))
.Returns(true)
.Verifiable();
mockProvider2
.Setup(p => p.GetCache(instance))
.Returns(new Dictionary<int, string>());
TypeDescriptor.AddProviderTransparent(mockProvider1.Object, instance);
TypeDescriptionProvider actualProvider1 = TypeDescriptor.GetProvider(instance);
Assert.NotSame(actualProvider1, mockProvider1.Object);
actualProvider1.IsSupportedType(typeof(int));
mockProvider1.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
mockProvider2.Verify(p => p.IsSupportedType(typeof(int)), Times.Never());
// Add another.
TypeDescriptor.AddProviderTransparent(mockProvider2.Object, instance);
TypeDescriptionProvider actualProvider2 = TypeDescriptor.GetProvider(instance);
Assert.NotSame(actualProvider1, actualProvider2);
actualProvider2.IsSupportedType(typeof(int));
mockProvider1.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
mockProvider2.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
}
[Fact]
public void AddProviderTransparent_InvokeObjectMultipleTimes_Refreshes()
{
var instance = new object();
var mockProvider1 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider1
.Setup(p => p.GetCache(instance))
.Returns(new Dictionary<int, string>())
.Verifiable();
var mockProvider2 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider2
.Setup(p => p.GetCache(instance))
.Returns(new Dictionary<int, string>())
.Verifiable();
int callCount = 0;
RefreshEventHandler handler = (e) =>
{
if (e.ComponentChanged == instance)
{
callCount++;
}
};
TypeDescriptor.Refreshed += handler;
try
{
TypeDescriptor.AddProviderTransparent(mockProvider1.Object, instance);
Assert.Equal(0, callCount);
mockProvider1.Verify(p => p.GetCache(instance), Times.Never());
mockProvider2.Verify(p => p.GetCache(instance), Times.Never());
// Add again.
TypeDescriptor.AddProviderTransparent(mockProvider1.Object, instance);
Assert.Equal(1, callCount);
mockProvider1.Verify(p => p.GetCache(instance), Times.Once());
mockProvider2.Verify(p => p.GetCache(instance), Times.Never());
// Add different.
TypeDescriptor.AddProviderTransparent(mockProvider2.Object, instance);
Assert.Equal(2, callCount);
mockProvider1.Verify(p => p.GetCache(instance), Times.Once());
mockProvider2.Verify(p => p.GetCache(instance), Times.Once());
}
finally
{
TypeDescriptor.Refreshed -= handler;
}
}
[Fact]
public void AddProviderTransparent_InvokeType_GetProviderReturnsExpected()
{
Type type = typeof(AddProviderTransparent_InvokeType_GetProviderReturnsExpectedType);
var mockProvider1 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider1
.Setup(p => p.IsSupportedType(typeof(int)))
.Returns(true)
.Verifiable();
var mockProvider2 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider2
.Setup(p => p.IsSupportedType(typeof(int)))
.Returns(true)
.Verifiable();
mockProvider2
.Setup(p => p.GetCache(type))
.Returns(new Dictionary<int, string>());
TypeDescriptor.AddProviderTransparent(mockProvider1.Object, type);
TypeDescriptionProvider actualProvider1 = TypeDescriptor.GetProvider(type);
Assert.NotSame(actualProvider1, mockProvider1.Object);
actualProvider1.IsSupportedType(typeof(int));
mockProvider1.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
mockProvider2.Verify(p => p.IsSupportedType(typeof(int)), Times.Never());
// Add another.
TypeDescriptor.AddProviderTransparent(mockProvider2.Object, type);
TypeDescriptionProvider actualProvider2 = TypeDescriptor.GetProvider(type);
Assert.NotSame(actualProvider1, actualProvider2);
actualProvider2.IsSupportedType(typeof(int));
mockProvider1.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
mockProvider2.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
}
private class AddProviderTransparent_InvokeType_GetProviderReturnsExpectedType { }
[Fact]
public void AddProviderTransparent_InvokeTypeMultipleTimes_Refreshes()
{
var type = typeof(AddProviderTransparent_InvokeTypeMultipleTimes_RefreshesType);
var mockProvider1 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider1
.Setup(p => p.GetCache(type))
.Returns(new Dictionary<int, string>())
.Verifiable();
var mockProvider2 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider2
.Setup(p => p.GetCache(type))
.Returns(new Dictionary<int, string>())
.Verifiable();
int callCount = 0;
RefreshEventHandler handler = (e) =>
{
if (e.TypeChanged == type)
{
callCount++;
}
};
TypeDescriptor.Refreshed += handler;
try
{
TypeDescriptor.AddProviderTransparent(mockProvider1.Object, type);
Assert.Equal(1, callCount);
mockProvider1.Verify(p => p.GetCache(type), Times.Never());
mockProvider2.Verify(p => p.GetCache(type), Times.Never());
// Add again.
TypeDescriptor.AddProviderTransparent(mockProvider1.Object, type);
Assert.Equal(2, callCount);
mockProvider1.Verify(p => p.GetCache(type), Times.Never());
mockProvider2.Verify(p => p.GetCache(type), Times.Never());
// Add different.
TypeDescriptor.AddProviderTransparent(mockProvider2.Object, type);
Assert.Equal(3, callCount);
mockProvider1.Verify(p => p.GetCache(type), Times.Never());
mockProvider2.Verify(p => p.GetCache(type), Times.Never());
}
finally
{
TypeDescriptor.Refreshed -= handler;
}
}
private class AddProviderTransparent_InvokeTypeMultipleTimes_RefreshesType { }
[Fact]
public void AddProviderTransparent_NullProvider_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("provider", () => TypeDescriptor.AddProviderTransparent(null, new object()));
Assert.Throws<ArgumentNullException>("provider", () => TypeDescriptor.AddProviderTransparent(null, typeof(int)));
}
[Fact]
public void AddProviderTransparent_NullInstance_ThrowsArgumentNullException()
{
var mockProvider = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
Assert.Throws<ArgumentNullException>("instance", () => TypeDescriptor.AddProviderTransparent(mockProvider.Object, (object)null));
}
[Fact]
public void AddProviderTransparent_NullType_ThrowsArgumentNullException()
{
var mockProvider = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
Assert.Throws<ArgumentNullException>("type", () => TypeDescriptor.AddProviderTransparent(mockProvider.Object, null));
}
[Fact]
public void AddAttribute()
{
var component = new DescriptorTestComponent();
var addedAttribute = new DescriptorTestAttribute("expected string");
TypeDescriptor.AddAttributes(component.GetType(), addedAttribute);
AttributeCollection attributes = TypeDescriptor.GetAttributes(component);
Assert.True(attributes.Contains(addedAttribute));
}
[Fact]
public void CreateInstancePassesCtorParameters()
{
var expectedString = "expected string";
var component = TypeDescriptor.CreateInstance(null, typeof(DescriptorTestComponent), new[] { expectedString.GetType() }, new[] { expectedString });
Assert.NotNull(component);
Assert.IsType<DescriptorTestComponent>(component);
Assert.Equal(expectedString, (component as DescriptorTestComponent).StringProperty);
}
[Fact]
public void GetAssociationReturnsExpectedObject()
{
var primaryObject = new DescriptorTestComponent();
var secondaryObject = new MockEventDescriptor();
TypeDescriptor.CreateAssociation(primaryObject, secondaryObject);
var associatedObject = TypeDescriptor.GetAssociation(secondaryObject.GetType(), primaryObject);
Assert.IsType(secondaryObject.GetType(), associatedObject);
Assert.Equal(secondaryObject, associatedObject);
}
[Fact]
public void GetAssociationReturnsDesigner()
{
var designer = new MockDesigner();
var designerHost = new MockDesignerHost();
var component = new DescriptorTestComponent();
designerHost.AddDesigner(component, designer);
component.AddService(typeof(IDesignerHost), designerHost);
object associatedObject = TypeDescriptor.GetAssociation(designer.GetType(), component);
Assert.IsType<MockDesigner>(associatedObject);
Assert.Same(designer, associatedObject);
}
[Theory]
[InlineData(typeof(bool), typeof(BooleanConverter))]
[InlineData(typeof(byte), typeof(ByteConverter))]
[InlineData(typeof(sbyte), typeof(SByteConverter))]
[InlineData(typeof(char), typeof(CharConverter))]
[InlineData(typeof(double), typeof(DoubleConverter))]
[InlineData(typeof(string), typeof(StringConverter))]
[InlineData(typeof(short), typeof(Int16Converter))]
[InlineData(typeof(int), typeof(Int32Converter))]
[InlineData(typeof(long), typeof(Int64Converter))]
[InlineData(typeof(float), typeof(SingleConverter))]
[InlineData(typeof(ushort), typeof(UInt16Converter))]
[InlineData(typeof(uint), typeof(UInt32Converter))]
[InlineData(typeof(ulong), typeof(UInt64Converter))]
[InlineData(typeof(object), typeof(TypeConverter))]
[InlineData(typeof(void), typeof(TypeConverter))]
[InlineData(typeof(DateTime), typeof(DateTimeConverter))]
[InlineData(typeof(DateTimeOffset), typeof(DateTimeOffsetConverter))]
[InlineData(typeof(decimal), typeof(DecimalConverter))]
[InlineData(typeof(TimeSpan), typeof(TimeSpanConverter))]
[InlineData(typeof(Guid), typeof(GuidConverter))]
[InlineData(typeof(Array), typeof(ArrayConverter))]
[InlineData(typeof(ICollection), typeof(CollectionConverter))]
[InlineData(typeof(Enum), typeof(EnumConverter))]
[InlineData(typeof(SomeEnum), typeof(EnumConverter))]
[InlineData(typeof(SomeValueType?), typeof(NullableConverter))]
[InlineData(typeof(int?), typeof(NullableConverter))]
[InlineData(typeof(ClassWithNoConverter), typeof(TypeConverter))]
[InlineData(typeof(BaseClass), typeof(BaseClassConverter))]
[InlineData(typeof(DerivedClass), typeof(DerivedClassConverter))]
[InlineData(typeof(IBase), typeof(IBaseConverter))]
[InlineData(typeof(IDerived), typeof(IBaseConverter))]
[InlineData(typeof(ClassIBase), typeof(IBaseConverter))]
[InlineData(typeof(ClassIDerived), typeof(IBaseConverter))]
[InlineData(typeof(Uri), typeof(UriTypeConverter))]
[InlineData(typeof(CultureInfo), typeof(CultureInfoConverter))]
public static void GetConverter(Type targetType, Type resultConverterType)
{
TypeConverter converter = TypeDescriptor.GetConverter(targetType);
Assert.NotNull(converter);
Assert.Equal(resultConverterType, converter.GetType());
Assert.True(converter.CanConvertTo(typeof(string)));
}
[Fact]
public static void GetConverter_null()
{
Assert.Throws<ArgumentNullException>(() => TypeDescriptor.GetConverter(null));
}
[Fact]
public static void GetConverter_NotAvailable()
{
Assert.Throws<MissingMethodException>(
() => TypeDescriptor.GetConverter(typeof(ClassWithInvalidConverter)));
// GetConverter should throw MissingMethodException because parameterless constructor is missing in the InvalidConverter class.
}
[Fact]
public void GetEvents()
{
var component = new DescriptorTestComponent();
EventDescriptorCollection events = TypeDescriptor.GetEvents(component);
Assert.Equal(2, events.Count);
}
[Fact]
public void GetEventsFiltersByAttribute()
{
var defaultValueAttribute = new DefaultValueAttribute(null);
EventDescriptorCollection events = TypeDescriptor.GetEvents(typeof(DescriptorTestComponent), new[] { defaultValueAttribute });
Assert.Equal(1, events.Count);
}
[Fact]
public void GetPropertiesFiltersByAttribute()
{
var defaultValueAttribute = new DefaultValueAttribute(DescriptorTestComponent.DefaultPropertyValue);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(DescriptorTestComponent), new[] { defaultValueAttribute });
Assert.Equal(1, properties.Count);
}
[Fact]
public void RemoveProvider_InvokeObject_RemovesProvider()
{
var instance = new object();
var mockProvider1 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider1
.Setup(p => p.GetCache(instance))
.Returns(new Dictionary<int, string>());
mockProvider1
.Setup(p => p.IsSupportedType(typeof(int)))
.Returns(true)
.Verifiable();
var mockProvider2 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider2
.Setup(p => p.GetCache(instance))
.Returns(new Dictionary<int, string>());
mockProvider2
.Setup(p => p.IsSupportedType(typeof(int)))
.Returns(true)
.Verifiable();
var mockProvider3 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider3
.Setup(p => p.GetCache(instance))
.Returns(new Dictionary<int, string>());
mockProvider3
.Setup(p => p.IsSupportedType(typeof(int)))
.Returns(true)
.Verifiable();
TypeDescriptor.AddProvider(mockProvider1.Object, instance);
TypeDescriptor.AddProvider(mockProvider2.Object, instance);
TypeDescriptor.AddProvider(mockProvider3.Object, instance);
// Remove middle.
TypeDescriptor.RemoveProvider(mockProvider2.Object, instance);
TypeDescriptor.GetProvider(instance).IsSupportedType(typeof(int));
mockProvider1.Verify(p => p.IsSupportedType(typeof(int)), Times.Never());
mockProvider2.Verify(p => p.IsSupportedType(typeof(int)), Times.Never());
mockProvider3.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
// Remove end.
TypeDescriptor.RemoveProvider(mockProvider3.Object, instance);
TypeDescriptor.GetProvider(instance).IsSupportedType(typeof(int));
mockProvider1.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
mockProvider2.Verify(p => p.IsSupportedType(typeof(int)), Times.Never());
mockProvider3.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
// Remove start.
TypeDescriptor.RemoveProvider(mockProvider1.Object, instance);
TypeDescriptor.GetProvider(instance).IsSupportedType(typeof(int));
mockProvider1.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
mockProvider2.Verify(p => p.IsSupportedType(typeof(int)), Times.Never());
mockProvider3.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
}
[Fact]
public void RemoveProvider_InvokeObjectWithProviders_Refreshes()
{
var instance = new object();
var mockProvider1 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
var mockProvider2 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
int callCount = 0;
RefreshEventHandler handler = (e) =>
{
if (e.ComponentChanged == instance)
{
callCount++;
}
};
TypeDescriptor.Refreshed += handler;
try
{
TypeDescriptor.AddProvider(mockProvider1.Object, instance);
Assert.Equal(0, callCount);
TypeDescriptor.RemoveProvider(mockProvider1.Object, instance);
Assert.Equal(1, callCount);
// Remove again.
TypeDescriptor.RemoveProvider(mockProvider1.Object, instance);
Assert.Equal(2, callCount);
// Remove different.
TypeDescriptor.RemoveProvider(mockProvider2.Object, instance);
Assert.Equal(3, callCount);
}
finally
{
TypeDescriptor.Refreshed -= handler;
}
}
[Fact]
public void RemoveProvider_InvokeObjectWithoutProviders_Refreshes()
{
var instance = new object();
var mockProvider = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
int callCount = 0;
RefreshEventHandler handler = (e) =>
{
if (e.ComponentChanged == instance)
{
callCount++;
}
};
TypeDescriptor.Refreshed += handler;
try
{
TypeDescriptor.RemoveProvider(mockProvider.Object, instance);
Assert.Equal(1, callCount);
}
finally
{
TypeDescriptor.Refreshed -= handler;
}
}
[Fact]
public void RemoveProvider_InvokeType_RemovesProvider()
{
Type type = typeof(RemoveProvider_InvokeType_RemovesProviderType);
var mockProvider1 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider1
.Setup(p => p.GetCache(type))
.Returns(new Dictionary<int, string>());
mockProvider1
.Setup(p => p.IsSupportedType(typeof(int)))
.Returns(true)
.Verifiable();
var mockProvider2 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider2
.Setup(p => p.GetCache(type))
.Returns(new Dictionary<int, string>());
mockProvider2
.Setup(p => p.IsSupportedType(typeof(int)))
.Returns(true)
.Verifiable();
var mockProvider3 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider3
.Setup(p => p.GetCache(type))
.Returns(new Dictionary<int, string>());
mockProvider3
.Setup(p => p.IsSupportedType(typeof(int)))
.Returns(true)
.Verifiable();
TypeDescriptor.AddProvider(mockProvider1.Object, type);
TypeDescriptor.AddProvider(mockProvider2.Object, type);
TypeDescriptor.AddProvider(mockProvider3.Object, type);
// Remove middle.
TypeDescriptor.RemoveProvider(mockProvider2.Object, type);
TypeDescriptor.GetProvider(type).IsSupportedType(typeof(int));
mockProvider1.Verify(p => p.IsSupportedType(typeof(int)), Times.Never());
mockProvider2.Verify(p => p.IsSupportedType(typeof(int)), Times.Never());
mockProvider3.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
// Remove end.
TypeDescriptor.RemoveProvider(mockProvider3.Object, type);
TypeDescriptor.GetProvider(type).IsSupportedType(typeof(int));
mockProvider1.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
mockProvider2.Verify(p => p.IsSupportedType(typeof(int)), Times.Never());
mockProvider3.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
// Remove start.
TypeDescriptor.RemoveProvider(mockProvider1.Object, type);
TypeDescriptor.GetProvider(type).IsSupportedType(typeof(int));
mockProvider1.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
mockProvider2.Verify(p => p.IsSupportedType(typeof(int)), Times.Never());
mockProvider3.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
}
private class RemoveProvider_InvokeType_RemovesProviderType { }
[Fact]
public void RemoveProvider_InvokeTypeWithProviders_Refreshes()
{
Type type = typeof(RemoveProvider_InvokeObjectWithProviders_RefreshesType);
var mockProvider1 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
var mockProvider2 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
int callCount = 0;
RefreshEventHandler handler = (e) =>
{
if (e.TypeChanged == type)
{
callCount++;
}
};
TypeDescriptor.Refreshed += handler;
try
{
TypeDescriptor.AddProvider(mockProvider1.Object, type);
Assert.Equal(1, callCount);
TypeDescriptor.RemoveProvider(mockProvider1.Object, type);
Assert.Equal(2, callCount);
// Remove again.
TypeDescriptor.RemoveProvider(mockProvider1.Object, type);
Assert.Equal(3, callCount);
// Remove different.
TypeDescriptor.RemoveProvider(mockProvider2.Object, type);
Assert.Equal(4, callCount);
}
finally
{
TypeDescriptor.Refreshed -= handler;
}
}
private class RemoveProvider_InvokeObjectWithProviders_RefreshesType { }
[Fact]
public void RemoveProvider_InvokeTypeWithoutProviders_Refreshes()
{
Type type = typeof(RemoveProvider_InvokeTypeWithoutProviders_RefreshesType);
var mockProvider = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
int callCount = 0;
RefreshEventHandler handler = (e) =>
{
if (e.TypeChanged == type)
{
callCount++;
}
};
TypeDescriptor.Refreshed += handler;
try
{
TypeDescriptor.RemoveProvider(mockProvider.Object, type);
Assert.Equal(1, callCount);
}
finally
{
TypeDescriptor.Refreshed -= handler;
}
}
private class RemoveProvider_InvokeTypeWithoutProviders_RefreshesType { }
[Fact]
public void RemoveProvider_NullProvider_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("provider", () => TypeDescriptor.RemoveProvider(null, new object()));
Assert.Throws<ArgumentNullException>("provider", () => TypeDescriptor.RemoveProvider(null, typeof(int)));
}
[Fact]
public void RemoveProvider_NullInstance_ThrowsArgumentNullException()
{
var mockProvider = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
Assert.Throws<ArgumentNullException>("instance", () => TypeDescriptor.RemoveProvider(mockProvider.Object, (object)null));
}
[Fact]
public void RemoveProvider_NullType_ThrowsArgumentNullException()
{
var mockProvider = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
Assert.Throws<ArgumentNullException>("type", () => TypeDescriptor.RemoveProvider(mockProvider.Object, null));
}
[Fact]
public void RemoveProviderTransparent_InvokeObject_RemovesProvider()
{
var instance = new object();
var mockProvider1 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider1
.Setup(p => p.GetCache(instance))
.Returns(new Dictionary<int, string>());
mockProvider1
.Setup(p => p.IsSupportedType(typeof(int)))
.Returns(true)
.Verifiable();
var mockProvider2 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider2
.Setup(p => p.GetCache(instance))
.Returns(new Dictionary<int, string>());
mockProvider2
.Setup(p => p.IsSupportedType(typeof(int)))
.Returns(true)
.Verifiable();
var mockProvider3 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider3
.Setup(p => p.GetCache(instance))
.Returns(new Dictionary<int, string>());
mockProvider3
.Setup(p => p.IsSupportedType(typeof(int)))
.Returns(true)
.Verifiable();
TypeDescriptor.AddProvider(mockProvider1.Object, instance);
TypeDescriptor.AddProvider(mockProvider2.Object, instance);
TypeDescriptor.AddProvider(mockProvider3.Object, instance);
// Remove middle.
TypeDescriptor.RemoveProviderTransparent(mockProvider2.Object, instance);
TypeDescriptor.GetProvider(instance).IsSupportedType(typeof(int));
mockProvider1.Verify(p => p.IsSupportedType(typeof(int)), Times.Never());
mockProvider2.Verify(p => p.IsSupportedType(typeof(int)), Times.Never());
mockProvider3.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
// Remove end.
TypeDescriptor.RemoveProviderTransparent(mockProvider3.Object, instance);
TypeDescriptor.GetProvider(instance).IsSupportedType(typeof(int));
mockProvider1.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
mockProvider2.Verify(p => p.IsSupportedType(typeof(int)), Times.Never());
mockProvider3.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
// Remove start.
TypeDescriptor.RemoveProviderTransparent(mockProvider1.Object, instance);
TypeDescriptor.GetProvider(instance).IsSupportedType(typeof(int));
mockProvider1.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
mockProvider2.Verify(p => p.IsSupportedType(typeof(int)), Times.Never());
mockProvider3.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
}
[Fact]
public void RemoveProviderTransparent_InvokeObjectWithProviders_Refreshes()
{
var instance = new object();
var mockProvider1 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
var mockProvider2 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
int callCount = 0;
RefreshEventHandler handler = (e) =>
{
if (e.ComponentChanged == instance)
{
callCount++;
}
};
TypeDescriptor.Refreshed += handler;
try
{
TypeDescriptor.AddProvider(mockProvider1.Object, instance);
Assert.Equal(0, callCount);
TypeDescriptor.RemoveProviderTransparent(mockProvider1.Object, instance);
Assert.Equal(1, callCount);
// Remove again.
TypeDescriptor.RemoveProviderTransparent(mockProvider1.Object, instance);
Assert.Equal(2, callCount);
// Remove different.
TypeDescriptor.RemoveProviderTransparent(mockProvider2.Object, instance);
Assert.Equal(3, callCount);
}
finally
{
TypeDescriptor.Refreshed -= handler;
}
}
[Fact]
public void RemoveProviderTransparent_InvokeObjectWithoutProviders_Refreshes()
{
var instance = new object();
var mockProvider = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
int callCount = 0;
RefreshEventHandler handler = (e) =>
{
if (e.ComponentChanged == instance)
{
callCount++;
}
};
TypeDescriptor.Refreshed += handler;
try
{
TypeDescriptor.RemoveProviderTransparent(mockProvider.Object, instance);
Assert.Equal(1, callCount);
}
finally
{
TypeDescriptor.Refreshed -= handler;
}
}
[Fact]
public void RemoveProviderTransparent_InvokeType_RemovesProvider()
{
Type type = typeof(RemoveProviderTransparent_InvokeType_RemovesProviderType);
var mockProvider1 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider1
.Setup(p => p.GetCache(type))
.Returns(new Dictionary<int, string>());
mockProvider1
.Setup(p => p.IsSupportedType(typeof(int)))
.Returns(true)
.Verifiable();
var mockProvider2 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider2
.Setup(p => p.GetCache(type))
.Returns(new Dictionary<int, string>());
mockProvider2
.Setup(p => p.IsSupportedType(typeof(int)))
.Returns(true)
.Verifiable();
var mockProvider3 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
mockProvider3
.Setup(p => p.GetCache(type))
.Returns(new Dictionary<int, string>());
mockProvider3
.Setup(p => p.IsSupportedType(typeof(int)))
.Returns(true)
.Verifiable();
TypeDescriptor.AddProvider(mockProvider1.Object, type);
TypeDescriptor.AddProvider(mockProvider2.Object, type);
TypeDescriptor.AddProvider(mockProvider3.Object, type);
// Remove middle.
TypeDescriptor.RemoveProviderTransparent(mockProvider2.Object, type);
TypeDescriptor.GetProvider(type).IsSupportedType(typeof(int));
mockProvider1.Verify(p => p.IsSupportedType(typeof(int)), Times.Never());
mockProvider2.Verify(p => p.IsSupportedType(typeof(int)), Times.Never());
mockProvider3.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
// Remove end.
TypeDescriptor.RemoveProviderTransparent(mockProvider3.Object, type);
TypeDescriptor.GetProvider(type).IsSupportedType(typeof(int));
mockProvider1.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
mockProvider2.Verify(p => p.IsSupportedType(typeof(int)), Times.Never());
mockProvider3.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
// Remove start.
TypeDescriptor.RemoveProviderTransparent(mockProvider1.Object, type);
TypeDescriptor.GetProvider(type).IsSupportedType(typeof(int));
mockProvider1.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
mockProvider2.Verify(p => p.IsSupportedType(typeof(int)), Times.Never());
mockProvider3.Verify(p => p.IsSupportedType(typeof(int)), Times.Once());
}
private class RemoveProviderTransparent_InvokeType_RemovesProviderType { }
[Fact]
public void RemoveProviderTransparent_InvokeTypeWithProviders_Refreshes()
{
Type type = typeof(RemoveProviderTransparent_InvokeObjectWithProviders_RefreshesType);
var mockProvider1 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
var mockProvider2 = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
int callCount = 0;
RefreshEventHandler handler = (e) =>
{
if (e.TypeChanged == type)
{
callCount++;
}
};
TypeDescriptor.Refreshed += handler;
try
{
TypeDescriptor.AddProvider(mockProvider1.Object, type);
Assert.Equal(1, callCount);
TypeDescriptor.RemoveProviderTransparent(mockProvider1.Object, type);
Assert.Equal(2, callCount);
// Remove again.
TypeDescriptor.RemoveProviderTransparent(mockProvider1.Object, type);
Assert.Equal(3, callCount);
// Remove different.
TypeDescriptor.RemoveProviderTransparent(mockProvider2.Object, type);
Assert.Equal(4, callCount);
}
finally
{
TypeDescriptor.Refreshed -= handler;
}
}
private class RemoveProviderTransparent_InvokeObjectWithProviders_RefreshesType { }
[Fact]
public void RemoveProviderTransparent_InvokeTypeWithoutProviders_Refreshes()
{
Type type = typeof(RemoveProviderTransparent_InvokeTypeWithoutProviders_RefreshesType);
var mockProvider = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
int callCount = 0;
RefreshEventHandler handler = (e) =>
{
if (e.TypeChanged == type)
{
callCount++;
}
};
TypeDescriptor.Refreshed += handler;
try
{
TypeDescriptor.RemoveProviderTransparent(mockProvider.Object, type);
Assert.Equal(1, callCount);
}
finally
{
TypeDescriptor.Refreshed -= handler;
}
}
private class RemoveProviderTransparent_InvokeTypeWithoutProviders_RefreshesType { }
[Fact]
public void RemoveProviderTransparent_NullProvider_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("provider", () => TypeDescriptor.RemoveProviderTransparent(null, new object()));
Assert.Throws<ArgumentNullException>("provider", () => TypeDescriptor.RemoveProviderTransparent(null, typeof(int)));
}
[Fact]
public void RemoveProviderTransparent_NullInstance_ThrowsArgumentNullException()
{
var mockProvider = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
Assert.Throws<ArgumentNullException>("instance", () => TypeDescriptor.RemoveProviderTransparent(mockProvider.Object, (object)null));
}
[Fact]
public void RemoveProviderTransparent_NullType_ThrowsArgumentNullException()
{
var mockProvider = new Mock<TypeDescriptionProvider>(MockBehavior.Strict);
Assert.Throws<ArgumentNullException>("type", () => TypeDescriptor.RemoveProviderTransparent(mockProvider.Object, null));
}
[Fact]
public void RemoveAssociationsRemovesAllAssociations()
{
var primaryObject = new DescriptorTestComponent();
var firstAssociatedObject = new MockEventDescriptor();
var secondAssociatedObject = new MockPropertyDescriptor();
TypeDescriptor.CreateAssociation(primaryObject, firstAssociatedObject);
TypeDescriptor.CreateAssociation(primaryObject, secondAssociatedObject);
TypeDescriptor.RemoveAssociations(primaryObject);
// GetAssociation never returns null. The default implementation returns the
// primary object when an association doesn't exist. This isn't documented,
// however, so here we only verify that the formerly associated objects aren't returned.
var firstAssociation = TypeDescriptor.GetAssociation(firstAssociatedObject.GetType(), primaryObject);
Assert.NotEqual(firstAssociatedObject, firstAssociation);
var secondAssociation = TypeDescriptor.GetAssociation(secondAssociatedObject.GetType(), primaryObject);
Assert.NotEqual(secondAssociatedObject, secondAssociation);
}
[Fact]
public void RemoveSingleAssociation()
{
var primaryObject = new DescriptorTestComponent();
var firstAssociatedObject = new MockEventDescriptor();
var secondAssociatedObject = new MockPropertyDescriptor();
TypeDescriptor.CreateAssociation(primaryObject, firstAssociatedObject);
TypeDescriptor.CreateAssociation(primaryObject, secondAssociatedObject);
TypeDescriptor.RemoveAssociation(primaryObject, firstAssociatedObject);
// the second association should remain
var secondAssociation = TypeDescriptor.GetAssociation(secondAssociatedObject.GetType(), primaryObject);
Assert.Equal(secondAssociatedObject, secondAssociation);
// the first association should not
var firstAssociation = TypeDescriptor.GetAssociation(firstAssociatedObject.GetType(), primaryObject);
Assert.NotEqual(firstAssociatedObject, firstAssociation);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework throws NullReferenceException")]
public void SortDescriptorArray_Invoke_ReturnsExpected()
{
var notADescriptor1 = new object();
var notADescriptor2 = new object();
var mockDescriptor1 = new Mock<EventDescriptor>(MockBehavior.Strict, "Name1", new Attribute[0]);
mockDescriptor1
.Setup(d => d.Name)
.Returns("Name1");
var mockDescriptor2 = new Mock<EventDescriptor>(MockBehavior.Strict, "Name2", new Attribute[0]);
mockDescriptor2
.Setup(d => d.Name)
.Returns("Name2");
var mockDescriptor3 = new Mock<EventDescriptor>(MockBehavior.Strict, "Name3", new Attribute[0]);
mockDescriptor3
.Setup(d => d.Name)
.Returns("Name3");
var infos = new object[] { null, mockDescriptor3.Object, notADescriptor2, mockDescriptor1.Object, mockDescriptor2.Object, null, notADescriptor1 };
TypeDescriptor.SortDescriptorArray(infos);
Assert.True(infos[0] == null || infos[0] == notADescriptor1 || infos[0] == notADescriptor2);
Assert.True(infos[1] == null || infos[1] == notADescriptor1 || infos[1] == notADescriptor2);
Assert.True(infos[2] == null || infos[2] == notADescriptor1 || infos[2] == notADescriptor2);
Assert.True(infos[3] == null || infos[3] == notADescriptor1 || infos[3] == notADescriptor2);
Assert.Same(mockDescriptor1.Object, infos[4]);
Assert.Same(mockDescriptor2.Object, infos[5]);
Assert.Same(mockDescriptor3.Object, infos[6]);
}
[Fact]
public void SortDescriptorArray_NullInfos_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("infos", () => TypeDescriptor.SortDescriptorArray(null));
}
[Fact]
public void DerivedPropertyAttribute()
{
PropertyDescriptor property = TypeDescriptor.GetProperties(typeof(FooBarDerived))["Value"];
var descriptionAttribute = (DescriptionAttribute)property.Attributes[typeof(DescriptionAttribute)];
Assert.Equal("Derived", descriptionAttribute.Description);
}
class FooBarBase
{
[Description("Base")]
public virtual int Value { get; set; }
}
class FooBarDerived : FooBarBase
{
[Description("Derived")]
public override int Value { get; set; }
}
}
}
| |
// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
using System;
using System.Buffers.Binary;
using System.IO;
using System.Linq;
using Geb.Image.Formats.Png.Filters;
using Geb.Image.Formats.Png.Zlib;
using Geb.Image.Formats.Quantization;
namespace Geb.Image.Formats.Png
{
/// <summary>
/// Performs the png encoding operation.
/// </summary>
internal sealed class PngEncoderCore : IDisposable
{
private readonly MemoryManager memoryManager;
/// <summary>
/// The maximum block size, defaults at 64k for uncompressed blocks.
/// </summary>
private const int MaxBlockSize = 65535;
/// <summary>
/// Reusable buffer for writing general data.
/// </summary>
private readonly byte[] buffer = new byte[8];
/// <summary>
/// Reusable buffer for writing chunk data.
/// </summary>
private readonly byte[] chunkDataBuffer = new byte[16];
/// <summary>
/// Reusable crc for validating chunks.
/// </summary>
private readonly Crc32 crc = new Crc32();
/// <summary>
/// The png color type.
/// </summary>
private readonly PngColorType pngColorType;
/// <summary>
/// The png filter method.
/// </summary>
private readonly PngFilterMethod pngFilterMethod;
/// <summary>
/// The quantizer for reducing the color count.
/// </summary>
private readonly IQuantizer quantizer;
/// <summary>
/// Gets or sets the CompressionLevel value
/// </summary>
private readonly int compressionLevel;
/// <summary>
/// Gets or sets the Gamma value
/// </summary>
private readonly float gamma;
/// <summary>
/// Gets or sets the Threshold value
/// </summary>
private readonly byte threshold;
/// <summary>
/// Gets or sets a value indicating whether to Write Gamma
/// </summary>
private readonly bool writeGamma;
/// <summary>
/// Contains the raw pixel data from an indexed image.
/// </summary>
private byte[] palettePixelData;
/// <summary>
/// The image width.
/// </summary>
private int width;
/// <summary>
/// The image height.
/// </summary>
private int height;
/// <summary>
/// The number of bits required to encode the colors in the png.
/// </summary>
private byte bitDepth;
/// <summary>
/// The number of bytes per pixel.
/// </summary>
private int bytesPerPixel;
/// <summary>
/// The number of bytes per scanline.
/// </summary>
private int bytesPerScanline;
/// <summary>
/// The previous scanline.
/// </summary>
private IManagedByteBuffer previousScanline;
/// <summary>
/// The raw scanline.
/// </summary>
private IManagedByteBuffer rawScanline;
/// <summary>
/// The filtered scanline result.
/// </summary>
private IManagedByteBuffer result;
/// <summary>
/// The buffer for the sub filter
/// </summary>
private IManagedByteBuffer sub;
/// <summary>
/// The buffer for the up filter
/// </summary>
private IManagedByteBuffer up;
/// <summary>
/// The buffer for the average filter
/// </summary>
private IManagedByteBuffer average;
/// <summary>
/// The buffer for the Paeth filter
/// </summary>
private IManagedByteBuffer paeth;
/// <summary>
/// Initializes a new instance of the <see cref="PngEncoderCore"/> class.
/// </summary>
/// <param name="memoryManager">The <see cref="MemoryManager"/> to use for buffer allocations.</param>
/// <param name="options">The options for influencing the encoder</param>
public PngEncoderCore(MemoryManager memoryManager, PngEncoderOptions options)
{
if (options == null) options = PngEncoderOptions.Png32;
this.memoryManager = memoryManager;
this.pngColorType = options.PngColorType;
this.pngFilterMethod = options.PngFilterMethod;
this.compressionLevel = options.CompressionLevel;
this.gamma = options.Gamma;
this.quantizer = options.Quantizer;
this.threshold = options.Threshold;
this.writeGamma = options.WriteGamma;
}
/// <summary>
/// Encodes the image to the specified stream from the <see cref="Image{TPixel}"/>.
/// </summary>
/// <typeparam name="TPixel">The pixel format.</typeparam>
/// <param name="image">The <see cref="ImageFrame{TPixel}"/> to encode from.</param>
/// <param name="stream">The <see cref="Stream"/> to encode the image data to.</param>
public void Encode(IImage image, Stream stream)
{
this.width = image.Width;
this.height = image.Height;
stream.Write(PngConstants.HeaderBytes, 0, PngConstants.HeaderBytes.Length);
this.bitDepth = 8;
this.bytesPerPixel = this.CalculateBytesPerPixel();
var header = new PngHeader(
width: image.Width,
height: image.Height,
colorType: this.pngColorType,
bitDepth: this.bitDepth,
filterMethod: 0, // None
compressionMethod: 0,
interlaceMethod: 0);
this.WriteHeaderChunk(stream, header);
this.WriteDataChunks(image, stream);
this.WriteEndChunk(stream);
stream.Flush();
}
/// <inheritdoc />
public void Dispose()
{
this.previousScanline?.Dispose();
this.rawScanline?.Dispose();
this.result?.Dispose();
this.sub?.Dispose();
this.up?.Dispose();
this.average?.Dispose();
this.paeth?.Dispose();
}
/// <summary>
/// Collects a row of grayscale pixels.
/// </summary>
/// <typeparam name="TPixel">The pixel format.</typeparam>
/// <param name="rowSpan">The image row span.</param>
private void CollectGrayscaleBytes(ReadOnlySpan<Bgra32> rowSpan)
{
byte[] rawScanlineArray = this.rawScanline.Array;
// Copy the pixels across from the image.
// Reuse the chunk type buffer.
for (int x = 0; x < this.width; x++)
{
// Convert the color to YCbCr and store the luminance
// Optionally store the original color alpha.
int offset = x * this.bytesPerPixel;
Bgra32 bgra = rowSpan[x];
byte luminance = (byte)((0.299F * bgra.Red) + (0.587F * bgra.Green) + (0.114F * bgra.Blue));
for (int i = 0; i < this.bytesPerPixel; i++)
{
if (i == 0)
{
rawScanlineArray[offset] = luminance;
}
else
{
rawScanlineArray[offset + i] = bgra.Alpha;
}
}
}
}
private void CollectGrayscaleBytes(ReadOnlySpan<Byte> rowSpan)
{
byte[] rawScanlineArray = this.rawScanline.Array;
// Copy the pixels across from the image.
// Reuse the chunk type buffer.
if(this.bytesPerPixel == 1)
{
for (int x = 0; x < this.width; x++)
{
rawScanlineArray[x] = rowSpan[x];
}
}
else
{
for (int x = 0; x < this.width; x++)
{
// Convert the color to YCbCr and store the luminance
// Optionally store the original color alpha.
int offset = x * this.bytesPerPixel;
Byte bgra = rowSpan[x];
for (int i = 0; i < this.bytesPerPixel; i++)
{
if (i == 0)
{
rawScanlineArray[offset] = bgra;
}
else
{
rawScanlineArray[offset + i] = 0xFF;
}
}
}
}
}
/// <summary>
/// Collects a row of true color pixel data.
/// </summary>
/// <typeparam name="TPixel">The pixel format.</typeparam>
/// <param name="rowSpan">The row span.</param>
private void CollectTPixelBytes(ReadOnlySpan<Bgra32> rowSpan)
{
if (this.bytesPerPixel == 4)
{
rowSpan.ToRgba32Bytes(rawScanline.Span, this.width);
}
else
{
rowSpan.ToRgb24Bytes(rawScanline.Span, this.width);
}
}
private void CollectTPixelBytes(ReadOnlySpan<Byte> rowSpan)
{
byte[] rawScanlineArray = this.rawScanline.Array;
for (int x = 0; x < this.width; x++)
{
// Convert the color to YCbCr and store the luminance
// Optionally store the original color alpha.
int offset = x * this.bytesPerPixel;
Byte val = rowSpan[x];
for (int i = 0; i < this.bytesPerPixel; i++)
{
rawScanlineArray[offset + i] = i < 2 ? val : (Byte)0xFF;
}
}
}
/// <summary>
/// Encodes the pixel data line by line.
/// Each scanline is encoded in the most optimal manner to improve compression.
/// </summary>
/// <typeparam name="TPixel">The pixel format.</typeparam>
/// <param name="rowSpan">The row span.</param>
/// <param name="row">The row.</param>
/// <returns>The <see cref="IManagedByteBuffer"/></returns>
private IManagedByteBuffer EncodePixelRow(ReadOnlySpan<Bgra32> rowSpan, int row)
{
switch (this.pngColorType)
{
case PngColorType.Palette:
Buffer.BlockCopy(this.palettePixelData, row * this.rawScanline.Length(), this.rawScanline.Array, 0, this.rawScanline.Length());
break;
case PngColorType.Grayscale:
case PngColorType.GrayscaleWithAlpha:
this.CollectGrayscaleBytes(rowSpan);
break;
default:
this.CollectTPixelBytes(rowSpan);
break;
}
return FilterPixelRow();
}
private IManagedByteBuffer EncodePixelRow(ReadOnlySpan<Byte> rowSpan, int row)
{
switch (this.pngColorType)
{
case PngColorType.Palette:
Buffer.BlockCopy(this.palettePixelData, row * this.rawScanline.Length(), this.rawScanline.Array, 0, this.rawScanline.Length());
break;
case PngColorType.Grayscale:
case PngColorType.GrayscaleWithAlpha:
this.CollectGrayscaleBytes(rowSpan);
break;
default:
this.CollectTPixelBytes(rowSpan);
break;
}
return FilterPixelRow();
}
private IManagedByteBuffer FilterPixelRow()
{
switch (this.pngFilterMethod)
{
case PngFilterMethod.None:
NoneFilter.Encode(this.rawScanline.Span, this.result.Span);
return this.result;
case PngFilterMethod.Sub:
SubFilter.Encode(this.rawScanline.Span, this.sub.Span, this.bytesPerPixel, out int _);
return this.sub;
case PngFilterMethod.Up:
UpFilter.Encode(this.rawScanline.Span, this.previousScanline.Span, this.up.Span, out int _);
return this.up;
case PngFilterMethod.Average:
AverageFilter.Encode(this.rawScanline.Span, this.previousScanline.Span, this.average.Span, this.bytesPerPixel, out int _);
return this.average;
case PngFilterMethod.Paeth:
PaethFilter.Encode(this.rawScanline.Span, this.previousScanline.Span, this.paeth.Span, this.bytesPerPixel, out int _);
return this.paeth;
default:
return this.GetOptimalFilteredScanline();
}
return this.GetOptimalFilteredScanline();
}
/// <summary>
/// Applies all PNG filters to the given scanline and returns the filtered scanline that is deemed
/// to be most compressible, using lowest total variation as proxy for compressibility.
/// </summary>
/// <returns>The <see cref="T:byte[]"/></returns>
private IManagedByteBuffer GetOptimalFilteredScanline()
{
// Palette images don't compress well with adaptive filtering.
if (this.pngColorType == PngColorType.Palette || this.bitDepth < 8)
{
NoneFilter.Encode(this.rawScanline.Span, this.result.Span);
return this.result;
}
Span<byte> scanSpan = this.rawScanline.Span;
Span<byte> prevSpan = this.previousScanline.Span;
// This order, while different to the enumerated order is more likely to produce a smaller sum
// early on which shaves a couple of milliseconds off the processing time.
UpFilter.Encode(scanSpan, prevSpan, this.up.Span, out int currentSum);
int lowestSum = currentSum;
IManagedByteBuffer actualResult = this.up;
PaethFilter.Encode(scanSpan, prevSpan, this.paeth.Span, this.bytesPerPixel, out currentSum);
if (currentSum < lowestSum)
{
lowestSum = currentSum;
actualResult = this.paeth;
}
SubFilter.Encode(scanSpan, this.sub.Span, this.bytesPerPixel, out currentSum);
if (currentSum < lowestSum)
{
lowestSum = currentSum;
actualResult = this.sub;
}
AverageFilter.Encode(scanSpan, prevSpan, this.average.Span, this.bytesPerPixel, out currentSum);
if (currentSum < lowestSum)
{
actualResult = this.average;
}
return actualResult;
}
/// <summary>
/// Calculates the correct number of bytes per pixel for the given color type.
/// </summary>
/// <returns>The <see cref="int"/></returns>
private int CalculateBytesPerPixel()
{
switch (this.pngColorType)
{
case PngColorType.Grayscale:
return 1;
case PngColorType.GrayscaleWithAlpha:
return 2;
case PngColorType.Palette:
return 1;
case PngColorType.Rgb:
return 3;
// PngColorType.RgbWithAlpha
// TODO: Maybe figure out a way to detect if there are any transparent
// pixels and encode RGB if none.
default:
return 4;
}
}
/// <summary>
/// Writes the header chunk to the stream.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> containing image data.</param>
/// <param name="header">The <see cref="PngHeader"/>.</param>
private void WriteHeaderChunk(Stream stream, in PngHeader header)
{
BinaryPrimitives.WriteInt32BigEndian(this.chunkDataBuffer.AsSpan(0, 4), header.Width);
BinaryPrimitives.WriteInt32BigEndian(this.chunkDataBuffer.AsSpan(4, 4), header.Height);
this.chunkDataBuffer[8] = header.BitDepth;
this.chunkDataBuffer[9] = (byte)header.ColorType;
this.chunkDataBuffer[10] = header.CompressionMethod;
this.chunkDataBuffer[11] = header.FilterMethod;
this.chunkDataBuffer[12] = (byte)header.InterlaceMethod;
this.WriteChunk(stream, PngChunkType.Header, this.chunkDataBuffer, 0, 13);
}
/// <summary>
/// Writes the gamma information to the stream.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> containing image data.</param>
private void WriteGammaChunk(Stream stream)
{
if (this.writeGamma)
{
// 4-byte unsigned integer of gamma * 100,000.
uint gammaValue = (uint)(this.gamma * 100_000F);
BinaryPrimitives.WriteUInt32BigEndian(this.chunkDataBuffer.AsSpan(0, 4), gammaValue);
this.WriteChunk(stream, PngChunkType.Gamma, this.chunkDataBuffer, 0, 4);
}
}
/// <summary>
/// Writes the pixel information to the stream.
/// </summary>
/// <typeparam name="TPixel">The pixel format.</typeparam>
/// <param name="pixels">The image.</param>
/// <param name="stream">The stream.</param>
private void WriteDataChunks(IImage pixels, Stream stream)
{
this.bytesPerScanline = this.width * this.bytesPerPixel;
int resultLength = this.bytesPerScanline + 1;
this.previousScanline = this.memoryManager.AllocateCleanManagedByteBuffer(this.bytesPerScanline);
this.rawScanline = this.memoryManager.AllocateCleanManagedByteBuffer(this.bytesPerScanline);
this.result = this.memoryManager.AllocateCleanManagedByteBuffer(resultLength);
if (this.pngColorType != PngColorType.Palette)
{
this.sub = this.memoryManager.AllocateCleanManagedByteBuffer(resultLength);
this.up = this.memoryManager.AllocateCleanManagedByteBuffer(resultLength);
this.average = this.memoryManager.AllocateCleanManagedByteBuffer(resultLength);
this.paeth = this.memoryManager.AllocateCleanManagedByteBuffer(resultLength);
}
byte[] buffer;
int bufferLength;
using (var memoryStream = new MemoryStream())
{
using (var deflateStream = new ZlibDeflateStream(memoryStream, this.compressionLevel))
{
for (int y = 0; y < this.height; y++)
{
IManagedByteBuffer r = EncodePixelRow(pixels, y);
deflateStream.Write(r.Array, 0, resultLength);
IManagedByteBuffer temp = this.rawScanline;
this.rawScanline = this.previousScanline;
this.previousScanline = temp;
}
}
buffer = memoryStream.ToArray();
bufferLength = buffer.Length;
}
// Store the chunks in repeated 64k blocks.
// This reduces the memory load for decoding the image for many decoders.
int numChunks = bufferLength / MaxBlockSize;
if (bufferLength % MaxBlockSize != 0)
{
numChunks++;
}
for (int i = 0; i < numChunks; i++)
{
int length = bufferLength - (i * MaxBlockSize);
if (length > MaxBlockSize)
{
length = MaxBlockSize;
}
this.WriteChunk(stream, PngChunkType.Data, buffer, i * MaxBlockSize, length);
}
}
private IManagedByteBuffer EncodePixelRow(IImage image, int y)
{
if(image.BytesPerPixel == 4)
return this.EncodePixelRow(((ImageBgra32)image).GetPixelRowReadOnlySpan(y), y);
else
return this.EncodePixelRow(((ImageU8)image).GetPixelRowReadOnlySpan(y), y);
}
/// <summary>
/// Writes the chunk end to the stream.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> containing image data.</param>
private void WriteEndChunk(Stream stream)
{
this.WriteChunk(stream, PngChunkType.End, null);
}
/// <summary>
/// Writes a chunk to the stream.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> to write to.</param>
/// <param name="type">The type of chunk to write.</param>
/// <param name="data">The <see cref="T:byte[]"/> containing data.</param>
private void WriteChunk(Stream stream, PngChunkType type, byte[] data)
{
this.WriteChunk(stream, type, data, 0, data?.Length ?? 0);
}
/// <summary>
/// Writes a chunk of a specified length to the stream at the given offset.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> to write to.</param>
/// <param name="type">The type of chunk to write.</param>
/// <param name="data">The <see cref="T:byte[]"/> containing data.</param>
/// <param name="offset">The position to offset the data at.</param>
/// <param name="length">The of the data to write.</param>
private void WriteChunk(Stream stream, PngChunkType type, byte[] data, int offset, int length)
{
BinaryPrimitives.WriteInt32BigEndian(this.buffer, length);
BinaryPrimitives.WriteUInt32BigEndian(this.buffer.AsSpan(4, 4), (uint)type);
stream.Write(this.buffer, 0, 8);
this.crc.Reset();
this.crc.Update(this.buffer.AsSpan(4, 4)); // Write the type buffer
if (data != null && length > 0)
{
stream.Write(data, offset, length);
this.crc.Update(data.AsSpan(offset, length));
}
BinaryPrimitives.WriteUInt32BigEndian(this.buffer, (uint)this.crc.Value);
stream.Write(this.buffer, 0, 4); // write the crc
}
}
}
| |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using GgpGrpc.Models;
using NSubstitute;
using NUnit.Framework;
using System.Diagnostics;
using System.IO;
using System.IO.Abstractions.TestingHelpers;
using System.Threading.Tasks;
using YetiCommon;
using YetiCommon.SSH;
using YetiVSI.Metrics;
using YetiVSI.ProjectSystem.Abstractions;
using YetiVSI.Shared.Metrics;
namespace YetiVSI.Test
{
[TestFixture]
class RemoteDeployTests
{
readonly string _binaryName = "Player.so";
readonly string _chmodFailed = "Error running chmod a+x";
readonly string _rsyncFailed = "Error copying files with ggp_rsync";
[Test]
public async Task DeployGameExecutableDeploysBinaryAndSetsExecutableBitAsync(
[Values(DeployOnLaunchSetting.DELTA, DeployOnLaunchSetting.ALWAYS)]
DeployOnLaunchSetting value)
{
string localPath = GetLocalPath();
IAsyncProject project = GetProjectWithLocalPathAndDeployMode(localPath, value);
(SshTarget target, IAction action, ICancelable cancelable) = GetDeploymentArguments();
(IRemoteFile file, IRemoteCommand command, IRemoteDeploy deploy, _) = GetTestObjects();
await deploy.DeployGameExecutableAsync(project, target, cancelable, action);
Assert.Multiple(async () =>
{
await file.Received(1).SyncAsync(target, localPath,
YetiConstants.RemoteDeployPath, cancelable,
Arg.Any<bool>());
await command.Received(1)
.RunWithSuccessAsync(
target, $"chmod a+x {YetiConstants.RemoteDeployPath}{_binaryName}");
});
}
[Test]
public async Task DeployGameExecutablePopulatesActionEventOnSuccessAsync(
[Values(DeployOnLaunchSetting.DELTA, DeployOnLaunchSetting.ALWAYS)]
DeployOnLaunchSetting value)
{
string localPath = GetLocalPath();
IAsyncProject project = GetProjectWithLocalPathAndDeployMode(localPath, value);
(SshTarget target, IAction action, ICancelable cancelable) = GetDeploymentArguments();
(_, _, IRemoteDeploy deploy, _) = GetTestObjects();
await deploy.DeployGameExecutableAsync(project, target, cancelable, action);
Assert.Multiple(() =>
{
CopyBinaryData actionEvent = action.GetEvent().CopyExecutable;
Assert.NotNull(actionEvent);
Assert.NotNull(actionEvent.CopyBinaryBytes);
Assert.IsTrue(actionEvent.CopyAttempted);
Assert.That(actionEvent.CopyExitCode, Is.EqualTo(0));
Assert.That(actionEvent.SshChmodExitCode, Is.EqualTo(0));
});
}
[Test]
public void DeployGameExecutablePopulatesActionEventOnFailureInDeployment(
[Values(DeployOnLaunchSetting.DELTA, DeployOnLaunchSetting.ALWAYS)]
DeployOnLaunchSetting value)
{
string localPath = GetLocalPath();
IAsyncProject project = GetProjectWithLocalPathAndDeployMode(localPath, value);
(SshTarget target, IAction action, ICancelable cancelable) = GetDeploymentArguments();
(IRemoteFile file, _, IRemoteDeploy deploy, _) = GetTestObjects();
file
.SyncAsync(Arg.Any<SshTarget>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<ICancelable>(), Arg.Any<bool>())
.Returns<Task>(_ => throw new ProcessException(_rsyncFailed));
var error = Assert.ThrowsAsync<DeployException>(
async () =>
await deploy.DeployGameExecutableAsync(
project, target, cancelable, action));
Assert.Multiple(() =>
{
string expectedError = ErrorStrings.FailedToDeployExecutable(_rsyncFailed);
Assert.That(error.Message, Is.EqualTo(expectedError));
CopyBinaryData actionEvent = action.GetEvent().CopyExecutable;
Assert.NotNull(actionEvent);
Assert.NotNull(actionEvent.CopyBinaryBytes);
Assert.IsTrue(actionEvent.CopyAttempted);
Assert.That(actionEvent.CopyExitCode, Is.EqualTo(-1));
Assert.IsNull(actionEvent.SshChmodExitCode);
});
}
[Test]
public void DeployGameExecutablePopulatesActionEventOnFailureInSettingExecutableBit(
[Values(DeployOnLaunchSetting.DELTA, DeployOnLaunchSetting.ALWAYS)]
DeployOnLaunchSetting value)
{
string localPath = GetLocalPath();
IAsyncProject project = GetProjectWithLocalPathAndDeployMode(localPath, value);
(SshTarget target, IAction action, ICancelable cancelable) = GetDeploymentArguments();
(_, IRemoteCommand command, IRemoteDeploy deploy, _) = GetTestObjects();
command.RunWithSuccessAsync(Arg.Any<SshTarget>(), Arg.Any<string>())
.Returns(_ => throw new ProcessException(_chmodFailed));
var error = Assert.ThrowsAsync<DeployException>(
async () => await deploy
.DeployGameExecutableAsync(project, target, cancelable, action));
Assert.Multiple(() =>
{
string expectedError =
ErrorStrings.FailedToSetExecutablePermissions(_chmodFailed);
Assert.That(error.Message, Is.EqualTo(expectedError));
CopyBinaryData actionEvent = action.GetEvent().CopyExecutable;
Assert.NotNull(actionEvent);
Assert.NotNull(actionEvent.CopyBinaryBytes);
Assert.IsTrue(actionEvent.CopyAttempted);
Assert.That(actionEvent.CopyExitCode, Is.EqualTo(0));
Assert.That(actionEvent.SshChmodExitCode, Is.EqualTo(-1));
});
}
[Test]
public async Task DeployGameExecutableDoesNotCopyWhenSetToFalseAsync()
{
string localPath = GetLocalPath();
IAsyncProject project =
GetProjectWithLocalPathAndDeployMode(localPath, DeployOnLaunchSetting.FALSE);
(SshTarget target, IAction action, ICancelable cancelable) = GetDeploymentArguments();
(IRemoteFile file, IRemoteCommand command, IRemoteDeploy deploy, _) = GetTestObjects();
await deploy.DeployGameExecutableAsync(project, target, cancelable, action);
Assert.Multiple(async () =>
{
await file.Received(0).SyncAsync(Arg.Any<SshTarget>(), Arg.Any<string>(),
Arg.Any<string>(), Arg.Any<ICancelable>());
await command.Received(0)
.RunWithSuccessAsync(Arg.Any<SshTarget>(), Arg.Any<string>());
Assert.IsFalse(action.GetEvent().CopyExecutable.CopyAttempted);
});
}
[Test]
public async Task DeployGamePopulatesDeploymentModeAsync(
[Values(DeployOnLaunchSetting.DELTA, DeployOnLaunchSetting.ALWAYS)]
DeployOnLaunchSetting value, [Values] bool commandSucceeds)
{
string localPath = GetLocalPath();
IAsyncProject project = GetProjectWithLocalPathAndDeployMode(localPath, value);
(SshTarget target, IAction action, ICancelable cancelable) = GetDeploymentArguments();
(_, IRemoteCommand command, IRemoteDeploy deploy, _) = GetTestObjects();
if (!commandSucceeds)
{
command.RunWithSuccessAsync(Arg.Any<SshTarget>(), Arg.Any<string>())
.Returns(_ => throw new ProcessException(_chmodFailed));
}
try
{
await deploy.DeployGameExecutableAsync(project, target, cancelable, action);
}
catch (DeployException)
{
Assert.IsFalse(commandSucceeds);
}
CopyBinaryData actionEvent = action.GetEvent().CopyExecutable;
Assert.That(actionEvent.DeploymentMode,
Is.EqualTo(CopyBinaryType.Types.DeploymentMode.GgpRsync));
}
[Test]
public async Task DeployGameSetToNeverDoesNotPopulateDeploymentModeAsync()
{
string localPath = GetLocalPath();
IAsyncProject project = GetProjectWithLocalPathAndDeployMode(localPath,
DeployOnLaunchSetting.FALSE);
(SshTarget target, IAction action, ICancelable cancelable) = GetDeploymentArguments();
(_, _, IRemoteDeploy deploy, _) = GetTestObjects();
await deploy.DeployGameExecutableAsync(project, target, cancelable, action);
CopyBinaryData actionEvent = action.GetEvent().CopyExecutable;
Assert.That(actionEvent.DeploymentMode, Is.Null);
}
[TestCase(DeployOnLaunchSetting.ALWAYS, BinarySignatureCheck.Types.Result.AlwaysCopy)]
[TestCase(DeployOnLaunchSetting.FALSE, BinarySignatureCheck.Types.Result.NoCopy)]
[TestCase(DeployOnLaunchSetting.DELTA, BinarySignatureCheck.Types.Result.YesCopy)]
public async Task DeployGamePopulatesSignatureCheckModeAsync(
DeployOnLaunchSetting deploySetting,
BinarySignatureCheck.Types.Result signatureCheck)
{
string localPath = GetLocalPath();
IAsyncProject project = GetProjectWithLocalPathAndDeployMode(localPath, deploySetting);
(SshTarget target, IAction action, ICancelable cancelable) = GetDeploymentArguments();
(_, _, IRemoteDeploy deploy, _) = GetTestObjects();
await deploy.DeployGameExecutableAsync(project, target, cancelable, action);
CopyBinaryData actionEvent = action.GetEvent().CopyExecutable;
Assert.That(actionEvent.SignatureCheckResult, Is.EqualTo(signatureCheck));
}
[Test]
public async Task DeployLldbServerDeploysBinaryAndSetsExecutableBitAsync()
{
string remotePath = YetiConstants.LldbServerLinuxPath;
(IRemoteFile file, IRemoteCommand command, RemoteDeploy deploy, _) =
GetTestObjects();
string localPath = deploy.GetLldbServerPath();
(SshTarget target, IAction action, ICancelable _) = GetDeploymentArguments();
await deploy.DeployLldbServerAsync(target, action);
Assert.Multiple(async () =>
{
await file.Received(1)
.SyncAsync(target, localPath, remotePath, Arg.Any<ICancelable>());
await command.Received(1).RunWithSuccessAsync(
target, $"chmod a+x {remotePath}{YetiConstants.LldbServerLinuxExecutable}");
});
}
[Test]
public async Task DeployLldbServerPopulatesActionEventOnSuccessAsync()
{
(SshTarget target, IAction action, var _) = GetDeploymentArguments();
(_, _, RemoteDeploy deploy, _) = GetTestObjects();
await deploy.DeployLldbServerAsync(target, action);
Assert.Multiple(() =>
{
CopyBinaryData actionEvent = action.GetEvent().CopyLldbServer;
Assert.NotNull(actionEvent);
Assert.NotNull(actionEvent.CopyBinaryBytes);
Assert.IsTrue(actionEvent.CopyAttempted);
Assert.That(actionEvent.CopyExitCode, Is.EqualTo(0));
Assert.That(actionEvent.SshChmodExitCode, Is.EqualTo(0));
});
}
[Test]
public void DeployLldbServerPopulatesActionEventOnFailureInSettingExecutableBit()
{
(SshTarget target, IAction action, var _) = GetDeploymentArguments();
(_, IRemoteCommand command, RemoteDeploy deploy, _) = GetTestObjects();
command.RunWithSuccessAsync(Arg.Any<SshTarget>(), Arg.Any<string>())
.Returns(_ => throw new ProcessException(_chmodFailed));
var error = Assert.ThrowsAsync<DeployException>(
async () => await deploy.DeployLldbServerAsync(target, action));
Assert.Multiple(() =>
{
string expectedError =
ErrorStrings.FailedToSetExecutablePermissions(_chmodFailed);
Assert.That(error.Message, Is.EqualTo(expectedError));
CopyBinaryData actionEvent = action.GetEvent().CopyLldbServer;
Assert.NotNull(actionEvent);
Assert.NotNull(actionEvent.CopyBinaryBytes);
Assert.IsTrue(actionEvent.CopyAttempted);
Assert.That(actionEvent.CopyExitCode, Is.EqualTo(0));
Assert.That(actionEvent.SshChmodExitCode, Is.EqualTo(-1));
});
}
[Test]
public void DeployLldbServerPopulatesActionEventOnFailureInDeployment()
{
(SshTarget target, IAction action, var _) = GetDeploymentArguments();
(IRemoteFile file, _, RemoteDeploy deploy, _) = GetTestObjects();
file
.SyncAsync(Arg.Any<SshTarget>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<ICancelable>(), Arg.Any<bool>())
.Returns(_ => throw new ProcessException(_rsyncFailed));
var error = Assert.ThrowsAsync<DeployException>(
async () => await deploy.DeployLldbServerAsync(target, action));
Assert.Multiple(() =>
{
string expectedError = ErrorStrings.FailedToDeployExecutable(_rsyncFailed);
Assert.That(error.Message, Is.EqualTo(expectedError));
CopyBinaryData actionEvent = action.GetEvent().CopyLldbServer;
Assert.NotNull(actionEvent);
Assert.NotNull(actionEvent.CopyBinaryBytes);
Assert.IsTrue(actionEvent.CopyAttempted);
Assert.That(actionEvent.CopyExitCode, Is.EqualTo(-1));
Assert.That(actionEvent.SshChmodExitCode, Is.EqualTo(null));
});
}
[Test]
public async Task DeployVulkanLayerDeploysExecutableAndManifestAsync()
{
string remotePath = YetiConstants.OrbitVulkanLayerLinuxPath;
(IRemoteFile file, IRemoteCommand command, RemoteDeploy deploy, _) = GetTestObjects();
string localOrbitCollectorDir =
Path.Combine(SDKUtil.GetSDKPath(), YetiConstants.OrbitCollectorDir);
string localManifestPath =
Path.Combine(localOrbitCollectorDir, YetiConstants.OrbitVulkanLayerManifest);
string localLayerPath =
Path.Combine(localOrbitCollectorDir, YetiConstants.OrbitVulkanLayerExecutable);
(SshTarget target, IAction _, ICancelable task) = GetDeploymentArguments();
var project = GetProjectWithOrbitVulkanLayerDeployMode(true);
await deploy.DeployOrbitVulkanLayerAsync(project, target, task);
Assert.Multiple(async () => {
await file.Received(1).SyncAsync(target, localManifestPath, remotePath, task);
await file.Received(1).SyncAsync(target, localLayerPath, remotePath, task);
});
}
[Test]
public async Task DeployVulkanLayerDoesNotDeploysExecutableAndManifestIfDisabledAsync()
{
(IRemoteFile file, IRemoteCommand command, RemoteDeploy deploy, _) = GetTestObjects();
(SshTarget target, IAction _, ICancelable task) = GetDeploymentArguments();
var project = GetProjectWithOrbitVulkanLayerDeployMode(false);
await deploy.DeployOrbitVulkanLayerAsync(project, target, task);
Assert.Multiple(() => { file.Received(0); });
}
[Test]
public void DeployVulkanLAyerThrowsExceptionOnFailureInManifestDeployment()
{
string localManifestPath =
Path.Combine(SDKUtil.GetSDKPath(), YetiConstants.OrbitCollectorDir,
YetiConstants.OrbitVulkanLayerManifest);
(SshTarget target, IAction _, ICancelable task) = GetDeploymentArguments();
(IRemoteFile file, _, RemoteDeploy deploy, _) = GetTestObjects();
file.SyncAsync(target, localManifestPath, Arg.Any<string>(), task, Arg.Any<bool>())
.Returns(_ => throw new ProcessException(_rsyncFailed));
var project = GetProjectWithOrbitVulkanLayerDeployMode(true);
var error = Assert.ThrowsAsync<DeployException>(
async () => await deploy.DeployOrbitVulkanLayerAsync(project, target, task));
string expectedError = ErrorStrings.FailedToDeployExecutable(_rsyncFailed);
Assert.That(error.Message, Is.EqualTo(expectedError));
}
[Test]
public void DeployVulkanLAyerThrowsExceptionOnFailureInExecutableDeployment()
{
string localLayerPath =
Path.Combine(SDKUtil.GetSDKPath(), YetiConstants.OrbitCollectorDir,
YetiConstants.OrbitVulkanLayerExecutable);
(SshTarget target, IAction _, ICancelable task) = GetDeploymentArguments();
(IRemoteFile file, _, RemoteDeploy deploy, _) = GetTestObjects();
file.SyncAsync(target, localLayerPath, Arg.Any<string>(), task, Arg.Any<bool>())
.Returns(_ => throw new ProcessException(_rsyncFailed));
var project = GetProjectWithOrbitVulkanLayerDeployMode(true);
var error = Assert.ThrowsAsync<DeployException>(
async () => await deploy.DeployOrbitVulkanLayerAsync(project, target, task));
string expectedError = ErrorStrings.FailedToDeployExecutable(_rsyncFailed);
Assert.That(error.Message, Is.EqualTo(expectedError));
}
[Test]
public async Task ExecuteCustomCommandWhenRunsSuccessfullyAsync()
{
string command = "ls '/mnt/developer'";
string rootPath = @"c:\src\game\bin";
(SshTarget _, IAction action, ICancelable _) = GetDeploymentArguments();
(_, _, RemoteDeploy deploy, ManagedProcess.Factory factory) = GetTestObjects();
IProcess process = GetCustomDeployProcess(factory);
IAsyncProject project = GetProject();
var gamelet = new Gamelet();
await deploy.ExecuteCustomCommandAsync(project, gamelet, action);
Assert.Multiple(async () =>
{
await process.Received(1).RunToExitAsync();
Assert.IsTrue(action.GetEvent().CustomCommand.CustomCommandAttempted);
Assert.IsTrue(action.GetEvent().CustomCommand.CustomCommandSucceeded);
});
IAsyncProject GetProject()
{
var local = Substitute.For<IAsyncProject>();
local.GetCustomDeployOnLaunchAsync().Returns(command);
local.GetAbsoluteRootPathAsync().Returns(rootPath);
return local;
}
IProcess GetCustomDeployProcess(ManagedProcess.Factory managedProcessFactory)
{
var local = Substitute.For<IProcess>();
managedProcessFactory.CreateVisible(
Arg.Is<ProcessStartInfo>(x => x.FileName.EndsWith(YetiConstants.Command) &&
x.Arguments.Equals($"/C \"{command}\"") &&
x.WorkingDirectory == rootPath), int.MaxValue)
.Returns(local);
return local;
}
}
public (IRemoteFile file, IRemoteCommand command, RemoteDeploy deploy,
ManagedProcess.Factory factory) GetTestObjects()
{
var remoteFile = Substitute.For<IRemoteFile>();
var remoteCommand = Substitute.For<IRemoteCommand>();
var managedProcessFactory = Substitute.For<ManagedProcess.Factory>();
var remoteDeploy = new RemoteDeploy(remoteCommand, remoteFile, managedProcessFactory,
new MockFileSystem());
return (remoteFile, remoteCommand, remoteDeploy, managedProcessFactory);
}
string GetLocalPath() => $@"c:\src\game\bin\{_binaryName}";
IAsyncProject GetProjectWithLocalPathAndDeployMode(string localPath,
DeployOnLaunchSetting
deployOnLaunchSetting)
{
var project = Substitute.For<IAsyncProject>();
project.GetDeployOnLaunchAsync().Returns(deployOnLaunchSetting);
project.GetTargetPathAsync().Returns(localPath);
return project;
}
IAsyncProject GetProjectWithOrbitVulkanLayerDeployMode(bool deployOrbitVulkanLayerOnLaunch)
{
var project = Substitute.For<IAsyncProject>();
project.GetDeployOrbitVulkanLayerOnLaunch().Returns(deployOrbitVulkanLayerOnLaunch);
return project;
}
(SshTarget target, IAction action, ICancelable task) GetDeploymentArguments()
{
var target = new SshTarget(new Gamelet { Id = "instance_id", IpAddr = "1.2.3.4" });
var cancelable = Substitute.For<ICancelableTask>();
IAction action = new Action(DeveloperEventType.Types.Type.VsiDeployBinary,
Substitute.For<Timer.Factory>(),
Substitute.For<IMetrics>());
return (target, action, cancelable);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace NntpClientLib
{
/// <summary>
/// <para>
/// This is a very lightweight NNTP client library. It is written a base class the implements
/// the RFC977 and a subclass that implements common extensions. At some point one might implement
/// the RFC3997 as a stand alone replacement for both of these classes. I've not tried to make that
/// kind of transition transparent.
/// </para>
/// <para>
/// I'm using iterators to avoid building collections (either arrays or collection objects) to
/// hold the contents of the articles or headers that we receive from the server. Thus, one has
/// this template for most of the protocol requests
/// <code>
/// string server = "freenews.netfront.net";
/// using (Rfc977NntpClient client = new Rfc977NntpClient())
/// {
/// client.Connect(server);
/// int groupCount = 0;
/// foreach (NewsgroupHeader h in client.RetrieveNewsgroups())
/// {
/// groupCount++;
/// }
/// }
/// </code>
/// For more examples of how this library is used, please see the NUnit tests included in the
/// distribution.
/// </para>
/// <para>
/// One interesting aspect of this is the default text encoding for communication between the
/// library and the NNTP server. Most of the time it's undocumented and others, it's either 7 bit
/// ASCII or UTF8. Here I'm using ISO-8859-1 because I want to correctly deal with 8 bit article
/// bodies (possibly encoded in yEnc).
/// </para>
/// </summary>
public class Rfc977NntpClient : IDisposable
{
internal static readonly Encoding DefaultEncoding = Encoding.GetEncoding("iso-8859-1");
internal static IFormatProvider FormatProvider
{
get { return System.Globalization.CultureInfo.InvariantCulture; }
}
internal static System.Globalization.CultureInfo CultureInfo
{
get { return System.Globalization.CultureInfo.InvariantCulture; }
}
internal static int ConvertToInt32(string argument)
{
if (argument == null)
{
throw new ArgumentNullException("argument");
}
return Convert.ToInt32(argument, CultureInfo);
}
private NewsgroupStatistics m_currentGroup;
/// <summary>
/// Gets a value indicating whether a newgroup is selected.
/// </summary>
/// <value>
/// <c>true</c> if newsgroup selected; otherwise, <c>false</c>.
/// </value>
public bool CurrentGroupSelected
{
get { return m_currentGroup != null; }
}
/// <summary>
/// Gets the current group.
/// </summary>
/// <value>The current group.</value>
public NewsgroupStatistics CurrentGroup
{
get { return m_currentGroup; }
}
private bool m_postingIsAllowed;
/// <summary>
/// Gets or sets a value indicating whether posting is allowed.
/// </summary>
/// <value><c>true</c> if posting is allowed; otherwise, <c>false</c>.</value>
public bool PostingAllowed
{
get { return m_postingIsAllowed; }
protected set { m_postingIsAllowed = value; }
}
private int m_connectionTimeout = -1;
/// <summary>
/// Gets or sets the connection timeout.
/// </summary>
/// <value>The connection timeout.</value>
public int ConnectionTimeout
{
get { return m_connectionTimeout; }
set { m_connectionTimeout = value; }
}
private int m_port;
/// <summary>
/// Gets the port.
/// </summary>
/// <value>The port.</value>
public int Port
{
get { return m_port; }
}
private string m_host;
/// <summary>
/// Gets the host.
/// </summary>
/// <value>The host.</value>
public string Host
{
get { return m_host; }
}
/// <summary>
/// Gets a value indicating whether this <see cref="Rfc977NntpClient"/> is connected.
/// </summary>
/// <value><c>true</c> if connected; otherwise, <c>false</c>.</value>
public bool Connected
{
get { return (m_connection != null && m_connection.Connected); }
}
NntpProtocolReaderWriter m_nntpStream;
internal NntpProtocolReaderWriter NntpReaderWriter
{
get { return m_nntpStream; }
set { m_nntpStream = value; }
}
private TextWriter m_logger;
public TextWriter ProtocolLogger
{
set
{
m_logger = value;
if (NntpReaderWriter != null)
{
NntpReaderWriter.LogWriter = value;
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="Rfc977NntpClient"/> class.
/// The most common usage pattern is:
/// <code>
/// using (Rfc977NntpClient client = new Rfc977Client())
/// {
/// client.Connect("nntp.server.net", 119);
/// foreach (NewsgroupHeader header in client.RetrieveNewsgroups())
/// {
/// Console.WriteLine(header);
/// }
/// }
/// </code>
/// </summary>
public Rfc977NntpClient()
{
}
private TcpClient m_connection;
/// <summary>
/// Connects using the specified host name.
/// </summary>
/// <param name="hostName">Name of the host.</param>
public void Connect(string hostName)
{
Connect(hostName, 119);
}
/// <summary>
/// Connects using the specified host name and port number.
/// </summary>
/// <param name="hostName">Name of the host.</param>
/// <param name="port">The port.</param>
public virtual void Connect(string hostName, int port)
{
Open(hostName, port);
NntpReaderWriter.ReadResponse();
if (NntpReaderWriter.LastResponseCode == Rfc977ResponseCodes.ServerReadyPostingAllowed)
{
m_postingIsAllowed = true;
}
else if (NntpReaderWriter.LastResponseCode == Rfc977ResponseCodes.ServerReadyNoPostingAllowed)
{
m_postingIsAllowed = false;
}
else
{
throw new NntpResponseException(Resource.ErrorMessage01, NntpReaderWriter.LastResponse);
}
}
/// <summary>
/// Opens the specified host name.
/// </summary>
/// <param name="hostName">Name of the host.</param>
/// <param name="port">The port.</param>
protected virtual void Open(string hostName, int port)
{
m_host = hostName;
m_port = port;
if (string.IsNullOrEmpty(hostName))
{
throw new ArgumentNullException("hostName");
}
m_connection = new TcpClient(hostName, port);
NntpReaderWriter = new NntpProtocolReaderWriter(m_connection);
if (m_logger != null)
{
NntpReaderWriter.LogWriter = m_logger;
}
if (ConnectionTimeout != -1)
{
m_connection.SendTimeout = m_connection.ReceiveTimeout = ConnectionTimeout;
}
}
/// <summary>
/// Closes this instance.
/// </summary>
public virtual void Close()
{
if (m_connection == null)
{
return;
}
try
{
if (m_connection.Connected)
{
NntpReaderWriter.WriteCommand("QUIT");
NntpReaderWriter.Dispose();
m_nntpStream = null;
m_connection.Close();
}
}
finally
{
try
{
m_connection.Close();
}
catch
{
}
m_connection = null;
}
}
/// <summary>
/// Gets the last NNTP command.
/// </summary>
/// <value>The last NNTP command.</value>
public string LastNntpCommand
{
get { return (NntpReaderWriter == null ? null : NntpReaderWriter.LastCommand); }
}
/// <summary>
/// Gets the last NNTP response.
/// </summary>
/// <value>The last NNTP response.</value>
public string LastNntpResponse
{
get { return (NntpReaderWriter == null ? null : NntpReaderWriter.LastResponse); }
}
/// <summary>
/// Retrieves the help content from the server.
/// </summary>
/// <remarks>
/// Below is an example of the output of this command.
/// <code>
/// authinfo user Name|pass Password
/// article [MessageID|Number]
/// body [MessageID|Number]
/// check MessageID
/// value
/// group newsgroup
/// head [MessageID|Number]
/// help
/// ihave
/// last
/// list [active|active.times|newsgroups|subscriptions]
/// listgroup newsgroup
/// mode stream
/// mode reader
/// newgroups yymmdd hhmmss [GMT] [<distributions>]
/// newnews newsgroups yymmdd hhmmss [GMT] [<distributions>]
/// next
/// post
/// slave
/// stat [MessageID|Number]
/// takethis MessageID
/// xgtitle [group_pattern]
/// xhdr header [range|MessageID]
/// xover [range]
/// xpat header range|MessageID pat [morepat...]
/// </code>
/// </remarks>
/// <returns></returns>
public virtual IEnumerable<string> RetrieveHelp()
{
return DoBasicCommand("HELP", Rfc977ResponseCodes.HelpTextFollows);
}
/// <summary>
/// Retrieves the newsgroups.
/// </summary>
/// <returns></returns>
public virtual IEnumerable<NewsgroupHeader> RetrieveNewsgroups()
{
foreach (string s in DoBasicCommand("LIST", Rfc977ResponseCodes.NewsgroupsFollow))
{
yield return NewsgroupHeader.Parse(s);
}
}
/// <summary>
/// Retrieves the new newsgroups.
/// </summary>
/// <param name="dateTime">The value time.</param>
/// <returns></returns>
public IEnumerable<NewsgroupHeader> RetrieveNewNewsgroups(DateTime dateTime)
{
return RetrieveNewNewsgroups(dateTime, TimeZoneOption.None, null);
}
/// <summary>
/// Retrieves the new newsgroups.
/// </summary>
/// <param name="dateTime">The value time.</param>
/// <param name="timeZone">The time zone.</param>
/// <param name="distributions">The distributions.</param>
/// <returns></returns>
public virtual IEnumerable<NewsgroupHeader> RetrieveNewNewsgroups(DateTime dateTime, TimeZoneOption timeZone, string distributions)
{
string command = string.Format("NEWGROUPS {0:yyMMdd} {0:HHmmss}", dateTime);
if (timeZone == TimeZoneOption.UseGreenwichMeanTime)
{
command += " GMT";
}
if (!string.IsNullOrEmpty(distributions))
{
command += " ";
command += distributions;
}
foreach (string s in DoBasicCommand(command, Rfc977ResponseCodes.NewNewsgroupsFollow))
{
yield return NewsgroupHeader.Parse(s);
}
}
/// <summary>
/// Retrieves the new news for all of the groups.
/// </summary>
/// <param name="dateTime">The value time.</param>
/// <returns></returns>
public IEnumerable<string> RetrieveNewNews(DateTime dateTime)
{
return RetrieveNewNews("*", dateTime, TimeZoneOption.None, null);
}
/// <summary>
/// Retrieves the new news for the newsgroups that match the wildcard.
/// </summary>
/// <param name="newsgroupWildcardMatch">The newsgroup wildcard match.</param>
/// <param name="dateTime">The value time.</param>
/// <returns></returns>
public IEnumerable<string> RetrieveNewNews(string newsgroupWildcardMatch, DateTime dateTime)
{
return RetrieveNewNews(newsgroupWildcardMatch, dateTime, TimeZoneOption.None, null);
}
/// <summary>
/// Retrieves the new news.
/// </summary>
/// <param name="newsgroupWildcardMatch">The newsgroup wildcard match.</param>
/// <param name="dateTime">The value time.</param>
/// <param name="timeZone">The time zone.</param>
/// <param name="distributions">The distributions.</param>
/// <returns></returns>
public virtual IEnumerable<string> RetrieveNewNews(string newsgroupWildcardMatch, DateTime dateTime, TimeZoneOption timeZone, string distributions)
{
string command = string.Format("NEWNEWS {0} {1:yyMMdd} {1:HHmmss}", newsgroupWildcardMatch, dateTime);
if (timeZone == TimeZoneOption.UseGreenwichMeanTime)
{
command += " GMT";
}
if (!string.IsNullOrEmpty(distributions))
{
command += " ";
command += distributions;
}
foreach (string s in DoBasicCommand(command, Rfc977ResponseCodes.NewArticlesFollow))
{
yield return s;
}
}
/// <summary>
/// Selects the newsgroup.
/// </summary>
/// <param name="group">The group.</param>
public virtual void SelectNewsgroup(string group)
{
if (string.IsNullOrEmpty(group))
{
throw new ArgumentNullException("group");
}
ValidateConnectionState();
NntpReaderWriter.WriteCommand("GROUP " + group);
string response = NntpReaderWriter.ReadResponse();
if (NntpReaderWriter.LastResponseCode == Rfc977ResponseCodes.NewsgroupSelected)
{
string[] parts = response.Split(' ');
NewsgroupStatistics g = new NewsgroupStatistics(group, ConvertToInt32(parts[1]), ConvertToInt32(parts[2]), ConvertToInt32(parts[3]));
m_currentGroup = g;
}
else
{
m_currentGroup = null;
if (NntpReaderWriter.LastResponseCode == Rfc977ResponseCodes.NoSuchNewsgroup)
{
throw new NntpGroupNotSelectedException();
}
else
{
throw new NntpResponseException(Resource.ErrorMessage02, NntpReaderWriter.LastResponse);
}
}
}
/// <summary>
/// Sets the previous article.
/// </summary>
/// <returns></returns>
public virtual ArticleResponseIds SetPreviousArticle()
{
return SetArticleCursor("LAST");
}
/// <summary>
/// Sets the next article.
/// </summary>
/// <returns></returns>
public virtual ArticleResponseIds SetNextArticle()
{
return SetArticleCursor("NEXT");
}
/// <summary>
/// Sets the article cursor.
/// </summary>
/// <param name="direction">The direction.</param>
/// <returns></returns>
private ArticleResponseIds SetArticleCursor(string direction)
{
if (direction == null)
{
throw new ArgumentNullException("direction");
}
if (!(direction.Equals("LAST", StringComparison.InvariantCultureIgnoreCase) || direction.Equals("NEXT", StringComparison.InvariantCultureIgnoreCase)))
{
throw new ArgumentException(Resource.ErrorMessage03, "direction");
}
if (!CurrentGroupSelected)
{
throw new NntpGroupNotSelectedException();
}
ValidateConnectionState();
NntpReaderWriter.WriteCommand(direction);
NntpReaderWriter.ReadResponse();
if (NntpReaderWriter.LastResponseCode != Rfc977ResponseCodes.ArticleRetrievedTextSeparate)
{
throw new NntpResponseException(Resource.ErrorMessage04, NntpReaderWriter.LastResponse);
}
return ArticleResponseIds.Parse(NntpReaderWriter.LastResponse);
}
/// <summary>
/// Retrieves the statistics for a current article.
/// </summary>
/// <returns></returns>
public ArticleResponseIds RetrieveStatistics()
{
return RetrieveStatisticsCore("STAT");
}
/// <summary>
/// Retrieves the statistics for the selected article.
/// </summary>
/// <param name="articleId">The article id.</param>
/// <returns></returns>
public ArticleResponseIds RetrieveStatistics(int articleId)
{
// TODO: validate id?
return RetrieveStatisticsCore("STAT " + articleId);
}
/// <summary>
/// Retrieves the statistics for the selected article.
/// </summary>
/// <param name="messageId">The message id.</param>
/// <returns></returns>
public ArticleResponseIds RetrieveStatistics(string messageId)
{
ValidateMessageIdArgument(messageId);
return RetrieveStatisticsCore("STAT " + messageId);
}
/// <summary>
/// Retrieves the statistics for an article based on the command.
/// </summary>
/// <param name="command">The command.</param>
/// <returns></returns>
protected virtual ArticleResponseIds RetrieveStatisticsCore(string command)
{
ValidateConnectionState();
if (!CurrentGroupSelected)
{
throw new NntpGroupNotSelectedException();
}
NntpReaderWriter.WriteCommand(command);
NntpReaderWriter.ReadResponse();
if (NntpReaderWriter.LastResponseCode != Rfc977ResponseCodes.ArticleRetrievedTextSeparate)
{
throw new NntpResponseException(Resource.ErrorMessage05, NntpReaderWriter.LastResponse);
}
return ArticleResponseIds.Parse(NntpReaderWriter.LastResponse);
}
/// <summary>
/// Retrieves the article headers for the current article.
/// </summary>
/// <returns></returns>
public IEnumerable<ArticleHeadersDictionary> RetrieveArticleHeaders()
{
if (!CurrentGroupSelected)
{
throw new NntpGroupNotSelectedException();
}
return RetrieveArticleHeaders(CurrentGroup.FirstArticleId, CurrentGroup.LastArticleId);
}
/// <summary>
/// Retrieves the article headers for the specified range. Since this iterates over the article identifiers and
/// that range may contain identifiers that are not legal (i.e. they don't exist on the server), this method will
/// catch NNTP RFC 997 423 response codes and therefore skip the article identifier.
/// </summary>
/// <param name="firstArticleId">The first article id.</param>
/// <param name="lastArticleId">The last article id.</param>
/// <returns></returns>
public virtual IEnumerable<ArticleHeadersDictionary> RetrieveArticleHeaders(int firstArticleId, int lastArticleId)
{
if (!CurrentGroupSelected)
{
throw new NntpGroupNotSelectedException();
}
for (; firstArticleId < lastArticleId; firstArticleId++)
{
ArticleHeadersDictionary d = null;
try
{
d = RetrieveArticleHeader(firstArticleId);
}
catch (NntpResponseException error)
{
if (error.LastResponseCode == 423)
{
continue;
}
throw error;
}
yield return d;
}
}
/// <summary>
/// Retrieves the article header the current article.
/// </summary>
/// <returns></returns>
public virtual ArticleHeadersDictionary RetrieveArticleHeader()
{
return RetrieveArticleHeaderCore("HEAD");
}
/// <summary>
/// Retrieves the article header for the specified article.
/// </summary>
/// <param name="articleId">The article id.</param>
/// <returns></returns>
public virtual ArticleHeadersDictionary RetrieveArticleHeader(int articleId)
{
return RetrieveArticleHeaderCore("HEAD " + articleId);
}
/// <summary>
/// Retrieves the article header for the specified article.
/// </summary>
/// <param name="messageId">The message id.</param>
/// <returns></returns>
public virtual ArticleHeadersDictionary RetrieveArticleHeader(string messageId)
{
ValidateMessageIdArgument(messageId);
return RetrieveArticleHeaderCore("HEAD " + messageId);
}
/// <summary>
/// Retrieves the article header common functionality. The command argument
/// should be in the form "HEAD [article-id|message-id]."
/// </summary>
/// <param name="command">The command.</param>
/// <returns></returns>
protected ArticleHeadersDictionary RetrieveArticleHeaderCore(string command)
{
ArticleHeadersDictionary headers = new ArticleHeadersDictionary();
foreach (string s in DoArticleCommand(command, Rfc977ResponseCodes.ArticleRetrievedHeadFollows))
{
if (s.Length == 0)
{
break;
}
else
{
headers.AddHeader(s);
}
}
return headers;
}
public virtual IEnumerable<string> RetrieveArticleBody()
{
return DoArticleCommand("BODY", Rfc977ResponseCodes.ArticleRetrievedBodyFollows);
}
/// <summary>
/// Retrieves the article body for the specified article.
/// </summary>
/// <param name="articleId">The article id.</param>
/// <returns></returns>
public virtual IEnumerable<string> RetrieveArticleBody(int articleId)
{
return DoArticleCommand("BODY " + articleId, Rfc977ResponseCodes.ArticleRetrievedBodyFollows);
}
/// <summary>
/// Retrieves the article body for the specified message id.
/// </summary>
/// <param name="messageId">The message id.</param>
/// <returns></returns>
public virtual IEnumerable<string> RetrieveArticleBody(string messageId)
{
ValidateMessageIdArgument(messageId);
return DoArticleCommand("BODY " + messageId, Rfc977ResponseCodes.ArticleRetrievedBodyFollows);
}
/// <summary>
/// Retrieves the article that is currently selected.
/// </summary>
/// <param name="header">The header.</param>
/// <param name="body">The body.</param>
public virtual void RetrieveArticle(IArticleHeadersProcessor header, IArticleBodyProcessor body)
{
RetrieveArticleCore("ARTICLE", header, body);
}
/// <summary>
/// Retrieves the article for the specified article id.
/// </summary>
/// <param name="articleId">The article id.</param>
/// <param name="header">The header.</param>
/// <param name="body">The body.</param>
public virtual void RetrieveArticle(int articleId, IArticleHeadersProcessor header, IArticleBodyProcessor body)
{
RetrieveArticleCore("ARTICLE " + articleId, header, body);
}
/// <summary>
/// Retrieves the article for the specified message id.
/// </summary>
/// <param name="messageId">The message id.</param>
/// <param name="header">The header.</param>
/// <param name="body">The body.</param>
public virtual void RetrieveArticle(string messageId, IArticleHeadersProcessor header, IArticleBodyProcessor body)
{
ValidateMessageIdArgument(messageId);
RetrieveArticleCore("ARTICLE " + messageId, header, body);
}
private void RetrieveArticleCore(string command, IArticleHeadersProcessor headers, IArticleBodyProcessor body)
{
bool readingHeader = true;
foreach (string s in DoArticleCommand(command, Rfc977ResponseCodes.ArticleRetrieved))
{
if (readingHeader)
{
if (s.Length == 0)
{
readingHeader = false;
}
else
{
headers.AddHeader(s);
}
}
else
{
body.AddText(s);
}
}
}
/// <summary>
/// Posts the article.
/// </summary>
/// <param name="header">The header.</param>
/// <param name="body">The body.</param>
public virtual void PostArticle(IArticleHeaderEnumerator header, IEnumerable<string> body)
{
if (header == null)
{
throw new ArgumentNullException("header");
}
if (body == null)
{
throw new ArgumentNullException("body");
}
ValidateConnectionState();
NntpReaderWriter.WriteCommand("POST");
NntpReaderWriter.ReadResponse();
if (NntpReaderWriter.LastResponseCode != Rfc977ResponseCodes.SendArticleToPost)
{
throw new NntpResponseException(Resource.ErrorMessage06, NntpReaderWriter.LastResponse);
}
foreach (string key in header.HeaderKeys)
{
int count = 0;
foreach (string v in header[key])
{
if (count > 0)
{
NntpReaderWriter.Write("\t");
}
else
{
NntpReaderWriter.Write(key);
NntpReaderWriter.Write(": ");
}
NntpReaderWriter.WriteLine(v);
count++;
}
}
NntpReaderWriter.WriteLine("");
foreach (string s in body)
{
if (s.StartsWith("."))
{
NntpReaderWriter.Write(".");
}
NntpReaderWriter.WriteLine(s);
}
NntpReaderWriter.WriteLine(".");
NntpReaderWriter.ReadResponse();
if (NntpReaderWriter.LastResponseCode != Rfc977ResponseCodes.ArticlePostedOk)
{
throw new NntpResponseException(Resource.ErrorMessage07, NntpReaderWriter.LastResponse);
}
}
/// <summary>
/// Sends the slave command.
/// </summary>
public virtual void SendSlave()
{
ValidateConnectionState();
NntpReaderWriter.WriteLine("SLAVE");
NntpReaderWriter.ReadResponse();
if (NntpReaderWriter.LastResponseCode != Rfc977ResponseCodes.SlaveStatusNoted)
{
throw new NntpResponseException(Resource.ErrorMessage08, NntpReaderWriter.LastResponse);
}
}
/// <summary>
/// Validates the message id argument.
/// </summary>
/// <param name="messageId">The message id.</param>
protected static void ValidateMessageIdArgument(string messageId)
{
if (string.IsNullOrEmpty(messageId))
{
throw new ArgumentNullException("messageId");
}
if (!(messageId.StartsWith("<") && messageId.EndsWith(">")))
{
throw new ArgumentException(Resource.ErrorMessage09, "messageId");
}
if (messageId.Length < 3)
{
throw new ArgumentException(Resource.ErrorMessage10, "messageId");
}
}
/// <summary>
/// Validates the state of the connection.
/// </summary>
protected void ValidateConnectionState()
{
if (m_connection == null || !m_connection.Connected)
{
throw new InvalidOperationException(Resource.ErrorMessage11);
}
}
/// <summary>
/// Does the article command but checks that a group is currently selected.
/// </summary>
/// <param name="command">The command.</param>
/// <param name="expectedResponseCode">The expected response code.</param>
/// <returns></returns>
protected IEnumerable<string> DoArticleCommand(string command, int expectedResponseCode)
{
if (!CurrentGroupSelected)
{
throw new NntpGroupNotSelectedException();
}
return DoBasicCommand(command, expectedResponseCode);
}
/// <summary>
/// Does the basic command. In the NNTP protocol, a command is sent and the server
/// possibly returns some text and finally is returns a response code. If a server
/// returned line equal a single "." we are done and nothing more is returned. If
/// the server returns a ".." (double period) the leading period is removed and the
/// remaining string is returned.
/// </summary>
/// <param name="command">The command.</param>
/// <param name="expectedResponseCode">The expected response code.</param>
/// <returns></returns>
protected IEnumerable<string> DoBasicCommand(string command, int expectedResponseCode)
{
ValidateConnectionState();
NntpReaderWriter.WriteCommand(command);
NntpReaderWriter.ReadResponse();
if (NntpReaderWriter.LastResponseCode != expectedResponseCode)
{
throw new NntpResponseException(Resource.ErrorMessage12, NntpReaderWriter.LastResponse);
}
do
{
string line = NntpReaderWriter.ReadLine();
if (line.Equals("."))
{
break;
}
else if (line.StartsWith(".."))
{
line = line.Substring(1);
}
yield return line;
} while (true);
}
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
/// <summary>
/// Disposes the specified disposing.
/// </summary>
/// <param name="disposing">if set to <c>true</c> [disposing].</param>
protected virtual void Dispose(bool disposing)
{
if (m_connection == null) return;
if (disposing)
{
Close();
}
}
}
}
| |
#if WINDOWS
#define USE_CUSTOM_SHADER
#endif
using System;
using System.Collections.Generic;
using System.Text;
using FlatRedBall.Graphics;
using FlatRedBall.Graphics.Animation;
using FlatRedBall.Gui;
using FlatRedBall.Input;
using FlatRedBall.Math;
using FlatRedBall.Math.Geometry;
using Microsoft.Xna.Framework.Graphics;
using AnimationChain = FlatRedBall.Graphics.Animation.AnimationChain;
using Vector3 = Microsoft.Xna.Framework.Vector3;
using Vector2 = Microsoft.Xna.Framework.Vector2;
//using FlatRedBall.Content.Scene;
using FileManager = FlatRedBall.IO.FileManager;
using AnimationChainList = FlatRedBall.Graphics.Animation.AnimationChainList;
using IInstructable = FlatRedBall.Instructions.IInstructable;
using Matrix = Microsoft.Xna.Framework.Matrix;
using FlatRedBall.ManagedSpriteGroups;
using FlatRedBall.Utilities;
using FlatRedBall.Graphics.Texture;
namespace FlatRedBall
{
#region XML docs
/// <summary>
/// Delegate for methods which can be assigned to the Sprite for every-frame
/// custom logic or when a Sprite is removed.
/// </summary>
/// <remarks>
/// <seealso cref="FlatRedBall.Sprite.CustomBehavior"/>
/// <seealso cref="FlatRedBall.Sprite.Remove"/>
/// </remarks>
/// <param name="sprite">The Sprite on which the logic should execute.</param>
#endregion
public delegate void SpriteCustomBehavior(Sprite sprite);
public partial class Sprite : IColorable, ICursorSelectable,
ITexturable
#if FRB_XNA && !MONOGAME
, IMouseOver
#endif
{
#region Fields
public bool IsBillboarded;
#region Color/Fade
float mAlphaRate;
float mRedRate;
float mGreenRate;
float mBlueRate;
internal ColorOperation mColorOperation;
internal BlendOperation mBlendOperation;
// This used to only be on MonoDroid and WP7, but we need it on PC for premult alpha when using ColorOperation.Color
// internal to skip the property and speed things up a little
internal float mRed;
internal float mGreen;
internal float mBlue;
internal float mAlpha;
#endregion
#region ICursorSelectable
protected bool mCursorSelectable;
#endregion
#region Texture and pixel size
internal Texture2D mTexture; // made internal to avoid a getter in tight loops
internal float mPixelSize;
bool mFlipHorizontal;
bool mFlipVertical;
#endregion
#region Internal Drawing members
internal bool mInCameraView;
internal bool mAutomaticallyUpdated;
internal VertexPositionColorTexture[] mVerticesForDrawing;
internal Vector3 mOldPosition; // used when sorting along forward vector to hold old position
internal SpriteVertex[] mVertices;
internal bool mOrdered = true;
#endregion
#endregion
#region Properties
#region IColorable
#region XML Docs
/// <summary>
/// Controls the Sprite's transparency.
/// </summary>
/// <remarks>
/// Fade controls a Sprite's transparency. A completely opaque Sprite has an
/// Alpha of 1 while a completely transparent object has an Alpha of 0.
///
/// Setting the AlphaRate of a completely opaque Sprite to -1 will
/// make the sprite disappear in one second. Invisible Sprites continue
/// to remain in memory and are managed by the SpriteManager. The Alpha variable
/// will automatically regulate itself if the value is set to something outside of the
/// 0 - 1 range.
/// </remarks>
#endregion
public float Alpha
{
get { return mVertices[0].Color.W; }
set
{
value =
System.Math.Min(FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue, value);
value =
System.Math.Max(0, value);
mVertices[0].Color.W = value;
mVertices[1].Color.W = value;
mVertices[2].Color.W = value;
mVertices[3].Color.W = value;
mAlpha = value;
UpdateColorsAccordingToAlpha();
}
}
#region XML Docs
/// <summary>
/// Sets the rate at which the Alpha property changes. This is in units per second. A fully opaque
/// Sprite (Alpha = 1) will disappear in 1 second if its AlphaRate is set to -1.
/// </summary>
/// <remarks>
/// The AlphaRate changes Alpha as follows:
/// <para>
/// Alpha += AlphaRate * TimeManager.SecondDifference;
/// </para>
/// This is automatically applied if the Sprite is managed by the SpriteManager(usually the case).
/// </remarks>
#endregion
public float AlphaRate
{
get { return mAlphaRate; }
set
{
mAlphaRate = value;
}
}
private void UpdateColorsAccordingToAlpha()
{
float redValue = mRed;
float greenValue = mGreen;
float blueValue = mBlue;
#if USE_CUSTOM_SHADER
if (ColorOperation == Graphics.ColorOperation.Color)
#else
if (ColorOperation == Graphics.ColorOperation.Modulate ||
ColorOperation == Graphics.ColorOperation.Color ||
ColorOperation == Graphics.ColorOperation.ColorTextureAlpha ||
Texture == null
)
#endif
{
redValue = mRed * mAlpha;
greenValue = mGreen * mAlpha;
blueValue = mBlue * mAlpha;
}
else
{
#if USE_CUSTOM_SHADER
redValue = mRed;
greenValue = mGreen;
blueValue = mBlue;
#else
redValue = mAlpha;
greenValue = mAlpha;
blueValue = mAlpha;
#endif
}
if ((Texture == null || ColorOperation == Graphics.ColorOperation.Color) &&
(mBlendOperation == Graphics.BlendOperation.Modulate || mBlendOperation == Graphics.BlendOperation.Modulate2X)
)
{
float toWhiteInterpolationValue = 1 - mAlpha;
redValue = redValue + (1 - redValue) * toWhiteInterpolationValue;
greenValue = greenValue + (1 - greenValue) * toWhiteInterpolationValue;
blueValue = blueValue + (1 - blueValue) * toWhiteInterpolationValue;
}
mVertices[0].Color.X = redValue;
mVertices[1].Color.X = redValue;
mVertices[2].Color.X = redValue;
mVertices[3].Color.X = redValue;
mVertices[0].Color.Y = greenValue;
mVertices[1].Color.Y = greenValue;
mVertices[2].Color.Y = greenValue;
mVertices[3].Color.Y = greenValue;
mVertices[0].Color.Z = blueValue;
mVertices[1].Color.Z = blueValue;
mVertices[2].Color.Z = blueValue;
mVertices[3].Color.Z = blueValue;
}
public float Red
{
get
{
return mRed;
}
set
{
value =
System.Math.Min(FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue, value);
value =
System.Math.Max(-FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue, value);
mRed = value;
UpdateColorsAccordingToAlpha();
}
}
public float Green
{
get
{
return mGreen;
}
set
{
value =
System.Math.Min(FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue, value);
value =
System.Math.Max(-FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue, value);
mGreen = value;
UpdateColorsAccordingToAlpha();
}
}
public float Blue
{
get
{
return mBlue;
}
set
{
value =
System.Math.Min(FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue, value);
value =
System.Math.Max(-FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue, value);
mBlue = value;
UpdateColorsAccordingToAlpha();
}
}
public float RedRate
{
get { return mRedRate; }
set
{
mRedRate = value;
}
}
public float GreenRate
{
get { return mGreenRate; }
set
{
mGreenRate = value;
}
}
public float BlueRate
{
get { return mBlueRate; }
set
{
mBlueRate = value;
}
}
public ColorOperation ColorOperation
{
get { return mColorOperation; }
set
{
#if DEBUG
// Check for unsupporte color operations
if(Debugging.CrossPlatform.ShouldApplyRestrictionsFor(Debugging.Platform.iOS) ||
Debugging.CrossPlatform.ShouldApplyRestrictionsFor(Debugging.Platform.Android) ||
Debugging.CrossPlatform.ShouldApplyRestrictionsFor(Debugging.Platform.WindowsRt))
{
if(value == Graphics.ColorOperation.Add || value == Graphics.ColorOperation.Subtract ||
value == Graphics.ColorOperation.InterpolateColor || value == Graphics.ColorOperation.InverseTexture ||
value == Graphics.ColorOperation.Modulate2X || value == Graphics.ColorOperation.Modulate4X)
{
throw new Exception("The color operation " + value + " is not available due to platform restrictions");
}
}
#endif
mColorOperation = value;
UpdateColorsAccordingToAlpha();
}
}
public BlendOperation BlendOperation
{
get { return mBlendOperation; }
set
{
mBlendOperation = value;
UpdateColorsAccordingToAlpha();
}
}
#endregion
#region Texture and PixelSize
/// <summary>
/// The texture to be displayed by the Sprite.
/// </summary>
[ExportOrder(0)]
public Texture2D Texture
{
get { return mTexture; }
set
{
if (mTexture != value)
{
mTexture = value;
if (this.TextureAddressMode != Microsoft.Xna.Framework.Graphics.TextureAddressMode.Clamp &&
FlatRedBallServices.GraphicsDevice.GraphicsProfile == GraphicsProfile.Reach && mTexture != null)
{
bool isNotPowerOfTwo = !MathFunctions.IsPowerOfTwo (mTexture.Width) ||
!MathFunctions.IsPowerOfTwo (mTexture.Height);
if (isNotPowerOfTwo)
{
throw new NotImplementedException (
"The texture " +
mTexture.Name +
" must be power of two if using non-Clamp texture address mode on Reach");
}
}
UpdateColorsAccordingToAlpha ();
UpdateScale ();
}
}
}
AtlasedTexture atlasedTexture;
public AtlasedTexture AtlasedTexture
{
get
{
return atlasedTexture;
}
set
{
atlasedTexture = value;
// todo - eventually we don't want to modify the original values, just use this in rendering, but
// I'm doing this to get it implemented quickly:
Texture = atlasedTexture.Texture;
LeftTexturePixel = atlasedTexture.SourceRectangle.Left;
TopTexturePixel = atlasedTexture.SourceRectangle.Top;
RightTexturePixel = atlasedTexture.SourceRectangle.Right;
BottomTexturePixel = atlasedTexture.SourceRectangle.Bottom;
}
}
[ExportOrder(1)]
[Obsolete("Use TextureScale")]
public float PixelSize
{
get { return mPixelSize; }
set
{
mPixelSize = value;
UpdateScale();
}
}
/// <summary>
/// The relationship between the displayed portion of the Sprite's texture and
/// its Width/Height. If this value is less than or equal to 0, then Width and Height
/// values are not set according to the displayed portion of the Sprite's texture. Otherwise,
/// the displayed portion of the texture are multiplied by this value to determine the Sprite's
/// Width and Height.
/// </summary>
public float TextureScale
{
get
{
return mPixelSize * 2.0f;
}
set
{
PixelSize = value / 2.0f;
}
}
#region XML Docs
/// <summary>
/// Whether to flip the Sprite's texture on the y Axis (left and right switch).
/// </summary>
/// <remarks>
/// This kind of texture rotation can be accomplished by simply rotating
/// a Sprite on its yAxis; however, there are times when this
/// is inconvenient or impossible due to attachment relationships. There
/// is no efficiency consequence for using either method. If a Sprite
/// is animated, this value will be overwritten by the AnimationChain being used.
/// </remarks>
#endregion
public bool FlipHorizontal
{
get { return mFlipHorizontal; }
set { mFlipHorizontal = value; }
}
#region XML Docs
/// <summary>
/// Whether to flip the Sprite's texture on the x Axis (top and bottom switch).
/// </summary>
/// <remarks>
/// This kind of texture rotation can be accomplished by simply rotating a
/// Sprite on its xAxis; however, there are times when this
/// is inconvenient or impossible due to attachment relationships.
/// There is no efficiency consequence for using either method. If a Sprite
/// is animated, this value will be overwritten by the AnimationChain being used.
/// </remarks>
#endregion
public bool FlipVertical
{
get { return mFlipVertical; }
set { mFlipVertical = value; }
}
/// <summary>
/// The top coordinate in texture coordinates on the sprite. Default is 0.
/// This value is in texture coordinates, not pixels. A value of 1 represents the bottom-side of the texture.
/// </summary>
[ExportOrder(2)]
public float TopTextureCoordinate
{
get { return mVertices[0].TextureCoordinate.Y; }
set
{
mVertices[0].TextureCoordinate.Y = value;
mVertices[1].TextureCoordinate.Y = value;
UpdateScale();
}
}
/// <summary>
/// The top pixel displayed on the sprite. Default is 0.
/// This value is in pixel coordiantes, so it typically ranges from 0 to the height of the referenced texture.
/// </summary>
[ExportOrder(2)]
public float TopTexturePixel
{
get
{
if (Texture != null)
{
return TopTextureCoordinate * Texture.Height;
}
else
{
return 0;
}
}
set
{
if (Texture != null)
{
TopTextureCoordinate = value / Texture.Height;
}
else
{
throw new Exception("You must have a Texture set before setting this value");
}
}
}
[ExportOrder(2)]
public float BottomTextureCoordinate
{
get { return mVertices[2].TextureCoordinate.Y; }
set
{
mVertices[2].TextureCoordinate.Y = value;
mVertices[3].TextureCoordinate.Y = value;
UpdateScale();
}
}
[ExportOrder(2)]
public float BottomTexturePixel
{
get
{
if (Texture != null)
{
return BottomTextureCoordinate * Texture.Height;
}
else
{
return 0;
}
}
set
{
if (Texture != null)
{
BottomTextureCoordinate = value / Texture.Height;
}
else
{
throw new Exception("You must have a Texture set before setting this value");
}
}
}
[ExportOrder(2)]
public float LeftTextureCoordinate
{
get { return mVertices[0].TextureCoordinate.X; }
set
{
mVertices[0].TextureCoordinate.X = value;
mVertices[3].TextureCoordinate.X = value;
UpdateScale();
}
}
[ExportOrder(2)]
public float LeftTexturePixel
{
get
{
if (Texture != null)
{
return LeftTextureCoordinate * Texture.Width;
}
else
{
return 0;
}
}
set
{
if (Texture != null)
{
LeftTextureCoordinate = value / Texture.Width;
}
else
{
throw new Exception("You must have a Texture set before setting this value");
}
}
}
[ExportOrder(2)]
public float RightTextureCoordinate
{
get { return mVertices[1].TextureCoordinate.X; }
set
{
mVertices[1].TextureCoordinate.X = value;
mVertices[2].TextureCoordinate.X = value;
UpdateScale();
}
}
[ExportOrder(2)]
public float RightTexturePixel
{
get
{
if (Texture != null)
{
return RightTextureCoordinate * Texture.Width;
}
else
{
return 0;
}
}
set
{
if (mTexture != null)
{
RightTextureCoordinate = value / (float)mTexture.Width;
}
else
{
throw new Exception("You must have a Texture set before setting this value");
}
}
}
public TextureAddressMode TextureAddressMode;
public TextureFilter? TextureFilter;
#endregion
#region XML Docs
/// <summary>
/// These can be used to change Sprite appearance
/// on individual vertices.
/// </summary>
/// <remarks>
/// The index begins counting at the top left (index 0)
/// and increases moving clockwise.
/// </remarks>
#endregion
public SpriteVertex[] Vertices
{
get { return mVertices; }
}
/// <summary>
/// Represents the four (4) vertices used to render the Sprite. This value is set
/// if the Sprite is either a manuall updated Sprite, or if the SpriteManager's ManualUpdate
/// method is called on this.
/// </summary>
public VertexPositionColorTexture[] VerticesForDrawing
{
get { return mVerticesForDrawing; }
}
#endregion
#region Events
// Vic says - I tried removing this but it is used by particles so we'd need a new list for particles to be removed when out of screen.
[Obsolete("Do not use this! This will go away. Use the Entity pattern instead")]
public SpriteCustomBehavior CustomBehavior;
public event SpriteCustomBehavior Remove;
#endregion
#region Methods
#region Constructor
public Sprite()
: base()
{
mVisible = true;
mScaleX = 1;
mScaleY = 1;
mVertices = new SpriteVertex[4];
mVertices[0] = new SpriteVertex();
mVertices[1] = new SpriteVertex();
mVertices[2] = new SpriteVertex();
mVertices[3] = new SpriteVertex();
mVertices[0].TextureCoordinate.X = 0;
mVertices[0].TextureCoordinate.Y = 0;
mVertices[0].Scale = new Vector2(-1, 1);
mVertices[1].TextureCoordinate.X = 1;
mVertices[1].TextureCoordinate.Y = 0;
mVertices[1].Scale = new Vector2(1, 1);
mVertices[2].TextureCoordinate.X = 1;
mVertices[2].TextureCoordinate.Y = 1;
mVertices[2].Scale = new Vector2(1, -1);
mVertices[3].TextureCoordinate.X = 0;
mVertices[3].TextureCoordinate.Y = 1;
mVertices[3].Scale = new Vector2(-1, -1);
TimeCreated = TimeManager.CurrentTime;
#if MONODROID
mVertices[0].Color.X = 1;
mVertices[1].Color.X = 1;
mVertices[2].Color.X = 1;
mVertices[3].Color.X = 1;
mVertices[0].Color.Y = 1;
mVertices[1].Color.Y = 1;
mVertices[2].Color.Y = 1;
mVertices[3].Color.Y = 1;
mVertices[0].Color.Z = 1;
mVertices[1].Color.Z = 1;
mVertices[2].Color.Z = 1;
mVertices[3].Color.Z = 1;
mVertices[0].Color.W = 1;
mVertices[1].Color.W = 1;
mVertices[2].Color.W = 1;
mVertices[3].Color.W = 1;
#endif
Alpha = GraphicalEnumerations.MaxColorComponentValue;
ColorOperation = ColorOperation.Texture;
mAnimationChains = new AnimationChainList();
mCurrentChainIndex = -1;
mAnimationSpeed = 1;
TextureAddressMode = TextureAddressMode.Clamp;
mCursorSelectable = true;
}
#endregion
#region Internal Methods
internal void OnCustomBehavior()
{
if (CustomBehavior != null)
CustomBehavior(this);
}
internal void OnRemove()
{
if (Remove != null)
Remove(this);
}
internal void UpdateVertices()
{
// Vic says: I tried to optimize this on
// March 6, 2011 for the windows phone - I
// couldn't get it to run any faster on the
// the emulator. Seems like it's pretty darn
// optimized.
mVertices[0].Position.X = (mScaleX * mVertices[0].Scale.X);
mVertices[1].Position.X = (mScaleX * mVertices[1].Scale.X);
mVertices[2].Position.X = (mScaleX * mVertices[2].Scale.X);
mVertices[3].Position.X = (mScaleX * mVertices[3].Scale.X);
mVertices[0].Position.Y = (mScaleY * mVertices[0].Scale.Y);
mVertices[1].Position.Y = (mScaleY * mVertices[1].Scale.Y);
mVertices[2].Position.Y = (mScaleY * mVertices[2].Scale.Y);
mVertices[3].Position.Y = (mScaleY * mVertices[3].Scale.Y);
mVertices[0].Position.Z = 0;
mVertices[1].Position.Z = 0;
mVertices[2].Position.Z = 0;
mVertices[3].Position.Z = 0;
if (IsBillboarded)
{
Matrix modifiedMatrix = mRotationMatrix * Camera.Main.RotationMatrix;
MathFunctions.TransformVector(ref mVertices[0].Position, ref modifiedMatrix);
MathFunctions.TransformVector(ref mVertices[1].Position, ref modifiedMatrix);
MathFunctions.TransformVector(ref mVertices[2].Position, ref modifiedMatrix);
MathFunctions.TransformVector(ref mVertices[3].Position, ref modifiedMatrix);
}
else
{
MathFunctions.TransformVector(ref mVertices[0].Position, ref mRotationMatrix);
MathFunctions.TransformVector(ref mVertices[1].Position, ref mRotationMatrix);
MathFunctions.TransformVector(ref mVertices[2].Position, ref mRotationMatrix);
MathFunctions.TransformVector(ref mVertices[3].Position, ref mRotationMatrix);
}
mVertices[0].Position += Position;
mVertices[1].Position += Position;
mVertices[2].Position += Position;
mVertices[3].Position += Position;
}
#endregion
#region Public Methods
public override void ForceUpdateDependenciesDeep()
{
base.ForceUpdateDependenciesDeep();
SpriteManager.ManualUpdate(this);
}
/// <summary>
/// Updates the sprite according to its current AnimationChain and AnimationFrame. Specifically this updates
/// - Texture
/// - Texture coordiantes
/// - Flip Horizontal (if IgnoreAnimationChainTextureFlip is true)
/// - Relative X and Y (if UseAnimationRelativePosition is true
/// - Executes AnimationFrame instructions
/// - Adjusts the size of the sprite if its TextureScale
/// </summary>
/// <remarks>
/// This method is automatically called for sprites which are automatically updated (default) and which are using
/// an AnimationChain. This can be manually called after assigning the AnimationFrame and AnimationChain.
/// </remarks>
public void UpdateToCurrentAnimationFrame()
{
if (mAnimationChains != null && mAnimationChains.Count > mCurrentChainIndex && mCurrentChainIndex != -1 &&
mCurrentFrameIndex > -1 &&
mCurrentFrameIndex < mAnimationChains[mCurrentChainIndex].Count)
{
var frame = mAnimationChains[mCurrentChainIndex][mCurrentFrameIndex];
// Set the property so that any necessary values change:
// mTexture = mAnimationChains[mCurrentChainIndex][mCurrentFrameIndex].Texture;
Texture = frame.Texture;
this.Vertices[0].TextureCoordinate.X = frame.LeftCoordinate;
this.Vertices[1].TextureCoordinate.X = frame.RightCoordinate;
this.Vertices[2].TextureCoordinate.X = frame.RightCoordinate;
this.Vertices[3].TextureCoordinate.X = frame.LeftCoordinate;
this.Vertices[0].TextureCoordinate.Y = frame.TopCoordinate;
this.Vertices[1].TextureCoordinate.Y = frame.TopCoordinate;
this.Vertices[2].TextureCoordinate.Y = frame.BottomCoordinate;
this.Vertices[3].TextureCoordinate.Y = frame.BottomCoordinate;
if (mIgnoreAnimationChainTextureFlip == false)
{
mFlipHorizontal = frame.FlipHorizontal;
mFlipVertical = frame.FlipVertical;
}
if (mUseAnimationRelativePosition)
{
RelativePosition.X = frame.RelativeX;
RelativePosition.Y = frame.RelativeY;
}
foreach(var instruction in frame.Instructions)
{
instruction.Execute();
}
UpdateScale();
}
}
#region XML Docs
/// <summary>
/// Returns a clone of this instance.
/// </summary>
/// <remarks>
/// Attachments are not cloned. The new clone
/// will not have any parents or children.
/// </remarks>
/// <returns>The new clone.</returns>
#endregion
public Sprite Clone()
{
Sprite sprite = base.Clone<Sprite>();
sprite.Texture = Texture;
sprite.FlipHorizontal = FlipHorizontal;
sprite.FlipVertical = FlipVertical;
sprite.ColorOperation = mColorOperation;
// Although the Scale has already been set at this point, set it again so that it will
// override the PixelSize IF the PixelSize is being overridden by the current scale:
sprite.ScaleX = ScaleX;
sprite.ScaleY = ScaleY;
sprite.TimeCreated = TimeManager.CurrentTime;
sprite.mVertices = new SpriteVertex[4];
for (int i = 0; i < 4; i++)
{
sprite.mVertices[i] = new SpriteVertex(mVertices[i]);
}
sprite.mVerticesForDrawing = new VertexPositionColorTexture[4];
sprite.mAnimationChains = new AnimationChainList();
for (int i = 0; i < mAnimationChains.Count; i++)
{
AnimationChain ac = mAnimationChains[i];
sprite.mAnimationChains.Add(ac);
}
if (CustomBehavior != null)
{
#if XNA4
throw new NotSupportedException("Sprite custom behavior is not supported in XNA 4");
#else
sprite.CustomBehavior = CustomBehavior.Clone() as SpriteCustomBehavior;
#endif
}
return sprite;
}
[Obsolete("Do not use this! This will go away. Use the Entity pattern instead", error:true)]
public void CopyCustomBehaviorFrom(Sprite spriteToCopyFrom)
{
if (spriteToCopyFrom.CustomBehavior != null)
{
this.CustomBehavior = null;
CustomBehavior += spriteToCopyFrom.CustomBehavior;
}
}
private void PlatformSpecificInitialization()
{
mColorOperation = ColorOperation.Texture;
mBlendOperation = BlendOperation.Regular;
// This is needed because SpriteChains may
// use particle Sprites which can screw up
mVertices[0].TextureCoordinate.X = 0;
mVertices[0].TextureCoordinate.Y = 0;
mVertices[0].Scale = new Vector2(-1, 1);
mVertices[1].TextureCoordinate.X = 1;
mVertices[1].TextureCoordinate.Y = 0;
mVertices[1].Scale = new Vector2(1, 1);
mVertices[2].TextureCoordinate.X = 1;
mVertices[2].TextureCoordinate.Y = 1;
mVertices[2].Scale = new Vector2(1, -1);
mVertices[3].TextureCoordinate.X = 0;
mVertices[3].TextureCoordinate.Y = 1;
mVertices[3].Scale = new Vector2(-1, -1);
CustomBehavior = null;
}
#if FRB_XNA && !MONOGAME
#region IMouseOver
bool IMouseOver.IsMouseOver(Cursor cursor)
{
return cursor.IsOn3D(this);
}
public bool IsMouseOver(Cursor cursor, Layer layer)
{
return cursor.IsOn3D(this, layer);
}
#endregion
#endif
public override string ToString()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(base.ToString());
if (Texture != null)
sb.Append("\nTexture: ").Append(this.Texture.Name);
sb.Append("\nVisible: ").Append(Visible.ToString());
return sb.ToString();
}
#endregion
#region Private Methods
private void UpdateScale()
{
if (mPixelSize > 0 && mTexture != null)
{
mScaleX = mTexture.Width * mPixelSize * (mVertices[1].TextureCoordinate.X - mVertices[0].TextureCoordinate.X);
mScaleY = mTexture.Height * mPixelSize * (mVertices[2].TextureCoordinate.Y - mVertices[1].TextureCoordinate.Y);
}
}
#endregion
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// ReSharper disable UnassignedField.Global
// ReSharper disable CollectionNeverUpdated.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
namespace Apache.Ignite.Core.Tests.Binary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Binary;
using NUnit.Framework;
/// <summary>
/// Binary builder self test.
/// </summary>
public class BinaryBuilderSelfTest
{
/** Undefined type: Empty. */
private const string TypeEmpty = "EmptyUndefined";
/** Grid. */
private Ignite _grid;
/** Marshaller. */
private Marshaller _marsh;
/// <summary>
/// Set up routine.
/// </summary>
[TestFixtureSetUp]
public void SetUp()
{
TestUtils.KillProcesses();
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = new List<BinaryTypeConfiguration>
{
new BinaryTypeConfiguration(typeof (Empty)),
new BinaryTypeConfiguration(typeof (Primitives)),
new BinaryTypeConfiguration(typeof (PrimitiveArrays)),
new BinaryTypeConfiguration(typeof (StringDateGuidEnum)),
new BinaryTypeConfiguration(typeof (WithRaw)),
new BinaryTypeConfiguration(typeof (MetaOverwrite)),
new BinaryTypeConfiguration(typeof (NestedOuter)),
new BinaryTypeConfiguration(typeof (NestedInner)),
new BinaryTypeConfiguration(typeof (MigrationOuter)),
new BinaryTypeConfiguration(typeof (MigrationInner)),
new BinaryTypeConfiguration(typeof (InversionOuter)),
new BinaryTypeConfiguration(typeof (InversionInner)),
new BinaryTypeConfiguration(typeof (CompositeOuter)),
new BinaryTypeConfiguration(typeof (CompositeInner)),
new BinaryTypeConfiguration(typeof (CompositeArray)),
new BinaryTypeConfiguration(typeof (CompositeContainer)),
new BinaryTypeConfiguration(typeof (ToBinary)),
new BinaryTypeConfiguration(typeof (Remove)),
new BinaryTypeConfiguration(typeof (RemoveInner)),
new BinaryTypeConfiguration(typeof (BuilderInBuilderOuter)),
new BinaryTypeConfiguration(typeof (BuilderInBuilderInner)),
new BinaryTypeConfiguration(typeof (BuilderCollection)),
new BinaryTypeConfiguration(typeof (BuilderCollectionItem)),
new BinaryTypeConfiguration(typeof (DecimalHolder)),
new BinaryTypeConfiguration(TypeEmpty),
new BinaryTypeConfiguration(typeof(TestEnumRegistered)),
new BinaryTypeConfiguration(typeof(NameMapperTestType))
},
DefaultIdMapper = new IdMapper(),
DefaultNameMapper = new NameMapper(),
CompactFooter = GetCompactFooter()
}
};
_grid = (Ignite) Ignition.Start(cfg);
_marsh = _grid.Marshaller;
}
/// <summary>
/// Gets the compact footer setting.
/// </summary>
protected virtual bool GetCompactFooter()
{
return true;
}
/// <summary>
/// Tear down routine.
/// </summary>
[TestFixtureTearDown]
public void TearDown()
{
if (_grid != null)
Ignition.Stop(_grid.Name, true);
_grid = null;
}
/// <summary>
/// Ensure that binary engine is able to work with type names, which are not configured.
/// </summary>
[Test]
public void TestNonConfigured()
{
string typeName1 = "Type1";
string typeName2 = "Type2";
string field1 = "field1";
string field2 = "field2";
// 1. Ensure that builder works fine.
IBinaryObject binObj1 = _grid.GetBinary().GetBuilder(typeName1).SetField(field1, 1).Build();
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
// 2. Ensure that object can be unmarshalled without deserialization.
byte[] data = ((BinaryObject) binObj1).Data;
binObj1 = _grid.Marshaller.Unmarshal<IBinaryObject>(data, BinaryMode.ForceBinary);
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
// 3. Ensure that we can nest one anonymous object inside another
IBinaryObject binObj2 =
_grid.GetBinary().GetBuilder(typeName2).SetField(field2, binObj1).Build();
Assert.AreEqual(typeName2, binObj2.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj2.GetBinaryType().Fields.Count);
Assert.AreEqual(field2, binObj2.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, binObj2.GetBinaryType().GetFieldTypeName(field2));
binObj1 = binObj2.GetField<IBinaryObject>(field2);
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
// 4. Ensure that we can unmarshal object with other nested object.
data = ((BinaryObject) binObj2).Data;
binObj2 = _grid.Marshaller.Unmarshal<IBinaryObject>(data, BinaryMode.ForceBinary);
Assert.AreEqual(typeName2, binObj2.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj2.GetBinaryType().Fields.Count);
Assert.AreEqual(field2, binObj2.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, binObj2.GetBinaryType().GetFieldTypeName(field2));
binObj1 = binObj2.GetField<IBinaryObject>(field2);
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
}
/// <summary>
/// Test "ToBinary()" method.
/// </summary>
[Test]
public void TestToBinary()
{
DateTime date = DateTime.Now.ToUniversalTime();
Guid guid = Guid.NewGuid();
IBinary api = _grid.GetBinary();
// 1. Primitives.
Assert.AreEqual(1, api.ToBinary<byte>((byte)1));
Assert.AreEqual(1, api.ToBinary<short>((short)1));
Assert.AreEqual(1, api.ToBinary<int>(1));
Assert.AreEqual(1, api.ToBinary<long>((long)1));
Assert.AreEqual((float)1, api.ToBinary<float>((float)1));
Assert.AreEqual((double)1, api.ToBinary<double>((double)1));
Assert.AreEqual(true, api.ToBinary<bool>(true));
Assert.AreEqual('a', api.ToBinary<char>('a'));
// 2. Special types.
Assert.AreEqual("a", api.ToBinary<string>("a"));
Assert.AreEqual(date, api.ToBinary<DateTime>(date));
Assert.AreEqual(guid, api.ToBinary<Guid>(guid));
Assert.AreEqual(TestEnumRegistered.One, api.ToBinary<IBinaryObject>(TestEnumRegistered.One)
.Deserialize<TestEnumRegistered>());
// 3. Arrays.
Assert.AreEqual(new byte[] { 1 }, api.ToBinary<byte[]>(new byte[] { 1 }));
Assert.AreEqual(new short[] { 1 }, api.ToBinary<short[]>(new short[] { 1 }));
Assert.AreEqual(new[] { 1 }, api.ToBinary<int[]>(new[] { 1 }));
Assert.AreEqual(new long[] { 1 }, api.ToBinary<long[]>(new long[] { 1 }));
Assert.AreEqual(new float[] { 1 }, api.ToBinary<float[]>(new float[] { 1 }));
Assert.AreEqual(new double[] { 1 }, api.ToBinary<double[]>(new double[] { 1 }));
Assert.AreEqual(new[] { true }, api.ToBinary<bool[]>(new[] { true }));
Assert.AreEqual(new[] { 'a' }, api.ToBinary<char[]>(new[] { 'a' }));
Assert.AreEqual(new[] { "a" }, api.ToBinary<string[]>(new[] { "a" }));
Assert.AreEqual(new[] { date }, api.ToBinary<DateTime[]>(new[] { date }));
Assert.AreEqual(new[] { guid }, api.ToBinary<Guid[]>(new[] { guid }));
Assert.AreEqual(new[] { TestEnumRegistered.One},
api.ToBinary<IBinaryObject[]>(new[] { TestEnumRegistered.One})
.Select(x => x.Deserialize<TestEnumRegistered>()).ToArray());
// 4. Objects.
IBinaryObject binObj = api.ToBinary<IBinaryObject>(new ToBinary(1));
Assert.AreEqual(typeof(ToBinary).Name, binObj.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj.GetBinaryType().Fields.Count);
Assert.AreEqual("Val", binObj.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj.GetBinaryType().GetFieldTypeName("Val"));
Assert.AreEqual(1, binObj.GetField<int>("val"));
Assert.AreEqual(1, binObj.Deserialize<ToBinary>().Val);
// 5. Object array.
var binObjArr = api.ToBinary<object[]>(new object[] {new ToBinary(1)})
.OfType<IBinaryObject>().ToArray();
Assert.AreEqual(1, binObjArr.Length);
Assert.AreEqual(1, binObjArr[0].GetField<int>("Val"));
Assert.AreEqual(1, binObjArr[0].Deserialize<ToBinary>().Val);
}
/// <summary>
/// Test builder field remove logic.
/// </summary>
[Test]
public void TestRemove()
{
// Create empty object.
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(Remove)).Build();
Assert.IsNull(binObj.GetField<object>("val"));
Assert.IsNull(binObj.Deserialize<Remove>().Val);
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(Remove).Name, meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
// Populate it with field.
IBinaryObjectBuilder builder = binObj.ToBuilder();
Assert.IsNull(builder.GetField<object>("val"));
object val = 1;
builder.SetField("val", val);
Assert.AreEqual(val, builder.GetField<object>("val"));
binObj = builder.Build();
Assert.AreEqual(val, binObj.GetField<object>("val"));
Assert.AreEqual(val, binObj.Deserialize<Remove>().Val);
meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(Remove).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("val", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("val"));
// Perform field remove.
builder = binObj.ToBuilder();
Assert.AreEqual(val, builder.GetField<object>("val"));
builder.RemoveField("val");
Assert.IsNull(builder.GetField<object>("val"));
builder.SetField("val", val);
Assert.AreEqual(val, builder.GetField<object>("val"));
builder.RemoveField("val");
Assert.IsNull(builder.GetField<object>("val"));
binObj = builder.Build();
Assert.IsNull(binObj.GetField<object>("val"));
Assert.IsNull(binObj.Deserialize<Remove>().Val);
// Test correct removal of field being referenced by handle somewhere else.
RemoveInner inner = new RemoveInner(2);
binObj = _grid.GetBinary().GetBuilder(typeof(Remove))
.SetField("val", inner)
.SetField("val2", inner)
.Build();
binObj = binObj.ToBuilder().RemoveField("val").Build();
Remove obj = binObj.Deserialize<Remove>();
Assert.IsNull(obj.Val);
Assert.AreEqual(2, obj.Val2.Val);
}
/// <summary>
/// Test builder-in-builder scenario.
/// </summary>
[Test]
public void TestBuilderInBuilder()
{
// Test different builders assembly.
IBinaryObjectBuilder builderOuter = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderOuter));
IBinaryObjectBuilder builderInner = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderInner));
builderOuter.SetField<object>("inner", builderInner);
builderInner.SetField<object>("outer", builderOuter);
IBinaryObject outerbinObj = builderOuter.Build();
IBinaryType meta = outerbinObj.GetBinaryType();
Assert.AreEqual(typeof(BuilderInBuilderOuter).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("inner", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner"));
IBinaryObject innerbinObj = outerbinObj.GetField<IBinaryObject>("inner");
meta = innerbinObj.GetBinaryType();
Assert.AreEqual(typeof(BuilderInBuilderInner).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("outer", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("outer"));
BuilderInBuilderOuter outer = outerbinObj.Deserialize<BuilderInBuilderOuter>();
Assert.AreSame(outer, outer.Inner.Outer);
// Test same builders assembly.
innerbinObj = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderInner)).Build();
outerbinObj = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderOuter))
.SetField("inner", innerbinObj)
.SetField("inner2", innerbinObj)
.Build();
meta = outerbinObj.GetBinaryType();
Assert.AreEqual(typeof(BuilderInBuilderOuter).Name, meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.IsTrue(meta.Fields.Contains("inner"));
Assert.IsTrue(meta.Fields.Contains("inner2"));
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner"));
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner2"));
outer = outerbinObj.Deserialize<BuilderInBuilderOuter>();
Assert.AreSame(outer.Inner, outer.Inner2);
builderOuter = _grid.GetBinary().GetBuilder(outerbinObj);
IBinaryObjectBuilder builderInner2 = builderOuter.GetField<IBinaryObjectBuilder>("inner2");
builderInner2.SetField("outer", builderOuter);
outerbinObj = builderOuter.Build();
outer = outerbinObj.Deserialize<BuilderInBuilderOuter>();
Assert.AreSame(outer, outer.Inner.Outer);
Assert.AreSame(outer.Inner, outer.Inner2);
}
/// <summary>
/// Test for decimals building.
/// </summary>
[Test]
public void TestDecimals()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(DecimalHolder))
.SetField("val", decimal.One)
.SetField("valArr", new decimal?[] { decimal.MinusOne })
.Build();
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(DecimalHolder).Name, meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.IsTrue(meta.Fields.Contains("val"));
Assert.IsTrue(meta.Fields.Contains("valArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameDecimal, meta.GetFieldTypeName("val"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayDecimal, meta.GetFieldTypeName("valArr"));
Assert.AreEqual(decimal.One, binObj.GetField<decimal>("val"));
Assert.AreEqual(new decimal?[] { decimal.MinusOne }, binObj.GetField<decimal?[]>("valArr"));
DecimalHolder obj = binObj.Deserialize<DecimalHolder>();
Assert.AreEqual(decimal.One, obj.Val);
Assert.AreEqual(new decimal?[] { decimal.MinusOne }, obj.ValArr);
}
/// <summary>
/// Test for an object returning collection of builders.
/// </summary>
[Test]
public void TestBuilderCollection()
{
// Test collection with single element.
IBinaryObjectBuilder builderCol = _grid.GetBinary().GetBuilder(typeof(BuilderCollection));
IBinaryObjectBuilder builderItem =
_grid.GetBinary().GetBuilder(typeof(BuilderCollectionItem)).SetField("val", 1);
builderCol.SetCollectionField("col", new ArrayList { builderItem });
IBinaryObject binCol = builderCol.Build();
IBinaryType meta = binCol.GetBinaryType();
Assert.AreEqual(typeof(BuilderCollection).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("col", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameCollection, meta.GetFieldTypeName("col"));
var binColItems = binCol.GetField<ArrayList>("col");
Assert.AreEqual(1, binColItems.Count);
var binItem = (IBinaryObject) binColItems[0];
meta = binItem.GetBinaryType();
Assert.AreEqual(typeof(BuilderCollectionItem).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("val", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, meta.GetFieldTypeName("val"));
BuilderCollection col = binCol.Deserialize<BuilderCollection>();
Assert.IsNotNull(col.Col);
Assert.AreEqual(1, col.Col.Count);
Assert.AreEqual(1, ((BuilderCollectionItem) col.Col[0]).Val);
// Add more binary objects to collection.
builderCol = _grid.GetBinary().GetBuilder(binCol);
IList builderColItems = builderCol.GetField<IList>("col");
Assert.AreEqual(1, builderColItems.Count);
BinaryObjectBuilder builderColItem = (BinaryObjectBuilder) builderColItems[0];
builderColItem.SetField("val", 2); // Change nested value.
builderColItems.Add(builderColItem); // Add the same object to check handles.
builderColItems.Add(builderItem); // Add item from another builder.
builderColItems.Add(binItem); // Add item in binary form.
binCol = builderCol.Build();
col = binCol.Deserialize<BuilderCollection>();
Assert.AreEqual(4, col.Col.Count);
var item0 = (BuilderCollectionItem) col.Col[0];
var item1 = (BuilderCollectionItem) col.Col[1];
var item2 = (BuilderCollectionItem) col.Col[2];
var item3 = (BuilderCollectionItem) col.Col[3];
Assert.AreEqual(2, item0.Val);
Assert.AreSame(item0, item1);
Assert.AreNotSame(item0, item2);
Assert.AreNotSame(item0, item3);
Assert.AreEqual(1, item2.Val);
Assert.AreEqual(1, item3.Val);
Assert.AreNotSame(item2, item3);
// Test handle update inside collection.
builderCol = _grid.GetBinary().GetBuilder(binCol);
builderColItems = builderCol.GetField<IList>("col");
((BinaryObjectBuilder) builderColItems[1]).SetField("val", 3);
binCol = builderCol.Build();
col = binCol.Deserialize<BuilderCollection>();
item0 = (BuilderCollectionItem) col.Col[0];
item1 = (BuilderCollectionItem) col.Col[1];
Assert.AreEqual(3, item0.Val);
Assert.AreSame(item0, item1);
}
/// <summary>
/// Test build of an empty object.
/// </summary>
[Test]
public void TestEmptyDefined()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(Empty)).Build();
Assert.IsNotNull(binObj);
Assert.AreEqual(0, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.IsNotNull(meta);
Assert.AreEqual(typeof(Empty).Name, meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
Empty obj = binObj.Deserialize<Empty>();
Assert.IsNotNull(obj);
}
/// <summary>
/// Test build of an empty undefined object.
/// </summary>
[Test]
public void TestEmptyUndefined()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(TypeEmpty).Build();
Assert.IsNotNull(binObj);
Assert.AreEqual(0, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.IsNotNull(meta);
Assert.AreEqual(TypeEmpty, meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
}
/// <summary>
/// Test object rebuild with no changes.
/// </summary>
[Test]
public void TestEmptyRebuild()
{
var binObj = (BinaryObject) _grid.GetBinary().GetBuilder(typeof(Empty)).Build();
BinaryObject newbinObj = (BinaryObject) _grid.GetBinary().GetBuilder(binObj).Build();
Assert.AreEqual(binObj.Data, newbinObj.Data);
}
/// <summary>
/// Test hash code alteration.
/// </summary>
[Test]
public void TestHashCodeChange()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(Empty)).SetHashCode(100).Build();
Assert.AreEqual(100, binObj.GetHashCode());
}
/// <summary>
/// Tests equality and formatting members.
/// </summary>
[Test]
public void TestEquality()
{
var bin = _grid.GetBinary();
var obj1 = bin.GetBuilder("myType").SetStringField("str", "foo").SetIntField("int", 1).Build();
var obj2 = bin.GetBuilder("myType").SetStringField("str", "foo").SetIntField("int", 1).Build();
Assert.AreEqual(obj1, obj2);
Assert.AreEqual(obj1.GetHashCode(), obj2.GetHashCode());
Assert.IsTrue(Regex.IsMatch(obj1.ToString(), @"myType \[idHash=[0-9]+, str=foo, int=1\]"));
}
/// <summary>
/// Test primitive fields setting.
/// </summary>
[Test]
public void TestPrimitiveFields()
{
// Generic SetField method.
var binObj = _grid.GetBinary().GetBuilder(typeof(Primitives))
.SetField<byte>("fByte", 1)
.SetField("fBool", true)
.SetField<short>("fShort", 2)
.SetField("fChar", 'a')
.SetField("fInt", 3)
.SetField<long>("fLong", 4)
.SetField<float>("fFloat", 5)
.SetField<double>("fDouble", 6)
.SetField("fDecimal", 7.7m)
.SetHashCode(100)
.Build();
CheckPrimitiveFields1(binObj);
// Specific setter methods.
binObj = _grid.GetBinary().GetBuilder(typeof(Primitives))
.SetByteField("fByte", 1)
.SetBooleanField("fBool", true)
.SetShortField("fShort", 2)
.SetCharField("fChar", 'a')
.SetIntField("fInt", 3)
.SetLongField("fLong", 4)
.SetFloatField("fFloat", 5)
.SetDoubleField("fDouble", 6)
.SetDecimalField("fDecimal", 7.7m)
.SetHashCode(100)
.Build();
CheckPrimitiveFields1(binObj);
// Overwrite with generic methods.
binObj = binObj.ToBuilder()
.SetField<byte>("fByte", 7)
.SetField("fBool", false)
.SetField<short>("fShort", 8)
.SetField("fChar", 'b')
.SetField("fInt", 9)
.SetField<long>("fLong", 10)
.SetField<float>("fFloat", 11)
.SetField<double>("fDouble", 12)
.SetField("fDecimal", 13.13m)
.SetHashCode(200)
.Build();
CheckPrimitiveFields2(binObj);
// Overwrite with specific methods.
binObj = binObj.ToBuilder()
.SetByteField("fByte", 7)
.SetBooleanField("fBool", false)
.SetShortField("fShort", 8)
.SetCharField("fChar", 'b')
.SetIntField("fInt", 9)
.SetLongField("fLong", 10)
.SetFloatField("fFloat", 11)
.SetDoubleField("fDouble", 12)
.SetDecimalField("fDecimal", 13.13m)
.SetHashCode(200)
.Build();
CheckPrimitiveFields2(binObj);
}
/// <summary>
/// Checks the primitive fields values.
/// </summary>
private static void CheckPrimitiveFields1(IBinaryObject binObj)
{
Assert.AreEqual(100, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(Primitives).Name, meta.TypeName);
Assert.AreEqual(9, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameByte, meta.GetFieldTypeName("fByte"));
Assert.AreEqual(BinaryTypeNames.TypeNameBool, meta.GetFieldTypeName("fBool"));
Assert.AreEqual(BinaryTypeNames.TypeNameShort, meta.GetFieldTypeName("fShort"));
Assert.AreEqual(BinaryTypeNames.TypeNameChar, meta.GetFieldTypeName("fChar"));
Assert.AreEqual(BinaryTypeNames.TypeNameInt, meta.GetFieldTypeName("fInt"));
Assert.AreEqual(BinaryTypeNames.TypeNameLong, meta.GetFieldTypeName("fLong"));
Assert.AreEqual(BinaryTypeNames.TypeNameFloat, meta.GetFieldTypeName("fFloat"));
Assert.AreEqual(BinaryTypeNames.TypeNameDouble, meta.GetFieldTypeName("fDouble"));
Assert.AreEqual(BinaryTypeNames.TypeNameDecimal, meta.GetFieldTypeName("fDecimal"));
Assert.AreEqual(1, binObj.GetField<byte>("fByte"));
Assert.AreEqual(true, binObj.GetField<bool>("fBool"));
Assert.AreEqual(2, binObj.GetField<short>("fShort"));
Assert.AreEqual('a', binObj.GetField<char>("fChar"));
Assert.AreEqual(3, binObj.GetField<int>("fInt"));
Assert.AreEqual(4, binObj.GetField<long>("fLong"));
Assert.AreEqual(5, binObj.GetField<float>("fFloat"));
Assert.AreEqual(6, binObj.GetField<double>("fDouble"));
Assert.AreEqual(7.7m, binObj.GetField<decimal>("fDecimal"));
Primitives obj = binObj.Deserialize<Primitives>();
Assert.AreEqual(1, obj.FByte);
Assert.AreEqual(true, obj.FBool);
Assert.AreEqual(2, obj.FShort);
Assert.AreEqual('a', obj.FChar);
Assert.AreEqual(3, obj.FInt);
Assert.AreEqual(4, obj.FLong);
Assert.AreEqual(5, obj.FFloat);
Assert.AreEqual(6, obj.FDouble);
Assert.AreEqual(7.7m, obj.FDecimal);
}
/// <summary>
/// Checks the primitive fields values.
/// </summary>
private static void CheckPrimitiveFields2(IBinaryObject binObj)
{
Assert.AreEqual(200, binObj.GetHashCode());
Assert.AreEqual(7, binObj.GetField<byte>("fByte"));
Assert.AreEqual(false, binObj.GetField<bool>("fBool"));
Assert.AreEqual(8, binObj.GetField<short>("fShort"));
Assert.AreEqual('b', binObj.GetField<char>("fChar"));
Assert.AreEqual(9, binObj.GetField<int>("fInt"));
Assert.AreEqual(10, binObj.GetField<long>("fLong"));
Assert.AreEqual(11, binObj.GetField<float>("fFloat"));
Assert.AreEqual(12, binObj.GetField<double>("fDouble"));
Assert.AreEqual(13.13m, binObj.GetField<decimal>("fDecimal"));
var obj = binObj.Deserialize<Primitives>();
Assert.AreEqual(7, obj.FByte);
Assert.AreEqual(false, obj.FBool);
Assert.AreEqual(8, obj.FShort);
Assert.AreEqual('b', obj.FChar);
Assert.AreEqual(9, obj.FInt);
Assert.AreEqual(10, obj.FLong);
Assert.AreEqual(11, obj.FFloat);
Assert.AreEqual(12, obj.FDouble);
Assert.AreEqual(13.13m, obj.FDecimal);
}
/// <summary>
/// Test primitive array fields setting.
/// </summary>
[Test]
public void TestPrimitiveArrayFields()
{
// Generic SetField method.
var binObj = _grid.GetBinary().GetBuilder(typeof(PrimitiveArrays))
.SetField("fByte", new byte[] { 1 })
.SetField("fBool", new[] { true })
.SetField("fShort", new short[] { 2 })
.SetField("fChar", new[] { 'a' })
.SetField("fInt", new[] { 3 })
.SetField("fLong", new long[] { 4 })
.SetField("fFloat", new float[] { 5 })
.SetField("fDouble", new double[] { 6 })
.SetField("fDecimal", new decimal?[] { 7.7m })
.SetHashCode(100)
.Build();
CheckPrimitiveArrayFields1(binObj);
// Specific setters.
binObj = _grid.GetBinary().GetBuilder(typeof(PrimitiveArrays))
.SetByteArrayField("fByte", new byte[] {1})
.SetBooleanArrayField("fBool", new[] {true})
.SetShortArrayField("fShort", new short[] {2})
.SetCharArrayField("fChar", new[] {'a'})
.SetIntArrayField("fInt", new[] {3})
.SetLongArrayField("fLong", new long[] {4})
.SetFloatArrayField("fFloat", new float[] {5})
.SetDoubleArrayField("fDouble", new double[] {6})
.SetDecimalArrayField("fDecimal", new decimal?[] {7.7m})
.SetHashCode(100)
.Build();
// Overwrite with generic setter.
binObj = _grid.GetBinary().GetBuilder(binObj)
.SetField("fByte", new byte[] { 7 })
.SetField("fBool", new[] { false })
.SetField("fShort", new short[] { 8 })
.SetField("fChar", new[] { 'b' })
.SetField("fInt", new[] { 9 })
.SetField("fLong", new long[] { 10 })
.SetField("fFloat", new float[] { 11 })
.SetField("fDouble", new double[] { 12 })
.SetField("fDecimal", new decimal?[] { 13.13m })
.SetHashCode(200)
.Build();
CheckPrimitiveArrayFields2(binObj);
// Overwrite with specific setters.
binObj = _grid.GetBinary().GetBuilder(binObj)
.SetByteArrayField("fByte", new byte[] { 7 })
.SetBooleanArrayField("fBool", new[] { false })
.SetShortArrayField("fShort", new short[] { 8 })
.SetCharArrayField("fChar", new[] { 'b' })
.SetIntArrayField("fInt", new[] { 9 })
.SetLongArrayField("fLong", new long[] { 10 })
.SetFloatArrayField("fFloat", new float[] { 11 })
.SetDoubleArrayField("fDouble", new double[] { 12 })
.SetDecimalArrayField("fDecimal", new decimal?[] { 13.13m })
.SetHashCode(200)
.Build();
CheckPrimitiveArrayFields2(binObj);
}
/// <summary>
/// Checks the primitive array fields.
/// </summary>
private static void CheckPrimitiveArrayFields1(IBinaryObject binObj)
{
Assert.AreEqual(100, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(PrimitiveArrays).Name, meta.TypeName);
Assert.AreEqual(9, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameArrayByte, meta.GetFieldTypeName("fByte"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayBool, meta.GetFieldTypeName("fBool"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayShort, meta.GetFieldTypeName("fShort"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayChar, meta.GetFieldTypeName("fChar"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayInt, meta.GetFieldTypeName("fInt"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayLong, meta.GetFieldTypeName("fLong"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayFloat, meta.GetFieldTypeName("fFloat"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayDouble, meta.GetFieldTypeName("fDouble"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayDecimal, meta.GetFieldTypeName("fDecimal"));
Assert.AreEqual(new byte[] { 1 }, binObj.GetField<byte[]>("fByte"));
Assert.AreEqual(new[] { true }, binObj.GetField<bool[]>("fBool"));
Assert.AreEqual(new short[] { 2 }, binObj.GetField<short[]>("fShort"));
Assert.AreEqual(new[] { 'a' }, binObj.GetField<char[]>("fChar"));
Assert.AreEqual(new[] { 3 }, binObj.GetField<int[]>("fInt"));
Assert.AreEqual(new long[] { 4 }, binObj.GetField<long[]>("fLong"));
Assert.AreEqual(new float[] { 5 }, binObj.GetField<float[]>("fFloat"));
Assert.AreEqual(new double[] { 6 }, binObj.GetField<double[]>("fDouble"));
Assert.AreEqual(new decimal?[] { 7.7m }, binObj.GetField<decimal?[]>("fDecimal"));
PrimitiveArrays obj = binObj.Deserialize<PrimitiveArrays>();
Assert.AreEqual(new byte[] { 1 }, obj.FByte);
Assert.AreEqual(new[] { true }, obj.FBool);
Assert.AreEqual(new short[] { 2 }, obj.FShort);
Assert.AreEqual(new[] { 'a' }, obj.FChar);
Assert.AreEqual(new[] { 3 }, obj.FInt);
Assert.AreEqual(new long[] { 4 }, obj.FLong);
Assert.AreEqual(new float[] { 5 }, obj.FFloat);
Assert.AreEqual(new double[] { 6 }, obj.FDouble);
Assert.AreEqual(new decimal?[] { 7.7m }, obj.FDecimal);
}
/// <summary>
/// Checks the primitive array fields.
/// </summary>
private static void CheckPrimitiveArrayFields2(IBinaryObject binObj)
{
Assert.AreEqual(200, binObj.GetHashCode());
Assert.AreEqual(new byte[] { 7 }, binObj.GetField<byte[]>("fByte"));
Assert.AreEqual(new[] { false }, binObj.GetField<bool[]>("fBool"));
Assert.AreEqual(new short[] { 8 }, binObj.GetField<short[]>("fShort"));
Assert.AreEqual(new[] { 'b' }, binObj.GetField<char[]>("fChar"));
Assert.AreEqual(new[] { 9 }, binObj.GetField<int[]>("fInt"));
Assert.AreEqual(new long[] { 10 }, binObj.GetField<long[]>("fLong"));
Assert.AreEqual(new float[] { 11 }, binObj.GetField<float[]>("fFloat"));
Assert.AreEqual(new double[] { 12 }, binObj.GetField<double[]>("fDouble"));
Assert.AreEqual(new decimal?[] { 13.13m }, binObj.GetField<decimal?[]>("fDecimal"));
var obj = binObj.Deserialize<PrimitiveArrays>();
Assert.AreEqual(new byte[] { 7 }, obj.FByte);
Assert.AreEqual(new[] { false }, obj.FBool);
Assert.AreEqual(new short[] { 8 }, obj.FShort);
Assert.AreEqual(new[] { 'b' }, obj.FChar);
Assert.AreEqual(new[] { 9 }, obj.FInt);
Assert.AreEqual(new long[] { 10 }, obj.FLong);
Assert.AreEqual(new float[] { 11 }, obj.FFloat);
Assert.AreEqual(new double[] { 12 }, obj.FDouble);
Assert.AreEqual(new decimal?[] { 13.13m }, obj.FDecimal);
}
/// <summary>
/// Test non-primitive fields and their array counterparts.
/// </summary>
[Test]
public void TestStringDateGuidEnum()
{
DateTime? nDate = DateTime.Now.ToUniversalTime();
Guid? nGuid = Guid.NewGuid();
// Generic setters.
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(StringDateGuidEnum))
.SetField("fStr", "str")
.SetField("fNDate", nDate)
.SetTimestampField("fNTimestamp", nDate)
.SetField("fNGuid", nGuid)
.SetField("fEnum", TestEnum.One)
.SetStringArrayField("fStrArr", new[] { "str" })
.SetArrayField("fDateArr", new[] { nDate })
.SetTimestampArrayField("fTimestampArr", new[] { nDate })
.SetGuidArrayField("fGuidArr", new[] { nGuid })
.SetEnumArrayField("fEnumArr", new[] { TestEnum.One })
.SetHashCode(100)
.Build();
CheckStringDateGuidEnum1(binObj, nDate, nGuid);
// Specific setters.
binObj = _grid.GetBinary().GetBuilder(typeof(StringDateGuidEnum))
.SetStringField("fStr", "str")
.SetField("fNDate", nDate)
.SetTimestampField("fNTimestamp", nDate)
.SetGuidField("fNGuid", nGuid)
.SetEnumField("fEnum", TestEnum.One)
.SetStringArrayField("fStrArr", new[] { "str" })
.SetArrayField("fDateArr", new[] { nDate })
.SetTimestampArrayField("fTimestampArr", new[] { nDate })
.SetGuidArrayField("fGuidArr", new[] { nGuid })
.SetEnumArrayField("fEnumArr", new[] { TestEnum.One })
.SetHashCode(100)
.Build();
CheckStringDateGuidEnum1(binObj, nDate, nGuid);
// Overwrite.
nDate = DateTime.Now.ToUniversalTime();
nGuid = Guid.NewGuid();
binObj = _grid.GetBinary().GetBuilder(typeof(StringDateGuidEnum))
.SetField("fStr", "str2")
.SetField("fNDate", nDate)
.SetTimestampField("fNTimestamp", nDate)
.SetField("fNGuid", nGuid)
.SetField("fEnum", TestEnum.Two)
.SetField("fStrArr", new[] { "str2" })
.SetArrayField("fDateArr", new[] { nDate })
.SetTimestampArrayField("fTimestampArr", new[] { nDate })
.SetField("fGuidArr", new[] { nGuid })
.SetField("fEnumArr", new[] { TestEnum.Two })
.SetHashCode(200)
.Build();
CheckStringDateGuidEnum2(binObj, nDate, nGuid);
// Overwrite with specific setters
binObj = _grid.GetBinary().GetBuilder(typeof(StringDateGuidEnum))
.SetStringField("fStr", "str2")
.SetField("fNDate", nDate)
.SetTimestampField("fNTimestamp", nDate)
.SetGuidField("fNGuid", nGuid)
.SetEnumField("fEnum", TestEnum.Two)
.SetStringArrayField("fStrArr", new[] { "str2" })
.SetArrayField("fDateArr", new[] { nDate })
.SetTimestampArrayField("fTimestampArr", new[] { nDate })
.SetGuidArrayField("fGuidArr", new[] { nGuid })
.SetEnumArrayField("fEnumArr", new[] { TestEnum.Two })
.SetHashCode(200)
.Build();
CheckStringDateGuidEnum2(binObj, nDate, nGuid);
}
/// <summary>
/// Checks the string date guid enum values.
/// </summary>
private void CheckStringDateGuidEnum1(IBinaryObject binObj, DateTime? nDate, Guid? nGuid)
{
Assert.AreEqual(100, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(StringDateGuidEnum).Name, meta.TypeName);
Assert.AreEqual(10, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameString, meta.GetFieldTypeName("fStr"));
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("fNDate"));
Assert.AreEqual(BinaryTypeNames.TypeNameTimestamp, meta.GetFieldTypeName("fNTimestamp"));
Assert.AreEqual(BinaryTypeNames.TypeNameGuid, meta.GetFieldTypeName("fNGuid"));
Assert.AreEqual(BinaryTypeNames.TypeNameEnum, meta.GetFieldTypeName("fEnum"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayString, meta.GetFieldTypeName("fStrArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("fDateArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayTimestamp, meta.GetFieldTypeName("fTimestampArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayGuid, meta.GetFieldTypeName("fGuidArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayEnum, meta.GetFieldTypeName("fEnumArr"));
Assert.AreEqual("str", binObj.GetField<string>("fStr"));
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNDate"));
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNTimestamp"));
Assert.AreEqual(nGuid, binObj.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.One, binObj.GetField<TestEnum>("fEnum"));
Assert.AreEqual(new[] {"str"}, binObj.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] {nDate}, binObj.GetField<DateTime?[]>("fDateArr"));
Assert.AreEqual(new[] {nDate}, binObj.GetField<DateTime?[]>("fTimestampArr"));
Assert.AreEqual(new[] {nGuid}, binObj.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] {TestEnum.One}, binObj.GetField<TestEnum[]>("fEnumArr"));
StringDateGuidEnum obj = binObj.Deserialize<StringDateGuidEnum>();
Assert.AreEqual("str", obj.FStr);
Assert.AreEqual(nDate, obj.FnDate);
Assert.AreEqual(nDate, obj.FnTimestamp);
Assert.AreEqual(nGuid, obj.FnGuid);
Assert.AreEqual(TestEnum.One, obj.FEnum);
Assert.AreEqual(new[] {"str"}, obj.FStrArr);
Assert.AreEqual(new[] {nDate}, obj.FDateArr);
Assert.AreEqual(new[] {nGuid}, obj.FGuidArr);
Assert.AreEqual(new[] {TestEnum.One}, obj.FEnumArr);
// Check builder field caching.
var builder = _grid.GetBinary().GetBuilder(binObj);
Assert.AreEqual("str", builder.GetField<string>("fStr"));
Assert.AreEqual(nDate, builder.GetField<DateTime?>("fNDate"));
Assert.AreEqual(nDate, builder.GetField<DateTime?>("fNTimestamp"));
Assert.AreEqual(nGuid, builder.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.One, builder.GetField<TestEnum>("fEnum"));
Assert.AreEqual(new[] {"str"}, builder.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] {nDate}, builder.GetField<DateTime?[]>("fDateArr"));
Assert.AreEqual(new[] {nDate}, builder.GetField<DateTime?[]>("fTimestampArr"));
Assert.AreEqual(new[] {nGuid}, builder.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] {TestEnum.One}, builder.GetField<TestEnum[]>("fEnumArr"));
// Check reassemble.
binObj = builder.Build();
Assert.AreEqual("str", binObj.GetField<string>("fStr"));
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNDate"));
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNTimestamp"));
Assert.AreEqual(nGuid, binObj.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.One, binObj.GetField<TestEnum>("fEnum"));
Assert.AreEqual(new[] {"str"}, binObj.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] {nDate}, binObj.GetField<DateTime?[]>("fDateArr"));
Assert.AreEqual(new[] {nDate}, binObj.GetField<DateTime?[]>("fTimestampArr"));
Assert.AreEqual(new[] {nGuid}, binObj.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] {TestEnum.One}, binObj.GetField<TestEnum[]>("fEnumArr"));
obj = binObj.Deserialize<StringDateGuidEnum>();
Assert.AreEqual("str", obj.FStr);
Assert.AreEqual(nDate, obj.FnDate);
Assert.AreEqual(nDate, obj.FnTimestamp);
Assert.AreEqual(nGuid, obj.FnGuid);
Assert.AreEqual(TestEnum.One, obj.FEnum);
Assert.AreEqual(new[] {"str"}, obj.FStrArr);
Assert.AreEqual(new[] {nDate}, obj.FDateArr);
Assert.AreEqual(new[] {nGuid}, obj.FGuidArr);
Assert.AreEqual(new[] {TestEnum.One}, obj.FEnumArr);
}
/// <summary>
/// Checks the string date guid enum values.
/// </summary>
private static void CheckStringDateGuidEnum2(IBinaryObject binObj, DateTime? nDate, Guid? nGuid)
{
Assert.AreEqual(200, binObj.GetHashCode());
Assert.AreEqual("str2", binObj.GetField<string>("fStr"));
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNDate"));
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNTimestamp"));
Assert.AreEqual(nGuid, binObj.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.Two, binObj.GetField<TestEnum>("fEnum"));
Assert.AreEqual(new[] { "str2" }, binObj.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] { nDate }, binObj.GetField<DateTime?[]>("fDateArr"));
Assert.AreEqual(new[] { nDate }, binObj.GetField<DateTime?[]>("fTimestampArr"));
Assert.AreEqual(new[] { nGuid }, binObj.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] { TestEnum.Two }, binObj.GetField<TestEnum[]>("fEnumArr"));
var obj = binObj.Deserialize<StringDateGuidEnum>();
Assert.AreEqual("str2", obj.FStr);
Assert.AreEqual(nDate, obj.FnDate);
Assert.AreEqual(nDate, obj.FnTimestamp);
Assert.AreEqual(nGuid, obj.FnGuid);
Assert.AreEqual(TestEnum.Two, obj.FEnum);
Assert.AreEqual(new[] { "str2" }, obj.FStrArr);
Assert.AreEqual(new[] { nDate }, obj.FDateArr);
Assert.AreEqual(new[] { nGuid }, obj.FGuidArr);
Assert.AreEqual(new[] { TestEnum.Two }, obj.FEnumArr);
}
[Test]
public void TestEnumMeta()
{
var bin = _grid.GetBinary();
// Put to cache to populate metas
var binEnum = bin.ToBinary<IBinaryObject>(TestEnumRegistered.One);
Assert.AreEqual(_marsh.GetDescriptor(typeof (TestEnumRegistered)).TypeId, binEnum.GetBinaryType().TypeId);
Assert.AreEqual(0, binEnum.EnumValue);
var meta = binEnum.GetBinaryType();
Assert.IsTrue(meta.IsEnum);
Assert.AreEqual(typeof (TestEnumRegistered).Name, meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
}
/// <summary>
/// Test arrays.
/// </summary>
[Test]
public void TestCompositeArray()
{
// 1. Test simple array.
object[] inArr = { new CompositeInner(1) };
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(CompositeArray)).SetHashCode(100)
.SetField("inArr", inArr).Build();
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(CompositeArray).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("inArr"));
Assert.AreEqual(100, binObj.GetHashCode());
var binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(1, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
CompositeArray arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(1, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner) arr.InArr[0]).Val);
// 2. Test addition to array.
binObj = _grid.GetBinary().GetBuilder(binObj).SetHashCode(200)
.SetField("inArr", new[] { binInArr[0], null }).Build();
Assert.AreEqual(200, binObj.GetHashCode());
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
Assert.IsNull(binInArr[1]);
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner) arr.InArr[0]).Val);
Assert.IsNull(arr.InArr[1]);
binInArr[1] = _grid.GetBinary().GetBuilder(typeof(CompositeInner)).SetField("val", 2).Build();
binObj = _grid.GetBinary().GetBuilder(binObj).SetHashCode(300)
.SetField("inArr", binInArr.OfType<object>().ToArray()).Build();
Assert.AreEqual(300, binObj.GetHashCode());
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
Assert.AreEqual(2, binInArr[1].GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[0]).Val);
Assert.AreEqual(2, ((CompositeInner)arr.InArr[1]).Val);
// 3. Test top-level handle inversion.
CompositeInner inner = new CompositeInner(1);
inArr = new object[] { inner, inner };
binObj = _grid.GetBinary().GetBuilder(typeof(CompositeArray)).SetHashCode(100)
.SetField("inArr", inArr).Build();
Assert.AreEqual(100, binObj.GetHashCode());
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
Assert.AreEqual(1, binInArr[1].GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[0]).Val);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[1]).Val);
binInArr[0] = _grid.GetBinary().GetBuilder(typeof(CompositeInner)).SetField("val", 2).Build();
binObj = _grid.GetBinary().GetBuilder(binObj).SetHashCode(200)
.SetField("inArr", binInArr.ToArray<object>()).Build();
Assert.AreEqual(200, binObj.GetHashCode());
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(2, binInArr[0].GetField<int>("val"));
Assert.AreEqual(1, binInArr[1].GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(2, ((CompositeInner)arr.InArr[0]).Val);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[1]).Val);
// 4. Test nested object handle inversion.
CompositeOuter[] outArr = { new CompositeOuter(inner), new CompositeOuter(inner) };
binObj = _grid.GetBinary().GetBuilder(typeof(CompositeArray)).SetHashCode(100)
.SetField("outArr", outArr.ToArray<object>()).Build();
meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(CompositeArray).Name, meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("inArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("outArr"));
Assert.AreEqual(100, binObj.GetHashCode());
var binOutArr = binObj.GetField<IBinaryObject[]>("outArr").ToArray();
Assert.AreEqual(2, binOutArr.Length);
Assert.AreEqual(1, binOutArr[0].GetField<IBinaryObject>("inner").GetField<int>("val"));
Assert.AreEqual(1, binOutArr[1].GetField<IBinaryObject>("inner").GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.InArr);
Assert.AreEqual(2, arr.OutArr.Length);
Assert.AreEqual(1, ((CompositeOuter) arr.OutArr[0]).Inner.Val);
Assert.AreEqual(1, ((CompositeOuter) arr.OutArr[0]).Inner.Val);
binOutArr[0] = _grid.GetBinary().GetBuilder(typeof(CompositeOuter))
.SetField("inner", new CompositeInner(2)).Build();
binObj = _grid.GetBinary().GetBuilder(binObj).SetHashCode(200)
.SetField("outArr", binOutArr.ToArray<object>()).Build();
Assert.AreEqual(200, binObj.GetHashCode());
binInArr = binObj.GetField<IBinaryObject[]>("outArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(2, binOutArr[0].GetField<IBinaryObject>("inner").GetField<int>("val"));
Assert.AreEqual(1, binOutArr[1].GetField<IBinaryObject>("inner").GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.InArr);
Assert.AreEqual(2, arr.OutArr.Length);
Assert.AreEqual(2, ((CompositeOuter)arr.OutArr[0]).Inner.Val);
Assert.AreEqual(1, ((CompositeOuter)arr.OutArr[1]).Inner.Val);
}
/// <summary>
/// Test container types other than array.
/// </summary>
[Test]
public void TestCompositeContainer()
{
ArrayList col = new ArrayList();
IDictionary dict = new Hashtable();
col.Add(new CompositeInner(1));
dict[3] = new CompositeInner(3);
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(CompositeContainer)).SetHashCode(100)
.SetCollectionField("col", col)
.SetDictionaryField("dict", dict).Build();
// 1. Check meta.
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(CompositeContainer).Name, meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameCollection, meta.GetFieldTypeName("col"));
Assert.AreEqual(BinaryTypeNames.TypeNameMap, meta.GetFieldTypeName("dict"));
// 2. Check in binary form.
Assert.AreEqual(1, binObj.GetField<ICollection>("col").Count);
Assert.AreEqual(1, binObj.GetField<ICollection>("col").OfType<IBinaryObject>().First()
.GetField<int>("val"));
Assert.AreEqual(1, binObj.GetField<IDictionary>("dict").Count);
Assert.AreEqual(3, ((IBinaryObject) binObj.GetField<IDictionary>("dict")[3]).GetField<int>("val"));
// 3. Check in deserialized form.
CompositeContainer obj = binObj.Deserialize<CompositeContainer>();
Assert.AreEqual(1, obj.Col.Count);
Assert.AreEqual(1, obj.Col.OfType<CompositeInner>().First().Val);
Assert.AreEqual(1, obj.Dict.Count);
Assert.AreEqual(3, ((CompositeInner) obj.Dict[3]).Val);
}
/// <summary>
/// Ensure that raw data is not lost during build.
/// </summary>
[Test]
public void TestRawData()
{
var raw = new WithRaw
{
A = 1,
B = 2
};
var binObj = _marsh.Unmarshal<IBinaryObject>(_marsh.Marshal(raw), BinaryMode.ForceBinary);
raw = binObj.Deserialize<WithRaw>();
Assert.AreEqual(1, raw.A);
Assert.AreEqual(2, raw.B);
IBinaryObject newbinObj = _grid.GetBinary().GetBuilder(binObj).SetField("a", 3).Build();
raw = newbinObj.Deserialize<WithRaw>();
Assert.AreEqual(3, raw.A);
Assert.AreEqual(2, raw.B);
}
/// <summary>
/// Test nested objects.
/// </summary>
[Test]
public void TestNested()
{
// 1. Create from scratch.
IBinaryObjectBuilder builder = _grid.GetBinary().GetBuilder(typeof(NestedOuter));
NestedInner inner1 = new NestedInner {Val = 1};
builder.SetField("inner1", inner1);
IBinaryObject outerbinObj = builder.Build();
IBinaryType meta = outerbinObj.GetBinaryType();
Assert.AreEqual(typeof(NestedOuter).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner1"));
IBinaryObject innerbinObj1 = outerbinObj.GetField<IBinaryObject>("inner1");
IBinaryType innerMeta = innerbinObj1.GetBinaryType();
Assert.AreEqual(typeof(NestedInner).Name, innerMeta.TypeName);
Assert.AreEqual(1, innerMeta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameInt, innerMeta.GetFieldTypeName("Val"));
inner1 = innerbinObj1.Deserialize<NestedInner>();
Assert.AreEqual(1, inner1.Val);
NestedOuter outer = outerbinObj.Deserialize<NestedOuter>();
Assert.AreEqual(outer.Inner1.Val, 1);
Assert.IsNull(outer.Inner2);
// 2. Add another field over existing binary object.
builder = _grid.GetBinary().GetBuilder(outerbinObj);
NestedInner inner2 = new NestedInner {Val = 2};
builder.SetField("inner2", inner2);
outerbinObj = builder.Build();
outer = outerbinObj.Deserialize<NestedOuter>();
Assert.AreEqual(1, outer.Inner1.Val);
Assert.AreEqual(2, outer.Inner2.Val);
// 3. Try setting inner object in binary form.
innerbinObj1 = _grid.GetBinary().GetBuilder(innerbinObj1).SetField("val", 3).Build();
inner1 = innerbinObj1.Deserialize<NestedInner>();
Assert.AreEqual(3, inner1.Val);
outerbinObj = _grid.GetBinary().GetBuilder(outerbinObj).SetField<object>("inner1", innerbinObj1).Build();
outer = outerbinObj.Deserialize<NestedOuter>();
Assert.AreEqual(3, outer.Inner1.Val);
Assert.AreEqual(2, outer.Inner2.Val);
}
/// <summary>
/// Test handle migration.
/// </summary>
[Test]
public void TestHandleMigration()
{
// 1. Simple comparison of results.
MigrationInner inner = new MigrationInner {Val = 1};
MigrationOuter outer = new MigrationOuter
{
Inner1 = inner,
Inner2 = inner
};
byte[] outerBytes = _marsh.Marshal(outer);
IBinaryObjectBuilder builder = _grid.GetBinary().GetBuilder(typeof(MigrationOuter));
builder.SetHashCode(outer.GetHashCode());
builder.SetField<object>("inner1", inner);
builder.SetField<object>("inner2", inner);
BinaryObject portOuter = (BinaryObject) builder.Build();
byte[] portOuterBytes = new byte[outerBytes.Length];
Buffer.BlockCopy(portOuter.Data, 0, portOuterBytes, 0, portOuterBytes.Length);
Assert.AreEqual(outerBytes, portOuterBytes);
// 2. Change the first inner object so that the handle must migrate.
MigrationInner inner1 = new MigrationInner {Val = 2};
IBinaryObject portOuterMigrated =
_grid.GetBinary().GetBuilder(portOuter).SetField<object>("inner1", inner1).Build();
MigrationOuter outerMigrated = portOuterMigrated.Deserialize<MigrationOuter>();
Assert.AreEqual(2, outerMigrated.Inner1.Val);
Assert.AreEqual(1, outerMigrated.Inner2.Val);
// 3. Change the first value using serialized form.
IBinaryObject inner1Port =
_grid.GetBinary().GetBuilder(typeof(MigrationInner)).SetField("val", 2).Build();
portOuterMigrated =
_grid.GetBinary().GetBuilder(portOuter).SetField<object>("inner1", inner1Port).Build();
outerMigrated = portOuterMigrated.Deserialize<MigrationOuter>();
Assert.AreEqual(2, outerMigrated.Inner1.Val);
Assert.AreEqual(1, outerMigrated.Inner2.Val);
}
/// <summary>
/// Test handle inversion.
/// </summary>
[Test]
public void TestHandleInversion()
{
InversionInner inner = new InversionInner();
InversionOuter outer = new InversionOuter();
inner.Outer = outer;
outer.Inner = inner;
byte[] rawOuter = _marsh.Marshal(outer);
IBinaryObject portOuter = _marsh.Unmarshal<IBinaryObject>(rawOuter, BinaryMode.ForceBinary);
IBinaryObject portInner = portOuter.GetField<IBinaryObject>("inner");
// 1. Ensure that inner object can be deserialized after build.
IBinaryObject portInnerNew = _grid.GetBinary().GetBuilder(portInner).Build();
InversionInner innerNew = portInnerNew.Deserialize<InversionInner>();
Assert.AreSame(innerNew, innerNew.Outer.Inner);
// 2. Ensure that binary object with external dependencies could be added to builder.
IBinaryObject portOuterNew =
_grid.GetBinary().GetBuilder(typeof(InversionOuter)).SetField<object>("inner", portInner).Build();
InversionOuter outerNew = portOuterNew.Deserialize<InversionOuter>();
Assert.AreNotSame(outerNew, outerNew.Inner.Outer);
Assert.AreSame(outerNew.Inner, outerNew.Inner.Outer.Inner);
}
/// <summary>
/// Test build multiple objects.
/// </summary>
[Test]
public void TestBuildMultiple()
{
IBinaryObjectBuilder builder = _grid.GetBinary().GetBuilder(typeof(Primitives));
builder.SetField<byte>("fByte", 1).SetField("fBool", true);
IBinaryObject po1 = builder.Build();
IBinaryObject po2 = builder.Build();
Assert.AreEqual(1, po1.GetField<byte>("fByte"));
Assert.AreEqual(true, po1.GetField<bool>("fBool"));
Assert.AreEqual(1, po2.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
builder.SetField<byte>("fByte", 2);
IBinaryObject po3 = builder.Build();
Assert.AreEqual(1, po1.GetField<byte>("fByte"));
Assert.AreEqual(true, po1.GetField<bool>("fBool"));
Assert.AreEqual(1, po2.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
Assert.AreEqual(2, po3.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
builder = _grid.GetBinary().GetBuilder(po1);
builder.SetField<byte>("fByte", 10);
po1 = builder.Build();
po2 = builder.Build();
builder.SetField<byte>("fByte", 20);
po3 = builder.Build();
Assert.AreEqual(10, po1.GetField<byte>("fByte"));
Assert.AreEqual(true, po1.GetField<bool>("fBool"));
Assert.AreEqual(10, po2.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
Assert.AreEqual(20, po3.GetField<byte>("fByte"));
Assert.AreEqual(true, po3.GetField<bool>("fBool"));
}
/// <summary>
/// Tests type id method.
/// </summary>
[Test]
public void TestTypeId()
{
Assert.Throws<ArgumentException>(() => _grid.GetBinary().GetTypeId(null));
Assert.AreEqual(IdMapper.TestTypeId, _grid.GetBinary().GetTypeId(IdMapper.TestTypeName));
Assert.AreEqual(BinaryUtils.GetStringHashCode("someTypeName"), _grid.GetBinary().GetTypeId("someTypeName"));
}
/// <summary>
/// Tests type name mapper.
/// </summary>
[Test]
public void TestTypeName()
{
var bytes = _marsh.Marshal(new NameMapperTestType {NameMapperTestField = 17});
var bin = _marsh.Unmarshal<IBinaryObject>(bytes, BinaryMode.ForceBinary);
var binType = bin.GetBinaryType();
Assert.AreEqual(BinaryUtils.GetStringHashCode(NameMapper.TestTypeName + "_"), binType.TypeId);
Assert.AreEqual(17, bin.GetField<int>(NameMapper.TestFieldName));
}
/// <summary>
/// Tests metadata methods.
/// </summary>
[Test]
public void TestMetadata()
{
// Populate metadata
var binary = _grid.GetBinary();
binary.ToBinary<IBinaryObject>(new DecimalHolder());
// All meta
var allMetas = binary.GetBinaryTypes();
var decimalMeta = allMetas.Single(x => x.TypeName == "DecimalHolder");
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
// By type
decimalMeta = binary.GetBinaryType(typeof (DecimalHolder));
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
// By type id
decimalMeta = binary.GetBinaryType(binary.GetTypeId("DecimalHolder"));
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
// By type name
decimalMeta = binary.GetBinaryType("DecimalHolder");
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
}
[Test]
public void TestBuildEnum()
{
var binary = _grid.GetBinary();
int val = (int) TestEnumRegistered.Two;
var binEnums = new[]
{
binary.BuildEnum(typeof (TestEnumRegistered), val),
binary.BuildEnum(typeof (TestEnumRegistered).Name, val)
};
foreach (var binEnum in binEnums)
{
Assert.IsTrue(binEnum.GetBinaryType().IsEnum);
Assert.AreEqual(val, binEnum.EnumValue);
Assert.AreEqual((TestEnumRegistered) val, binEnum.Deserialize<TestEnumRegistered>());
}
Assert.AreEqual(binEnums[0], binEnums[1]);
}
/// <summary>
/// Tests the compact footer setting.
/// </summary>
[Test]
public void TestCompactFooterSetting()
{
Assert.AreEqual(GetCompactFooter(), _marsh.CompactFooter);
}
/// <summary>
/// Tests the binary mode on remote node.
/// </summary>
[Test]
public void TestRemoteBinaryMode()
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
GridName = "grid2",
BinaryConfiguration = new BinaryConfiguration
{
CompactFooter = GetCompactFooter()
}
};
using (var grid2 = Ignition.Start(cfg))
{
var cache1 = _grid.GetOrCreateCache<int, Primitives>("cache");
var cache2 = grid2.GetCache<int, object>("cache").WithKeepBinary<int, IBinaryObject>();
// Exchange data
cache1[1] = new Primitives {FByte = 3};
var obj = cache2[1];
// Rebuild with no changes
cache2[2] = obj.ToBuilder().Build();
Assert.AreEqual(3, cache1[2].FByte);
// Rebuild with read
Assert.AreEqual(3, obj.GetField<byte>("FByte"));
cache2[3] = obj.ToBuilder().Build();
Assert.AreEqual(3, cache1[3].FByte);
// Modify and rebuild
cache2[4] = obj.ToBuilder().SetField("FShort", (short) 15).Build();
Assert.AreEqual(15, cache1[4].FShort);
// New binary type without a class
cache2[5] = grid2.GetBinary().GetBuilder("myNewType").SetField("foo", "bar").Build();
var cache1Bin = cache1.WithKeepBinary<int, IBinaryObject>();
var newObj = cache1Bin[5];
Assert.AreEqual("bar", newObj.GetField<string>("foo"));
cache1Bin[6] = newObj.ToBuilder().SetField("foo2", 3).Build();
Assert.AreEqual(3, cache2[6].GetField<int>("foo2"));
}
}
}
/// <summary>
/// Empty binary class.
/// </summary>
public class Empty
{
// No-op.
}
/// <summary>
/// binary with primitive fields.
/// </summary>
public class Primitives
{
public byte FByte;
public bool FBool;
public short FShort;
public char FChar;
public int FInt;
public long FLong;
public float FFloat;
public double FDouble;
public decimal FDecimal;
}
/// <summary>
/// binary with primitive array fields.
/// </summary>
public class PrimitiveArrays
{
public byte[] FByte;
public bool[] FBool;
public short[] FShort;
public char[] FChar;
public int[] FInt;
public long[] FLong;
public float[] FFloat;
public double[] FDouble;
public decimal?[] FDecimal;
}
/// <summary>
/// binary having strings, dates, Guids and enums.
/// </summary>
public class StringDateGuidEnum
{
public string FStr;
public DateTime? FnDate;
public DateTime? FnTimestamp;
public Guid? FnGuid;
public TestEnum FEnum;
public string[] FStrArr;
public DateTime?[] FDateArr;
public Guid?[] FGuidArr;
public TestEnum[] FEnumArr;
}
/// <summary>
/// Enumeration.
/// </summary>
public enum TestEnum
{
One, Two
}
/// <summary>
/// Registered enumeration.
/// </summary>
public enum TestEnumRegistered
{
One, Two
}
/// <summary>
/// binary with raw data.
/// </summary>
public class WithRaw : IBinarizable
{
public int A;
public int B;
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
writer.WriteInt("a", A);
writer.GetRawWriter().WriteInt(B);
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
A = reader.ReadInt("a");
B = reader.GetRawReader().ReadInt();
}
}
/// <summary>
/// Empty class for metadata overwrite test.
/// </summary>
public class MetaOverwrite
{
// No-op.
}
/// <summary>
/// Nested outer object.
/// </summary>
public class NestedOuter
{
public NestedInner Inner1;
public NestedInner Inner2;
}
/// <summary>
/// Nested inner object.
/// </summary>
public class NestedInner
{
public int Val;
}
/// <summary>
/// Outer object for handle migration test.
/// </summary>
public class MigrationOuter
{
public MigrationInner Inner1;
public MigrationInner Inner2;
}
/// <summary>
/// Inner object for handle migration test.
/// </summary>
public class MigrationInner
{
public int Val;
}
/// <summary>
/// Outer object for handle inversion test.
/// </summary>
public class InversionOuter
{
public InversionInner Inner;
}
/// <summary>
/// Inner object for handle inversion test.
/// </summary>
public class InversionInner
{
public InversionOuter Outer;
}
/// <summary>
/// Object for composite array tests.
/// </summary>
public class CompositeArray
{
public object[] InArr;
public object[] OutArr;
}
/// <summary>
/// Object for composite collection/dictionary tests.
/// </summary>
public class CompositeContainer
{
public ICollection Col;
public IDictionary Dict;
}
/// <summary>
/// OUter object for composite structures test.
/// </summary>
public class CompositeOuter
{
public CompositeInner Inner;
public CompositeOuter()
{
// No-op.
}
public CompositeOuter(CompositeInner inner)
{
Inner = inner;
}
}
/// <summary>
/// Inner object for composite structures test.
/// </summary>
public class CompositeInner
{
public int Val;
public CompositeInner()
{
// No-op.
}
public CompositeInner(int val)
{
Val = val;
}
}
/// <summary>
/// Type to test "ToBinary()" logic.
/// </summary>
public class ToBinary
{
public int Val;
public ToBinary(int val)
{
Val = val;
}
}
/// <summary>
/// Type to test removal.
/// </summary>
public class Remove
{
public object Val;
public RemoveInner Val2;
}
/// <summary>
/// Inner type to test removal.
/// </summary>
public class RemoveInner
{
/** */
public int Val;
/// <summary>
///
/// </summary>
/// <param name="val"></param>
public RemoveInner(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
public class BuilderInBuilderOuter
{
/** */
public BuilderInBuilderInner Inner;
/** */
public BuilderInBuilderInner Inner2;
}
/// <summary>
///
/// </summary>
public class BuilderInBuilderInner
{
/** */
public BuilderInBuilderOuter Outer;
}
/// <summary>
///
/// </summary>
public class BuilderCollection
{
/** */
public readonly ArrayList Col;
/// <summary>
///
/// </summary>
/// <param name="col"></param>
public BuilderCollection(ArrayList col)
{
Col = col;
}
}
/// <summary>
///
/// </summary>
public class BuilderCollectionItem
{
/** */
public int Val;
/// <summary>
///
/// </summary>
/// <param name="val"></param>
public BuilderCollectionItem(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
public class DecimalHolder
{
/** */
public decimal Val;
/** */
public decimal?[] ValArr;
}
/// <summary>
/// Test id mapper.
/// </summary>
public class IdMapper : IBinaryIdMapper
{
/** */
public const string TestTypeName = "IdMapperTestType";
/** */
public const int TestTypeId = -65537;
/** <inheritdoc /> */
public int GetTypeId(string typeName)
{
return typeName == TestTypeName ? TestTypeId : 0;
}
/** <inheritdoc /> */
public int GetFieldId(int typeId, string fieldName)
{
return 0;
}
}
/// <summary>
/// Test name mapper.
/// </summary>
public class NameMapper : IBinaryNameMapper
{
/** */
public const string TestTypeName = "NameMapperTestType";
/** */
public const string TestFieldName = "NameMapperTestField";
/** <inheritdoc /> */
public string GetTypeName(string name)
{
if (name == TestTypeName)
return name + "_";
return name;
}
/** <inheritdoc /> */
public string GetFieldName(string name)
{
if (name == TestFieldName)
return name + "_";
return name;
}
}
/// <summary>
/// Name mapper test type.
/// </summary>
public class NameMapperTestType
{
/** */
public int NameMapperTestField { get; set; }
}
}
| |
#if UNITY_ECS
using System.Collections;
using Svelto.Common;
using Svelto.DataStructures;
using Svelto.ECS.Native;
using Svelto.ECS.Schedulers;
using Unity.Entities;
using Unity.Jobs;
namespace Svelto.ECS.Extensions.Unity
{
/// <summary>
/// Group of UECS/Svelto SystemBase engines that creates UECS entities.
/// Svelto entities are submitted
/// Svelto Add and remove callback are called
/// OnUpdate of the systems are called
/// finally the UECS command buffer is flushed
/// Note: I cannot use Unity ComponentSystemGroups nor I can rely on the SystemBase Dependency field to
/// solve external dependencies. External dependencies are tracked, but only linked to the UECS components operations
/// With Dependency I cannot guarantee that an external container is used before previous jobs working on it are completed
/// </summary>
[DisableAutoCreation]
public sealed class SveltoUECSEntitiesSubmissionGroup : SystemBase, IQueryingEntitiesEngine , IReactOnAddAndRemove<UECSEntityComponent>
, IReactOnSwap<UECSEntityComponent>, ISveltoUECSSubmission
{
public SveltoUECSEntitiesSubmissionGroup(SimpleEntitiesSubmissionScheduler submissionScheduler)
{
_submissionScheduler = submissionScheduler;
_engines = new FasterList<SubmissionEngine>();
_afterSubmissionEngines = new FasterList<IUpdateAfterSubmission>();
_beforeSubmissionEngines = new FasterList<IUpdateBeforeSubmission>();
}
protected override void OnCreate()
{
_ECBSystem = World.CreateSystem<SubmissionEntitiesCommandBufferSystem>();
_entityQuery = GetEntityQuery(typeof(UpdateUECSEntityAfterSubmission));
}
public EntitiesDB entitiesDB { get; set; }
public void Ready() { }
public void Add(ref UECSEntityComponent entityComponent, EGID egid) { }
public void Remove(ref UECSEntityComponent entityComponent, EGID egid)
{
_ECB.DestroyEntity(entityComponent.uecsEntity);
}
public void MovedTo(ref UECSEntityComponent entityComponent, ExclusiveGroupStruct previousGroup, EGID egid)
{
_ECB.SetSharedComponent(entityComponent.uecsEntity, new UECSSveltoGroupID(egid.groupID));
}
public void Add(SubmissionEngine engine)
{
Svelto.Console.LogDebug($"Add Engine {engine} to the UECS world {_ECBSystem.World.Name}");
_ECBSystem.World.AddSystem(engine);
if (engine is IUpdateAfterSubmission afterSubmission)
_afterSubmissionEngines.Add(afterSubmission);
if (engine is IUpdateBeforeSubmission beforeSubmission)
_beforeSubmissionEngines.Add(beforeSubmission);
_engines.Add(engine);
}
public void SubmitEntities(JobHandle jobHandle)
{
if (_submissionScheduler.paused)
return;
using (var profiler = new PlatformProfiler("SveltoUECSEntitiesSubmissionGroup - PreSubmissionPhase"))
{
PreSubmissionPhase(ref jobHandle, profiler);
//Submit Svelto Entities, calls Add/Remove/MoveTo that can be used by the IUECSSubmissionEngines
using (profiler.Sample("Submit svelto entities"))
{
_submissionScheduler.SubmitEntities();
}
AfterSubmissionPhase(profiler);
}
}
public IEnumerator SubmitEntitiesAsync(JobHandle jobHandle, uint maxEntities)
{
if (_submissionScheduler.paused)
yield break;
using (var profiler = new PlatformProfiler("SveltoUECSEntitiesSubmissionGroup - PreSubmissionPhase"))
{
PreSubmissionPhase(ref jobHandle, profiler);
var submitEntitiesAsync = _submissionScheduler.SubmitEntitiesAsync(maxEntities);
//Submit Svelto Entities, calls Add/Remove/MoveTo that can be used by the IUECSSubmissionEngines
while (true)
{
using (profiler.Sample("Submit svelto entities async"))
{
submitEntitiesAsync.MoveNext();
}
if (submitEntitiesAsync.Current == true)
{
using (profiler.Yield())
yield return null;
}
else
break;
}
AfterSubmissionPhase(profiler);
}
}
void PreSubmissionPhase(ref JobHandle jobHandle, PlatformProfiler profiler)
{
JobHandle BeforeECBFlushEngines()
{
JobHandle jobHandle = default;
//execute submission engines and complete jobs because of this I don't need to do _ECBSystem.AddJobHandleForProducer(Dependency);
for (var index = 0; index < _beforeSubmissionEngines.count; index++)
{
ref var engine = ref _beforeSubmissionEngines[index];
using (profiler.Sample(engine.name))
{
jobHandle = JobHandle.CombineDependencies(jobHandle, engine.BeforeSubmissionUpdate(jobHandle));
}
}
return jobHandle;
}
using (profiler.Sample("Complete All Pending Jobs"))
{
jobHandle.Complete();
}
//prepare the entity command buffer to be used by the registered engines
var entityCommandBuffer = _ECBSystem.CreateCommandBuffer();
foreach (var system in _engines)
{
system.ECB = entityCommandBuffer;
}
_ECB = entityCommandBuffer;
RemovePreviousMarkingComponents(entityCommandBuffer);
using (profiler.Sample("Before Submission Engines"))
{
BeforeECBFlushEngines().Complete();
}
}
void AfterSubmissionPhase(PlatformProfiler profiler)
{
JobHandle AfterECBFlushEngines()
{
JobHandle jobHandle = default;
//execute submission engines and complete jobs because of this I don't need to do _ECBSystem.AddJobHandleForProducer(Dependency);
for (var index = 0; index < _afterSubmissionEngines.count; index++)
{
ref var engine = ref _afterSubmissionEngines[index];
using (profiler.Sample(engine.name))
{
jobHandle = JobHandle.CombineDependencies(jobHandle, engine.AfterSubmissionUpdate(jobHandle));
}
}
return jobHandle;
}
using (profiler.Sample("Flush Command Buffer"))
{
_ECBSystem.Update();
}
ConvertPendingEntities().Complete();
using (profiler.Sample("After Submission Engines"))
{
AfterECBFlushEngines().Complete();
}
}
void RemovePreviousMarkingComponents(EntityCommandBuffer ECB)
{
ECB.RemoveComponentForEntityQuery<UpdateUECSEntityAfterSubmission>(_entityQuery);
}
JobHandle ConvertPendingEntities()
{
if (_entityQuery.IsEmpty == false)
{
NativeEGIDMultiMapper<UECSEntityComponent> mapper =
entitiesDB.QueryNativeMappedEntities<UECSEntityComponent>(
entitiesDB.FindGroups<UECSEntityComponent>(), Allocator.TempJob);
Entities.ForEach((Entity id, ref UpdateUECSEntityAfterSubmission egidComponent) =>
{
mapper.Entity(egidComponent.egid).uecsEntity = id;
}).ScheduleParallel();
mapper.ScheduleDispose(Dependency);
}
return Dependency;
}
readonly SimpleEntitiesSubmissionScheduler _submissionScheduler;
SubmissionEntitiesCommandBufferSystem _ECBSystem;
readonly FasterList<SubmissionEngine> _engines;
readonly FasterList<IUpdateBeforeSubmission> _beforeSubmissionEngines;
readonly FasterList<IUpdateAfterSubmission> _afterSubmissionEngines;
[DisableAutoCreation]
class SubmissionEntitiesCommandBufferSystem : EntityCommandBufferSystem { }
protected override void OnUpdate() { }
EntityQuery _entityQuery;
EntityCommandBuffer _ECB;
}
public interface ISveltoUECSSubmission
{
void Add(SubmissionEngine engine);
void SubmitEntities(JobHandle jobHandle);
IEnumerator SubmitEntitiesAsync(JobHandle jobHandle, uint maxEntities);
}
}
#endif
| |
#region File Description
//-----------------------------------------------------------------------------
// Vat.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#endregion
namespace HoneycombRush
{
/// <summary>
/// A game component that represents the vat.
/// </summary>
public class Vat : TexturedDrawableGameComponent
{
#region Field/Properties
ScoreBar score;
SpriteFont font14px;
SpriteFont font16px;
SpriteFont font36px;
Vector2 emptyStringSize;
Vector2 fullStringSize;
Vector2 timeDigStringSize;
Vector2 timeleftStringSize;
TimeSpan timeLeft;
const string EmptyString = "Empty";
const string FullString = "Full";
const string TimeLeftString = "Time Left";
string timeLeftString = string.Empty;
public Vector2 Position
{
get
{
return position;
}
}
public Texture2D Texture
{
get
{
return texture;
}
}
public int MaxVatCapacity
{
get
{
return score.MaxValue;
}
}
public int CurrentVatCapacity
{
get
{
return score.CurrentValue;
}
}
public override Rectangle CentralCollisionArea
{
get
{
Rectangle bounds = Bounds;
int height = (int)bounds.Height / 10 * 5;
int width = (int)bounds.Width / 10 * 8;
int offsetY = ((int)bounds.Height - height) / 2;
int offsetX = ((int)bounds.Width - width) / 2;
return new Rectangle((int)bounds.X + offsetX, (int)bounds.Y + offsetY, width, height);
}
}
public Rectangle VatDepositArea
{
get
{
Rectangle bounds = Bounds;
float sizeFactor = 0.75f;
float marginFactor = (1 - sizeFactor) / 2;
int x = bounds.X + (int)(marginFactor * bounds.Width);
int y = bounds.Y + (int)(marginFactor * bounds.Height);
int width = (int)(bounds.Width * sizeFactor);
int height = (int)(bounds.Height * sizeFactor);
return new Rectangle(x, y, width, height);
}
}
#endregion
#region Initialization
/// <summary>
/// Creates a new vat instance.
/// </summary>
/// <param name="game">The associated game object.</param>
/// <param name="gamePlayScreen">Gameplay screen where the vat will be displayed.</param>
/// <param name="texture">The vat's texture.</param>
/// <param name="position">The position of the vat.</param>
/// <param name="score">An associated score bar.</param>
public Vat(Game game, GameplayScreen gamePlayScreen, Texture2D texture, Vector2 position, ScoreBar score)
: base(game, gamePlayScreen)
{
this.texture = texture;
this.position = position;
this.score = score;
DrawOrder = (int)(position.Y + Bounds.Height);
}
/// <summary>
/// Loads the content that will be used by this component.
/// </summary>
protected override void LoadContent()
{
font14px = Game.Content.Load<SpriteFont>("Fonts/GameScreenFont14px");
font16px = Game.Content.Load<SpriteFont>("Fonts/GameScreenFont16px");
font36px = Game.Content.Load<SpriteFont>("Fonts/GameScreenFont36px");
fullStringSize = font14px.MeasureString(FullString);
emptyStringSize = font14px.MeasureString(EmptyString);
timeleftStringSize = font16px.MeasureString(TimeLeftString);
base.LoadContent();
}
#endregion
#region Render
/// <summary>
/// Draws the component.
/// </summary>
/// <param name="gameTime">Game time information.</param>
public override void Draw(GameTime gameTime)
{
if (!gamePlayScreen.IsActive)
{
base.Draw(gameTime);
return;
}
// Draws the texture
spriteBatch.Begin();
spriteBatch.Draw(texture, position, Color.White);
// Draws the "time left" text
spriteBatch.DrawString(font16px, TimeLeftString,
position + new Vector2(texture.Width / 2 - timeleftStringSize.X / 2, timeleftStringSize.Y - 8),
Color.White, 0, Vector2.Zero, 0, SpriteEffects.None, 2f);
// Draws how much time is left
timeDigStringSize = font36px.MeasureString(timeLeftString);
Color colorToDraw = Color.White;
if (timeLeft.Minutes == 0 && (timeLeft.Seconds == 30 || timeLeft.Seconds <= 10))
{
colorToDraw = Color.Red;
}
spriteBatch.DrawString(font36px, timeLeftString,
position + new Vector2(texture.Width / 2 - timeDigStringSize.X / 2, timeDigStringSize.Y - 30),
colorToDraw);
// Draws the "full" and "empty" strings
spriteBatch.DrawString(font14px, EmptyString,
new Vector2(position.X, position.Y + texture.Height - emptyStringSize.Y), Color.White);
spriteBatch.DrawString(font14px, FullString,
new Vector2(position.X + texture.Width - fullStringSize.X,
position.Y + texture.Height - emptyStringSize.Y),
Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
#endregion
#region Public methods
/// <summary>
/// Translates time left in the game to a internal representation string.
/// </summary>
/// <param name="timeLeft">Time left before the current level ends.</param>
public void DrawTimeLeft(TimeSpan timeLeft)
{
this.timeLeft = timeLeft;
timeLeftString = String.Format("{0:00}:{1:00}", timeLeft.Minutes, timeLeft.Seconds);
}
/// <summary>
/// Adds honey to the amount stored in the vat.
/// </summary>
/// <param name="value">Amount of honey to add.</param>
public void IncreaseHoney(int value)
{
score.IncreaseCurrentValue(value);
}
#endregion
}
}
| |
using Microsoft.AspNetCore.Http;
using Ocelot.LoadBalancer.LoadBalancers;
using Ocelot.Middleware;
using Ocelot.Responses;
using Ocelot.Values;
using Shouldly;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.LoadBalancer
{
public class LeastConnectionTests
{
private ServiceHostAndPort _hostAndPort;
private Response<ServiceHostAndPort> _result;
private LeastConnection _leastConnection;
private List<Service> _services;
private Random _random;
private DownstreamContext _context;
public LeastConnectionTests()
{
_context = new DownstreamContext(new DefaultHttpContext());
_random = new Random();
}
[Fact]
public void should_be_able_to_lease_and_release_concurrently()
{
var serviceName = "products";
var availableServices = new List<Service>
{
new Service(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, new string[0]),
new Service(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, new string[0]),
};
_services = availableServices;
_leastConnection = new LeastConnection(() => Task.FromResult(_services), serviceName);
var tasks = new Task[100];
for (var i = 0; i < tasks.Length; i++)
{
tasks[i] = LeaseDelayAndRelease();
}
Task.WaitAll(tasks);
}
[Fact]
public void should_handle_service_returning_to_available()
{
var serviceName = "products";
var availableServices = new List<Service>
{
new Service(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, new string[0]),
new Service(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, new string[0]),
};
_leastConnection = new LeastConnection(() => Task.FromResult(availableServices), serviceName);
var hostAndPortOne = _leastConnection.Lease(_context).Result;
hostAndPortOne.Data.DownstreamHost.ShouldBe("127.0.0.1");
var hostAndPortTwo = _leastConnection.Lease(_context).Result;
hostAndPortTwo.Data.DownstreamHost.ShouldBe("127.0.0.2");
_leastConnection.Release(hostAndPortOne.Data);
_leastConnection.Release(hostAndPortTwo.Data);
availableServices = new List<Service>
{
new Service(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, new string[0]),
};
hostAndPortOne = _leastConnection.Lease(_context).Result;
hostAndPortOne.Data.DownstreamHost.ShouldBe("127.0.0.1");
hostAndPortTwo = _leastConnection.Lease(_context).Result;
hostAndPortTwo.Data.DownstreamHost.ShouldBe("127.0.0.1");
_leastConnection.Release(hostAndPortOne.Data);
_leastConnection.Release(hostAndPortTwo.Data);
availableServices = new List<Service>
{
new Service(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, new string[0]),
new Service(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, new string[0]),
};
hostAndPortOne = _leastConnection.Lease(_context).Result;
hostAndPortOne.Data.DownstreamHost.ShouldBe("127.0.0.1");
hostAndPortTwo = _leastConnection.Lease(_context).Result;
hostAndPortTwo.Data.DownstreamHost.ShouldBe("127.0.0.2");
_leastConnection.Release(hostAndPortOne.Data);
_leastConnection.Release(hostAndPortTwo.Data);
}
private async Task LeaseDelayAndRelease()
{
var hostAndPort = await _leastConnection.Lease(_context);
await Task.Delay(_random.Next(1, 100));
_leastConnection.Release(hostAndPort.Data);
}
[Fact]
public void should_get_next_url()
{
var serviceName = "products";
var hostAndPort = new ServiceHostAndPort("localhost", 80);
var availableServices = new List<Service>
{
new Service(serviceName, hostAndPort, string.Empty, string.Empty, new string[0])
};
this.Given(x => x.GivenAHostAndPort(hostAndPort))
.And(x => x.GivenTheLoadBalancerStarts(availableServices, serviceName))
.When(x => x.WhenIGetTheNextHostAndPort())
.Then(x => x.ThenTheNextHostAndPortIsReturned())
.BDDfy();
}
[Fact]
public void should_serve_from_service_with_least_connections()
{
var serviceName = "products";
var availableServices = new List<Service>
{
new Service(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, new string[0]),
new Service(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, new string[0]),
new Service(serviceName, new ServiceHostAndPort("127.0.0.3", 80), string.Empty, string.Empty, new string[0])
};
_services = availableServices;
_leastConnection = new LeastConnection(() => Task.FromResult(_services), serviceName);
var response = _leastConnection.Lease(_context).Result;
response.Data.DownstreamHost.ShouldBe(availableServices[0].HostAndPort.DownstreamHost);
response = _leastConnection.Lease(_context).Result;
response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost);
response = _leastConnection.Lease(_context).Result;
response.Data.DownstreamHost.ShouldBe(availableServices[2].HostAndPort.DownstreamHost);
}
[Fact]
public void should_build_connections_per_service()
{
var serviceName = "products";
var availableServices = new List<Service>
{
new Service(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, new string[0]),
new Service(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, new string[0]),
};
_services = availableServices;
_leastConnection = new LeastConnection(() => Task.FromResult(_services), serviceName);
var response = _leastConnection.Lease(_context).Result;
response.Data.DownstreamHost.ShouldBe(availableServices[0].HostAndPort.DownstreamHost);
response = _leastConnection.Lease(_context).Result;
response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost);
response = _leastConnection.Lease(_context).Result;
response.Data.DownstreamHost.ShouldBe(availableServices[0].HostAndPort.DownstreamHost);
response = _leastConnection.Lease(_context).Result;
response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost);
}
[Fact]
public void should_release_connection()
{
var serviceName = "products";
var availableServices = new List<Service>
{
new Service(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, new string[0]),
new Service(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, new string[0]),
};
_services = availableServices;
_leastConnection = new LeastConnection(() => Task.FromResult(_services), serviceName);
var response = _leastConnection.Lease(_context).Result;
response.Data.DownstreamHost.ShouldBe(availableServices[0].HostAndPort.DownstreamHost);
response = _leastConnection.Lease(_context).Result;
response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost);
response = _leastConnection.Lease(_context).Result;
response.Data.DownstreamHost.ShouldBe(availableServices[0].HostAndPort.DownstreamHost);
response = _leastConnection.Lease(_context).Result;
response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost);
//release this so 2 should have 1 connection and we should get 2 back as our next host and port
_leastConnection.Release(availableServices[1].HostAndPort);
response = _leastConnection.Lease(_context).Result;
response.Data.DownstreamHost.ShouldBe(availableServices[1].HostAndPort.DownstreamHost);
}
[Fact]
public void should_return_error_if_services_are_null()
{
var serviceName = "products";
var hostAndPort = new ServiceHostAndPort("localhost", 80);
this.Given(x => x.GivenAHostAndPort(hostAndPort))
.And(x => x.GivenTheLoadBalancerStarts(null, serviceName))
.When(x => x.WhenIGetTheNextHostAndPort())
.Then(x => x.ThenServiceAreNullErrorIsReturned())
.BDDfy();
}
[Fact]
public void should_return_error_if_services_are_empty()
{
var serviceName = "products";
var hostAndPort = new ServiceHostAndPort("localhost", 80);
this.Given(x => x.GivenAHostAndPort(hostAndPort))
.And(x => x.GivenTheLoadBalancerStarts(new List<Service>(), serviceName))
.When(x => x.WhenIGetTheNextHostAndPort())
.Then(x => x.ThenServiceAreEmptyErrorIsReturned())
.BDDfy();
}
private void ThenServiceAreNullErrorIsReturned()
{
_result.IsError.ShouldBeTrue();
_result.Errors[0].ShouldBeOfType<ServicesAreNullError>();
}
private void ThenServiceAreEmptyErrorIsReturned()
{
_result.IsError.ShouldBeTrue();
_result.Errors[0].ShouldBeOfType<ServicesAreEmptyError>();
}
private void GivenTheLoadBalancerStarts(List<Service> services, string serviceName)
{
_services = services;
_leastConnection = new LeastConnection(() => Task.FromResult(_services), serviceName);
}
private void WhenTheLoadBalancerStarts(List<Service> services, string serviceName)
{
GivenTheLoadBalancerStarts(services, serviceName);
}
private void GivenAHostAndPort(ServiceHostAndPort hostAndPort)
{
_hostAndPort = hostAndPort;
}
private void WhenIGetTheNextHostAndPort()
{
_result = _leastConnection.Lease(_context).Result;
}
private void ThenTheNextHostAndPortIsReturned()
{
_result.Data.DownstreamHost.ShouldBe(_hostAndPort.DownstreamHost);
_result.Data.DownstreamPort.ShouldBe(_hostAndPort.DownstreamPort);
}
}
}
| |
namespace Epi.Windows.MakeView.Dialogs.FieldDefinitionDialogs
{
partial class SingleLineTextFieldDefinition
{
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SingleLineTextFieldDefinition));
this.lblSize = new System.Windows.Forms.Label();
this.mtbSize = new System.Windows.Forms.MaskedTextBox();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// chkReadOnly
//
resources.ApplyResources(this.chkReadOnly, "chkReadOnly");
//
// chkRequired
//
resources.ApplyResources(this.chkRequired, "chkRequired");
//
// chkRepeatLast
//
resources.ApplyResources(this.chkRepeatLast, "chkRepeatLast");
//
// label1
//
resources.ApplyResources(this.label1, "label1");
//
// txtPrompt
//
resources.ApplyResources(this.txtPrompt, "txtPrompt");
//
// lblPrompt
//
resources.ApplyResources(this.lblPrompt, "lblPrompt");
//
// txtFieldName
//
resources.ApplyResources(this.txtFieldName, "txtFieldName");
//
// btnCancel
//
resources.ApplyResources(this.btnCancel, "btnCancel");
//
// btnOk
//
resources.ApplyResources(this.btnOk, "btnOk");
//
// groupBox1
//
resources.ApplyResources(this.groupBox1, "groupBox1");
//
// baseImageList
//
this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream")));
this.baseImageList.Images.SetKeyName(0, "");
this.baseImageList.Images.SetKeyName(1, "");
this.baseImageList.Images.SetKeyName(2, "");
this.baseImageList.Images.SetKeyName(3, "");
this.baseImageList.Images.SetKeyName(4, "");
this.baseImageList.Images.SetKeyName(5, "");
this.baseImageList.Images.SetKeyName(6, "");
this.baseImageList.Images.SetKeyName(7, "");
this.baseImageList.Images.SetKeyName(8, "");
this.baseImageList.Images.SetKeyName(9, "");
this.baseImageList.Images.SetKeyName(10, "");
this.baseImageList.Images.SetKeyName(11, "");
this.baseImageList.Images.SetKeyName(12, "");
this.baseImageList.Images.SetKeyName(13, "");
this.baseImageList.Images.SetKeyName(14, "");
this.baseImageList.Images.SetKeyName(15, "");
this.baseImageList.Images.SetKeyName(16, "");
this.baseImageList.Images.SetKeyName(17, "");
this.baseImageList.Images.SetKeyName(18, "");
this.baseImageList.Images.SetKeyName(19, "");
this.baseImageList.Images.SetKeyName(20, "");
this.baseImageList.Images.SetKeyName(21, "");
this.baseImageList.Images.SetKeyName(22, "");
this.baseImageList.Images.SetKeyName(23, "");
this.baseImageList.Images.SetKeyName(24, "");
this.baseImageList.Images.SetKeyName(25, "");
this.baseImageList.Images.SetKeyName(26, "");
this.baseImageList.Images.SetKeyName(27, "");
this.baseImageList.Images.SetKeyName(28, "");
this.baseImageList.Images.SetKeyName(29, "");
this.baseImageList.Images.SetKeyName(30, "");
this.baseImageList.Images.SetKeyName(31, "");
this.baseImageList.Images.SetKeyName(32, "");
this.baseImageList.Images.SetKeyName(33, "");
this.baseImageList.Images.SetKeyName(34, "");
this.baseImageList.Images.SetKeyName(35, "");
this.baseImageList.Images.SetKeyName(36, "");
this.baseImageList.Images.SetKeyName(37, "");
this.baseImageList.Images.SetKeyName(38, "");
this.baseImageList.Images.SetKeyName(39, "");
this.baseImageList.Images.SetKeyName(40, "");
this.baseImageList.Images.SetKeyName(41, "");
this.baseImageList.Images.SetKeyName(42, "");
this.baseImageList.Images.SetKeyName(43, "");
this.baseImageList.Images.SetKeyName(44, "");
this.baseImageList.Images.SetKeyName(45, "");
this.baseImageList.Images.SetKeyName(46, "");
this.baseImageList.Images.SetKeyName(47, "");
this.baseImageList.Images.SetKeyName(48, "");
this.baseImageList.Images.SetKeyName(49, "");
this.baseImageList.Images.SetKeyName(50, "");
this.baseImageList.Images.SetKeyName(51, "");
this.baseImageList.Images.SetKeyName(52, "");
this.baseImageList.Images.SetKeyName(53, "");
this.baseImageList.Images.SetKeyName(54, "");
this.baseImageList.Images.SetKeyName(55, "");
this.baseImageList.Images.SetKeyName(56, "");
this.baseImageList.Images.SetKeyName(57, "");
this.baseImageList.Images.SetKeyName(58, "");
this.baseImageList.Images.SetKeyName(59, "");
this.baseImageList.Images.SetKeyName(60, "");
this.baseImageList.Images.SetKeyName(61, "");
this.baseImageList.Images.SetKeyName(62, "");
this.baseImageList.Images.SetKeyName(63, "");
this.baseImageList.Images.SetKeyName(64, "");
this.baseImageList.Images.SetKeyName(65, "");
this.baseImageList.Images.SetKeyName(66, "");
this.baseImageList.Images.SetKeyName(67, "");
this.baseImageList.Images.SetKeyName(68, "");
this.baseImageList.Images.SetKeyName(69, "");
this.baseImageList.Images.SetKeyName(70, "");
this.baseImageList.Images.SetKeyName(71, "");
this.baseImageList.Images.SetKeyName(72, "");
this.baseImageList.Images.SetKeyName(73, "");
this.baseImageList.Images.SetKeyName(74, "");
this.baseImageList.Images.SetKeyName(75, "");
this.baseImageList.Images.SetKeyName(76, "");
this.baseImageList.Images.SetKeyName(77, "");
this.baseImageList.Images.SetKeyName(78, "");
this.baseImageList.Images.SetKeyName(79, "");
this.baseImageList.Images.SetKeyName(80, "");
this.baseImageList.Images.SetKeyName(81, "");
this.baseImageList.Images.SetKeyName(82, "");
this.baseImageList.Images.SetKeyName(83, "");
this.baseImageList.Images.SetKeyName(84, "");
this.baseImageList.Images.SetKeyName(85, "");
this.baseImageList.Images.SetKeyName(86, "");
//
// lblSize
//
resources.ApplyResources(this.lblSize, "lblSize");
this.lblSize.Name = "lblSize";
//
// mtbSize
//
resources.ApplyResources(this.mtbSize, "mtbSize");
this.mtbSize.Name = "mtbSize";
//
// SingleLineTextFieldDefinition
//
resources.ApplyResources(this, "$this");
this.Controls.Add(this.lblSize);
this.Controls.Add(this.mtbSize);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "SingleLineTextFieldDefinition";
this.Controls.SetChildIndex(this.mtbSize, 0);
this.Controls.SetChildIndex(this.lblSize, 0);
this.Controls.SetChildIndex(this.btnCancel, 0);
this.Controls.SetChildIndex(this.btnOk, 0);
this.Controls.SetChildIndex(this.groupBox1, 0);
this.Controls.SetChildIndex(this.txtFieldName, 0);
this.Controls.SetChildIndex(this.label1, 0);
this.Controls.SetChildIndex(this.lblPrompt, 0);
this.Controls.SetChildIndex(this.txtPrompt, 0);
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
/// <summary>
/// The Size label
/// </summary>
protected System.Windows.Forms.Label lblSize;
/// <summary>
/// The Size
/// </summary>
protected System.Windows.Forms.MaskedTextBox mtbSize;
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE_APACHE.txt in the project root for license information.
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Buffering
{
internal class BufferingWriteStream : Stream
{
private readonly Stream _innerStream;
private readonly MemoryStream _buffer = new MemoryStream();
private bool _isBuffering = true;
public BufferingWriteStream(Stream innerStream)
{
_innerStream = innerStream;
}
public override bool CanRead
{
get { return false; }
}
public override bool CanSeek
{
get { return _isBuffering; }
}
public override bool CanWrite
{
get { return _innerStream.CanWrite; }
}
public override long Length
{
get
{
if (_isBuffering)
{
return _buffer.Length;
}
// May throw
return _innerStream.Length;
}
}
// Clear/Reset the buffer by setting Position, Seek, or SetLength to 0. Random access is not supported.
public override long Position
{
get
{
if (_isBuffering)
{
return _buffer.Position;
}
// May throw
return _innerStream.Position;
}
set
{
if (_isBuffering)
{
if (value != 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, nameof(Position) + " can only be set to 0.");
}
_buffer.Position = value;
_buffer.SetLength(value);
}
else
{
// May throw
_innerStream.Position = value;
}
}
}
// Clear/Reset the buffer by setting Position, Seek, or SetLength to 0. Random access is not supported.
public override void SetLength(long value)
{
if (_isBuffering)
{
if (value != 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, nameof(Length) + " can only be set to 0.");
}
_buffer.Position = value;
_buffer.SetLength(value);
}
else
{
// May throw
_innerStream.SetLength(value);
}
}
// Clear/Reset the buffer by setting Position, Seek, or SetLength to 0. Random access is not supported.
public override long Seek(long offset, SeekOrigin origin)
{
if (_isBuffering)
{
if (origin != SeekOrigin.Begin)
{
throw new ArgumentException(nameof(origin), nameof(Seek) + " can only be set to " + nameof(SeekOrigin.Begin) + ".");
}
if (offset != 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, nameof(Seek) + " can only be set to 0.");
}
_buffer.SetLength(offset);
return _buffer.Seek(offset, origin);
}
// Try the inner stream instead, but this will usually fail.
return _innerStream.Seek(offset, origin);
}
internal void DisableBuffering()
{
_isBuffering = false;
if (_buffer.Length > 0)
{
Flush();
}
}
internal Task DisableBufferingAsync(CancellationToken cancellationToken)
{
_isBuffering = false;
if (_buffer.Length > 0)
{
return FlushAsync(cancellationToken);
}
return Task.CompletedTask;
}
public override void Write(byte[] buffer, int offset, int count)
{
if (_isBuffering)
{
_buffer.Write(buffer, offset, count);
}
else
{
_innerStream.Write(buffer, offset, count);
}
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (_isBuffering)
{
return _buffer.WriteAsync(buffer, offset, count, cancellationToken);
}
else
{
return _innerStream.WriteAsync(buffer, offset, count, cancellationToken);
}
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (_isBuffering)
{
return _buffer.BeginWrite(buffer, offset, count, callback, state);
}
else
{
return _innerStream.BeginWrite(buffer, offset, count, callback, state);
}
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (_isBuffering)
{
_buffer.EndWrite(asyncResult);
}
else
{
_innerStream.EndWrite(asyncResult);
}
}
public override void Flush()
{
_isBuffering = false;
if (_buffer.Length > 0)
{
_buffer.Seek(0, SeekOrigin.Begin);
_buffer.CopyTo(_innerStream);
_buffer.Seek(0, SeekOrigin.Begin);
_buffer.SetLength(0);
}
_innerStream.Flush();
}
public override async Task FlushAsync(CancellationToken cancellationToken)
{
_isBuffering = false;
if (_buffer.Length > 0)
{
_buffer.Seek(0, SeekOrigin.Begin);
await _buffer.CopyToAsync(_innerStream, 1024 * 16, cancellationToken);
_buffer.Seek(0, SeekOrigin.Begin);
_buffer.SetLength(0);
}
await _innerStream.FlushAsync(cancellationToken);
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException("This Stream only supports Write operations.");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using MessagePack;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
[MessagePackObject]
public struct QuadData
{
[Key(0)] public int SpriteId;
[Key(1)] public Vector2 origin;
[Key(2)] public Vector2 scale;
[Key(3)] public float topShear;
[Key(4)] public float rightShear;
[Key(5)] public bool flipX;
[IgnoreMember] public RectF atlasTile;
// public QuadData(RectF atlasTile, Vector2 origin, Vector2? scale = null, bool flipX = false, float topShear = 0, float rightShear = 0)
// {
// this.atlasTile = atlasTile;
// this.origin = Core.SnapToPixel(origin);
// this.flipX = flipX;
// this.topShear = topShear;
// this.rightShear = rightShear;
// this.scale = scale ?? Vector2.One;
// SetPPScaleFromRect();
// }
[SerializationConstructor]
public QuadData(int spriteId, Vector2 origin, Vector2 scale, float topShear, float rightShear, bool flipX) : this()
{
SpriteId = spriteId;
atlasTile = spriteId.GetSprite();
this.origin = origin;
this.scale = scale;
this.topShear = topShear;
this.rightShear = rightShear;
this.flipX = flipX;
}
public QuadData(int sprite, Vector2? scale = null, bool centered = true, bool flipX = false, float topShear = 0, float rightShear = 0) : this()
{
SpriteId = sprite;
atlasTile = sprite.GetSprite();
this.topShear = topShear;
this.rightShear = rightShear;
this.flipX = flipX;
if (centered)
{
origin = Core.SnapToPixel(new Vector2((atlasTile.width * Core.ATLAS_TO_WORLD) / 2, (atlasTile.height * Core.ATLAS_TO_WORLD) / 2));
}
this.scale = scale ?? Vector2.One;
SetPPScaleFromRect();
}
void SetPPScaleFromRect()
{
//scale = new Vector2(atlasTile.width * Core.ATLAS_TO_WORLD * scale.X, atlasTile.height * Core.ATLAS_TO_WORLD * scale.Y);
}
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct QuadSpec : IVertexType
{
public const int REAL_STRIDE = 96;
VertexDeclaration IVertexType.VertexDeclaration => throw new NotImplementedException();
public Vector3 Position0; public Color Color0; public Vector2 TextureCoordinate0;
public Vector3 Position1; public Color Color1; public Vector2 TextureCoordinate1;
public Vector3 Position2; public Color Color2; public Vector2 TextureCoordinate2;
public Vector3 Position3; public Color Color3; public Vector2 TextureCoordinate3;
public QuadSpec(
Vector3 position0, Vector3 position1, Vector3 position2, Vector3 position3,
Vector2 textureCoordinate0, Vector2 textureCoordinate1, Vector2 textureCoordinate2, Vector2 textureCoordinate3,
Color color0, Color color1, Color color2, Color color3)
{
Position0 = position0;
Position1 = position1;
Position2 = position2;
Position3 = position3;
TextureCoordinate0 = textureCoordinate0;
TextureCoordinate1 = textureCoordinate1;
TextureCoordinate2 = textureCoordinate2;
TextureCoordinate3 = textureCoordinate3;
Color0 = color0;
Color1 = color1;
Color2 = color2;
Color3 = color3;
}
}
public class QuadSystem : ChunkedComponentSystem<QuadComponent, QuadSystem>, IRenderableSystem
{
private IndexBuffer ib = new IndexBuffer(Graphics.Device, IndexElementSize.ThirtyTwoBits, 3, BufferUsage.WriteOnly);
private DynamicVertexBuffer vb = new DynamicVertexBuffer(Graphics.Device, VertexPositionColorTexture.VertexDeclaration, 2, BufferUsage.WriteOnly);
private readonly BasicEffect effect_;
private QuadSpec[] quadsArray_ = new QuadSpec[64];
private int quadCount_ = 0;
public Texture2D Texture { get; }
public QuadSystem()
{
effect_ = new BasicEffect(Graphics.Device);
Texture = Core.atlas;
}
public void Draw(Camera camera, RenderTarget2D renderTarget)
{
quadCount_ = 0;
//collect all quads
foreach (QuadComponent quad in GetComponentsInRect(camera.GetCullRect(CHUNK_SIZE)))
if (quad.PrepareQuad(camera.GetCullRect(), out QuadSpec quadSpec))
{
if(quadsArray_.Length <= quadCount_)
Array.Resize(ref quadsArray_, quadsArray_.Length*2);
quadsArray_[quadCount_] = quadSpec;
quadCount_++;
}
//Build Buffers And Render
while (quadCount_*4 > vb.VertexCount)
{
// each miss we double our buffers ;)
int newVtxQty = vb.VertexCount * 2;
int newIdxQty = ib.IndexCount * 2;
vb = new DynamicVertexBuffer(Graphics.Device, VertexPositionColorTexture.VertexDeclaration, newVtxQty, BufferUsage.WriteOnly);
ib = new IndexBuffer(Graphics.Device, IndexElementSize.ThirtyTwoBits, newIdxQty, BufferUsage.WriteOnly);
int[] indices = new int[newIdxQty]; //we could reuse old indices here probably
for (int i = 0, v = 0; i < newIdxQty; i += 6, v += 4)
{
indices[i + 0] = v + 0;
indices[i + 1] = v + 1;
indices[i + 2] = v + 2;
indices[i + 3] = v + 0;
indices[i + 4] = v + 2;
indices[i + 5] = v + 3;
}
ib.SetData(indices); // copy to gfx, create actual IBO, once per resize
}
if (quadCount_ < 1) return;
//actually draw shit
vb.SetData(0,quadsArray_,0,quadCount_,QuadSpec.REAL_STRIDE,SetDataOptions.None);
effect_.Projection = camera.GetGlobalViewMatrix();
effect_.Texture = Texture;
effect_.TextureEnabled = true;
effect_.CurrentTechnique.Passes[0].Apply();
Graphics.Device.Indices = ib;
Graphics.Device.SetVertexBuffer(vb);
Graphics.Device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, quadCount_*4, 0, quadCount_*2);
}
}
public class QuadComponent : ChunkedComponent<QuadComponent, QuadSystem>
{
public QuadData quadData;
static QuadComponent()
{
Camera.DEFAULT_RENDER_PATH.Enqueue(new Camera.RenderLayer(Systems.Default,0),100);
}
public QuadComponent(Entity entity, QuadData quadData) : base(entity)
{
this.quadData = quadData;
}
public QuadComponent(Entity entity, byte system = 0) : base(entity, system)
{
}
public QuadComponent(Entity entity, byte[] serialData) : this(entity, MessagePackSerializer.Deserialize<QuadData>(serialData)){}
public override ComponentData GetSerialData()
{
return new ComponentData(ComponentTypes.QuadComponent, MessagePackSerializer.Serialize(quadData));
}
public virtual bool PrepareQuad(RectF cullRect, out QuadSpec quad)
{
float entX = Core.SnapToPixel(entity.Position.X);
float entY = Core.SnapToPixel(entity.Position.Y);
float entZ = 0;//entY+entX*0.0001f; //TODO
float S = 4; // snap positions
float M = S / (float)Math.PI;
float visualRotation = (float)Math.Floor((entity.Rotation + Math.PI / S / 2) * M) / M;
//visualRotation = entity.Rotation;
bool flipX = quadData.flipX;
float scaleX = quadData.atlasTile.width * Core.ATLAS_TO_WORLD * quadData.scale.X;
float scaleY = quadData.atlasTile.height * Core.ATLAS_TO_WORLD * quadData.scale.Y;
float originX = quadData.origin.X;
float originY = quadData.origin.Y;
float topShear = quadData.topShear;
float rightShear = quadData.rightShear;
Vector3 corner0;
Vector3 corner1;
Vector3 corner2;
Vector3 corner3;
if (Math.Abs(visualRotation) > 0.001f)
{
float rotSin = (float)Math.Sin(visualRotation);
float rotCos = (float)Math.Cos(visualRotation);
float ooX = rotCos * originX - rotSin * originY;
float ooY = rotSin * originX + rotCos * originY;
corner0 = new Vector3(entX - ooX, entY - ooY, 0);
corner1 = new Vector3(entX - rotSin * scaleY - ooX + topShear, entY + rotCos * scaleY - ooY, 0);
corner2 = new Vector3(entX + (rotCos * scaleX - rotSin * scaleY - ooX) + topShear, entY + (rotCos * scaleY + rotSin * scaleX) - ooY + rightShear, 0);
corner3 = new Vector3(entX + rotCos * scaleX - ooX, entY + rotSin * scaleX - ooY + rightShear, 0);
}
else
{
corner0 = new Vector3(entX - originX, entY - originY, entZ);
corner1 = new Vector3(entX - originX + topShear, entY + scaleY - originY, entZ);
corner2 = new Vector3(entX + scaleX - originX + topShear, entY + scaleY - originY + rightShear, entZ);
corner3 = new Vector3(entX + scaleX - originX, entY - originY + rightShear, entZ);
}
//narrowphase culling
RectF aabb = MathUtils.AABBFromCorners(corner0, corner1, corner2, corner3);
if (!cullRect.Intersects(aabb))
{
quad = new QuadSpec();
return false;
}
Dbg.AddDebugRect(aabb, Color.Yellow, 0.5f);
//TODO: get verts positions and uv from quaddata method?
Vector2 corner0uv = new Vector2(quadData.atlasTile.X, quadData.atlasTile.Bottom);
Vector2 corner1uv = new Vector2(quadData.atlasTile.X, quadData.atlasTile.Y);
Vector2 corner2uv = new Vector2(quadData.atlasTile.Right, quadData.atlasTile.Y);
Vector2 corner3uv = new Vector2(quadData.atlasTile.Right, quadData.atlasTile.Bottom);
if (flipX)
{
GeneralUtils.Swap(ref corner0uv, ref corner3uv);
GeneralUtils.Swap(ref corner1uv, ref corner2uv);
}
quad = new QuadSpec(
corner0,corner1,corner2,corner3,
corner0uv,corner1uv,corner2uv,corner3uv,
Color.White,Color.White,Color.White,Color.White
);
return true;
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using Avalonia.Collections;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Diagnostics;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Logging;
using Avalonia.LogicalTree;
using Avalonia.Rendering;
using Avalonia.Styling;
using Avalonia.VisualTree;
namespace Avalonia.Controls
{
/// <summary>
/// Base class for Avalonia controls.
/// </summary>
/// <remarks>
/// The control class extends <see cref="InputElement"/> and adds the following features:
///
/// - An inherited <see cref="DataContext"/>.
/// - A <see cref="Tag"/> property to allow user-defined data to be attached to the control.
/// - A collection of class strings for custom styling.
/// - Implements <see cref="IStyleable"/> to allow styling to work on the control.
/// - Implements <see cref="ILogical"/> to form part of a logical tree.
/// </remarks>
public class Control : InputElement, IControl, INamed, ISetInheritanceParent, ISetLogicalParent, ISupportInitialize, IVisualBrushInitialize
{
/// <summary>
/// Defines the <see cref="DataContext"/> property.
/// </summary>
public static readonly StyledProperty<object> DataContextProperty =
AvaloniaProperty.Register<Control, object>(
nameof(DataContext),
inherits: true,
notifying: DataContextNotifying);
/// <summary>
/// Defines the <see cref="FocusAdorner"/> property.
/// </summary>
public static readonly StyledProperty<ITemplate<IControl>> FocusAdornerProperty =
AvaloniaProperty.Register<Control, ITemplate<IControl>>(nameof(FocusAdorner));
/// <summary>
/// Defines the <see cref="Name"/> property.
/// </summary>
public static readonly DirectProperty<Control, string> NameProperty =
AvaloniaProperty.RegisterDirect<Control, string>(nameof(Name), o => o.Name, (o, v) => o.Name = v);
/// <summary>
/// Defines the <see cref="Parent"/> property.
/// </summary>
public static readonly DirectProperty<Control, IControl> ParentProperty =
AvaloniaProperty.RegisterDirect<Control, IControl>(nameof(Parent), o => o.Parent);
/// <summary>
/// Defines the <see cref="Tag"/> property.
/// </summary>
public static readonly StyledProperty<object> TagProperty =
AvaloniaProperty.Register<Control, object>(nameof(Tag));
/// <summary>
/// Defines the <see cref="TemplatedParent"/> property.
/// </summary>
public static readonly StyledProperty<ITemplatedControl> TemplatedParentProperty =
AvaloniaProperty.Register<Control, ITemplatedControl>(nameof(TemplatedParent), inherits: true);
/// <summary>
/// Defines the <see cref="ContextMenu"/> property.
/// </summary>
public static readonly StyledProperty<ContextMenu> ContextMenuProperty =
AvaloniaProperty.Register<Control, ContextMenu>(nameof(ContextMenu));
/// <summary>
/// Event raised when an element wishes to be scrolled into view.
/// </summary>
public static readonly RoutedEvent<RequestBringIntoViewEventArgs> RequestBringIntoViewEvent =
RoutedEvent.Register<Control, RequestBringIntoViewEventArgs>("RequestBringIntoView", RoutingStrategies.Bubble);
private int _initCount;
private string _name;
private IControl _parent;
private readonly Classes _classes = new Classes();
private DataTemplates _dataTemplates;
private IControl _focusAdorner;
private bool _isAttachedToLogicalTree;
private IAvaloniaList<ILogical> _logicalChildren;
private INameScope _nameScope;
private Styles _styles;
private bool _styled;
private Subject<IStyleable> _styleDetach = new Subject<IStyleable>();
/// <summary>
/// Initializes static members of the <see cref="Control"/> class.
/// </summary>
static Control()
{
AffectsMeasure(IsVisibleProperty);
PseudoClass(IsEnabledCoreProperty, x => !x, ":disabled");
PseudoClass(IsFocusedProperty, ":focus");
PseudoClass(IsPointerOverProperty, ":pointerover");
}
/// <summary>
/// Initializes a new instance of the <see cref="Control"/> class.
/// </summary>
public Control()
{
_nameScope = this as INameScope;
_isAttachedToLogicalTree = this is IStyleRoot;
}
/// <summary>
/// Raised when the control is attached to a rooted logical tree.
/// </summary>
public event EventHandler<LogicalTreeAttachmentEventArgs> AttachedToLogicalTree;
/// <summary>
/// Raised when the control is detached from a rooted logical tree.
/// </summary>
public event EventHandler<LogicalTreeAttachmentEventArgs> DetachedFromLogicalTree;
/// <summary>
/// Occurs when the <see cref="DataContext"/> property changes.
/// </summary>
/// <remarks>
/// This event will be raised when the <see cref="DataContext"/> property has changed and
/// all subscribers to that change have been notified.
/// </remarks>
public event EventHandler DataContextChanged;
/// <summary>
/// Occurs when the control has finished initialization.
/// </summary>
/// <remarks>
/// The Initialized event indicates that all property values on the control have been set.
/// When loading the control from markup, it occurs when
/// <see cref="ISupportInitialize.EndInit"/> is called *and* the control
/// is attached to a rooted logical tree. When the control is created by code and
/// <see cref="ISupportInitialize"/> is not used, it is called when the control is attached
/// to the visual tree.
/// </remarks>
public event EventHandler Initialized;
/// <summary>
/// Gets or sets the name of the control.
/// </summary>
/// <remarks>
/// An element's name is used to uniquely identify a control within the control's name
/// scope. Once the element is added to a logical tree, its name cannot be changed.
/// </remarks>
public string Name
{
get
{
return _name;
}
set
{
if (value.Trim() == string.Empty)
{
throw new InvalidOperationException("Cannot set Name to empty string.");
}
if (_styled)
{
throw new InvalidOperationException("Cannot set Name : control already styled.");
}
_name = value;
}
}
/// <summary>
/// Gets or sets the control's classes.
/// </summary>
/// <remarks>
/// <para>
/// Classes can be used to apply user-defined styling to controls, or to allow controls
/// that share a common purpose to be easily selected.
/// </para>
/// <para>
/// Even though this property can be set, the setter is only intended for use in object
/// initializers. Assigning to this property does not change the underlying collection,
/// it simply clears the existing collection and addds the contents of the assigned
/// collection.
/// </para>
/// </remarks>
public Classes Classes
{
get
{
return _classes;
}
set
{
if (_classes != value)
{
_classes.Replace(value);
}
}
}
/// <summary>
/// Gets or sets the control's data context.
/// </summary>
/// <remarks>
/// The data context is an inherited property that specifies the default object that will
/// be used for data binding.
/// </remarks>
public object DataContext
{
get { return GetValue(DataContextProperty); }
set { SetValue(DataContextProperty, value); }
}
/// <summary>
/// Gets or sets the control's focus adorner.
/// </summary>
public ITemplate<IControl> FocusAdorner
{
get { return GetValue(FocusAdornerProperty); }
set { SetValue(FocusAdornerProperty, value); }
}
/// <summary>
/// Gets or sets the data templates for the control.
/// </summary>
/// <remarks>
/// Each control may define data templates which are applied to the control itself and its
/// children.
/// </remarks>
public DataTemplates DataTemplates
{
get { return _dataTemplates ?? (_dataTemplates = new DataTemplates()); }
set { _dataTemplates = value; }
}
/// <summary>
/// Gets a value that indicates whether the element has finished initialization.
/// </summary>
/// <remarks>
/// For more information about when IsInitialized is set, see the <see cref="Initialized"/>
/// event.
/// </remarks>
public bool IsInitialized { get; private set; }
/// <summary>
/// Gets or sets the styles for the control.
/// </summary>
/// <remarks>
/// Styles for the entire application are added to the Application.Styles collection, but
/// each control may in addition define its own styles which are applied to the control
/// itself and its children.
/// </remarks>
public Styles Styles
{
get { return _styles ?? (_styles = new Styles()); }
set { _styles = value; }
}
/// <summary>
/// Gets the control's logical parent.
/// </summary>
public IControl Parent => _parent;
/// <summary>
/// Gets or sets a context menu to the control.
/// </summary>
public ContextMenu ContextMenu
{
get { return GetValue(ContextMenuProperty); }
set { SetValue(ContextMenuProperty, value); }
}
/// <summary>
/// Gets or sets a user-defined object attached to the control.
/// </summary>
public object Tag
{
get { return GetValue(TagProperty); }
set { SetValue(TagProperty, value); }
}
/// <summary>
/// Gets the control whose lookless template this control is part of.
/// </summary>
public ITemplatedControl TemplatedParent
{
get { return GetValue(TemplatedParentProperty); }
internal set { SetValue(TemplatedParentProperty, value); }
}
/// <summary>
/// Gets a value indicating whether the element is attached to a rooted logical tree.
/// </summary>
bool ILogical.IsAttachedToLogicalTree => _isAttachedToLogicalTree;
/// <summary>
/// Gets the control's logical parent.
/// </summary>
ILogical ILogical.LogicalParent => Parent;
/// <summary>
/// Gets the control's logical children.
/// </summary>
IAvaloniaReadOnlyList<ILogical> ILogical.LogicalChildren => LogicalChildren;
/// <inheritdoc/>
IAvaloniaReadOnlyList<string> IStyleable.Classes => Classes;
/// <summary>
/// Gets the type by which the control is styled.
/// </summary>
/// <remarks>
/// Usually controls are styled by their own type, but there are instances where you want
/// a control to be styled by its base type, e.g. creating SpecialButton that
/// derives from Button and adds extra functionality but is still styled as a regular
/// Button.
/// </remarks>
Type IStyleable.StyleKey => GetType();
/// <inheritdoc/>
IObservable<IStyleable> IStyleable.StyleDetach => _styleDetach;
/// <inheritdoc/>
IStyleHost IStyleHost.StylingParent => (IStyleHost)InheritanceParent;
/// <inheritdoc/>
public virtual void BeginInit()
{
++_initCount;
}
/// <inheritdoc/>
public virtual void EndInit()
{
if (_initCount == 0)
{
throw new InvalidOperationException("BeginInit was not called.");
}
if (--_initCount == 0 && _isAttachedToLogicalTree)
{
InitializeStylesIfNeeded();
InitializeIfNeeded();
}
}
private void InitializeStylesIfNeeded(bool force = false)
{
if (_initCount == 0 && (!_styled || force))
{
RegisterWithNameScope();
ApplyStyling();
_styled = true;
}
}
private void InitializeIfNeeded()
{
if (_initCount == 0 && !IsInitialized)
{
IsInitialized = true;
Initialized?.Invoke(this, EventArgs.Empty);
}
}
/// <inheritdoc/>
void ILogical.NotifyAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
this.OnAttachedToLogicalTreeCore(e);
}
/// <inheritdoc/>
void ILogical.NotifyDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
this.OnDetachedFromLogicalTreeCore(e);
}
/// <summary>
/// Gets the control's logical children.
/// </summary>
protected IAvaloniaList<ILogical> LogicalChildren
{
get
{
if (_logicalChildren == null)
{
var list = new AvaloniaList<ILogical>();
list.ResetBehavior = ResetBehavior.Remove;
list.Validate = ValidateLogicalChild;
list.CollectionChanged += LogicalChildrenCollectionChanged;
_logicalChildren = list;
}
return _logicalChildren;
}
}
/// <summary>
/// Gets the <see cref="Classes"/> collection in a form that allows adding and removing
/// pseudoclasses.
/// </summary>
protected IPseudoClasses PseudoClasses => Classes;
/// <summary>
/// Sets the control's logical parent.
/// </summary>
/// <param name="parent">The parent.</param>
void ISetLogicalParent.SetParent(ILogical parent)
{
var old = Parent;
if (parent != old)
{
if (old != null && parent != null)
{
throw new InvalidOperationException("The Control already has a parent.");
}
if (_isAttachedToLogicalTree)
{
var oldRoot = FindStyleRoot(old) ?? this as IStyleRoot;
if (oldRoot == null)
{
throw new AvaloniaInternalException("Was attached to logical tree but cannot find root.");
}
var e = new LogicalTreeAttachmentEventArgs(oldRoot);
OnDetachedFromLogicalTreeCore(e);
}
if (InheritanceParent == null || parent == null)
{
InheritanceParent = parent as AvaloniaObject;
}
_parent = (IControl)parent;
if (_parent is IStyleRoot || _parent?.IsAttachedToLogicalTree == true || this is IStyleRoot)
{
var newRoot = FindStyleRoot(this);
if (newRoot == null)
{
throw new AvaloniaInternalException("Parent is atttached to logical tree but cannot find root.");
}
var e = new LogicalTreeAttachmentEventArgs(newRoot);
OnAttachedToLogicalTreeCore(e);
}
RaisePropertyChanged(ParentProperty, old, _parent, BindingPriority.LocalValue);
}
}
/// <summary>
/// Sets the control's inheritance parent.
/// </summary>
/// <param name="parent">The parent.</param>
void ISetInheritanceParent.SetParent(IAvaloniaObject parent)
{
InheritanceParent = parent;
}
/// <inheritdoc/>
void IVisualBrushInitialize.EnsureInitialized()
{
if (VisualRoot == null)
{
if (!IsInitialized)
{
foreach (var i in this.GetSelfAndVisualDescendants())
{
var c = i as IControl;
if (c?.IsInitialized == false)
{
var init = c as ISupportInitialize;
if (init != null)
{
init.BeginInit();
init.EndInit();
}
}
}
}
if (!IsArrangeValid)
{
Measure(Size.Infinity);
Arrange(new Rect(DesiredSize));
}
}
}
/// <summary>
/// Adds a pseudo-class to be set when a property is true.
/// </summary>
/// <param name="property">The property.</param>
/// <param name="className">The pseudo-class.</param>
protected static void PseudoClass(AvaloniaProperty<bool> property, string className)
{
PseudoClass(property, x => x, className);
}
/// <summary>
/// Adds a pseudo-class to be set when a property equals a certain value.
/// </summary>
/// <typeparam name="T">The type of the property.</typeparam>
/// <param name="property">The property.</param>
/// <param name="selector">Returns a boolean value based on the property value.</param>
/// <param name="className">The pseudo-class.</param>
protected static void PseudoClass<T>(
AvaloniaProperty<T> property,
Func<T, bool> selector,
string className)
{
Contract.Requires<ArgumentNullException>(property != null);
Contract.Requires<ArgumentNullException>(selector != null);
Contract.Requires<ArgumentNullException>(className != null);
Contract.Requires<ArgumentNullException>(property != null);
if (string.IsNullOrWhiteSpace(className))
{
throw new ArgumentException("Cannot supply an empty className.");
}
property.Changed.Merge(property.Initialized)
.Where(e => e.Sender is Control)
.Subscribe(e =>
{
if (selector((T)e.NewValue))
{
((Control)e.Sender).PseudoClasses.Add(className);
}
else
{
((Control)e.Sender).PseudoClasses.Remove(className);
}
});
}
/// <summary>
/// Gets the element that recieves the focus adorner.
/// </summary>
/// <returns>The control that recieves the focus adorner.</returns>
protected virtual IControl GetTemplateFocusTarget()
{
return this;
}
/// <summary>
/// Called when the control is added to a rooted logical tree.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
AttachedToLogicalTree?.Invoke(this, e);
}
/// <summary>
/// Called when the control is removed from a rooted logical tree.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
DetachedFromLogicalTree?.Invoke(this, e);
}
/// <inheritdoc/>
protected sealed override void OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTreeCore(e);
InitializeIfNeeded();
}
/// <inheritdoc/>
protected sealed override void OnDetachedFromVisualTreeCore(VisualTreeAttachmentEventArgs e)
{
base.OnDetachedFromVisualTreeCore(e);
}
/// <summary>
/// Called before the <see cref="DataContext"/> property changes.
/// </summary>
protected virtual void OnDataContextChanging()
{
}
/// <summary>
/// Called after the <see cref="DataContext"/> property changes.
/// </summary>
protected virtual void OnDataContextChanged()
{
DataContextChanged?.Invoke(this, EventArgs.Empty);
}
/// <inheritdoc/>
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
if (IsFocused &&
(e.NavigationMethod == NavigationMethod.Tab ||
e.NavigationMethod == NavigationMethod.Directional))
{
var adornerLayer = AdornerLayer.GetAdornerLayer(this);
if (adornerLayer != null)
{
if (_focusAdorner == null)
{
var template = GetValue(FocusAdornerProperty);
if (template != null)
{
_focusAdorner = template.Build();
}
}
if (_focusAdorner != null)
{
var target = (Visual)GetTemplateFocusTarget();
if (target != null)
{
AdornerLayer.SetAdornedElement((Visual)_focusAdorner, target);
adornerLayer.Children.Add(_focusAdorner);
}
}
}
}
}
/// <inheritdoc/>
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
if (_focusAdorner != null)
{
var adornerLayer = (IPanel)_focusAdorner.Parent;
adornerLayer.Children.Remove(_focusAdorner);
_focusAdorner = null;
}
}
/// <summary>
/// Called when the <see cref="DataContext"/> property begins and ends being notified.
/// </summary>
/// <param name="o">The object on which the DataContext is changing.</param>
/// <param name="notifying">Whether the notifcation is beginning or ending.</param>
private static void DataContextNotifying(IAvaloniaObject o, bool notifying)
{
var control = o as Control;
if (control != null)
{
if (notifying)
{
control.OnDataContextChanging();
}
else
{
control.OnDataContextChanged();
}
}
}
private static IStyleRoot FindStyleRoot(IStyleHost e)
{
while (e != null)
{
var root = e as IStyleRoot;
if (root != null && root.StylingParent == null)
{
return root;
}
e = e.StylingParent;
}
return null;
}
private void ApplyStyling()
{
AvaloniaLocator.Current.GetService<IStyler>()?.ApplyStyles(this);
}
private void RegisterWithNameScope()
{
if (_nameScope == null)
{
_nameScope = NameScope.GetNameScope(this) ?? ((Control)Parent)?._nameScope;
}
if (Name != null)
{
_nameScope?.Register(Name, this);
var visualParent = Parent as Visual;
if (this is INameScope && visualParent != null)
{
// If we have e.g. a named UserControl in a window then we want that control
// to be findable by name from the Window, so register with both name scopes.
// This differs from WPF's behavior in that XAML manually registers controls
// with name scopes based on the XAML file in which the name attribute appears,
// but we're trying to avoid XAML magic in Avalonia in order to made code-
// created UIs easy. This will cause problems if a UserControl declares a name
// in its XAML and that control is included multiple times in a parent control
// (as the name will be duplicated), however at the moment I'm fine with saying
// "don't do that".
var parentNameScope = NameScope.FindNameScope(visualParent);
parentNameScope?.Register(Name, this);
}
}
}
private static void ValidateLogicalChild(ILogical c)
{
if (c == null)
{
throw new ArgumentException("Cannot add null to LogicalChildren.");
}
}
private void OnAttachedToLogicalTreeCore(LogicalTreeAttachmentEventArgs e)
{
// This method can be called when a control is already attached to the logical tree
// in the following scenario:
// - ListBox gets assigned Items containing ListBoxItem
// - ListBox makes ListBoxItem a logical child
// - ListBox template gets applied; making its Panel get attached to logical tree
// - That AttachedToLogicalTree signal travels down to the ListBoxItem
if (!_isAttachedToLogicalTree)
{
_isAttachedToLogicalTree = true;
InitializeStylesIfNeeded(true);
OnAttachedToLogicalTree(e);
}
foreach (var child in LogicalChildren.OfType<Control>())
{
child.OnAttachedToLogicalTreeCore(e);
}
}
private void OnDetachedFromLogicalTreeCore(LogicalTreeAttachmentEventArgs e)
{
if (_isAttachedToLogicalTree)
{
if (Name != null)
{
_nameScope?.Unregister(Name);
}
_isAttachedToLogicalTree = false;
_styleDetach.OnNext(this);
OnDetachedFromLogicalTree(e);
foreach (var child in LogicalChildren.OfType<Control>())
{
child.OnDetachedFromLogicalTreeCore(e);
}
#if DEBUG
if (((INotifyCollectionChangedDebug)_classes).GetCollectionChangedSubscribers()?.Length > 0)
{
Logger.Warning(
LogArea.Control,
this,
"{Type} detached from logical tree but still has class listeners",
this.GetType());
}
#endif
}
}
private void LogicalChildrenCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
SetLogicalParent(e.NewItems.Cast<ILogical>());
break;
case NotifyCollectionChangedAction.Remove:
ClearLogicalParent(e.OldItems.Cast<ILogical>());
break;
case NotifyCollectionChangedAction.Replace:
ClearLogicalParent(e.OldItems.Cast<ILogical>());
SetLogicalParent(e.NewItems.Cast<ILogical>());
break;
case NotifyCollectionChangedAction.Reset:
throw new NotSupportedException("Reset should not be signalled on LogicalChildren collection");
}
}
private void SetLogicalParent(IEnumerable<ILogical> children)
{
foreach (var i in children)
{
if (i.LogicalParent == null)
{
((ISetLogicalParent)i).SetParent(this);
}
}
}
private void ClearLogicalParent(IEnumerable<ILogical> children)
{
foreach (var i in children)
{
if (i.LogicalParent == this)
{
((ISetLogicalParent)i).SetParent(null);
}
}
}
}
}
| |
using System;
using GuruComponents.Netrix.HtmlFormatting.Elements;
namespace GuruComponents.Netrix.VmlDesigner.Elements
{
/// <summary>
/// This class is used to store information about the kind of element.
/// </summary>
/// <remarks>
/// It is used internally to control the formatting behavior. Externally it is used to provide such information for plug-in modules.
/// </remarks>
public class VmlTagInfo : ITagInfo
{
private string _tagName;
private WhiteSpaceType _inner;
private WhiteSpaceType _following;
private FormattingFlags _flags;
private ElementType _type;
/// <summary>
/// The type of element controls the generel formatting behavior.
/// </summary>
public ElementType Type
{
get
{
return _type;
}
}
/// <summary>
/// Determines how to format this kind of element.
/// </summary>
public FormattingFlags Flags
{
get
{
return _flags;
}
}
/// <summary>
/// Determines how significant are whitespaces following this element.
/// </summary>
public WhiteSpaceType FollowingWhiteSpaceType
{
get
{
return _following;
}
}
/// <summary>
/// Determines how significant are whitespaces within this element.
/// </summary>
public WhiteSpaceType InnerWhiteSpaceType
{
get
{
return _inner;
}
}
/// <summary>
/// The element has to treated as comment.
/// </summary>
public bool IsComment
{
get
{
return (_flags & FormattingFlags.Comment) == 0 == false;
}
}
/// <summary>
/// The element is an inline element.
/// </summary>
public bool IsInline
{
get
{
return (_flags & FormattingFlags.Inline) == 0 == false;
}
}
/// <summary>
/// The element has to be treated as pure XML.
/// </summary>
public bool IsXml
{
get
{
return (_flags & FormattingFlags.Xml) == 0 == false;
}
}
/// <summary>
/// The element does not has an end tag, e.g. it is not a container.
/// </summary>
public bool NoEndTag
{
get
{
return (_flags & FormattingFlags.NoEndTag) == 0 == false;
}
}
/// <summary>
/// The element does not being indented, even if it starts at a new line.
/// </summary>
public bool NoIndent
{
get
{
if ((_flags & FormattingFlags.NoIndent) == 0)
{
return NoEndTag;
}
else
{
return true;
}
}
}
/// <summary>
/// The element is supposed to preserve its content.
/// </summary>
public bool PreserveContent
{
get
{
return (_flags & FormattingFlags.PreserveContent) == 0 == false;
}
}
/// <summary>
/// The tag name of the element.
/// </summary>
public string TagName
{
get
{
return String.Concat("v", ":", _tagName);
}
}
/// <overloads/>
/// <summary>
/// Creates a new tag info with basic parameters.
/// </summary>
/// <param name="tagName"></param>
/// <param name="flags"></param>
public VmlTagInfo(string tagName, FormattingFlags flags) : this(tagName, flags, WhiteSpaceType.CarryThrough, WhiteSpaceType.CarryThrough, ElementType.Other)
{
}
/// <summary>
/// Creates a new tag info with basic parameters.
/// </summary>
/// <param name="tagName"></param>
/// <param name="flags"></param>
/// <param name="type"></param>
public VmlTagInfo(string tagName, FormattingFlags flags, ElementType type) : this(tagName, flags, WhiteSpaceType.CarryThrough, WhiteSpaceType.CarryThrough, type)
{
}
/// <summary>
/// Creates a new tag info with basic parameters.
/// </summary>
/// <param name="tagName"></param>
/// <param name="flags"></param>
/// <param name="innerWhiteSpace"></param>
/// <param name="followingWhiteSpace"></param>
public VmlTagInfo(string tagName, FormattingFlags flags, WhiteSpaceType innerWhiteSpace, WhiteSpaceType followingWhiteSpace) : this(tagName, flags, innerWhiteSpace, followingWhiteSpace, ElementType.Other)
{
}
/// <summary>
/// Creates a new tag info with basic parameters.
/// </summary>
/// <param name="tagName"></param>
/// <param name="flags"></param>
/// <param name="innerWhiteSpace"></param>
/// <param name="followingWhiteSpace"></param>
/// <param name="type"></param>
public VmlTagInfo(string tagName, FormattingFlags flags, WhiteSpaceType innerWhiteSpace, WhiteSpaceType followingWhiteSpace, ElementType type)
{
_tagName = tagName;
_inner = innerWhiteSpace;
_following = followingWhiteSpace;
_flags = flags;
_type = type;
}
/// <summary>
/// Creates a new tag info with basic parameters.
/// </summary>
/// <param name="newTagName"></param>
/// <param name="info"></param>
public VmlTagInfo(string newTagName, ITagInfo info)
{
_tagName = newTagName;
_inner = info.InnerWhiteSpaceType;
_following = info.FollowingWhiteSpaceType;
_flags = info.Flags;
_type = info.Type;
}
/// <summary>
/// Informs that a element can carry another one.
/// </summary>
/// <remarks>
/// This method always returns true. Classes derive from <see cref="VmlTagInfo"/> may
/// overwrite it to control the behavior of complex elements.
/// </remarks>
/// <param name="info"></param>
/// <returns></returns>
public virtual bool CanContainTag(ITagInfo info)
{
return true;
}
}
}
| |
using System;
using System.IO;
using System.Text;
using IdSharp.Common.Utils;
namespace IdSharp.AudioInfo
{
/// <summary>
/// MPEG
/// </summary>
public class Mpeg : IAudioFile
{
static Mpeg()
{
BitrateTable = new[]
{
new[]
{
// MPEG-2.5
new[] { 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 }, // Layer-3
new[] { 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 }, // Layer-2
new[] { 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256 } // Layer-1
},
new int[3][],
new[]
{
// MPEG-2
new[] { 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 }, // Layer-3
new[] { 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 }, // Layer-2
new[] { 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256 } // Layer-1
},
new[]
{
// MPEG-1
new[] { 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 }, // Layer-3
new[] { 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384 }, // Layer-2
new[] { 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448 } // Layer-1
}
};
}
// References:
// http://www.mp3-tech.org/programmer/frame_header.html
private static readonly int[][][] BitrateTable;
private static readonly byte[] INFO_MARKER = Encoding.ASCII.GetBytes("Info");
private static readonly byte[] XING_MARKER = Encoding.ASCII.GetBytes("Xing");
private readonly int _frequency;
private decimal _totalSeconds;
private readonly int _channels;
//private readonly long _samples = 0;
private readonly int _samplesPerFrame;
private readonly byte fh1;
private readonly byte fh2;
private readonly MpegVersion _mpegVersion;
private readonly MpegLayer _mpegLayer;
private readonly bool _isPrivate;
private readonly bool _isCopyright;
private readonly bool _isOriginal;
private readonly double _frameSizeConst;
private readonly int _paddingSizeConst;
private readonly long _headerOffset;
private readonly string _fileName;
private decimal _bitrate;
private bool? _isVBR;
private int _frames;
/// <summary>
/// Initializes a new instance of the <see cref="Mpeg"/> class.
/// </summary>
/// <param name="path">The full path of the file.</param>
/// <param name="calculateBitrate">if set to <c>true</c> the bitrate will be calculated before the constructor returns.</param>
public Mpeg(string path, bool calculateBitrate)
{
_fileName = path;
using (FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
int tmpID3v2TagSize = ID3v2.GetTagSize(stream);
stream.Seek(tmpID3v2TagSize, SeekOrigin.Begin);
byte[] tmpFrameHeader = new byte[4];
bool acceptNullSamples = false;
while (true)
{
int tmpByte = stream.ReadByte(); // keep as ReadByte
while (tmpByte != 0xFF && tmpByte != -1)
{
tmpByte = stream.ReadByte(); // keep as ReadByte
}
if (tmpByte == -1)
{
if (acceptNullSamples)
{
throw new InvalidDataException(string.Format("'{0}': Can't find frame sync", path));
}
stream.Seek(tmpID3v2TagSize, SeekOrigin.Begin);
acceptNullSamples = true;
continue;
}
tmpFrameHeader[0] = (byte)tmpByte;
// Get frame header
if (stream.Read(tmpFrameHeader, 1, 3) != 3)
{
throw new InvalidDataException(string.Format("'{0}': Invalid MPEG file; end of stream reached", path));
}
// No sync
if ((tmpFrameHeader[1] >> 5) != 0x07 ||
((tmpFrameHeader[1] >> 1) & 0x03) == 0) // 2/18/05 - ignore reserved layer
{
stream.Seek(-3, SeekOrigin.Current);
}
else if (tmpFrameHeader[1] == 0xFF ||
((tmpFrameHeader[1] >> 3) & 0x03) == 1) // 2/19/05 - more bad data
{
stream.Seek(-3, SeekOrigin.Current);
}
else
{
int tmpMpegID = (tmpFrameHeader[1] >> 3) & 0x03;
int tmpLayerNum = (tmpFrameHeader[1] >> 1) & 0x03;
int tmpFrequency = GetFrequency((MpegVersion)tmpMpegID, (tmpFrameHeader[2] >> 2) & 0x03);
// Check for invalid frequency
if (tmpFrequency == 0)
{
stream.Seek(-3, SeekOrigin.Current);
continue;
}
int tmpSamplesPerFrame = GetSamplesPerFrame((MpegVersion)tmpMpegID, (MpegLayer)tmpLayerNum);
int tmpUsesPadding = (tmpFrameHeader[2] >> 1) & 0x01;
double tmpFrameSizeConst = 125.0 * tmpSamplesPerFrame / tmpFrequency;
int tmpPaddingSize = (tmpLayerNum == 3 ? 4 : 1);
int tmpBitrateIndex = tmpFrameHeader[2] >> 4;
// Check for invalid values
if (tmpBitrateIndex < 1 || tmpBitrateIndex > 14 || tmpLayerNum == 0)
{
stream.Seek(-3, SeekOrigin.Current);
continue;
}
int tmpFrameBitrate = GetBitrate((MpegVersion)tmpMpegID, (MpegLayer)tmpLayerNum, tmpBitrateIndex);
int tmpFrameSize = (int)(tmpFrameBitrate * tmpFrameSizeConst) + (tmpUsesPadding * tmpPaddingSize);
_headerOffset = stream.Position - 4;
if (tmpFrameSize < 8)
{
stream.Seek(-3, SeekOrigin.Current);
continue;
}
// 7/21/05 - Check for 0x00 or 0xFF at end of last frame
// this sucks for tracks that start with silence
if (_headerOffset >= 1 && !acceptNullSamples) // if (ftell(fp) >= 5)
{
stream.Seek(-5, SeekOrigin.Current);
byte tmpLastByte = stream.Read1();
stream.Seek(4, SeekOrigin.Current);
if (tmpFrameBitrate != 320 && (tmpLastByte == 0x00 || tmpLastByte == 0xFF))
{
// 7/31/05
// may be a valid frame - skip its contents to prevent false sync
long tmpNewPosition = _headerOffset + tmpFrameSize;
if (tmpFrameSize == 0)
tmpNewPosition++;
stream.Seek(tmpNewPosition, SeekOrigin.Begin);
continue;
}
}
/*if (BR == 0 || FrameSizeConst == 0)
{
startpos = HeaderOffset+1;
fseek(fp, startpos, SEEK_SET);
continue;
}*/
stream.Seek(_headerOffset + tmpFrameSize, SeekOrigin.Begin);
if (stream.Read1() == 0xFF)
{
fh1 = stream.Read1();
fh2 = stream.Read1();
if (tmpFrameHeader[1] == fh1 &&
(tmpFrameHeader[2] & 0x0D) == (fh2 & 0x0D))
{
// header found
break;
}
}
stream.Seek(_headerOffset + 1, SeekOrigin.Begin);
continue;
}
}
_mpegVersion = (MpegVersion)((tmpFrameHeader[1] >> 3) & 0x03);
_mpegLayer = (MpegLayer)((tmpFrameHeader[1] >> 1) & 0x03);
_frequency = GetFrequency(_mpegVersion, (tmpFrameHeader[2] >> 2) & 0x03);
if (_frequency == 0)
{
throw new InvalidDataException(String.Format("'{0}'; cannot determine frequency", path));
}
_isPrivate = ((tmpFrameHeader[2] & 0x01) == 0x01);
_samplesPerFrame = GetSamplesPerFrame(_mpegVersion, _mpegLayer);
_frameSizeConst = 125.0 * _samplesPerFrame / _frequency;
_paddingSizeConst = (_mpegLayer == MpegLayer.Layer1 ? 4 : 1);
_isCopyright = (((tmpFrameHeader[3] >> 3) & 0x01) == 0x01);
_isOriginal = (((tmpFrameHeader[3] >> 2) & 0x01) == 0x01);
//tmpModeExtension = (FH[3] >> 4) & 0x03; // not interested, only used in joint-stereo
//_mpegEmphasis = (MpegEmphasis)(tmpFrameHeader[3] & 0x03);
if ((tmpFrameHeader[3] >> 6) == 3) _channels = 1; // Single Channel
else _channels = 2;
// Read LAME Info Tag
bool tmpHasLameInfoTag = false;
stream.Seek(tmpID3v2TagSize + 36, SeekOrigin.Begin);
Byte[] buf = stream.Read(4);
if (ByteUtils.Compare(buf, INFO_MARKER)) // CBR
{
tmpHasLameInfoTag = true;
_isVBR = false;
}
else if (ByteUtils.Compare(buf, XING_MARKER)) // VBR
{
tmpHasLameInfoTag = true;
_isVBR = true;
}
if (tmpHasLameInfoTag)
{
stream.Seek(4, SeekOrigin.Current);
int tmpFrames = stream.ReadInt32();
uint tmpBytes = (uint)stream.ReadInt32();
if (tmpFrames > 256 && tmpBytes > 50000)
{
decimal tmpBitrate = tmpBytes / 125.0m / (tmpFrames * _samplesPerFrame / (decimal)_frequency);
if (tmpBitrate <= 320 && tmpBitrate >= 32)
{
_frames = tmpFrames;
_bitrate = tmpBitrate;
_totalSeconds = (tmpBytes / 125.0m) / _bitrate;
}
}
}
// TODO: Take these 2 lines out
/*fs.Position = 0;
CalculateBitrate(fs, null);*/
if (calculateBitrate)
{
if (_bitrate == 0 || _isVBR == null || _frames == 0 || _totalSeconds == 0)
{
stream.Position = 0;
CalculateBitrate(stream, null);
}
}
}
}
private static int GetBitrate(MpegVersion mpegVersion, MpegLayer mpegLayer, int bitrateIndex)
{
return BitrateTable[(int)mpegVersion][(int)mpegLayer - 1][bitrateIndex - 1];
}
private class CInterestedFrames
{
// TODO: stuff for split CUE
}
private void CalculateBitrate(Stream stream, CInterestedFrames InterestedFrames)
{
int totalTagSize = ID3v2.GetTagSize(stream);
totalTagSize += ID3v1.GetTagSize(stream);
totalTagSize += APEv2.GetTagSize(stream);
Int64 audioLength = stream.Length - totalTagSize;
_bitrate = 0;
_isVBR = null;
_frames = 0;
_totalSeconds = 0;
String step = "";
try
{
int BR, Padding;
int FrameSize;
int TotalBR = 0;
int FrameOffset = 0;
//Int64 TagOffset = 0;
bool bTrusting = true;
bool ignoreall = false;
Byte[] FH = new Byte[4];
bool mPerfect = true;
stream.Position = _headerOffset;
// if (_headerOffset > 0)
// {
// TagOffset = _headerOffset;
// }
int offset = 0;
int frameCount = 0;
int FirstBR = 0;
int audioDataSize = (int)(stream.Length - _headerOffset);
Byte[] audioData = new Byte[audioDataSize];
//Int64 startoffset = stream.Position;
int BufLen = stream.Read(audioData, 0, audioDataSize);
while (offset < BufLen - 16 && !ignoreall)
{
bool reservedlayer = false;
// Find FrameSync
if (FindFrameSync(FH, audioData, BufLen, ref FrameOffset, ref offset, ref mPerfect, ref ignoreall, ref bTrusting, ref reservedlayer))
{
FrameOffset = 0;
int bitrateIndex = FH[2] >> 4;
if (bitrateIndex <= 0 || bitrateIndex >= 15)
{
offset -= 3;
continue;
}
Padding = (FH[2] >> 1) & 0x01;
BR = GetBitrate(_mpegVersion, _mpegLayer, bitrateIndex);
if (BR == 0 || BR % 8 != 0)
{
offset -= 3;
continue;
}
//step = "last good frame @ " + String(startoffset + offset - 4) + ", frame " +
// String(_frames + 1);
// todo: put back later
/*if (InterestedFrames != NULL)
{
if (((_frames + 1) * _samplesperframe / (float)_Frequency) * 75.0 >= InterestedFrames->CurrentFrame())
{
if (_frames == 0 || InterestedFrames->NoAccomodation)
{
InterestedFrames->SetCurrentByteOffset(startoffset + offset - 4);
InterestedFrames->SetCurrentFrameOffset(_frames);
}
InterestedFrames->SetCurrentByteEndOffset(startoffset + offset - 4);
InterestedFrames->Cur += 1;
}
else
{
InterestedFrames->SetCurrentByteOffset(startoffset + offset - 4);
InterestedFrames->SetCurrentFrameOffset(_frames);
}
}*/
if (_isVBR != true)
{
if (TotalBR == 0)
{
FirstBR = BR;
}
else if (BR != FirstBR)
{
_isVBR = true;
}
}
TotalBR += BR;
FrameSize = (int)(BR * _frameSizeConst + Padding * _paddingSizeConst);
offset += FrameSize - 4;
frameCount++;
}
}// end while
if (frameCount == 0)
{
throw new InvalidDataException(String.Format("No frames found in {0}", _fileName));
}
_frames = frameCount;
if (_isVBR == null)
{
_bitrate = FirstBR;
_isVBR = false;
}
else
{
_bitrate = TotalBR / _frames;
}
if (_bitrate == 0)
{
throw new InvalidDataException(String.Format("Error determining bitrate: {0}", _fileName));
}
_totalSeconds = (audioLength / 125.0m) / _bitrate;
}
catch (Exception ex)
{
throw new Exception(String.Format("Error calculating bitrate; {0}", step), ex);
}
}
private bool FindFrameSync(Byte[] FH, Byte[] audioData, int BufLen, ref int FrameOffset, ref int offset, ref bool mPerfect, ref bool ignoreall, ref bool bTrusting, ref bool reservedlayer)
{
while (true)
{
if (FrameOffset == 0)
{
if (offset >= BufLen - 8)
{
return false;
}
FH[0] = audioData[offset++];
while (FH[0] != 0xFF && offset < BufLen)
{
// Leading 0's
if (offset - 1 == 0 && FH[0] == 0)
{
mPerfect = false;
do
{
FH[0] = audioData[offset++];
} while (FH[0] == 0 && offset < BufLen);
continue;
}
if (FH[0] == 'L' && audioData[offset] == 'Y' && audioData[offset + 1] == 'R')
{
// todo: don't want to return, just stop reading data
ignoreall = true;
return false;
}
if (FH[0] == 'T' && audioData[offset] == 'A' && audioData[offset + 1] == 'G')
{
// todo: don't want to return, just stop reading data
ignoreall = true;
return false;
}
if (FH[0] == 'A' && audioData[offset] == 'P' && audioData[offset + 1] == 'E')
{
// todo: don't want to return, just stop reading data
ignoreall = true;
return false;
}
// ignore cut off frames
// todo: eh.. is this really important?
/*if (BufLen < cuiReadBufSize)
{
if (BufLen - offset < TagContainer->Lyrics3ExistingOffset + 128)
{
ignoreall = true;
mPerfect = false;
return;
}
}*/
FH[0] = audioData[offset++];
if (bTrusting == true)
{
mPerfect = false;
if (!reservedlayer)
{
bTrusting = false;
}
}
}
if (offset == BufLen)
{
return false;
}
FrameOffset = 1;
} // end if (FrameOffset == 0)
// Get frame header
int i;
for (i = FrameOffset; i < 4 && offset != BufLen; i++)
{
FH[i] = audioData[offset++];
}
if (i != 4 && offset == BufLen)
{
FrameOffset = i;
return false;
}
// No sync
if ((FH[1] >> 5) != 0x07 || ((FH[1] >> 1) & 0x03) == 0) // 2/18/05 ignore reserved layer
{
if (((FH[1] >> 1) & 0x03) == 0) reservedlayer = true;
FrameOffset = 0;
offset -= 3;
mPerfect = false;
}
else if (FH[1] != fh1 || (FH[2] & 0x0D) != (fh2 & 0x0D))
{
// sync doesn't match expected type
//
FrameOffset = 0;
offset -= 3;
mPerfect = false;
}
else
{
break;
}
} // end find frame sync
return true;
}
private static int GetSamplesPerFrame(MpegVersion mpegVersion, MpegLayer mpegLayer)
{
int tmpSamplesPerFrame = 0;
switch (mpegVersion)
{
// MPEG-1
case MpegVersion.Mpeg1:
if (mpegLayer == MpegLayer.Layer1) tmpSamplesPerFrame = 384;
else if (mpegLayer == MpegLayer.Layer2 ||
mpegLayer == MpegLayer.Layer3) tmpSamplesPerFrame = 1152;
break;
// MPEG-2/2.5
case MpegVersion.Mpeg2:
case MpegVersion.Mpeg25:
if (mpegLayer == MpegLayer.Layer1) tmpSamplesPerFrame = 384;
else if (mpegLayer == MpegLayer.Layer2) tmpSamplesPerFrame = 1152;
else if (mpegLayer == MpegLayer.Layer3) tmpSamplesPerFrame = 576;
break;
} // end switch (ID)
return tmpSamplesPerFrame;
}
private static int GetFrequency(MpegVersion mpegVersion, int frequencyID)
{
int tmpFrequency = 0;
switch (mpegVersion)
{
// MPEG-1
case MpegVersion.Mpeg1:
switch (frequencyID)
{
case 0:
tmpFrequency = 44100;
break;
case 1:
tmpFrequency = 48000;
break;
case 2:
tmpFrequency = 32000;
break;
} // end switch (Frequency)
break;
// MPEG-2
case MpegVersion.Mpeg2:
switch (frequencyID)
{
case 0:
tmpFrequency = 22050;
break;
case 1:
tmpFrequency = 24000;
break;
case 2:
tmpFrequency = 16000;
break;
} // end switch (Frequency)
break;
// MPEG-2.5
case MpegVersion.Mpeg25:
switch (frequencyID)
{
case 0:
tmpFrequency = 11025;
break;
case 1:
tmpFrequency = 12000;
break;
case 2:
tmpFrequency = 8000;
break;
} // end switch (Frequency)
break;
} // end switch (ID)
return tmpFrequency;
}
/// <summary>
/// Gets the frequency.
/// </summary>
/// <value>The frequency.</value>
public int Frequency
{
get { return _frequency; }
}
private void CalculateBitrate()
{
using (FileStream fs = File.Open(_fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
CalculateBitrate(fs, null);
}
}
/// <summary>
/// Gets the total seconds.
/// </summary>
/// <value>The total seconds.</value>
public decimal TotalSeconds
{
get
{
if (_totalSeconds == 0) CalculateBitrate();
return _totalSeconds;
}
}
/// <summary>
/// Gets the bitrate.
/// </summary>
/// <value>The bitrate.</value>
public decimal Bitrate
{
get
{
if (_bitrate == 0) CalculateBitrate();
return _bitrate;
}
}
/// <summary>
/// Gets a value indicating whether the bitrate has been determined.
/// </summary>
/// <value>
/// <c>true</c> if this instance is the bitrate has been determined; otherwise, <c>false</c>.
/// </value>
public bool IsBitrateDetermined
{
get { return _bitrate != 0; }
}
/// <summary>
/// Gets the number of channels.
/// </summary>
/// <value>The number of channels.</value>
public int Channels
{
get { return _channels; }
}
/// <summary>
/// Gets the type of the audio file.
/// </summary>
/// <value>The type of the audio file.</value>
public AudioFileType FileType
{
get { return AudioFileType.Mpeg; }
}
/*/// <summary>
/// Gets the number of samples.
/// </summary>
/// <value>The number of samples.</value>
public long Samples
{
get
{
if (_samples == 0) CalculateBitrate();
return _samples;
}
}*/
/// <summary>
/// Gets a value indicating whether the audio is encoded with a variable bitrate.
/// </summary>
/// <value><c>true</c> if the audio is encoded with a variable bitrate; otherwise, <c>false</c>.</value>
public bool IsVBR
{
get
{
if (_isVBR == null) CalculateBitrate();
return _isVBR.Value;
}
}
/// <summary>
/// Gets a value indicating whether the 'private' bit is set in the frame header.
/// </summary>
/// <value>
/// <c>true</c> if the 'private' bit is set in the frame header; otherwise, <c>false</c>.
/// </value>
public bool IsPrivate
{
get { return _isPrivate; }
}
/// <summary>
/// Gets a value indicating whether the 'copyright' bit is set in the frame header.
/// </summary>
/// <value>
/// <c>true</c> if the 'copyright' bit is set in the frame header; otherwise, <c>false</c>.
/// </value>
public bool IsCopyright
{
get { return _isCopyright; }
}
/// <summary>
/// Gets a value indicating whether the 'original' bit is set in the frame header.
/// </summary>
/// <value>
/// <c>true</c> if the 'original' bit is set in the frame header; otherwise, <c>false</c>.
/// </value>
public bool IsOriginal
{
get { return _isOriginal; }
}
}
}
| |
//
// WebHeaderCollection.cs
// Copied from System.Net.WebHeaderCollection.cs
//
// Authors:
// Lawrence Pit ([email protected])
// Gonzalo Paniagua Javier ([email protected])
// Miguel de Icaza ([email protected])
// sta ([email protected])
//
// Copyright (c) 2003 Ximian, Inc. (http://www.ximian.com)
// Copyright (c) 2007 Novell, Inc. (http://www.novell.com)
// Copyright (c) 2012-2013 sta.blockhead
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
namespace WebSocketSharp.Net
{
/// <summary>
/// Provides a collection of the HTTP headers associated with a request or response.
/// </summary>
[Serializable]
[ComVisible (true)]
public class WebHeaderCollection : NameValueCollection, ISerializable
{
#region Fields
static readonly Dictionary<string, HttpHeaderInfo> headers;
bool internallyCreated;
HttpHeaderType state;
#endregion
#region Constructors
static WebHeaderCollection ()
{
headers = new Dictionary<string, HttpHeaderInfo> (StringComparer.InvariantCultureIgnoreCase)
{
{ "Accept", new HttpHeaderInfo () {
Name = "Accept",
Type = HttpHeaderType.Request | HttpHeaderType.Restricted | HttpHeaderType.MultiValue } },
{ "AcceptCharset", new HttpHeaderInfo () {
Name = "Accept-Charset",
Type = HttpHeaderType.Request | HttpHeaderType.MultiValue } },
{ "AcceptEncoding", new HttpHeaderInfo () {
Name = "Accept-Encoding",
Type = HttpHeaderType.Request | HttpHeaderType.MultiValue } },
{ "AcceptLanguage", new HttpHeaderInfo () {
Name = "Accept-language",
Type = HttpHeaderType.Request | HttpHeaderType.MultiValue } },
{ "AcceptRanges", new HttpHeaderInfo () {
Name = "Accept-Ranges",
Type = HttpHeaderType.Response | HttpHeaderType.MultiValue } },
{ "Age", new HttpHeaderInfo () {
Name = "Age",
Type = HttpHeaderType.Response } },
{ "Allow", new HttpHeaderInfo () {
Name = "Allow",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue } },
{ "Authorization", new HttpHeaderInfo () {
Name = "Authorization",
Type = HttpHeaderType.Request | HttpHeaderType.MultiValue } },
{ "CacheControl", new HttpHeaderInfo () {
Name = "Cache-Control",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue } },
{ "Connection", new HttpHeaderInfo () {
Name = "Connection",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted | HttpHeaderType.MultiValue } },
{ "ContentEncoding", new HttpHeaderInfo () {
Name = "Content-Encoding",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue } },
{ "ContentLanguage", new HttpHeaderInfo () {
Name = "Content-Language",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue } },
{ "ContentLength", new HttpHeaderInfo () {
Name = "Content-Length",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted } },
{ "ContentLocation", new HttpHeaderInfo () {
Name = "Content-Location",
Type = HttpHeaderType.Request | HttpHeaderType.Response } },
{ "ContentMd5", new HttpHeaderInfo () {
Name = "Content-MD5",
Type = HttpHeaderType.Request | HttpHeaderType.Response } },
{ "ContentRange", new HttpHeaderInfo () {
Name = "Content-Range",
Type = HttpHeaderType.Request | HttpHeaderType.Response } },
{ "ContentType", new HttpHeaderInfo () {
Name = "Content-Type",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted } },
{ "Cookie", new HttpHeaderInfo () {
Name = "Cookie",
Type = HttpHeaderType.Request } },
{ "Cookie2", new HttpHeaderInfo () {
Name = "Cookie2",
Type = HttpHeaderType.Request } },
{ "Date", new HttpHeaderInfo () {
Name = "Date",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted } },
{ "Expect", new HttpHeaderInfo () {
Name = "Expect",
Type = HttpHeaderType.Request | HttpHeaderType.Restricted | HttpHeaderType.MultiValue } },
{ "Expires", new HttpHeaderInfo () {
Name = "Expires",
Type = HttpHeaderType.Request | HttpHeaderType.Response } },
{ "ETag", new HttpHeaderInfo () {
Name = "ETag",
Type = HttpHeaderType.Response } },
{ "From", new HttpHeaderInfo () {
Name = "From",
Type = HttpHeaderType.Request } },
{ "Host", new HttpHeaderInfo () {
Name = "Host",
Type = HttpHeaderType.Request | HttpHeaderType.Restricted } },
{ "IfMatch", new HttpHeaderInfo () {
Name = "If-Match",
Type = HttpHeaderType.Request | HttpHeaderType.MultiValue } },
{ "IfModifiedSince", new HttpHeaderInfo () {
Name = "If-Modified-Since",
Type = HttpHeaderType.Request | HttpHeaderType.Restricted } },
{ "IfNoneMatch", new HttpHeaderInfo () {
Name = "If-None-Match",
Type = HttpHeaderType.Request | HttpHeaderType.MultiValue } },
{ "IfRange", new HttpHeaderInfo () {
Name = "If-Range",
Type = HttpHeaderType.Request } },
{ "IfUnmodifiedSince", new HttpHeaderInfo () {
Name = "If-Unmodified-Since",
Type = HttpHeaderType.Request } },
{ "KeepAlive", new HttpHeaderInfo () {
Name = "Keep-Alive",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue } },
{ "LastModified", new HttpHeaderInfo () {
Name = "Last-Modified",
Type = HttpHeaderType.Request | HttpHeaderType.Response } },
{ "Location", new HttpHeaderInfo () {
Name = "Location",
Type = HttpHeaderType.Response } },
{ "MaxForwards", new HttpHeaderInfo () {
Name = "Max-Forwards",
Type = HttpHeaderType.Request } },
{ "Pragma", new HttpHeaderInfo () {
Name = "Pragma",
Type = HttpHeaderType.Request | HttpHeaderType.Response } },
{ "ProxyConnection", new HttpHeaderInfo () {
Name = "Proxy-Connection",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted } },
{ "ProxyAuthenticate", new HttpHeaderInfo () {
Name = "Proxy-Authenticate",
Type = HttpHeaderType.Response | HttpHeaderType.MultiValue } },
{ "ProxyAuthorization", new HttpHeaderInfo () {
Name = "Proxy-Authorization",
Type = HttpHeaderType.Request } },
{ "Public", new HttpHeaderInfo () {
Name = "Public",
Type = HttpHeaderType.Response | HttpHeaderType.MultiValue } },
{ "Range", new HttpHeaderInfo () {
Name = "Range",
Type = HttpHeaderType.Request | HttpHeaderType.Restricted | HttpHeaderType.MultiValue } },
{ "Referer", new HttpHeaderInfo () {
Name = "Referer",
Type = HttpHeaderType.Request | HttpHeaderType.Restricted } },
{ "RetryAfter", new HttpHeaderInfo () {
Name = "Retry-After",
Type = HttpHeaderType.Response } },
{ "SecWebSocketAccept", new HttpHeaderInfo () {
Name = "Sec-WebSocket-Accept",
Type = HttpHeaderType.Response | HttpHeaderType.Restricted } },
{ "SecWebSocketExtensions", new HttpHeaderInfo () {
Name = "Sec-WebSocket-Extensions",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted | HttpHeaderType.MultiValueInRequest } },
{ "SecWebSocketKey", new HttpHeaderInfo () {
Name = "Sec-WebSocket-Key",
Type = HttpHeaderType.Request | HttpHeaderType.Restricted } },
{ "SecWebSocketProtocol", new HttpHeaderInfo () {
Name = "Sec-WebSocket-Protocol",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValueInRequest } },
{ "SecWebSocketVersion", new HttpHeaderInfo () {
Name = "Sec-WebSocket-Version",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted | HttpHeaderType.MultiValueInResponse } },
{ "Server", new HttpHeaderInfo () {
Name = "Server",
Type = HttpHeaderType.Response } },
{ "SetCookie", new HttpHeaderInfo () {
Name = "Set-Cookie",
Type = HttpHeaderType.Response | HttpHeaderType.MultiValue } },
{ "SetCookie2", new HttpHeaderInfo () {
Name = "Set-Cookie2",
Type = HttpHeaderType.Response | HttpHeaderType.MultiValue } },
{ "Te", new HttpHeaderInfo () {
Name = "TE",
Type = HttpHeaderType.Request } },
{ "Trailer", new HttpHeaderInfo () {
Name = "Trailer",
Type = HttpHeaderType.Request | HttpHeaderType.Response } },
{ "TransferEncoding", new HttpHeaderInfo () {
Name = "Transfer-Encoding",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.Restricted | HttpHeaderType.MultiValue } },
{ "Translate", new HttpHeaderInfo () {
Name = "Translate",
Type = HttpHeaderType.Request } },
{ "Upgrade", new HttpHeaderInfo () {
Name = "Upgrade",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue } },
{ "UserAgent", new HttpHeaderInfo () {
Name = "User-Agent",
Type = HttpHeaderType.Request | HttpHeaderType.Restricted } },
{ "Vary", new HttpHeaderInfo () {
Name = "Vary",
Type = HttpHeaderType.Response | HttpHeaderType.MultiValue } },
{ "Via", new HttpHeaderInfo () {
Name = "Via",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue } },
{ "Warning", new HttpHeaderInfo () {
Name = "Warning",
Type = HttpHeaderType.Request | HttpHeaderType.Response | HttpHeaderType.MultiValue } },
{ "WwwAuthenticate", new HttpHeaderInfo () {
Name = "WWW-Authenticate",
Type = HttpHeaderType.Response | HttpHeaderType.Restricted | HttpHeaderType.MultiValue } }
};
}
internal WebHeaderCollection (bool internallyCreated)
{
this.internallyCreated = internallyCreated;
state = HttpHeaderType.Unspecified;
}
/// <summary>
/// Initializes a new instance of the <see cref="WebHeaderCollection"/> class
/// with the specified <see cref="SerializationInfo"/> and <see cref="StreamingContext"/>.
/// </summary>
/// <param name="serializationInfo">
/// A <see cref="SerializationInfo"/> that contains the data to need to serialize the <see cref="WebHeaderCollection"/> object.
/// </param>
/// <param name="streamingContext">
/// A <see cref="StreamingContext"/> that contains the source of the serialized stream associated with the new <see cref="WebHeaderCollection"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializationInfo"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// An element with the specified name is not found in <paramref name="serializationInfo"/>.
/// </exception>
protected WebHeaderCollection (
SerializationInfo serializationInfo, StreamingContext streamingContext)
{
if (serializationInfo == null)
throw new ArgumentNullException ("serializationInfo");
try {
internallyCreated = serializationInfo.GetBoolean ("InternallyCreated");
state = (HttpHeaderType) serializationInfo.GetInt32 ("State");
int count = serializationInfo.GetInt32 ("Count");
for (int i = 0; i < count; i++) {
base.Add (
serializationInfo.GetString (i.ToString ()),
serializationInfo.GetString ((count + i).ToString ()));
}
} catch (SerializationException ex) {
throw new ArgumentException (ex.Message, "serializationInfo", ex);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="WebHeaderCollection"/> class.
/// </summary>
public WebHeaderCollection ()
{
internallyCreated = false;
state = HttpHeaderType.Unspecified;
}
#endregion
#region Properties
/// <summary>
/// Gets all header names in the collection.
/// </summary>
/// <value>
/// An array of <see cref="string"/> that contains all header names in the collection.
/// </value>
public override string [] AllKeys
{
get {
return base.AllKeys;
}
}
/// <summary>
/// Gets the number of headers in the collection.
/// </summary>
/// <value>
/// An <see cref="int"/> that indicates the number of headers in the collection.
/// </value>
public override int Count
{
get {
return base.Count;
}
}
/// <summary>
/// Gets or sets the specified request <paramref name="header"/> in the collection.
/// </summary>
/// <value>
/// A <see cref="string"/> that contains the value of the specified request <paramref name="header"/>.
/// </value>
/// <param name="header">
/// A <see cref="HttpRequestHeader"/> that indicates a request header.
/// </param>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance does not allow any of <see cref="HttpRequestHeader"/> values.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65535.
/// </exception>
public string this [HttpRequestHeader header]
{
get {
return Get (Convert (header));
}
set {
Add (header, value);
}
}
/// <summary>
/// Gets or sets the specified response <paramref name="header"/> in the collection.
/// </summary>
/// <value>
/// A <see cref="string"/> that contains the value of the specified response <paramref name="header"/>.
/// </value>
/// <param name="header">
/// A <see cref="HttpResponseHeader"/> that indicates a response header.
/// </param>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance does not allow any of <see cref="HttpResponseHeader"/> values.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65535.
/// </exception>
public string this [HttpResponseHeader header]
{
get {
return Get (Convert (header));
}
set {
Add (header, value);
}
}
/// <summary>
/// Gets a collection of header names in the collection.
/// </summary>
/// <value>
/// A <see cref="NameObjectCollectionBase.KeysCollection"/> that contains a collection
/// of header names in the collection.
/// </value>
public override KeysCollection Keys
{
get {
return base.Keys;
}
}
#endregion
#region Private Methods
void Add (string name, string value, bool ignoreRestricted)
{
Action <string, string> add;
if (ignoreRestricted)
add = AddWithoutCheckingNameAndRestricted;
else
add = AddWithoutCheckingName;
DoWithCheckingState (add, CheckName (name), value, true);
}
void AddWithoutCheckingName (string name, string value)
{
DoWithoutCheckingName (base.Add, name, value);
}
void AddWithoutCheckingNameAndRestricted (string name, string value)
{
base.Add (name, CheckValue (value));
}
static int CheckColonSeparated (string header)
{
int i = header.IndexOf (':');
if (i == -1)
throw new ArgumentException ("No colon found.", "header");
return i;
}
static HttpHeaderType CheckHeaderType (string name)
{
HttpHeaderInfo info;
return !TryGetHeaderInfo (name, out info)
? HttpHeaderType.Unspecified
: info.IsRequest && !info.IsResponse
? HttpHeaderType.Request
: !info.IsRequest && info.IsResponse
? HttpHeaderType.Response
: HttpHeaderType.Unspecified;
}
static string CheckName (string name)
{
if (name.IsNullOrEmpty ())
throw new ArgumentNullException ("name");
name = name.Trim ();
if (!IsHeaderName (name))
throw new ArgumentException ("Contains invalid characters.", "name");
return name;
}
void CheckRestricted (string name)
{
if (!internallyCreated && ContainsInRestricted (name, true))
throw new ArgumentException ("This header must be modified with the appropiate property.");
}
void CheckState (bool response)
{
if (state == HttpHeaderType.Unspecified)
return;
if (response && state == HttpHeaderType.Request)
throw new InvalidOperationException ("This collection has already been used to store the request headers.");
if (!response && state == HttpHeaderType.Response)
throw new InvalidOperationException ("This collection has already been used to store the response headers.");
}
static string CheckValue (string value)
{
if (value.IsNullOrEmpty ())
return String.Empty;
value = value.Trim ();
if (value.Length > 65535)
throw new ArgumentOutOfRangeException ("value", "The length must not be greater than 65535.");
if (!IsHeaderValue (value))
throw new ArgumentException ("Contains invalid characters.", "value");
return value;
}
static string Convert (string key)
{
HttpHeaderInfo info;
return headers.TryGetValue (key, out info)
? info.Name
: String.Empty;
}
static bool ContainsInRestricted (string name, bool response)
{
HttpHeaderInfo info;
return TryGetHeaderInfo (name, out info)
? info.IsRestricted (response)
: false;
}
void DoWithCheckingState (
Action <string, string> act, string name, string value, bool setState)
{
var type = CheckHeaderType (name);
if (type == HttpHeaderType.Request)
DoWithCheckingState (act, name, value, false, setState);
else if (type == HttpHeaderType.Response)
DoWithCheckingState (act, name, value, true, setState);
else
act (name, value);
}
void DoWithCheckingState (
Action <string, string> act, string name, string value, bool response, bool setState)
{
CheckState (response);
act (name, value);
if (setState)
SetState (response);
}
void DoWithoutCheckingName (Action <string, string> act, string name, string value)
{
CheckRestricted (name);
act (name, CheckValue (value));
}
static HttpHeaderInfo GetHeaderInfo (string name)
{
return (from HttpHeaderInfo info in headers.Values
where info.Name.Equals (name, StringComparison.InvariantCultureIgnoreCase)
select info).FirstOrDefault ();
}
void RemoveWithoutCheckingName (string name, string unuse)
{
CheckRestricted (name);
base.Remove (name);
}
void SetState (bool response)
{
if (state == HttpHeaderType.Unspecified)
state = response
? HttpHeaderType.Response
: HttpHeaderType.Request;
}
void SetWithoutCheckingName (string name, string value)
{
DoWithoutCheckingName (base.Set, name, value);
}
static bool TryGetHeaderInfo (string name, out HttpHeaderInfo info)
{
info = GetHeaderInfo (name);
return info != null;
}
#endregion
#region Internal Methods
internal static string Convert (HttpRequestHeader header)
{
return Convert (header.ToString ());
}
internal static string Convert (HttpResponseHeader header)
{
return Convert (header.ToString ());
}
internal static bool IsHeaderName (string name)
{
return name.IsNullOrEmpty ()
? false
: name.IsToken ();
}
internal static bool IsHeaderValue (string value)
{
return value.IsText ();
}
internal static bool IsMultiValue (string headerName, bool response)
{
if (headerName.IsNullOrEmpty ())
return false;
HttpHeaderInfo info;
return TryGetHeaderInfo (headerName, out info)
? info.IsMultiValue (response)
: false;
}
internal void RemoveInternal (string name)
{
base.Remove (name);
}
internal void SetInternal (string header, bool response)
{
int pos = CheckColonSeparated (header);
SetInternal (header.Substring (0, pos), header.Substring (pos + 1), response);
}
internal void SetInternal (string name, string value, bool response)
{
value = CheckValue (value);
if (IsMultiValue (name, response))
base.Add (name, value);
else
base.Set (name, value);
}
internal string ToStringMultiValue (bool response)
{
var sb = new StringBuilder ();
Count.Times (i => {
string key = GetKey (i);
if (IsMultiValue (key, response)) {
foreach (string value in GetValues (i))
sb.AppendFormat ("{0}: {1}\r\n", key, value);
} else {
sb.AppendFormat ("{0}: {1}\r\n", key, Get (i));
}
});
return sb.Append ("\r\n").ToString ();
}
#endregion
#region Explicit Interface Implementation
/// <summary>
/// Populates the specified <see cref="SerializationInfo"/> with the data to need to
/// serialize the <see cref="WebHeaderCollection"/> object.
/// </summary>
/// <param name="serializationInfo">
/// A <see cref="SerializationInfo"/> that holds the data to need to serialize the <see cref="WebHeaderCollection"/> object.
/// </param>
/// <param name="streamingContext">
/// A <see cref="StreamingContext"/> that specifies the destination for the serialization.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializationInfo"/> is <see langword="null"/>.
/// </exception>
[SecurityPermission (SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter, SerializationFormatter = true)]
void ISerializable.GetObjectData (
SerializationInfo serializationInfo, StreamingContext streamingContext)
{
GetObjectData (serializationInfo, streamingContext);
}
#endregion
#region Protected Methods
/// <summary>
/// Adds a header to the collection without checking whether the header is on the restricted header list.
/// </summary>
/// <param name="headerName">
/// A <see cref="string"/> that contains the name of the header to add.
/// </param>
/// <param name="headerValue">
/// A <see cref="string"/> that contains the value of the header to add.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="headerName"/> is <see langword="null"/> or <see cref="String.Empty"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="headerName"/> or <paramref name="headerValue"/> contains invalid characters.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="headerValue"/> is greater than 65535.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance does not allow the <paramref name="headerName"/>.
/// </exception>
protected void AddWithoutValidate (string headerName, string headerValue)
{
Add (headerName, headerValue, true);
}
#endregion
#region Public Methods
/// <summary>
/// Adds the specified <paramref name="header"/> to the collection.
/// </summary>
/// <param name="header">
/// A <see cref="string"/> that contains a header with the name and value separated by a colon (:).
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="header"/> is <see langword="null"/>, <see cref="String.Empty"/>, or
/// the name part of <paramref name="header"/> is <see cref="String.Empty"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> does not contain a colon.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The name or value part of <paramref name="header"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of the value part of <paramref name="header"/> is greater than 65535.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance does not allow the <paramref name="header"/>.
/// </exception>
public void Add (string header)
{
if (header.IsNullOrEmpty ())
throw new ArgumentNullException ("header");
int pos = CheckColonSeparated (header);
Add (header.Substring (0, pos), header.Substring (pos + 1));
}
/// <summary>
/// Adds the specified request <paramref name="header"/> with the specified <paramref name="value"/> to the collection.
/// </summary>
/// <param name="header">
/// A <see cref="HttpRequestHeader"/> is a request header to add.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that contains the value of the header to add.
/// </param>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance does not allow any of <see cref="HttpRequestHeader"/> values.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65535.
/// </exception>
public void Add (HttpRequestHeader header, string value)
{
DoWithCheckingState (AddWithoutCheckingName, Convert (header), value, false, true);
}
/// <summary>
/// Adds the specified response <paramref name="header"/> with the specified <paramref name="value"/> to the collection.
/// </summary>
/// <param name="header">
/// A <see cref="HttpResponseHeader"/> is a response header to add.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that contains the value of the header to add.
/// </param>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance does not allow any of <see cref="HttpResponseHeader"/> values.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65535.
/// </exception>
public void Add (HttpResponseHeader header, string value)
{
DoWithCheckingState (AddWithoutCheckingName, Convert (header), value, true, true);
}
/// <summary>
/// Adds a header with the specified <paramref name="name"/> and <paramref name="value"/> to the collection.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that contains the name of the header to add.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that contains the value of the header to add.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/> or <see cref="String.Empty"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> or <paramref name="value"/> contains invalid characters.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="name"/> is a restricted header name.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65535.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance does not allow the header <paramref name="name"/>.
/// </exception>
public override void Add (string name, string value)
{
Add (name, value, false);
}
/// <summary>
/// Removes all headers from the collection.
/// </summary>
public override void Clear ()
{
base.Clear ();
state = HttpHeaderType.Unspecified;
}
/// <summary>
/// Get the value of the header with the specified <paramref name="index"/> in the collection.
/// </summary>
/// <returns>
/// A <see cref="string"/> that receives the value of the header.
/// </returns>
/// <param name="index">
/// An <see cref="int"/> that is the zero-based index of the header to get.
/// </param>
public override string Get (int index)
{
return base.Get (index);
}
/// <summary>
/// Get the value of the header with the specified <paramref name="name"/> in the collection.
/// </summary>
/// <returns>
/// A <see cref="string"/> that receives the value of the header.
/// <see langword="null"/> if there is no header with <paramref name="name"/> in the collection.
/// </returns>
/// <param name="name">
/// A <see cref="string"/> that contains the name of the header to get.
/// </param>
public override string Get (string name)
{
return base.Get (name);
}
/// <summary>
/// Gets the enumerator to use to iterate through the <see cref="WebHeaderCollection"/>.
/// </summary>
/// <returns>
/// An instance of an implementation of the <see cref="IEnumerator"/> interface
/// to use to iterate through the <see cref="WebHeaderCollection"/>.
/// </returns>
public override IEnumerator GetEnumerator ()
{
return base.GetEnumerator ();
}
/// <summary>
/// Get the header name at the specified <paramref name="index"/> position in the collection.
/// </summary>
/// <returns>
/// A <see cref="string"/> that receives the header name.
/// </returns>
/// <param name="index">
/// An <see cref="int"/> is the zero-based index of the key to get from the collection.
/// </param>
public override string GetKey (int index)
{
return base.GetKey (index);
}
/// <summary>
/// Gets an array of header values stored in the specified <paramref name="header"/> name.
/// </summary>
/// <returns>
/// An array of <see cref="string"/> that receives the header values.
/// </returns>
/// <param name="header">
/// A <see cref="string"/> that contains a header name.
/// </param>
public override string [] GetValues (string header)
{
string [] values = base.GetValues (header);
return values == null || values.Length == 0
? null
: values;
}
/// <summary>
/// Gets an array of header values stored in the specified <paramref name="index"/> position of the header collection.
/// </summary>
/// <returns>
/// An array of <see cref="string"/> that receives the header values.
/// </returns>
/// <param name="index">
/// An <see cref="int"/> is the zero-based index of the header in the collection.
/// </param>
public override string [] GetValues (int index)
{
string [] values = base.GetValues (index);
return values == null || values.Length == 0
? null
: values;
}
/// <summary>
/// Populates the specified <see cref="SerializationInfo"/> with the data to need to
/// serialize the <see cref="WebHeaderCollection"/> object.
/// </summary>
/// <param name="serializationInfo">
/// A <see cref="SerializationInfo"/> that holds the data to need to serialize the <see cref="WebHeaderCollection"/> object.
/// </param>
/// <param name="streamingContext">
/// A <see cref="StreamingContext"/> that specifies the destination for the serialization.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializationInfo"/> is <see langword="null"/>.
/// </exception>
[SecurityPermission (SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public override void GetObjectData (
SerializationInfo serializationInfo, StreamingContext streamingContext)
{
if (serializationInfo == null)
throw new ArgumentNullException ("serializationInfo");
serializationInfo.AddValue ("InternallyCreated", internallyCreated);
serializationInfo.AddValue ("State", (int) state);
int count = Count;
serializationInfo.AddValue ("Count", count);
count.Times (i => {
serializationInfo.AddValue (i.ToString (), GetKey (i));
serializationInfo.AddValue ((count + i).ToString (), Get (i));
});
}
/// <summary>
/// Determines whether the specified header can be set for the request.
/// </summary>
/// <returns>
/// <c>true</c> if the header is restricted; otherwise, <c>false</c>.
/// </returns>
/// <param name="headerName">
/// A <see cref="string"/> that contains the name of the header to test.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="headerName"/> is <see langword="null"/> or <see cref="String.Empty"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="headerName"/> contains invalid characters.
/// </exception>
public static bool IsRestricted (string headerName)
{
return IsRestricted (headerName, false);
}
/// <summary>
/// Determines whether the specified header can be set for the request or the response.
/// </summary>
/// <returns>
/// <c>true</c> if the header is restricted; otherwise, <c>false</c>.
/// </returns>
/// <param name="headerName">
/// A <see cref="string"/> that contains the name of the header to test.
/// </param>
/// <param name="response">
/// <c>true</c> if does the test for the response; for the request, <c>false</c>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="headerName"/> is <see langword="null"/> or <see cref="String.Empty"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="headerName"/> contains invalid characters.
/// </exception>
public static bool IsRestricted (string headerName, bool response)
{
return ContainsInRestricted (CheckName (headerName), response);
}
/// <summary>
/// Implements the <see cref="ISerializable"/> interface and raises the deserialization event
/// when the deserialization is complete.
/// </summary>
/// <param name="sender">
/// An <see cref="object"/> that contains the source of the deserialization event.
/// </param>
public override void OnDeserialization (object sender)
{
}
/// <summary>
/// Removes the specified header from the collection.
/// </summary>
/// <param name="header">
/// A <see cref="HttpRequestHeader"/> to remove from the collection.
/// </param>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance does not allow any of <see cref="HttpRequestHeader"/> values.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="header"/> is a restricted header.
/// </exception>
public void Remove (HttpRequestHeader header)
{
DoWithCheckingState (RemoveWithoutCheckingName, Convert (header), null, false, false);
}
/// <summary>
/// Removes the specified header from the collection.
/// </summary>
/// <param name="header">
/// A <see cref="HttpResponseHeader"/> to remove from the collection.
/// </param>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance does not allow any of <see cref="HttpResponseHeader"/> values.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="header"/> is a restricted header.
/// </exception>
public void Remove (HttpResponseHeader header)
{
DoWithCheckingState (RemoveWithoutCheckingName, Convert (header), null, true, false);
}
/// <summary>
/// Removes the specified header from the collection.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that contains the name of the header to remove from the collection.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/> or <see cref="String.Empty"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> contains invalid characters.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="name"/> is a restricted header name.
/// </para>
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance does not allow the header <paramref name="name"/>.
/// </exception>
public override void Remove (string name)
{
DoWithCheckingState (RemoveWithoutCheckingName, CheckName (name), null, false);
}
/// <summary>
/// Sets the specified header to the specified value.
/// </summary>
/// <param name="header">
/// A <see cref="HttpRequestHeader"/> to set.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that contains the value of the header to set.
/// </param>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance does not allow any of <see cref="HttpRequestHeader"/> values.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65535.
/// </exception>
public void Set (HttpRequestHeader header, string value)
{
DoWithCheckingState (SetWithoutCheckingName, Convert (header), value, false, true);
}
/// <summary>
/// Sets the specified header to the specified value.
/// </summary>
/// <param name="header">
/// A <see cref="HttpResponseHeader"/> to set.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that contains the value of the header to set.
/// </param>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance does not allow any of <see cref="HttpResponseHeader"/> values.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="header"/> is a restricted header.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="value"/> contains invalid characters.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65535.
/// </exception>
public void Set (HttpResponseHeader header, string value)
{
DoWithCheckingState (SetWithoutCheckingName, Convert (header), value, true, true);
}
/// <summary>
/// Sets the specified header to the specified value.
/// </summary>
/// <param name="name">
/// A <see cref="string"/> that contains the name of the header to set.
/// </param>
/// <param name="value">
/// A <see cref="string"/> that contains the value of the header to set.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/> or <see cref="String.Empty"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="name"/> or <paramref name="value"/> contain invalid characters.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="name"/> is a restricted header name.
/// </para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// The length of <paramref name="value"/> is greater than 65535.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="WebHeaderCollection"/> instance does not allow the header <paramref name="name"/>.
/// </exception>
public override void Set (string name, string value)
{
DoWithCheckingState (SetWithoutCheckingName, CheckName (name), value, true);
}
/// <summary>
/// Converts the current <see cref="WebHeaderCollection"/> to an array of <see cref="byte"/>.
/// </summary>
/// <returns>
/// An array of <see cref="byte"/> that receives the converted current <see cref="WebHeaderCollection"/>.
/// </returns>
public byte [] ToByteArray ()
{
return Encoding.UTF8.GetBytes (ToString ());
}
/// <summary>
/// Returns a <see cref="string"/> that represents the current <see cref="WebHeaderCollection"/>.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents the current <see cref="WebHeaderCollection"/>.
/// </returns>
public override string ToString ()
{
var sb = new StringBuilder();
Count.Times (i => {
sb.AppendFormat ("{0}: {1}\r\n", GetKey (i), Get (i));
});
return sb.Append ("\r\n").ToString ();
}
#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 TrackYourSmoking.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>ChangeEvent</c> resource.</summary>
public sealed partial class ChangeEventName : gax::IResourceName, sys::IEquatable<ChangeEventName>
{
/// <summary>The possible contents of <see cref="ChangeEventName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>customers/{customer_id}/changeEvents/{timestamp_micros}~{command_index}~{mutate_index}</c>.
/// </summary>
CustomerTimestampMicrosCommandIndexMutateIndex = 1,
}
private static gax::PathTemplate s_customerTimestampMicrosCommandIndexMutateIndex = new gax::PathTemplate("customers/{customer_id}/changeEvents/{timestamp_micros_command_index_mutate_index}");
/// <summary>Creates a <see cref="ChangeEventName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="ChangeEventName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ChangeEventName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ChangeEventName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ChangeEventName"/> with the pattern
/// <c>customers/{customer_id}/changeEvents/{timestamp_micros}~{command_index}~{mutate_index}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="timestampMicrosId">The <c>TimestampMicros</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="commandIndexId">The <c>CommandIndex</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="mutateIndexId">The <c>MutateIndex</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ChangeEventName"/> constructed from the provided ids.</returns>
public static ChangeEventName FromCustomerTimestampMicrosCommandIndexMutateIndex(string customerId, string timestampMicrosId, string commandIndexId, string mutateIndexId) =>
new ChangeEventName(ResourceNameType.CustomerTimestampMicrosCommandIndexMutateIndex, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), timestampMicrosId: gax::GaxPreconditions.CheckNotNullOrEmpty(timestampMicrosId, nameof(timestampMicrosId)), commandIndexId: gax::GaxPreconditions.CheckNotNullOrEmpty(commandIndexId, nameof(commandIndexId)), mutateIndexId: gax::GaxPreconditions.CheckNotNullOrEmpty(mutateIndexId, nameof(mutateIndexId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ChangeEventName"/> with pattern
/// <c>customers/{customer_id}/changeEvents/{timestamp_micros}~{command_index}~{mutate_index}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="timestampMicrosId">The <c>TimestampMicros</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="commandIndexId">The <c>CommandIndex</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="mutateIndexId">The <c>MutateIndex</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ChangeEventName"/> with pattern
/// <c>customers/{customer_id}/changeEvents/{timestamp_micros}~{command_index}~{mutate_index}</c>.
/// </returns>
public static string Format(string customerId, string timestampMicrosId, string commandIndexId, string mutateIndexId) =>
FormatCustomerTimestampMicrosCommandIndexMutateIndex(customerId, timestampMicrosId, commandIndexId, mutateIndexId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ChangeEventName"/> with pattern
/// <c>customers/{customer_id}/changeEvents/{timestamp_micros}~{command_index}~{mutate_index}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="timestampMicrosId">The <c>TimestampMicros</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="commandIndexId">The <c>CommandIndex</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="mutateIndexId">The <c>MutateIndex</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ChangeEventName"/> with pattern
/// <c>customers/{customer_id}/changeEvents/{timestamp_micros}~{command_index}~{mutate_index}</c>.
/// </returns>
public static string FormatCustomerTimestampMicrosCommandIndexMutateIndex(string customerId, string timestampMicrosId, string commandIndexId, string mutateIndexId) =>
s_customerTimestampMicrosCommandIndexMutateIndex.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(timestampMicrosId, nameof(timestampMicrosId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(commandIndexId, nameof(commandIndexId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(mutateIndexId, nameof(mutateIndexId)))}");
/// <summary>Parses the given resource name string into a new <see cref="ChangeEventName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/changeEvents/{timestamp_micros}~{command_index}~{mutate_index}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="changeEventName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ChangeEventName"/> if successful.</returns>
public static ChangeEventName Parse(string changeEventName) => Parse(changeEventName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ChangeEventName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/changeEvents/{timestamp_micros}~{command_index}~{mutate_index}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="changeEventName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="ChangeEventName"/> if successful.</returns>
public static ChangeEventName Parse(string changeEventName, bool allowUnparsed) =>
TryParse(changeEventName, allowUnparsed, out ChangeEventName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ChangeEventName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/changeEvents/{timestamp_micros}~{command_index}~{mutate_index}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="changeEventName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ChangeEventName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string changeEventName, out ChangeEventName result) =>
TryParse(changeEventName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ChangeEventName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>customers/{customer_id}/changeEvents/{timestamp_micros}~{command_index}~{mutate_index}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="changeEventName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ChangeEventName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string changeEventName, bool allowUnparsed, out ChangeEventName result)
{
gax::GaxPreconditions.CheckNotNull(changeEventName, nameof(changeEventName));
gax::TemplatedResourceName resourceName;
if (s_customerTimestampMicrosCommandIndexMutateIndex.TryParseName(changeEventName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerTimestampMicrosCommandIndexMutateIndex(resourceName[0], split1[0], split1[1], split1[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(changeEventName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private ChangeEventName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string commandIndexId = null, string customerId = null, string mutateIndexId = null, string timestampMicrosId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CommandIndexId = commandIndexId;
CustomerId = customerId;
MutateIndexId = mutateIndexId;
TimestampMicrosId = timestampMicrosId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ChangeEventName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/changeEvents/{timestamp_micros}~{command_index}~{mutate_index}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="timestampMicrosId">The <c>TimestampMicros</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="commandIndexId">The <c>CommandIndex</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="mutateIndexId">The <c>MutateIndex</c> ID. Must not be <c>null</c> or empty.</param>
public ChangeEventName(string customerId, string timestampMicrosId, string commandIndexId, string mutateIndexId) : this(ResourceNameType.CustomerTimestampMicrosCommandIndexMutateIndex, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), timestampMicrosId: gax::GaxPreconditions.CheckNotNullOrEmpty(timestampMicrosId, nameof(timestampMicrosId)), commandIndexId: gax::GaxPreconditions.CheckNotNullOrEmpty(commandIndexId, nameof(commandIndexId)), mutateIndexId: gax::GaxPreconditions.CheckNotNullOrEmpty(mutateIndexId, nameof(mutateIndexId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>CommandIndex</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string CommandIndexId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>MutateIndex</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string MutateIndexId { get; }
/// <summary>
/// The <c>TimestampMicros</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string TimestampMicrosId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerTimestampMicrosCommandIndexMutateIndex: return s_customerTimestampMicrosCommandIndexMutateIndex.Expand(CustomerId, $"{TimestampMicrosId}~{CommandIndexId}~{MutateIndexId}");
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as ChangeEventName);
/// <inheritdoc/>
public bool Equals(ChangeEventName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ChangeEventName a, ChangeEventName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ChangeEventName a, ChangeEventName b) => !(a == b);
}
public partial class ChangeEvent
{
/// <summary>
/// <see cref="ChangeEventName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal ChangeEventName ResourceNameAsChangeEventName
{
get => string.IsNullOrEmpty(ResourceName) ? null : ChangeEventName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CampaignName"/>-typed view over the <see cref="Campaign"/> resource name property.
/// </summary>
internal CampaignName CampaignAsCampaignName
{
get => string.IsNullOrEmpty(Campaign) ? null : CampaignName.Parse(Campaign, allowUnparsed: true);
set => Campaign = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="AdGroupName"/>-typed view over the <see cref="AdGroup"/> resource name property.
/// </summary>
internal AdGroupName AdGroupAsAdGroupName
{
get => string.IsNullOrEmpty(AdGroup) ? null : AdGroupName.Parse(AdGroup, allowUnparsed: true);
set => AdGroup = value?.ToString() ?? "";
}
/// <summary><see cref="FeedName"/>-typed view over the <see cref="Feed"/> resource name property.</summary>
internal FeedName FeedAsFeedName
{
get => string.IsNullOrEmpty(Feed) ? null : FeedName.Parse(Feed, allowUnparsed: true);
set => Feed = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="FeedItemName"/>-typed view over the <see cref="FeedItem"/> resource name property.
/// </summary>
internal FeedItemName FeedItemAsFeedItemName
{
get => string.IsNullOrEmpty(FeedItem) ? null : FeedItemName.Parse(FeedItem, allowUnparsed: true);
set => FeedItem = value?.ToString() ?? "";
}
/// <summary><see cref="AssetName"/>-typed view over the <see cref="Asset"/> resource name property.</summary>
internal AssetName AssetAsAssetName
{
get => string.IsNullOrEmpty(Asset) ? null : AssetName.Parse(Asset, allowUnparsed: true);
set => Asset = value?.ToString() ?? "";
}
}
}
| |
//
// Utilities.cs
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2010 Jb Evain
//
// 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 ScriptSharp.Importer.IL.Metadata;
namespace ScriptSharp.Importer.IL {
static partial class Mixin {
public static uint ReadCompressedUInt32 (this byte [] data, ref int position)
{
uint integer;
if ((data [position] & 0x80) == 0) {
integer = data [position];
position++;
} else if ((data [position] & 0x40) == 0) {
integer = (uint) (data [position] & ~0x80) << 8;
integer |= data [position + 1];
position += 2;
} else {
integer = (uint) (data [position] & ~0xc0) << 24;
integer |= (uint) data [position + 1] << 16;
integer |= (uint) data [position + 2] << 8;
integer |= (uint) data [position + 3];
position += 4;
}
return integer;
}
public static MetadataToken GetMetadataToken (this CodedIndex self, uint data)
{
uint rid;
TokenType token_type;
switch (self) {
case CodedIndex.TypeDefOrRef:
rid = data >> 2;
switch (data & 3) {
case 0:
token_type = TokenType.TypeDef; goto ret;
case 1:
token_type = TokenType.TypeRef; goto ret;
case 2:
token_type = TokenType.TypeSpec; goto ret;
default:
goto exit;
}
case CodedIndex.HasConstant:
rid = data >> 2;
switch (data & 3) {
case 0:
token_type = TokenType.Field; goto ret;
case 1:
token_type = TokenType.Param; goto ret;
case 2:
token_type = TokenType.Property; goto ret;
default:
goto exit;
}
case CodedIndex.HasCustomAttribute:
rid = data >> 5;
switch (data & 31) {
case 0:
token_type = TokenType.Method; goto ret;
case 1:
token_type = TokenType.Field; goto ret;
case 2:
token_type = TokenType.TypeRef; goto ret;
case 3:
token_type = TokenType.TypeDef; goto ret;
case 4:
token_type = TokenType.Param; goto ret;
case 5:
token_type = TokenType.InterfaceImpl; goto ret;
case 6:
token_type = TokenType.MemberRef; goto ret;
case 7:
token_type = TokenType.Module; goto ret;
case 8:
token_type = TokenType.Permission; goto ret;
case 9:
token_type = TokenType.Property; goto ret;
case 10:
token_type = TokenType.Event; goto ret;
case 11:
token_type = TokenType.Signature; goto ret;
case 12:
token_type = TokenType.ModuleRef; goto ret;
case 13:
token_type = TokenType.TypeSpec; goto ret;
case 14:
token_type = TokenType.Assembly; goto ret;
case 15:
token_type = TokenType.AssemblyRef; goto ret;
case 16:
token_type = TokenType.File; goto ret;
case 17:
token_type = TokenType.ExportedType; goto ret;
case 18:
token_type = TokenType.ManifestResource; goto ret;
case 19:
token_type = TokenType.GenericParam; goto ret;
default:
goto exit;
}
case CodedIndex.HasFieldMarshal:
rid = data >> 1;
switch (data & 1) {
case 0:
token_type = TokenType.Field; goto ret;
case 1:
token_type = TokenType.Param; goto ret;
default:
goto exit;
}
case CodedIndex.HasDeclSecurity:
rid = data >> 2;
switch (data & 3) {
case 0:
token_type = TokenType.TypeDef; goto ret;
case 1:
token_type = TokenType.Method; goto ret;
case 2:
token_type = TokenType.Assembly; goto ret;
default:
goto exit;
}
case CodedIndex.MemberRefParent:
rid = data >> 3;
switch (data & 7) {
case 0:
token_type = TokenType.TypeDef; goto ret;
case 1:
token_type = TokenType.TypeRef; goto ret;
case 2:
token_type = TokenType.ModuleRef; goto ret;
case 3:
token_type = TokenType.Method; goto ret;
case 4:
token_type = TokenType.TypeSpec; goto ret;
default:
goto exit;
}
case CodedIndex.HasSemantics:
rid = data >> 1;
switch (data & 1) {
case 0:
token_type = TokenType.Event; goto ret;
case 1:
token_type = TokenType.Property; goto ret;
default:
goto exit;
}
case CodedIndex.MethodDefOrRef:
rid = data >> 1;
switch (data & 1) {
case 0:
token_type = TokenType.Method; goto ret;
case 1:
token_type = TokenType.MemberRef; goto ret;
default:
goto exit;
}
case CodedIndex.MemberForwarded:
rid = data >> 1;
switch (data & 1) {
case 0:
token_type = TokenType.Field; goto ret;
case 1:
token_type = TokenType.Method; goto ret;
default:
goto exit;
}
case CodedIndex.Implementation:
rid = data >> 2;
switch (data & 3) {
case 0:
token_type = TokenType.File; goto ret;
case 1:
token_type = TokenType.AssemblyRef; goto ret;
case 2:
token_type = TokenType.ExportedType; goto ret;
default:
goto exit;
}
case CodedIndex.CustomAttributeType:
rid = data >> 3;
switch (data & 7) {
case 2:
token_type = TokenType.Method; goto ret;
case 3:
token_type = TokenType.MemberRef; goto ret;
default:
goto exit;
}
case CodedIndex.ResolutionScope:
rid = data >> 2;
switch (data & 3) {
case 0:
token_type = TokenType.Module; goto ret;
case 1:
token_type = TokenType.ModuleRef; goto ret;
case 2:
token_type = TokenType.AssemblyRef; goto ret;
case 3:
token_type = TokenType.TypeRef; goto ret;
default:
goto exit;
}
case CodedIndex.TypeOrMethodDef:
rid = data >> 1;
switch (data & 1) {
case 0:
token_type = TokenType.TypeDef; goto ret;
case 1:
token_type = TokenType.Method; goto ret;
default: goto exit;
}
default:
goto exit;
}
ret:
return new MetadataToken (token_type, rid);
exit:
return MetadataToken.Zero;
}
#if !IL_READ_ONLY
public static uint CompressMetadataToken (this CodedIndex self, MetadataToken token)
{
uint ret = 0;
if (token.RID == 0)
return ret;
switch (self) {
case CodedIndex.TypeDefOrRef:
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.TypeDef:
return ret | 0;
case TokenType.TypeRef:
return ret | 1;
case TokenType.TypeSpec:
return ret | 2;
default:
goto exit;
}
case CodedIndex.HasConstant:
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.Field:
return ret | 0;
case TokenType.Param:
return ret | 1;
case TokenType.Property:
return ret | 2;
default:
goto exit;
}
case CodedIndex.HasCustomAttribute:
ret = token.RID << 5;
switch (token.TokenType) {
case TokenType.Method:
return ret | 0;
case TokenType.Field:
return ret | 1;
case TokenType.TypeRef:
return ret | 2;
case TokenType.TypeDef:
return ret | 3;
case TokenType.Param:
return ret | 4;
case TokenType.InterfaceImpl:
return ret | 5;
case TokenType.MemberRef:
return ret | 6;
case TokenType.Module:
return ret | 7;
case TokenType.Permission:
return ret | 8;
case TokenType.Property:
return ret | 9;
case TokenType.Event:
return ret | 10;
case TokenType.Signature:
return ret | 11;
case TokenType.ModuleRef:
return ret | 12;
case TokenType.TypeSpec:
return ret | 13;
case TokenType.Assembly:
return ret | 14;
case TokenType.AssemblyRef:
return ret | 15;
case TokenType.File:
return ret | 16;
case TokenType.ExportedType:
return ret | 17;
case TokenType.ManifestResource:
return ret | 18;
case TokenType.GenericParam:
return ret | 19;
default:
goto exit;
}
case CodedIndex.HasFieldMarshal:
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.Field:
return ret | 0;
case TokenType.Param:
return ret | 1;
default:
goto exit;
}
case CodedIndex.HasDeclSecurity:
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.TypeDef:
return ret | 0;
case TokenType.Method:
return ret | 1;
case TokenType.Assembly:
return ret | 2;
default:
goto exit;
}
case CodedIndex.MemberRefParent:
ret = token.RID << 3;
switch (token.TokenType) {
case TokenType.TypeDef:
return ret | 0;
case TokenType.TypeRef:
return ret | 1;
case TokenType.ModuleRef:
return ret | 2;
case TokenType.Method:
return ret | 3;
case TokenType.TypeSpec:
return ret | 4;
default:
goto exit;
}
case CodedIndex.HasSemantics:
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.Event:
return ret | 0;
case TokenType.Property:
return ret | 1;
default:
goto exit;
}
case CodedIndex.MethodDefOrRef:
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.Method:
return ret | 0;
case TokenType.MemberRef:
return ret | 1;
default:
goto exit;
}
case CodedIndex.MemberForwarded:
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.Field:
return ret | 0;
case TokenType.Method:
return ret | 1;
default:
goto exit;
}
case CodedIndex.Implementation:
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.File:
return ret | 0;
case TokenType.AssemblyRef:
return ret | 1;
case TokenType.ExportedType:
return ret | 2;
default:
goto exit;
}
case CodedIndex.CustomAttributeType:
ret = token.RID << 3;
switch (token.TokenType) {
case TokenType.Method:
return ret | 2;
case TokenType.MemberRef:
return ret | 3;
default:
goto exit;
}
case CodedIndex.ResolutionScope:
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.Module:
return ret | 0;
case TokenType.ModuleRef:
return ret | 1;
case TokenType.AssemblyRef:
return ret | 2;
case TokenType.TypeRef:
return ret | 3;
default:
goto exit;
}
case CodedIndex.TypeOrMethodDef:
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.TypeDef:
return ret | 0;
case TokenType.Method:
return ret | 1;
default:
goto exit;
}
default:
goto exit;
}
exit:
throw new ArgumentException ();
}
#endif
public static int GetSize (this CodedIndex self, Func<Table, int> counter)
{
int bits;
Table [] tables;
switch (self) {
case CodedIndex.TypeDefOrRef:
bits = 2;
tables = new [] { Table.TypeDef, Table.TypeRef, Table.TypeSpec };
break;
case CodedIndex.HasConstant:
bits = 2;
tables = new [] { Table.Field, Table.Param, Table.Property };
break;
case CodedIndex.HasCustomAttribute:
bits = 5;
tables = new [] {
Table.Method, Table.Field, Table.TypeRef, Table.TypeDef, Table.Param, Table.InterfaceImpl, Table.MemberRef,
Table.Module, Table.DeclSecurity, Table.Property, Table.Event, Table.StandAloneSig, Table.ModuleRef,
Table.TypeSpec, Table.Assembly, Table.AssemblyRef, Table.File, Table.ExportedType,
Table.ManifestResource, Table.GenericParam
};
break;
case CodedIndex.HasFieldMarshal:
bits = 1;
tables = new [] { Table.Field, Table.Param };
break;
case CodedIndex.HasDeclSecurity:
bits = 2;
tables = new [] { Table.TypeDef, Table.Method, Table.Assembly };
break;
case CodedIndex.MemberRefParent:
bits = 3;
tables = new [] { Table.TypeDef, Table.TypeRef, Table.ModuleRef, Table.Method, Table.TypeSpec };
break;
case CodedIndex.HasSemantics:
bits = 1;
tables = new [] { Table.Event, Table.Property };
break;
case CodedIndex.MethodDefOrRef:
bits = 1;
tables = new [] { Table.Method, Table.MemberRef };
break;
case CodedIndex.MemberForwarded:
bits = 1;
tables = new [] { Table.Field, Table.Method };
break;
case CodedIndex.Implementation:
bits = 2;
tables = new [] { Table.File, Table.AssemblyRef, Table.ExportedType };
break;
case CodedIndex.CustomAttributeType:
bits = 3;
tables = new [] { Table.Method, Table.MemberRef };
break;
case CodedIndex.ResolutionScope:
bits = 2;
tables = new [] { Table.Module, Table.ModuleRef, Table.AssemblyRef, Table.TypeRef };
break;
case CodedIndex.TypeOrMethodDef:
bits = 1;
tables = new [] { Table.TypeDef, Table.Method };
break;
default:
throw new ArgumentException ();
}
int max = 0;
for (int i = 0; i < tables.Length; i++) {
max = System.Math.Max (counter (tables [i]), max);
}
return max < (1 << (16 - bits)) ? 2 : 4;
}
}
}
| |
#region CopyrightHeader
//
// Copyright by Contributors
//
// 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.txt
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
namespace gov.va.medora.mdo.dao.vista
{
[TestFixture]
public class VistaDateTimeIteratorTest
{
[Test]
[Category("unit_only")]
public void TestSetIteratorLengthFromDates()
{
VistaDateTimeIterator testIterator = new VistaDateTimeIterator("20080102.234556", "20080103");
Assert.IsTrue(testIterator._iterLength == VistaDateTimeIterator.SECOND_ITERATION);
Assert.AreEqual((int)VistaDateTimeIterator.PRECISION.SECOND, testIterator._precision);
}
[Test]
[Category("unit_only")]
public void TestSetIteratorLengthFromEndDate()
{
VistaDateTimeIterator testIterator = new VistaDateTimeIterator("20080102", "20080103.01");
Assert.IsTrue(testIterator._iterLength == VistaDateTimeIterator.HOUR_ITERATION);
Assert.AreEqual((int)VistaDateTimeIterator.PRECISION.HOUR, testIterator._precision);
}
[Test]
[Category("unit_only")]
public void TestSetIteratorLengthFromEndDateZero()
{
VistaDateTimeIterator testIterator = new VistaDateTimeIterator("20080102", "20080103.00");
Assert.IsTrue(testIterator._iterLength == VistaDateTimeIterator.HOUR_ITERATION);
Assert.AreEqual((int)VistaDateTimeIterator.PRECISION.HOUR, testIterator._precision);
}
/// <summary>
/// BEWARE: A DateTime string that gets padded with 0s will cause you to iterate
/// in seconds.
/// </summary>
[Test]
[Category("unit_only")]
public void TestSetIteratorLengthNormalizedNumber()
{
VistaDateTimeIterator testIterator = new VistaDateTimeIterator("20080102.000000", "20080103.0000");
Assert.IsTrue(testIterator._iterLength == VistaDateTimeIterator.SECOND_ITERATION);
Assert.AreEqual((int)VistaDateTimeIterator.PRECISION.SECOND, testIterator._precision);
}
/// <summary>Dummy check...</summary>
[Test]
[Category("unit_only")]
public void TestPrecisionPositions()
{
string testDate = VistaTimestamp.fromDateTime(new DateTime(2008, 01, 23, 12, 34, 56, 789));
Assert.AreEqual("308",testDate.Substring(0,(int)VistaDateTimeIterator.PRECISION.YEAR));
Assert.AreEqual("30801", testDate.Substring(0,(int)VistaDateTimeIterator.PRECISION.MONTH));
Assert.AreEqual("3080123", testDate.Substring(0,(int)VistaDateTimeIterator.PRECISION.DAY));
Assert.AreEqual("3080123.12", testDate.Substring(0, (int)VistaDateTimeIterator.PRECISION.HOUR));
Assert.AreEqual("3080123.1234", testDate.Substring(0, (int)VistaDateTimeIterator.PRECISION.MINUTE));
Assert.AreEqual("3080123.123456", testDate.Substring(0, (int)VistaDateTimeIterator.PRECISION.SECOND));
}
public string CalculateMD5Hash(string input)
{
// step 1, calculate MD5 hash from input
System.Security.Cryptography.MD5 md5
= System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);
// step 2, convert byte array to hex string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
/// <summary>
/// Test to see that as we roll over days, that the iterator will do the right thing as well.
/// </summary>
[Test]
[Category("unit_only")]
public void TestHourRollOver()
{
//http://msdn.microsoft.com/en-us/library/system.string.gethashcode.aspx
// If two string objects are equal, the GetHashCode method returns identical values. However, there is not a unique hash code value for each unique string value. Different strings can return the same hash code.
VistaDateTimeIterator testIterator = new VistaDateTimeIterator(
new DateTime(2008, 01, 01, 22, 0, 0)
, new DateTime(2008, 01, 03)
, new TimeSpan(1, 0, 0)
);
List<string> values = new List<string>();
while (!testIterator.IsDone())
{
testIterator.SetIterEndDate(); // put at start of loop
values.Add(testIterator.GetDdrListerPart());
testIterator.AdvanceIterStartDate(); // put at end of loop
}
//Spot Check - Count
Assert.AreEqual(26, values.Count);
String[] strings = values.ToArray();
//Spot Check - Validate Start Value
Assert.IsTrue(strings[0].Equals("3080101.22"));
//Spot Check - Validate End Value
Assert.IsTrue(strings[25].Equals("3080102.23"));
//Spot Check - Validate an Intermediate Value
Assert.IsTrue(strings[14].Equals("3080102.12"));
//The MD5 hash value is stable across platforms
string hash = CalculateMD5Hash(string.Concat(values.ToArray()));
Assert.AreEqual("830FAB9CC0EB3A1E3855B5DF0F560213", hash);
}
[Test]
[Category("unit_only")]
public void TestIterationDays()
{
int result = VistaDateTimeIterator.IterationDays("1.000000");
Assert.AreEqual(1, result);
}
[Test]
[Category("unit_only")]
public void TestIterationDaysPoint()
{
int result = VistaDateTimeIterator.IterationDays(".000000");
Assert.AreEqual(0, result);
}
[Test]
[Category("unit_only")]
public void TestIterationDays1Hour()
{
int result = VistaDateTimeIterator.IterationDays(".100000");
Assert.AreEqual(0, result);
}
[Test]
[Category("unit_only")]
public void TestIterationDays1HourNoPoint()
{
int result = VistaDateTimeIterator.IterationDays("100000");
Assert.AreEqual(0, result);
}
[Test]
[Category("unit_only")]
public void TestIterationHours()
{
int result = VistaDateTimeIterator.IterationHours("1.100000");
Assert.AreEqual(10, result);
}
[Test]
[Category("unit_only")]
public void TestIterationHoursNoPoint()
{
int result = VistaDateTimeIterator.IterationHours("120000");
Assert.AreEqual(12, result);
}
[Test]
[Category("unit_only")]
public void TestIterationHoursPoint()
{
int result = VistaDateTimeIterator.IterationHours(".345000");
Assert.AreEqual(34, result);
}
[Test]
[Category("unit_only")]
public void TestIterationMinutes()
{
int result = VistaDateTimeIterator.IterationMinutes(".345000");
Assert.AreEqual(50, result);
}
[Test]
[Category("unit_only")]
public void TestIterationSecond()
{
int result = VistaDateTimeIterator.IterationSeconds(".345036");
Assert.AreEqual(36, result);
}
[Test]
[Category("unit_only")]
public void TestIterationTimeSpanFromString()
{
TimeSpan result = VistaDateTimeIterator.IterationTimeSpanFromString("1.010230");
Assert.AreEqual(1, result.Days);
Assert.AreEqual(1, result.Hours);
Assert.AreEqual(2, result.Minutes);
Assert.AreEqual(30, result.Seconds);
}
/// <summary>Values will roll over into next greater time range
/// - e.g. seconds to minutes and hours to days
/// </summary>
[Test]
[Category("unit_only")]
public void TestIterationTimeSpanFromStringTooManySeconds()
{
TimeSpan result = VistaDateTimeIterator.IterationTimeSpanFromString("1.250290");
Assert.AreEqual(2, result.Days);
Assert.AreEqual(1, result.Hours);
Assert.AreEqual(3, result.Minutes);
Assert.AreEqual(30, result.Seconds);
}
/// <summary>Values will roll over into next greater time range
/// - e.g. seconds to minutes and hours to days
/// </summary>
[Test]
[Category("unit_only")]
public void TestIterationTimeSpanFromStringOneDay()
{
TimeSpan result = VistaDateTimeIterator.IterationTimeSpanFromString("1.");
Assert.AreEqual(1, result.Days);
Assert.AreEqual(0, result.Hours);
Assert.AreEqual(0, result.Minutes);
Assert.AreEqual(0, result.Seconds);
}
/// <summary>
/// This actually gives you a zero timespan, so the default of one day is
/// used instead.
/// </summary>
[Test]
[Category("unit_only")]
public void TestIterationTimeSpanFromStringOne()
{
TimeSpan result = VistaDateTimeIterator.IterationTimeSpanFromString("1");
Assert.AreEqual(1, result.Days);
}
/// <summary>
/// One hour
/// </summary>
[Test]
[Category("unit_only")]
public void TestIterationTimeSpanFromStringDotOhOne()
{
TimeSpan result = VistaDateTimeIterator.IterationTimeSpanFromString(".01");
Assert.AreEqual(1, result.Hours);
}
[Test]
[Category("unit_only")]
public void TestIterationTimeSpanFromStringOhOne()
{
TimeSpan result = VistaDateTimeIterator.IterationTimeSpanFromString("01");
Assert.AreEqual(1, result.Hours);
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Threading.Tasks;
using IdentityServer4.Models;
using IdentityServer4.Extensions;
using IdentityServer4.Hosting;
using IdentityModel;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using IdentityServer4.Services;
using IdentityServer4.Configuration;
using IdentityServer4.Stores;
using IdentityServer4.ResponseHandling;
using Microsoft.AspNetCore.Authentication;
namespace IdentityServer4.Endpoints.Results
{
internal class AuthorizeResult : IEndpointResult
{
public AuthorizeResponse Response { get; }
public AuthorizeResult(AuthorizeResponse response)
{
Response = response ?? throw new ArgumentNullException(nameof(response));
}
internal AuthorizeResult(
AuthorizeResponse response,
IdentityServerOptions options,
IUserSession userSession,
IMessageStore<ErrorMessage> errorMessageStore,
ISystemClock clock)
: this(response)
{
_options = options;
_userSession = userSession;
_errorMessageStore = errorMessageStore;
_clock = clock;
}
private IdentityServerOptions _options;
private IUserSession _userSession;
private IMessageStore<ErrorMessage> _errorMessageStore;
private ISystemClock _clock;
private void Init(HttpContext context)
{
_options = _options ?? context.RequestServices.GetRequiredService<IdentityServerOptions>();
_userSession = _userSession ?? context.RequestServices.GetRequiredService<IUserSession>();
_errorMessageStore = _errorMessageStore ?? context.RequestServices.GetRequiredService<IMessageStore<ErrorMessage>>();
_clock = _clock ?? context.RequestServices.GetRequiredService<ISystemClock>();
}
public async Task ExecuteAsync(HttpContext context)
{
Init(context);
if (Response.IsError)
{
await ProcessErrorAsync(context);
}
else
{
await ProcessResponseAsync(context);
}
}
private async Task ProcessErrorAsync(HttpContext context)
{
// these are the conditions where we can send a response
// back directly to the client, otherwise we're only showing the error UI
var isPromptNoneError = Response.Error == OidcConstants.AuthorizeErrors.AccountSelectionRequired ||
Response.Error == OidcConstants.AuthorizeErrors.LoginRequired ||
Response.Error == OidcConstants.AuthorizeErrors.ConsentRequired ||
Response.Error == OidcConstants.AuthorizeErrors.InteractionRequired;
if (Response.Error == OidcConstants.AuthorizeErrors.AccessDenied ||
(isPromptNoneError && Response.Request?.PromptMode == OidcConstants.PromptModes.None)
)
{
// this scenario we can return back to the client
await ProcessResponseAsync(context);
}
else
{
// we now know we must show error page
await RedirectToErrorPageAsync(context);
}
}
protected async Task ProcessResponseAsync(HttpContext context)
{
if (!Response.IsError)
{
// success response -- track client authorization for sign-out
//_logger.LogDebug("Adding client {0} to client list cookie for subject {1}", request.ClientId, request.Subject.GetSubjectId());
await _userSession.AddClientIdAsync(Response.Request.ClientId);
}
await RenderAuthorizeResponseAsync(context);
}
private async Task RenderAuthorizeResponseAsync(HttpContext context)
{
if (Response.Request.ResponseMode == OidcConstants.ResponseModes.Query ||
Response.Request.ResponseMode == OidcConstants.ResponseModes.Fragment)
{
context.Response.SetNoCache();
context.Response.Redirect(BuildRedirectUri());
}
else if (Response.Request.ResponseMode == OidcConstants.ResponseModes.FormPost)
{
context.Response.SetNoCache();
AddSecurityHeaders(context);
await context.Response.WriteHtmlAsync(GetFormPostHtml());
}
else
{
//_logger.LogError("Unsupported response mode.");
throw new InvalidOperationException("Unsupported response mode");
}
}
private void AddSecurityHeaders(HttpContext context)
{
var formOrigin = Response.Request.RedirectUri.GetOrigin();
var csp = $"default-src 'none'; script-src 'sha256-VuNUSJ59bpCpw62HM2JG/hCyGiqoPN3NqGvNXQPU+rY='; ";
if (!context.Response.Headers.ContainsKey("Content-Security-Policy"))
{
context.Response.Headers.Add("Content-Security-Policy", csp);
}
if (!context.Response.Headers.ContainsKey("X-Content-Security-Policy"))
{
context.Response.Headers.Add("X-Content-Security-Policy", csp);
}
var referrer_policy = "no-referrer";
if (!context.Response.Headers.ContainsKey("Referrer-Policy"))
{
context.Response.Headers.Add("Referrer-Policy", referrer_policy);
}
}
private string BuildRedirectUri()
{
var uri = Response.RedirectUri;
var query = Response.ToNameValueCollection().ToQueryString();
if (Response.Request.ResponseMode == OidcConstants.ResponseModes.Query)
{
uri = uri.AddQueryString(query);
}
else
{
uri = uri.AddHashFragment(query);
}
if (Response.IsError && !uri.Contains("#"))
{
// https://tools.ietf.org/html/draft-bradley-oauth-open-redirector-00
uri += "#_=_";
}
return uri;
}
private const string FormPostHtml = "<form method='post' action='{uri}'>{body}<noscript><button>Click to continue</button></noscript></form><script>(function(){document.forms[0].submit();})();</script>";
private string GetFormPostHtml()
{
var html = FormPostHtml;
html = html.Replace("{uri}", Response.Request.RedirectUri);
html = html.Replace("{body}", Response.ToNameValueCollection().ToFormPost());
return html;
}
private async Task RedirectToErrorPageAsync(HttpContext context)
{
var errorModel = new ErrorMessage
{
RequestId = context.TraceIdentifier,
Error = Response.Error,
ErrorDescription = Response.ErrorDescription,
UiLocales = Response.Request?.UiLocales,
DisplayMode = Response.Request?.DisplayMode
};
if (Response.RedirectUri != null && Response.Request?.ResponseMode != null)
{
// if we have a valid redirect uri, then include it to the error page
errorModel.RedirectUri = BuildRedirectUri();
errorModel.ResponseMode = Response.Request.ResponseMode;
}
var message = new Message<ErrorMessage>(errorModel, _clock.UtcNow.UtcDateTime);
var id = await _errorMessageStore.WriteAsync(message);
var errorUrl = _options.UserInteraction.ErrorUrl;
var url = errorUrl.AddQueryString(_options.UserInteraction.ErrorIdParameter, id);
context.Response.RedirectToAbsoluteUrl(url);
}
}
}
| |
// 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.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
#if SRM
namespace System.Reflection
#else
namespace Roslyn.Reflection
#endif
{
internal static class BlobWriterImpl
{
internal const int SingleByteCompressedIntegerMaxValue = 0x7f;
internal const int TwoByteCompressedIntegerMaxValue = 0x3fff;
internal const int MaxCompressedIntegerValue = 0x1fffffff;
internal static int GetCompressedIntegerSize(int value)
{
Debug.Assert(value <= MaxCompressedIntegerValue);
if (value <= SingleByteCompressedIntegerMaxValue)
{
return 1;
}
if (value <= TwoByteCompressedIntegerMaxValue)
{
return 2;
}
return 4;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowValueArgumentOutOfRange()
{
throw new ArgumentOutOfRangeException("value");
}
internal static void WriteCompressedInteger(ref BlobWriter writer, int value)
{
unchecked
{
if (value <= SingleByteCompressedIntegerMaxValue)
{
writer.WriteByte((byte)value);
}
else if (value <= TwoByteCompressedIntegerMaxValue)
{
writer.WriteUInt16BE((ushort)(0x8000 | value));
}
else if (value <= MaxCompressedIntegerValue)
{
writer.WriteUInt32BE(0xc0000000 | (uint)value);
}
else
{
ThrowValueArgumentOutOfRange();
}
}
}
internal static void WriteCompressedInteger(BlobBuilder writer, int value)
{
unchecked
{
if (value <= SingleByteCompressedIntegerMaxValue)
{
writer.WriteByte((byte)value);
}
else if (value <= TwoByteCompressedIntegerMaxValue)
{
writer.WriteUInt16BE((ushort)(0x8000 | value));
}
else if (value <= MaxCompressedIntegerValue)
{
writer.WriteUInt32BE(0xc0000000 | (uint)value);
}
else
{
ThrowValueArgumentOutOfRange();
}
}
}
internal static void WriteCompressedSignedInteger(ref BlobWriter writer, int value)
{
unchecked
{
const int b6 = (1 << 6) - 1;
const int b13 = (1 << 13) - 1;
const int b28 = (1 << 28) - 1;
// 0xffffffff for negative value
// 0x00000000 for non-negative
int signMask = value >> 31;
if ((value & ~b6) == (signMask & ~b6))
{
int n = ((value & b6) << 1) | (signMask & 1);
writer.WriteByte((byte)n);
}
else if ((value & ~b13) == (signMask & ~b13))
{
int n = ((value & b13) << 1) | (signMask & 1);
writer.WriteUInt16BE((ushort)(0x8000 | n));
}
else if ((value & ~b28) == (signMask & ~b28))
{
int n = ((value & b28) << 1) | (signMask & 1);
writer.WriteUInt32BE(0xc0000000 | (uint)n);
}
else
{
ThrowValueArgumentOutOfRange();
}
}
}
internal static void WriteCompressedSignedInteger(BlobBuilder writer, int value)
{
unchecked
{
const int b6 = (1 << 6) - 1;
const int b13 = (1 << 13) - 1;
const int b28 = (1 << 28) - 1;
// 0xffffffff for negative value
// 0x00000000 for non-negative
int signMask = value >> 31;
if ((value & ~b6) == (signMask & ~b6))
{
int n = ((value & b6) << 1) | (signMask & 1);
writer.WriteByte((byte)n);
}
else if ((value & ~b13) == (signMask & ~b13))
{
int n = ((value & b13) << 1) | (signMask & 1);
writer.WriteUInt16BE((ushort)(0x8000 | n));
}
else if ((value & ~b28) == (signMask & ~b28))
{
int n = ((value & b28) << 1) | (signMask & 1);
writer.WriteUInt32BE(0xc0000000 | (uint)n);
}
else
{
ThrowValueArgumentOutOfRange();
}
}
}
internal static void WriteConstant(ref BlobWriter writer, object value)
{
if (value == null)
{
// The encoding of Type for the nullref value for FieldInit is ELEMENT_TYPE_CLASS with a Value of a 32-bit.
writer.WriteUInt32(0);
return;
}
var type = value.GetType();
if (type.GetTypeInfo().IsEnum)
{
type = Enum.GetUnderlyingType(type);
}
if (type == typeof(bool))
{
writer.WriteBoolean((bool)value);
}
else if (type == typeof(int))
{
writer.WriteInt32((int)value);
}
else if (type == typeof(string))
{
writer.WriteUTF16((string)value);
}
else if (type == typeof(byte))
{
writer.WriteByte((byte)value);
}
else if (type == typeof(char))
{
writer.WriteUInt16((char)value);
}
else if (type == typeof(double))
{
writer.WriteDouble((double)value);
}
else if (type == typeof(short))
{
writer.WriteInt16((short)value);
}
else if (type == typeof(long))
{
writer.WriteInt64((long)value);
}
else if (type == typeof(sbyte))
{
writer.WriteSByte((sbyte)value);
}
else if (type == typeof(float))
{
writer.WriteSingle((float)value);
}
else if (type == typeof(ushort))
{
writer.WriteUInt16((ushort)value);
}
else if (type == typeof(uint))
{
writer.WriteUInt32((uint)value);
}
else if (type == typeof(ulong))
{
writer.WriteUInt64((ulong)value);
}
else
{
// TODO: message
throw new ArgumentException();
}
}
internal static void WriteConstant(BlobBuilder writer, object value)
{
if (value == null)
{
// The encoding of Type for the nullref value for FieldInit is ELEMENT_TYPE_CLASS with a Value of a 32-bit.
writer.WriteUInt32(0);
return;
}
var type = value.GetType();
if (type.GetTypeInfo().IsEnum)
{
type = Enum.GetUnderlyingType(type);
}
if (type == typeof(bool))
{
writer.WriteBoolean((bool)value);
}
else if (type == typeof(int))
{
writer.WriteInt32((int)value);
}
else if (type == typeof(string))
{
writer.WriteUTF16((string)value);
}
else if (type == typeof(byte))
{
writer.WriteByte((byte)value);
}
else if (type == typeof(char))
{
writer.WriteUInt16((char)value);
}
else if (type == typeof(double))
{
writer.WriteDouble((double)value);
}
else if (type == typeof(short))
{
writer.WriteInt16((short)value);
}
else if (type == typeof(long))
{
writer.WriteInt64((long)value);
}
else if (type == typeof(sbyte))
{
writer.WriteSByte((sbyte)value);
}
else if (type == typeof(float))
{
writer.WriteSingle((float)value);
}
else if (type == typeof(ushort))
{
writer.WriteUInt16((ushort)value);
}
else if (type == typeof(uint))
{
writer.WriteUInt32((uint)value);
}
else if (type == typeof(ulong))
{
writer.WriteUInt64((ulong)value);
}
else
{
// TODO: message
throw new ArgumentException();
}
}
}
}
| |
//
// System.Web.Compilation.AspGenerator
//
// Authors:
// Gonzalo Paniagua Javier ([email protected])
//
// (C) 2002,2003 Ximian, Inc (http://www.ximian.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.Collections;
using System.CodeDom.Compiler;
using System.IO;
using System.Text;
using System.Web.Caching;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.Util;
namespace System.Web.Compilation
{
class BuilderLocation
{
public ControlBuilder Builder;
public ILocation Location;
public BuilderLocation (ControlBuilder builder, ILocation location)
{
this.Builder = builder;
this.Location = location;
}
}
class BuilderLocationStack : Stack
{
public override void Push (object o)
{
if (!(o is BuilderLocation))
throw new InvalidOperationException ();
base.Push (o);
}
public virtual void Push (ControlBuilder builder, ILocation location)
{
BuilderLocation bl = new BuilderLocation (builder, location);
Push (bl);
}
public new BuilderLocation Peek ()
{
return (BuilderLocation) base.Peek ();
}
public new BuilderLocation Pop ()
{
return (BuilderLocation) base.Pop ();
}
public ControlBuilder Builder {
get { return Peek ().Builder; }
}
}
class ParserStack
{
Hashtable files;
Stack parsers;
AspParser current;
public ParserStack ()
{
files = new Hashtable (); // may be this should be case sensitive for windows
parsers = new Stack ();
}
public bool Push (AspParser parser)
{
if (files.Contains (parser.Filename))
return false;
files [parser.Filename] = true;
parsers.Push (parser);
current = parser;
return true;
}
public AspParser Pop ()
{
if (parsers.Count == 0)
return null;
files.Remove (current.Filename);
AspParser result = (AspParser) parsers.Pop ();
if (parsers.Count > 0)
current = (AspParser) parsers.Peek ();
else
current = null;
return result;
}
public AspParser Parser {
get { return current; }
}
public string Filename {
get { return current.Filename; }
}
}
class TagStack
{
Stack tags;
public TagStack ()
{
tags = new Stack ();
}
public void Push (string tagid)
{
tags.Push (tagid);
}
public string Pop ()
{
if (tags.Count == 0)
return null;
return (string) tags.Pop ();
}
public bool CompareTo (string tagid)
{
if (tags.Count == 0)
return false;
return 0 == String.Compare (tagid, (string) tags.Peek (), true);
}
public int Count {
get { return tags.Count; }
}
public string Current {
get { return (string) tags.Peek (); }
}
}
class AspGenerator
{
ParserStack pstack;
BuilderLocationStack stack;
TemplateParser tparser;
StringBuilder text;
RootBuilder rootBuilder;
bool inScript, javascript;
ILocation location;
bool isApplication;
StringBuilder tagInnerText = new StringBuilder ();
static Hashtable emptyHash = new Hashtable ();
bool inForm;
bool useOtherTags;
public AspGenerator (TemplateParser tparser)
{
this.tparser = tparser;
text = new StringBuilder ();
stack = new BuilderLocationStack ();
rootBuilder = new RootBuilder (tparser);
stack.Push (rootBuilder, null);
tparser.RootBuilder = rootBuilder;
pstack = new ParserStack ();
}
public AspParser Parser {
get { return pstack.Parser; }
}
public string Filename {
get { return pstack.Filename; }
}
BaseCompiler GetCompilerFromType ()
{
Type type = tparser.GetType ();
if (type == typeof (PageParser))
return new PageCompiler ((PageParser) tparser);
if (type == typeof (ApplicationFileParser))
return new GlobalAsaxCompiler ((ApplicationFileParser) tparser);
if (type == typeof (UserControlParser))
return new UserControlCompiler ((UserControlParser) tparser);
#if NET_2_0
if (type == typeof(MasterPageParser))
return new UserControlCompiler ((UserControlParser) tparser);
#endif
throw new Exception ("Got type: " + type);
}
void InitParser (string filename)
{
StreamReader reader = new StreamReader (filename, WebEncoding.FileEncoding);
AspParser parser = new AspParser (filename, reader);
reader.Close ();
parser.Error += new ParseErrorHandler (ParseError);
parser.TagParsed += new TagParsedHandler (TagParsed);
parser.TextParsed += new TextParsedHandler (TextParsed);
if (!pstack.Push (parser))
throw new ParseException (Location, "Infinite recursion detected including file: " + filename);
tparser.AddDependency (filename);
}
void DoParse ()
{
pstack.Parser.Parse ();
if (text.Length > 0)
FlushText ();
pstack.Pop ();
}
public Type GetCompiledType ()
{
Type type = (Type) HttpRuntime.Cache.Get ("@@Type" + tparser.InputFile);
if (type != null) {
return type;
}
isApplication = tparser.DefaultDirectiveName == "application";
InitParser (Path.GetFullPath (tparser.InputFile));
DoParse ();
#if DEBUG
PrintTree (rootBuilder, 0);
#endif
if (stack.Count > 1)
throw new ParseException (stack.Builder.location,
"Expecting </" + stack.Builder.TagName + "> " + stack.Builder);
BaseCompiler compiler = GetCompilerFromType ();
type = compiler.GetCompiledType ();
CacheDependency cd = new CacheDependency ((string[])
tparser.Dependencies.ToArray (typeof (string)));
HttpRuntime.Cache.InsertPrivate ("@@Type" + tparser.InputFile, type, cd);
return type;
}
#if DEBUG
static void PrintTree (ControlBuilder builder, int indent)
{
if (builder == null)
return;
string i = new string ('\t', indent);
Console.Write (i);
Console.WriteLine ("b: {0} id: {1} type: {2} parent: {3}",
builder, builder.ID, builder.ControlType, builder.parentBuilder);
if (builder.Children != null)
foreach (object o in builder.Children) {
if (o is ControlBuilder)
PrintTree ((ControlBuilder) o, indent++);
}
}
static void PrintLocation (ILocation loc)
{
Console.WriteLine ("\tFile name: " + loc.Filename);
Console.WriteLine ("\tBegin line: " + loc.BeginLine);
Console.WriteLine ("\tEnd line: " + loc.EndLine);
Console.WriteLine ("\tBegin column: " + loc.BeginColumn);
Console.WriteLine ("\tEnd column: " + loc.EndColumn);
Console.WriteLine ("\tPlainText: " + loc.PlainText);
Console.WriteLine ();
}
#endif
void ParseError (ILocation location, string message)
{
throw new ParseException (location, message);
}
void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
{
this.location = new Location (location);
if (tparser != null)
tparser.Location = location;
if (text.Length != 0)
FlushText ();
if (0 == String.Compare (tagid, "script", true)) {
if (ProcessScript (tagtype, attributes))
return;
}
switch (tagtype) {
case TagType.Directive:
if (tagid == "")
tagid = tparser.DefaultDirectiveName;
tparser.AddDirective (tagid, attributes.GetDictionary (null));
break;
case TagType.Tag:
if (ProcessTag (tagid, attributes, tagtype)) {
useOtherTags = true;
break;
}
if (useOtherTags) {
stack.Builder.EnsureOtherTags ();
stack.Builder.OtherTags.Add (tagid);
}
TextParsed (location, location.PlainText);
break;
case TagType.Close:
bool notServer = (useOtherTags && TryRemoveTag (tagid, stack.Builder.OtherTags));
if (!notServer && CloseControl (tagid))
break;
TextParsed (location, location.PlainText);
break;
case TagType.SelfClosing:
int count = stack.Count;
if (!ProcessTag (tagid, attributes, tagtype)) {
TextParsed (location, location.PlainText);
} else if (stack.Count != count) {
CloseControl (tagid);
}
break;
case TagType.DataBinding:
goto case TagType.CodeRender;
case TagType.CodeRenderExpression:
goto case TagType.CodeRender;
case TagType.CodeRender:
if (isApplication)
throw new ParseException (location, "Invalid content for application file.");
ProcessCode (tagtype, tagid, location);
break;
case TagType.Include:
if (isApplication)
throw new ParseException (location, "Invalid content for application file.");
string file = attributes ["virtual"] as string;
bool isvirtual = (file != null);
if (!isvirtual)
file = attributes ["file"] as string;
if (isvirtual) {
file = tparser.MapPath (file);
} else {
file = GetIncludeFilePath (tparser.BaseDir, file);
}
InitParser (file);
DoParse ();
break;
default:
break;
}
//PrintLocation (location);
}
static bool TryRemoveTag (string tagid, ArrayList otags)
{
if (otags == null || otags.Count == 0)
return false;
int idx = otags.Count - 1;
string otagid = (string) otags [idx];
if (0 != String.Compare (tagid, otagid, true))
return false;
otags.RemoveAt (idx);
return true;
}
static string GetIncludeFilePath (string basedir, string filename)
{
if (Path.DirectorySeparatorChar == '/')
filename = filename.Replace ("\\", "/");
return Path.GetFullPath (Path.Combine (basedir, filename));
}
void TextParsed (ILocation location, string text)
{
if (text.IndexOf ("<%") != -1 && !inScript) {
if (this.text.Length > 0)
FlushText ();
CodeRenderParser r = new CodeRenderParser (text, stack.Builder);
r.AddChildren ();
return;
}
this.text.Append (text);
//PrintLocation (location);
}
void FlushText ()
{
string t = text.ToString ();
text.Length = 0;
if (inScript) {
// TODO: store location
tparser.Scripts.Add (t);
return;
}
if (tparser.DefaultDirectiveName == "application" && t.Trim () != "")
throw new ParseException (location, "Content not valid for application file.");
ControlBuilder current = stack.Builder;
current.AppendLiteralString (t);
if (current.NeedsTagInnerText ()) {
tagInnerText.Append (t);
}
}
bool ProcessTag (string tagid, TagAttributes atts, TagType tagtype)
{
if ((atts == null || !atts.IsRunAtServer ()) && String.Compare (tagid, "tbody", true) == 0) {
// MS completely ignores tbody or, if runat="server", fails when compiling
if (stack.Count > 0)
return stack.Builder.ChildrenAsProperties;
return false;
}
if (isApplication) {
if (String.Compare (tagid, "object", true) != 0)
throw new ParseException (location, "Invalid tag for application file.");
}
ControlBuilder parent = stack.Builder;
ControlBuilder builder = null;
Hashtable htable = (atts != null) ? atts.GetDictionary (null) : emptyHash;
if (stack.Count > 1) {
try {
builder = parent.CreateSubBuilder (tagid, htable, null, tparser, location);
} catch (TypeLoadException e) {
throw new ParseException (Location, "Type not found.", e);
} catch (Exception e) {
throw new ParseException (Location, e.Message, e);
}
}
if (builder == null && atts != null && atts.IsRunAtServer ()) {
string id = htable ["id"] as string;
if (id != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (id))
throw new ParseException (Location, "'" + id + "' is not a valid identifier");
try {
builder = rootBuilder.CreateSubBuilder (tagid, htable, null, tparser, location);
} catch (TypeLoadException e) {
throw new ParseException (Location, "Type not found.", e);
} catch (Exception e) {
throw new ParseException (Location, e.Message, e);
}
}
if (builder == null)
return false;
builder.location = location;
builder.ID = htable ["id"] as string;
if (typeof (HtmlForm).IsAssignableFrom (builder.ControlType)) {
if (inForm)
throw new ParseException (location, "Only one <form> allowed.");
inForm = true;
}
if (builder.HasBody () && !(builder is ObjectTagBuilder)) {
if (builder is TemplateBuilder) {
// push the id list
}
stack.Push (builder, location);
} else {
if (!isApplication && builder is ObjectTagBuilder) {
ObjectTagBuilder ot = (ObjectTagBuilder) builder;
if (ot.Scope != null && ot.Scope != "")
throw new ParseException (location, "Scope not allowed here");
if (tagtype == TagType.Tag) {
stack.Push (builder, location);
return true;
}
}
parent.AppendSubBuilder (builder);
builder.CloseControl ();
}
return true;
}
bool ProcessScript (TagType tagtype, TagAttributes attributes)
{
if (tagtype != TagType.Close) {
if (attributes != null && attributes.IsRunAtServer ()) {
CheckLanguage ((string) attributes ["language"]);
if (tagtype == TagType.Tag) {
Parser.VerbatimID = "script";
inScript = true;
} //else if (tagtype == TagType.SelfClosing)
// load script file here
return true;
} else {
if (tagtype != TagType.SelfClosing) {
Parser.VerbatimID = "script";
javascript = true;
}
TextParsed (location, location.PlainText);
return true;
}
}
bool result;
if (inScript) {
result = inScript;
inScript = false;
} else {
result = javascript;
javascript = false;
TextParsed (location, location.PlainText);
}
return result;
}
bool CloseControl (string tagid)
{
ControlBuilder current = stack.Builder;
string btag = current.TagName;
if (String.Compare (btag, "tbody", true) != 0 && String.Compare (tagid, "tbody", true) == 0) {
if (!current.ChildrenAsProperties) {
try {
TextParsed (location, location.PlainText);
FlushText ();
} catch {}
}
return true;
}
if (0 != String.Compare (tagid, btag, true))
return false;
// if (current is TemplateBuilder)
// pop from the id list
if (current.NeedsTagInnerText ()) {
try {
current.SetTagInnerText (tagInnerText.ToString ());
} catch (Exception e) {
throw new ParseException (current.location, e.Message, e);
}
tagInnerText.Length = 0;
}
if (typeof (HtmlForm).IsAssignableFrom (current.ControlType)) {
inForm = false;
}
current.CloseControl ();
stack.Pop ();
stack.Builder.AppendSubBuilder (current);
return true;
}
bool ProcessCode (TagType tagtype, string code, ILocation location)
{
ControlBuilder b = null;
if (tagtype == TagType.CodeRender)
b = new CodeRenderBuilder (code, false, location);
else if (tagtype == TagType.CodeRenderExpression)
b = new CodeRenderBuilder (code, true, location);
else if (tagtype == TagType.DataBinding)
b = new DataBindingBuilder (code, location);
else
throw new HttpException ("Should never happen");
stack.Builder.AppendSubBuilder (b);
return true;
}
public ILocation Location {
get { return location; }
}
void CheckLanguage (string lang)
{
if (lang == null || lang == "")
return;
if (String.Compare (lang, tparser.Language, true) == 0)
return;
CompilationConfiguration cfg = CompilationConfiguration.GetInstance (HttpContext.Current);
if (!cfg.Compilers.CompareLanguages (tparser.Language, lang)) {
throw new ParseException (Location,
String.Format ("Trying to mix language '{0}' and '{1}'.",
tparser.Language, lang));
}
}
// Used to get CodeRender tags in attribute values
class CodeRenderParser
{
string str;
ControlBuilder builder;
public CodeRenderParser (string str, ControlBuilder builder)
{
this.str = str;
this.builder = builder;
}
public void AddChildren ()
{
int index = str.IndexOf ("<%");
if (index > 0) {
TextParsed (null, str.Substring (0, index));
str = str.Substring (index);
}
AspParser parser = new AspParser ("@@inner_string@@", new StringReader (str));
parser.Error += new ParseErrorHandler (ParseError);
parser.TagParsed += new TagParsedHandler (TagParsed);
parser.TextParsed += new TextParsedHandler (TextParsed);
parser.Parse ();
}
void TagParsed (ILocation location, TagType tagtype, string tagid, TagAttributes attributes)
{
if (tagtype == TagType.CodeRender)
builder.AppendSubBuilder (new CodeRenderBuilder (tagid, false, location));
else if (tagtype == TagType.CodeRenderExpression)
builder.AppendSubBuilder (new CodeRenderBuilder (tagid, true, location));
else if (tagtype == TagType.DataBinding)
builder.AppendSubBuilder (new DataBindingBuilder (tagid, location));
else
builder.AppendLiteralString (location.PlainText);
}
void TextParsed (ILocation location, string text)
{
builder.AppendLiteralString (text);
}
void ParseError (ILocation location, string message)
{
throw new ParseException (location, message);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Internal.Cryptography.Pal.Native;
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using NTSTATUS = Interop.BCrypt.NTSTATUS;
using SafeBCryptKeyHandle = Microsoft.Win32.SafeHandles.SafeBCryptKeyHandle;
using static Interop.Crypt32;
namespace Internal.Cryptography.Pal
{
/// <summary>
/// A singleton class that encapsulates the native implementation of various X509 services. (Implementing this as a singleton makes it
/// easier to split the class into abstract and implementation classes if desired.)
/// </summary>
internal sealed partial class X509Pal : IX509Pal
{
const string BCRYPT_ECC_CURVE_NAME_PROPERTY = "ECCCurveName";
const string BCRYPT_ECC_PARAMETERS_PROPERTY = "ECCParameters";
public AsymmetricAlgorithm DecodePublicKey(Oid oid, byte[] encodedKeyValue, byte[] encodedParameters, ICertificatePal certificatePal)
{
if (oid.Value == Oids.Ecc && certificatePal != null)
{
return DecodeECDsaPublicKey((CertificatePal)certificatePal);
}
int algId = Interop.Crypt32.FindOidInfo(CryptOidInfoKeyType.CRYPT_OID_INFO_OID_KEY, oid.Value, OidGroup.PublicKeyAlgorithm, fallBackToAllGroups: true).AlgId;
switch (algId)
{
case AlgId.CALG_RSA_KEYX:
case AlgId.CALG_RSA_SIGN:
{
byte[] keyBlob = DecodeKeyBlob(CryptDecodeObjectStructType.CNG_RSA_PUBLIC_KEY_BLOB, encodedKeyValue);
CngKey cngKey = CngKey.Import(keyBlob, CngKeyBlobFormat.GenericPublicBlob);
return new RSACng(cngKey);
}
#if !NETNATIVE
case AlgId.CALG_DSS_SIGN:
{
byte[] keyBlob = ConstructDSSPublicKeyCspBlob(encodedKeyValue, encodedParameters);
DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
dsa.ImportCspBlob(keyBlob);
return dsa;
}
#endif
default:
throw new NotSupportedException(SR.NotSupported_KeyAlgorithm);
}
}
private static ECDsa DecodeECDsaPublicKey(CertificatePal certificatePal)
{
ECDsa ecdsa;
using (SafeBCryptKeyHandle bCryptKeyHandle = ImportPublicKeyInfo(certificatePal.CertContext))
{
CngKeyBlobFormat blobFormat;
byte[] keyBlob;
#if NETNATIVE
blobFormat = CngKeyBlobFormat.EccPublicBlob;
keyBlob = ExportKeyBlob(bCryptKeyHandle, blobFormat);
using (CngKey cngKey = CngKey.Import(keyBlob, blobFormat))
{
ecdsa = new ECDsaCng(cngKey);
}
#else
string curveName = GetCurveName(bCryptKeyHandle);
if (curveName == null)
{
if (HasExplicitParameters(bCryptKeyHandle))
{
blobFormat = CngKeyBlobFormat.EccFullPublicBlob;
}
else
{
blobFormat = CngKeyBlobFormat.EccPublicBlob;
}
keyBlob = ExportKeyBlob(bCryptKeyHandle, blobFormat);
using (CngKey cngKey = CngKey.Import(keyBlob, blobFormat))
{
ecdsa = new ECDsaCng(cngKey);
}
}
else
{
blobFormat = CngKeyBlobFormat.EccPublicBlob;
keyBlob = ExportKeyBlob(bCryptKeyHandle, blobFormat);
ECParameters ecparams = new ECParameters();
ExportNamedCurveParameters(ref ecparams, keyBlob, false);
ecparams.Curve = ECCurve.CreateFromFriendlyName(curveName);
ecdsa = new ECDsaCng();
ecdsa.ImportParameters(ecparams);
}
#endif
}
return ecdsa;
}
private static SafeBCryptKeyHandle ImportPublicKeyInfo(SafeCertContextHandle certContext)
{
#if NETNATIVE
// CryptImportPublicKeyInfoEx2() not in the UWP api list.
throw new PlatformNotSupportedException();
#else
unsafe
{
SafeBCryptKeyHandle bCryptKeyHandle;
bool mustRelease = false;
certContext.DangerousAddRef(ref mustRelease);
try
{
unsafe
{
bool success = Interop.crypt32.CryptImportPublicKeyInfoEx2(CertEncodingType.X509_ASN_ENCODING, &(certContext.CertContext->pCertInfo->SubjectPublicKeyInfo), 0, null, out bCryptKeyHandle);
if (!success)
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
return bCryptKeyHandle;
}
}
finally
{
if (mustRelease)
certContext.DangerousRelease();
}
}
#endif //NETNATIVE
}
private static byte[] ExportKeyBlob(SafeBCryptKeyHandle bCryptKeyHandle, CngKeyBlobFormat blobFormat)
{
#if NETNATIVE
// BCryptExportKey() not in the UWP api list.
throw new PlatformNotSupportedException();
#else
string blobFormatString = blobFormat.Format;
int numBytesNeeded = 0;
NTSTATUS ntStatus = Interop.BCrypt.BCryptExportKey(bCryptKeyHandle, IntPtr.Zero, blobFormatString, null, 0, out numBytesNeeded, 0);
if (ntStatus != NTSTATUS.STATUS_SUCCESS)
throw new CryptographicException(Interop.Kernel32.GetMessage((int)ntStatus));
byte[] keyBlob = new byte[numBytesNeeded];
ntStatus = Interop.BCrypt.BCryptExportKey(bCryptKeyHandle, IntPtr.Zero, blobFormatString, keyBlob, keyBlob.Length, out numBytesNeeded, 0);
if (ntStatus != NTSTATUS.STATUS_SUCCESS)
throw new CryptographicException(Interop.Kernel32.GetMessage((int)ntStatus));
Array.Resize(ref keyBlob, numBytesNeeded);
return keyBlob;
#endif //NETNATIVE
}
#if !NETNATIVE
private static void ExportNamedCurveParameters(ref ECParameters ecParams, byte[] ecBlob, bool includePrivateParameters)
{
// We now have a buffer laid out as follows:
// BCRYPT_ECCKEY_BLOB header
// byte[cbKey] Q.X
// byte[cbKey] Q.Y
// -- Private only --
// byte[cbKey] D
unsafe
{
Debug.Assert(ecBlob.Length >= sizeof(Interop.BCrypt.BCRYPT_ECCKEY_BLOB));
fixed (byte* pEcBlob = &ecBlob[0])
{
Interop.BCrypt.BCRYPT_ECCKEY_BLOB* pBcryptBlob = (Interop.BCrypt.BCRYPT_ECCKEY_BLOB*)pEcBlob;
int offset = sizeof(Interop.BCrypt.BCRYPT_ECCKEY_BLOB);
ecParams.Q = new ECPoint
{
X = Interop.BCrypt.Consume(ecBlob, ref offset, pBcryptBlob->cbKey),
Y = Interop.BCrypt.Consume(ecBlob, ref offset, pBcryptBlob->cbKey)
};
if (includePrivateParameters)
{
ecParams.D = Interop.BCrypt.Consume(ecBlob, ref offset, pBcryptBlob->cbKey);
}
}
}
}
#endif
private static byte[] DecodeKeyBlob(CryptDecodeObjectStructType lpszStructType, byte[] encodedKeyValue)
{
int cbDecoded = 0;
if (!Interop.crypt32.CryptDecodeObject(CertEncodingType.All, lpszStructType, encodedKeyValue, encodedKeyValue.Length, CryptDecodeObjectFlags.None, null, ref cbDecoded))
throw Marshal.GetLastWin32Error().ToCryptographicException();
byte[] keyBlob = new byte[cbDecoded];
if (!Interop.crypt32.CryptDecodeObject(CertEncodingType.All, lpszStructType, encodedKeyValue, encodedKeyValue.Length, CryptDecodeObjectFlags.None, keyBlob, ref cbDecoded))
throw Marshal.GetLastWin32Error().ToCryptographicException();
return keyBlob;
}
private static byte[] ConstructDSSPublicKeyCspBlob(byte[] encodedKeyValue, byte[] encodedParameters)
{
byte[] decodedKeyValue = DecodeDssKeyValue(encodedKeyValue);
byte[] p, q, g;
DecodeDssParameters(encodedParameters, out p, out q, out g);
const byte PUBLICKEYBLOB = 0x6;
const byte CUR_BLOB_VERSION = 2;
int cbKey = p.Length;
if (cbKey == 0)
throw ErrorCode.NTE_BAD_PUBLIC_KEY.ToCryptographicException();
const int DSS_Q_LEN = 20;
int capacity = 8 /* sizeof(CAPI.BLOBHEADER) */ + 8 /* sizeof(CAPI.DSSPUBKEY) */ +
cbKey + DSS_Q_LEN + cbKey + cbKey + 24 /* sizeof(CAPI.DSSSEED) */;
MemoryStream keyBlob = new MemoryStream(capacity);
BinaryWriter bw = new BinaryWriter(keyBlob);
// PUBLICKEYSTRUC
bw.Write((byte)PUBLICKEYBLOB); // pPubKeyStruc->bType = PUBLICKEYBLOB
bw.Write((byte)CUR_BLOB_VERSION); // pPubKeyStruc->bVersion = CUR_BLOB_VERSION
bw.Write((short)0); // pPubKeyStruc->reserved = 0;
bw.Write((uint)AlgId.CALG_DSS_SIGN); // pPubKeyStruc->aiKeyAlg = CALG_DSS_SIGN;
// DSSPUBKEY
bw.Write((int)(PubKeyMagic.DSS_MAGIC)); // pCspPubKey->magic = DSS_MAGIC; We are constructing a DSS1 Csp blob.
bw.Write((int)(cbKey * 8)); // pCspPubKey->bitlen = cbKey * 8;
// rgbP[cbKey]
bw.Write(p);
// rgbQ[20]
int cb = q.Length;
if (cb == 0 || cb > DSS_Q_LEN)
throw ErrorCode.NTE_BAD_PUBLIC_KEY.ToCryptographicException();
bw.Write(q);
if (DSS_Q_LEN > cb)
bw.Write(new byte[DSS_Q_LEN - cb]);
// rgbG[cbKey]
cb = g.Length;
if (cb == 0 || cb > cbKey)
throw ErrorCode.NTE_BAD_PUBLIC_KEY.ToCryptographicException();
bw.Write(g);
if (cbKey > cb)
bw.Write(new byte[cbKey - cb]);
// rgbY[cbKey]
cb = decodedKeyValue.Length;
if (cb == 0 || cb > cbKey)
throw ErrorCode.NTE_BAD_PUBLIC_KEY.ToCryptographicException();
bw.Write(decodedKeyValue);
if (cbKey > cb)
bw.Write(new byte[cbKey - cb]);
// DSSSEED: set counter to 0xFFFFFFFF to indicate not available
bw.Write((uint)0xFFFFFFFF);
bw.Write(new byte[20]);
return keyBlob.ToArray();
}
private static byte[] DecodeDssKeyValue(byte[] encodedKeyValue)
{
unsafe
{
byte[] decodedKeyValue = null;
encodedKeyValue.DecodeObject(
CryptDecodeObjectStructType.X509_DSS_PUBLICKEY,
delegate (void* pvDecoded)
{
CRYPTOAPI_BLOB* pBlob = (CRYPTOAPI_BLOB*)pvDecoded;
decodedKeyValue = pBlob->ToByteArray();
}
);
return decodedKeyValue;
}
}
private static void DecodeDssParameters(byte[] encodedParameters, out byte[] p, out byte[] q, out byte[] g)
{
byte[] pLocal = null;
byte[] qLocal = null;
byte[] gLocal = null;
unsafe
{
encodedParameters.DecodeObject(
CryptDecodeObjectStructType.X509_DSS_PARAMETERS,
delegate (void* pvDecoded)
{
CERT_DSS_PARAMETERS* pCertDssParameters = (CERT_DSS_PARAMETERS*)pvDecoded;
pLocal = pCertDssParameters->p.ToByteArray();
qLocal = pCertDssParameters->q.ToByteArray();
gLocal = pCertDssParameters->g.ToByteArray();
}
);
}
p = pLocal;
q = qLocal;
g = gLocal;
}
private static bool HasExplicitParameters(SafeBCryptKeyHandle bcryptHandle)
{
byte[] explicitParams = GetProperty(bcryptHandle, BCRYPT_ECC_PARAMETERS_PROPERTY);
return (explicitParams != null && explicitParams.Length > 0);
}
private static string GetCurveName(SafeBCryptKeyHandle bcryptHandle)
{
return GetPropertyAsString(bcryptHandle, BCRYPT_ECC_CURVE_NAME_PROPERTY);
}
private static string GetPropertyAsString(SafeBCryptKeyHandle cryptHandle, string propertyName)
{
Debug.Assert(!cryptHandle.IsInvalid);
byte[] value = GetProperty(cryptHandle, propertyName);
if (value == null || value.Length == 0)
return null;
unsafe
{
fixed (byte* pValue = &value[0])
{
string valueAsString = Marshal.PtrToStringUni((IntPtr)pValue);
return valueAsString;
}
}
}
private static byte[] GetProperty(SafeBCryptKeyHandle cryptHandle, string propertyName)
{
Debug.Assert(!cryptHandle.IsInvalid);
unsafe
{
int numBytesNeeded;
NTSTATUS errorCode = Interop.BCrypt.BCryptGetProperty(cryptHandle, propertyName, null, 0, out numBytesNeeded, 0);
if (errorCode != NTSTATUS.STATUS_SUCCESS)
return null;
byte[] propertyValue = new byte[numBytesNeeded];
fixed (byte* pPropertyValue = propertyValue)
{
errorCode = Interop.BCrypt.BCryptGetProperty(cryptHandle, propertyName, pPropertyValue, propertyValue.Length, out numBytesNeeded, 0);
}
if (errorCode != NTSTATUS.STATUS_SUCCESS)
return null;
Array.Resize(ref propertyValue, numBytesNeeded);
return propertyValue;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using Internal.Runtime.CompilerServices;
namespace System.Threading
{
/// <summary>Methods for accessing memory with volatile semantics.</summary>
public static unsafe class Volatile
{
// The VM may replace these implementations with more efficient ones in some cases.
// In coreclr, for example, see getILIntrinsicImplementationForVolatile() in jitinterface.cpp.
#region Boolean
private struct VolatileBoolean { public volatile bool Value; }
[Intrinsic]
[NonVersionable]
public static bool Read(ref bool location) =>
Unsafe.As<bool, VolatileBoolean>(ref location).Value;
[Intrinsic]
[NonVersionable]
public static void Write(ref bool location, bool value) =>
Unsafe.As<bool, VolatileBoolean>(ref location).Value = value;
#endregion
#region Byte
private struct VolatileByte { public volatile byte Value; }
[Intrinsic]
[NonVersionable]
public static byte Read(ref byte location) =>
Unsafe.As<byte, VolatileByte>(ref location).Value;
[Intrinsic]
[NonVersionable]
public static void Write(ref byte location, byte value) =>
Unsafe.As<byte, VolatileByte>(ref location).Value = value;
#endregion
#region Double
[Intrinsic]
[NonVersionable]
public static double Read(ref double location)
{
long result = Read(ref Unsafe.As<double, long>(ref location));
return *(double*)&result;
}
[Intrinsic]
[NonVersionable]
public static void Write(ref double location, double value) =>
Write(ref Unsafe.As<double, long>(ref location), *(long*)&value);
#endregion
#region Int16
private struct VolatileInt16 { public volatile short Value; }
[Intrinsic]
[NonVersionable]
public static short Read(ref short location) =>
Unsafe.As<short, VolatileInt16>(ref location).Value;
[Intrinsic]
[NonVersionable]
public static void Write(ref short location, short value) =>
Unsafe.As<short, VolatileInt16>(ref location).Value = value;
#endregion
#region Int32
private struct VolatileInt32 { public volatile int Value; }
[Intrinsic]
[NonVersionable]
public static int Read(ref int location) =>
Unsafe.As<int, VolatileInt32>(ref location).Value;
[Intrinsic]
[NonVersionable]
public static void Write(ref int location, int value) =>
Unsafe.As<int, VolatileInt32>(ref location).Value = value;
#endregion
#region Int64
[Intrinsic]
[NonVersionable]
public static long Read(ref long location) =>
#if BIT64
(Int64)Unsafe.As<Int64, VolatileIntPtr>(ref location).Value;
#else
// On 32-bit machines, we use Interlocked, since an ordinary volatile read would not be atomic.
Interlocked.CompareExchange(ref location, 0, 0);
#endif
[Intrinsic]
[NonVersionable]
public static void Write(ref long location, long value) =>
#if BIT64
Unsafe.As<Int64, VolatileIntPtr>(ref location).Value = (IntPtr)value;
#else
// On 32-bit, we use Interlocked, since an ordinary volatile write would not be atomic.
Interlocked.Exchange(ref location, value);
#endif
#endregion
#region IntPtr
private struct VolatileIntPtr { public volatile IntPtr Value; }
[Intrinsic]
[NonVersionable]
public static IntPtr Read(ref IntPtr location) =>
Unsafe.As<IntPtr, VolatileIntPtr>(ref location).Value;
[Intrinsic]
[NonVersionable]
public static void Write(ref IntPtr location, IntPtr value) =>
Unsafe.As<IntPtr, VolatileIntPtr>(ref location).Value = value;
#endregion
#region SByte
private struct VolatileSByte { public volatile sbyte Value; }
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
public static sbyte Read(ref sbyte location) =>
Unsafe.As<sbyte, VolatileSByte>(ref location).Value;
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
public static void Write(ref sbyte location, sbyte value) =>
Unsafe.As<sbyte, VolatileSByte>(ref location).Value = value;
#endregion
#region Single
private struct VolatileSingle { public volatile float Value; }
[Intrinsic]
[NonVersionable]
public static float Read(ref float location) =>
Unsafe.As<float, VolatileSingle>(ref location).Value;
[Intrinsic]
[NonVersionable]
public static void Write(ref float location, float value) =>
Unsafe.As<float, VolatileSingle>(ref location).Value = value;
#endregion
#region UInt16
private struct VolatileUInt16 { public volatile ushort Value; }
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
public static ushort Read(ref ushort location) =>
Unsafe.As<ushort, VolatileUInt16>(ref location).Value;
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
public static void Write(ref ushort location, ushort value) =>
Unsafe.As<ushort, VolatileUInt16>(ref location).Value = value;
#endregion
#region UInt32
private struct VolatileUInt32 { public volatile uint Value; }
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
public static uint Read(ref uint location) =>
Unsafe.As<uint, VolatileUInt32>(ref location).Value;
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
public static void Write(ref uint location, uint value) =>
Unsafe.As<uint, VolatileUInt32>(ref location).Value = value;
#endregion
#region UInt64
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
public static ulong Read(ref ulong location) =>
(ulong)Read(ref Unsafe.As<ulong, long>(ref location));
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
public static void Write(ref ulong location, ulong value) =>
Write(ref Unsafe.As<ulong, long>(ref location), (long)value);
#endregion
#region UIntPtr
private struct VolatileUIntPtr { public volatile UIntPtr Value; }
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
public static UIntPtr Read(ref UIntPtr location) =>
Unsafe.As<UIntPtr, VolatileUIntPtr>(ref location).Value;
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
public static void Write(ref UIntPtr location, UIntPtr value) =>
Unsafe.As<UIntPtr, VolatileUIntPtr>(ref location).Value = value;
#endregion
#region T
private struct VolatileObject { public volatile object? Value; }
[Intrinsic]
[NonVersionable]
[return: NotNullIfNotNull("location")]
public static T Read<T>(ref T location) where T : class? =>
Unsafe.As<T>(Unsafe.As<T, VolatileObject>(ref location).Value);
[Intrinsic]
[NonVersionable]
public static void Write<T>([NotNullIfNotNull("value")] ref T location, T value) where T : class? =>
Unsafe.As<T, VolatileObject>(ref location).Value = value;
#endregion
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;
using Microsoft.PythonTools;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.VisualStudio.Shell;
using Microsoft.Win32;
namespace Microsoft.IronPythonTools.Interpreter {
[InterpreterFactoryId("IronPython")]
[Export(typeof(IPythonInterpreterFactoryProvider))]
[PartCreationPolicy(CreationPolicy.Shared)]
sealed class IronPythonInterpreterFactoryProvider : IPythonInterpreterFactoryProvider, IDisposable {
private readonly IServiceProvider _site;
private bool _initialized;
private IPythonInterpreterFactory _interpreter;
private IPythonInterpreterFactory _interpreterX64;
private InterpreterConfiguration _config, _configX64;
const string IronPythonCorePath = "Software\\IronPython";
[ImportingConstructor]
public IronPythonInterpreterFactoryProvider([Import(typeof(SVsServiceProvider), AllowDefault = true)] IServiceProvider site = null) {
_site = site;
}
private void EnsureInitialized() {
if (_initialized) {
return;
}
_initialized = true;
DiscoverInterpreterFactories();
if (_config == null) {
StartWatching(RegistryHive.LocalMachine, RegistryView.Registry32);
}
}
public void Dispose() {
(_interpreter as IDisposable)?.Dispose();
(_interpreterX64 as IDisposable)?.Dispose();
}
private void StartWatching(RegistryHive hive, RegistryView view, int retries = 5) {
var tag = RegistryWatcher.Instance.TryAdd(
hive, view, IronPythonCorePath,
Registry_Changed,
recursive: true, notifyValueChange: true, notifyKeyChange: true
) ?? RegistryWatcher.Instance.TryAdd(
hive, view, "Software",
Registry_Software_Changed,
recursive: false, notifyValueChange: false, notifyKeyChange: true
);
if (tag == null && retries > 0) {
Trace.TraceWarning("Failed to watch registry. Retrying {0} more times", retries);
Thread.Sleep(100);
StartWatching(hive, view, retries - 1);
} else if (tag == null) {
Trace.TraceError("Failed to watch registry");
}
}
private void Registry_Changed(object sender, RegistryChangedEventArgs e) {
if (!Exists(e)) {
// IronPython key no longer exists, so go back to watching
// Software.
RegistryWatcher.Instance.Add(
RegistryHive.LocalMachine, RegistryView.Registry32, "Software",
Registry_Software_Changed,
recursive: false, notifyValueChange: false, notifyKeyChange: true
);
e.CancelWatcher = true;
} else {
DiscoverInterpreterFactories();
if (_config != null) {
e.CancelWatcher = true;
}
}
}
private static bool Exists(RegistryChangedEventArgs e) {
using (var root = RegistryKey.OpenBaseKey(e.Hive, e.View))
using (var key = root.OpenSubKey(e.Key)) {
return key != null;
}
}
private void Registry_Software_Changed(object sender, RegistryChangedEventArgs e) {
if (RegistryWatcher.Instance.TryAdd(
e.Hive, e.View, IronPythonCorePath, Registry_Changed,
recursive: true, notifyValueChange: true, notifyKeyChange: true
) != null) {
e.CancelWatcher = true;
Registry_Changed(sender, e);
}
}
#region IPythonInterpreterProvider Members
public IEnumerable<IPythonInterpreterFactory> GetInterpreterFactories() {
EnsureInitialized();
if (_config != null) {
yield return GetInterpreterFactory(_config.Id);
}
if (_configX64 != null) {
yield return GetInterpreterFactory(_configX64.Id);
}
}
public IEnumerable<InterpreterConfiguration> GetInterpreterConfigurations() {
EnsureInitialized();
if (_config != null) {
yield return _config;
}
if (_configX64 != null) {
yield return _configX64;
}
}
public IPythonInterpreterFactory GetInterpreterFactory(string id) {
EnsureInitialized();
if (_config != null && id == _config.Id) {
EnsureInterpreter();
return _interpreter;
} else if (_configX64 != null && id == _configX64.Id) {
EnsureInterpreterX64();
return _interpreterX64;
}
return null;
}
private void EnsureInterpreterX64() {
if (_interpreterX64 == null) {
lock (this) {
if (_interpreterX64 == null) {
var config = GetConfiguration(InterpreterArchitecture.x64);
var opts = GetCreationOptions(_site, config);
_interpreterX64 = new IronPythonAstInterpreterFactory(config, opts);
}
}
}
}
private void EnsureInterpreter() {
if (_interpreter == null) {
lock (this) {
if (_interpreter == null) {
var config = GetConfiguration(InterpreterArchitecture.x86);
var opts = GetCreationOptions(_site, config);
_interpreter = new IronPythonAstInterpreterFactory(config, opts);
}
}
}
}
private void DiscoverInterpreterFactories() {
if (_config == null && IronPythonResolver.GetPythonInstallDir() != null) {
_config = GetConfiguration(InterpreterArchitecture.x86);
if (Environment.Is64BitOperatingSystem) {
_configX64 = GetConfiguration(InterpreterArchitecture.x64);
}
InterpreterFactoriesChanged?.Invoke(this, EventArgs.Empty);
}
}
public event EventHandler InterpreterFactoriesChanged;
public object GetProperty(string id, string propName) {
switch (propName) {
// Should match PythonRegistrySearch.CompanyPropertyKey
case "Company":
return "IronPython team";
// Should match PythonRegistrySearch.SupportUrlPropertyKey
case "SupportUrl":
return "http://ironpython.net/";
case "PersistInteractive":
return true;
}
return null;
}
#endregion
internal static string GetInterpreterId(InterpreterArchitecture arch) {
if (arch == InterpreterArchitecture.x64) {
return "IronPython|2.7-64";
} else {
return "IronPython|2.7-32";
}
}
internal static VisualStudioInterpreterConfiguration GetConfiguration(InterpreterArchitecture arch) {
var prefixPath = IronPythonResolver.GetPythonInstallDir();
if (string.IsNullOrEmpty(prefixPath)) {
return null;
}
// IronPython 2.7.8 changed the executable names for 64-bit vs 32-bit
var ipyExe = arch == InterpreterArchitecture.x64 ? "ipy64.exe" : "ipy.exe";
var ipywExe = arch == InterpreterArchitecture.x64 ? "ipyw64.exe" : "ipyw.exe";
if (File.Exists(Path.Combine(prefixPath, "ipy32.exe"))) {
ipyExe = arch == InterpreterArchitecture.x64 ? "ipy.exe" : "ipy32.exe";
ipywExe = arch == InterpreterArchitecture.x64 ? "ipyw.exe" : "ipyw32.exe";
}
return new VisualStudioInterpreterConfiguration(
GetInterpreterId(arch),
string.Format("IronPython 2.7{0: ()}", arch),
prefixPath,
Path.Combine(prefixPath, ipyExe),
Path.Combine(prefixPath, ipywExe),
"IRONPYTHONPATH",
arch,
new Version(2, 7),
InterpreterUIMode.SupportsDatabase
);
}
internal static InterpreterFactoryCreationOptions GetCreationOptions(IServiceProvider site, InterpreterConfiguration config) {
return new InterpreterFactoryCreationOptions {};
}
}
}
| |
#region MigraDoc - Creating Documents on the Fly
//
// Authors:
// Stefan Lange (mailto:[email protected])
// Klaus Potzesny (mailto:[email protected])
// David Stephensen (mailto:[email protected])
//
// Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://www.migradoc.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Diagnostics;
using System.Reflection;
using MigraDoc.DocumentObjectModel.Internals;
using MigraDoc.DocumentObjectModel.Fields;
using MigraDoc.DocumentObjectModel.Shapes;
namespace MigraDoc.DocumentObjectModel
{
/// <summary>
/// A ParagraphElements collection contains the individual objects of a paragraph.
/// </summary>
public class ParagraphElements : DocumentObjectCollection
{
/// <summary>
/// Initializes a new instance of the ParagraphElements class.
/// </summary>
public ParagraphElements()
{
}
/// <summary>
/// Initializes a new instance of the ParagraphElements class with the specified parent.
/// </summary>
internal ParagraphElements(DocumentObject parent) : base(parent) { }
/// <summary>
/// Gets a ParagraphElement by its index.
/// </summary>
public new DocumentObject this[int index]
{
get { return base[index] as DocumentObject; }
}
#region Methods
/// <summary>
/// Creates a deep copy of this object.
/// </summary>
public new ParagraphElements Clone()
{
return (ParagraphElements)DeepCopy();
}
/// <summary>
/// Adds a Text object.
/// </summary>
/// <param name="text">Content of the new Text object.</param>
/// <returns>Returns a new Text object.</returns>
public Text AddText(string text)
{
if (text == null)
throw new ArgumentNullException("text");
#if true
Text txt = null;
string[] lines = text.Split('\n');
int lineCount = lines.Length;
for (int line = 0; line < lineCount; line++)
{
string[] tabParts = lines[line].Split('\t');
int count = tabParts.Length;
for (int idx = 0; idx < count; idx++)
{
if (tabParts[idx].Length != 0)
{
txt = new Text(tabParts[idx]);
this.Add(txt);
}
if (idx < count - 1)
this.AddTab();
}
if (line < lineCount - 1)
this.AddLineBreak();
}
return txt;
#else
Text txt = new Text();
txt.Content = text;
this.Add(txt);
return txt;
#endif
}
/// <summary>
/// Adds a single character repeated the specified number of times to the paragraph.
/// </summary>
public Text AddChar(char ch, int count)
{
return AddText(new string(ch, count));
}
/// <summary>
/// Adds a single character to the paragraph.
/// </summary>
public Text AddChar(char ch)
{
return AddText(new string(ch, 1));
}
/// <summary>
/// Adds a Character object.
/// </summary>
public Character AddCharacter(SymbolName symbolType)
{
return AddCharacter(symbolType, 1);
}
/// <summary>
/// Adds one or more Character objects.
/// </summary>
public Character AddCharacter(SymbolName symbolType, int count)
{
Character character = new Character();
this.Add(character);
character.SymbolName = symbolType;
character.Count = count;
return character;
}
/// <summary>
/// Adds a Character object defined by a character.
/// </summary>
public Character AddCharacter(char ch)
{
return AddCharacter((SymbolName)ch, 1);
}
/// <summary>
/// Adds one or more Character objects defined by a character.
/// </summary>
public Character AddCharacter(char ch, int count)
{
return AddCharacter((SymbolName)ch, count);
}
/// <summary>
/// Adds a space character as many as count.
/// </summary>
public Character AddSpace(int count)
{
return this.AddCharacter(DocumentObjectModel.SymbolName.Blank, count);
}
/// <summary>
/// Adds a horizontal tab.
/// </summary>
public Character AddTab()
{
return AddCharacter(SymbolName.Tab, 1);
}
/// <summary>
/// Adds a line break.
/// </summary>
public Character AddLineBreak()
{
return AddCharacter(SymbolName.LineBreak, 1);
}
/// <summary>
/// Adds a new FormattedText.
/// </summary>
public FormattedText AddFormattedText()
{
FormattedText formattedText = new FormattedText();
this.Add(formattedText);
return formattedText;
}
/// <summary>
/// Adds a new FormattedText object with the given format.
/// </summary>
public FormattedText AddFormattedText(TextFormat textFormat)
{
FormattedText formattedText = AddFormattedText();
if ((textFormat & TextFormat.Bold) == TextFormat.Bold)
formattedText.Bold = true;
if ((textFormat & TextFormat.NotBold) == TextFormat.NotBold)
formattedText.Bold = false;
if ((textFormat & TextFormat.Italic) == TextFormat.Italic)
formattedText.Italic = true;
if ((textFormat & TextFormat.NotItalic) == TextFormat.NotItalic)
formattedText.Italic = false;
if ((textFormat & TextFormat.Underline) == TextFormat.Underline)
formattedText.Underline = Underline.Single;
if ((textFormat & TextFormat.NoUnderline) == TextFormat.NoUnderline)
formattedText.Underline = Underline.None;
return formattedText;
}
/// <summary>
/// Adds a new FormattedText with the given Font.
/// </summary>
public FormattedText AddFormattedText(Font font)
{
FormattedText formattedText = new FormattedText();
formattedText.Font.ApplyFont(font);
this.Add(formattedText);
return formattedText;
}
/// <summary>
/// Adds a new FormattedText with the given text.
/// </summary>
public FormattedText AddFormattedText(string text)
{
FormattedText formattedText = new FormattedText();
formattedText.AddText(text);
this.Add(formattedText);
return formattedText;
}
/// <summary>
/// Adds a new FormattedText object with the given text and format.
/// </summary>
public FormattedText AddFormattedText(string text, TextFormat textFormat)
{
FormattedText formattedText = AddFormattedText(textFormat);
formattedText.AddText(text);
return formattedText;
}
/// <summary>
/// Adds a new FormattedText object with the given text and font.
/// </summary>
public FormattedText AddFormattedText(string text, Font font)
{
FormattedText formattedText = AddFormattedText(font);
formattedText.AddText(text);
return formattedText;
}
/// <summary>
/// Adds a new FormattedText object with the given text and style.
/// </summary>
public FormattedText AddFormattedText(string text, string style)
{
FormattedText formattedText = AddFormattedText(text);
formattedText.Style = style;
return formattedText;
}
/// <summary>
/// Adds a new Hyperlink of Type "Local", i.e. the Target is a Bookmark within the Document
/// </summary>
public Hyperlink AddHyperlink(string name)
{
Hyperlink hyperlink = new Hyperlink();
hyperlink.Name = name;
this.Add(hyperlink);
return hyperlink;
}
/// <summary>
/// Adds a new Hyperlink
/// </summary>
public Hyperlink AddHyperlink(string name, HyperlinkType type)
{
Hyperlink hyperlink = new Hyperlink();
hyperlink.Name = name;
hyperlink.Type = type;
this.Add(hyperlink);
return hyperlink;
}
/// <summary>
/// Adds a new Bookmark.
/// </summary>
public BookmarkField AddBookmark(string name)
{
BookmarkField fieldBookmark = new BookmarkField();
fieldBookmark.Name = name;
this.Add(fieldBookmark);
return fieldBookmark;
}
/// <summary>
/// Adds a new PageField.
/// </summary>
public PageField AddPageField()
{
PageField fieldPage = new PageField();
this.Add(fieldPage);
return fieldPage;
}
/// <summary>
/// Adds a new RefFieldPage.
/// </summary>
public PageRefField AddPageRefField(string name)
{
PageRefField fieldPageRef = new PageRefField();
fieldPageRef.Name = name;
this.Add(fieldPageRef);
return fieldPageRef;
}
/// <summary>
/// Adds a new NumPagesField.
/// </summary>
public NumPagesField AddNumPagesField()
{
NumPagesField fieldNumPages = new NumPagesField();
this.Add(fieldNumPages);
return fieldNumPages;
}
/// <summary>
/// Adds a new SectionField.
/// </summary>
public SectionField AddSectionField()
{
SectionField fieldSection = new SectionField();
this.Add(fieldSection);
return fieldSection;
}
/// <summary>
/// Adds a new SectionPagesField.
/// </summary>
public SectionPagesField AddSectionPagesField()
{
SectionPagesField fieldSectionPages = new SectionPagesField();
this.Add(fieldSectionPages);
return fieldSectionPages;
}
/// <summary>
/// Adds a new DateField.
/// </summary>
///
public DateField AddDateField()
{
DateField fieldDate = new DateField();
this.Add(fieldDate);
return fieldDate;
}
/// <summary>
/// Adds a new DateField with the given format.
/// </summary>
public DateField AddDateField(string format)
{
DateField fieldDate = new DateField();
fieldDate.Format = format;
this.Add(fieldDate);
return fieldDate;
}
/// <summary>
/// Adds a new InfoField with the given type.
/// </summary>
public InfoField AddInfoField(InfoFieldType iType)
{
InfoField fieldInfo = new InfoField();
fieldInfo.Name = iType.ToString();
this.Add(fieldInfo);
return fieldInfo;
}
/// <summary>
/// Adds a new Footnote with the specified Text.
/// </summary>
public Footnote AddFootnote(string text)
{
Footnote footnote = new Footnote();
Paragraph par = footnote.Elements.AddParagraph();
par.AddText(text);
Add(footnote);
return footnote;
}
/// <summary>
/// Adds a new Footnote.
/// </summary>
public Footnote AddFootnote()
{
Footnote footnote = new Footnote();
Add(footnote);
return footnote;
}
/// <summary>
/// Adds a new Image.
/// </summary>
public Image AddImage(string name)
{
Image image = new Image();
image.Name = name;
Add(image);
return image;
}
/// <summary>
///
/// </summary>
public override void Add(DocumentObject docObj)
{
base.Add(docObj);
}
#endregion
#region Internal
/// <summary>
/// Converts ParagraphElements into DDL.
/// </summary>
internal override void Serialize(Serializer serializer)
{
int count = Count;
for (int index = 0; index < count; ++index)
{
DocumentObject element = this[index];
element.Serialize(serializer);
}
}
/// <summary>
/// Returns the meta object of this instance.
/// </summary>
internal override Meta Meta
{
get
{
if (meta == null)
meta = new Meta(typeof(ParagraphElements));
return meta;
}
}
static Meta meta;
#endregion
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.PythonTools.EnvironmentsList.Properties;
using Microsoft.VisualStudioTools;
namespace Microsoft.PythonTools.EnvironmentsList {
internal sealed class PipPackageView : INotifyPropertyChanged {
private readonly PipPackageCache _provider;
private readonly string _name;
private readonly Pep440Version _version;
private Pep440Version? _upgradeVersion;
private string _description;
private static readonly Regex PipListOutputRegex = new Regex(
@"^\s*(?<name>[^\s=:]+)\s+\((?<version>[^:]+)\)(\:(?<description>.*))?\s*$",
RegexOptions.None,
TimeSpan.FromSeconds(1.0)
);
private static readonly Regex PipFreezeOutputRegex = new Regex(
@"^\s*(?<name>[^\s=:]+)==(?<version>[^:]+)?(\:(?<description>.*))?\s*$",
RegexOptions.None,
TimeSpan.FromSeconds(1.0)
);
private static readonly Regex NameAndDescriptionRegex = new Regex(
@"^\s*(?<name>[^\s=:]+)\:(?<description>.*)\s*$",
RegexOptions.None,
TimeSpan.FromSeconds(1.0)
);
internal PipPackageView(PipPackageCache provider, string name, string version, string description) {
_provider = provider;
_name = name ?? "";
if (!string.IsNullOrEmpty(version)) {
Pep440Version.TryParse(version, out _version);
}
_description = description ?? "";
}
internal PipPackageView(PipPackageCache provider, string packageSpec, bool versionIsInstalled = true) {
_provider = provider;
Match m;
try {
m = PipListOutputRegex.Match(packageSpec);
} catch (RegexMatchTimeoutException) {
Debug.Fail("Regex timeout");
m = null;
}
if (m == null || !m.Success) {
try {
m = PipFreezeOutputRegex.Match(packageSpec);
} catch (RegexMatchTimeoutException) {
Debug.Fail("Regex timeout");
m = null;
}
if (m == null || !m.Success) {
try {
m = NameAndDescriptionRegex.Match(packageSpec);
} catch (RegexMatchTimeoutException) {
Debug.Fail("Regex timeout");
m = null;
}
}
}
Pep440Version version;
if (m.Success) {
_name = m.Groups["name"].Value;
Pep440Version.TryParse(m.Groups["version"].Value, out version);
} else {
_name = packageSpec;
version = Pep440Version.Empty;
}
var description = m.Groups["description"].Value;
if (!string.IsNullOrEmpty(description)) {
_description = Uri.UnescapeDataString(description);
}
if (versionIsInstalled) {
_version = version;
_upgradeVersion = null;
} else {
_version = Pep440Version.Empty;
_upgradeVersion = version;
}
}
private async void SetUpgradeVersionAsync() {
if (!_upgradeVersion.HasValue) {
try {
await _provider.UpdatePackageInfoAsync(this, CancellationToken.None);
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
Debug.Fail("Unhandled exception: " + ex.ToString());
// Nowhere else to report the exception, so just swallow it to
// avoid bringing down the whole process.
}
}
}
public string PackageSpec {
get {
return GetPackageSpec(false, false);
}
}
public string GetPackageSpec(bool includeDescription, bool useUpgradeVersion) {
var descr = string.Empty;
if (includeDescription && !string.IsNullOrEmpty(_description)) {
descr = ":" + Uri.EscapeDataString(_description);
}
var ver = useUpgradeVersion ? _upgradeVersion.GetValueOrDefault() : _version;
if (ver.IsEmpty) {
return _name + descr;
} else {
return string.Format("{0}=={1}{2}", _name, ver, descr);
}
}
public string Name {
get { return _name; }
}
public Pep440Version Version {
get { return _version; }
}
public string DisplayName {
get {
if (_version.IsEmpty) {
return _name;
} else {
return string.Format("{0} ({1})", _name, _version);
}
}
}
private async void TriggerDescriptionUpdate() {
try {
await _provider.UpdatePackageInfoAsync(this, CancellationToken.None);
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
Description = string.Empty;
}
}
public string Description {
get {
if (_description == null) {
_description = Resources.LoadingDescription;
TriggerDescriptionUpdate();
}
return _description;
}
set {
if (_description != value) {
_description = value;
OnPropertyChanged();
}
}
}
public Pep440Version UpgradeVersion {
get {
if (!_upgradeVersion.HasValue) {
// Kick off the Get, but return empty. We will raise an
// event when the get completes.
SetUpgradeVersionAsync();
}
return _upgradeVersion.GetValueOrDefault();
}
set {
if (!_upgradeVersion.HasValue || !_upgradeVersion.GetValueOrDefault().Equals(value)) {
_upgradeVersion = value;
OnPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null) {
var evt = PropertyChanged;
if (evt != null) {
evt(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| |
using global::System;
using global::System.Linq.Expressions;
namespace ExpressiveExpressionTrees {
#if EXPRESSIVE_EXPRESSION_TREES_ASSEMBLY
public
#endif
partial class ExpressionGenerator {
public Expression<Func<T2>> FromFunc<T1, T2>(Expression<Func<T1>> p1, Expression<Func<T1, T2>> expr)
{
return Expression.Lambda<Func<T2>>(
ExpressionReplacer.
Search(expr.Body).
When(expr.Parameters[0], p1.Body).
GetResult()
);
}
public Expression<Func<T3>> FromFunc<T1, T2, T3>(Expression<Func<T1>> p1, Expression<Func<T2>> p2, Expression<Func<T1, T2, T3>> expr)
{
return Expression.Lambda<Func<T3>>(
ExpressionReplacer.
Search(expr.Body).
When(expr.Parameters[0], p1.Body).
When(expr.Parameters[1], p2.Body).
GetResult()
);
}
public Expression<Func<T4>> FromFunc<T1, T2, T3, T4>(Expression<Func<T1>> p1, Expression<Func<T2>> p2, Expression<Func<T3>> p3, Expression<Func<T1, T2, T3, T4>> expr)
{
return Expression.Lambda<Func<T4>>(
ExpressionReplacer.
Search(expr.Body).
When(expr.Parameters[0], p1.Body).
When(expr.Parameters[1], p2.Body).
When(expr.Parameters[2], p3.Body).
GetResult()
);
}
public Expression<Func<T5>> FromFunc<T1, T2, T3, T4, T5>(Expression<Func<T1>> p1, Expression<Func<T2>> p2, Expression<Func<T3>> p3, Expression<Func<T4>> p4, Expression<Func<T1, T2, T3, T4, T5>> expr)
{
return Expression.Lambda<Func<T5>>(
ExpressionReplacer.
Search(expr.Body).
When(expr.Parameters[0], p1.Body).
When(expr.Parameters[1], p2.Body).
When(expr.Parameters[2], p3.Body).
When(expr.Parameters[3], p4.Body).
GetResult()
);
}
public Expression<Func<T6>> FromFunc<T1, T2, T3, T4, T5, T6>(Expression<Func<T1>> p1, Expression<Func<T2>> p2, Expression<Func<T3>> p3, Expression<Func<T4>> p4, Expression<Func<T5>> p5, Expression<Func<T1, T2, T3, T4, T5, T6>> expr)
{
return Expression.Lambda<Func<T6>>(
ExpressionReplacer.
Search(expr.Body).
When(expr.Parameters[0], p1.Body).
When(expr.Parameters[1], p2.Body).
When(expr.Parameters[2], p3.Body).
When(expr.Parameters[3], p4.Body).
When(expr.Parameters[4], p5.Body).
GetResult()
);
}
public Expression<Func<T7>> FromFunc<T1, T2, T3, T4, T5, T6, T7>(Expression<Func<T1>> p1, Expression<Func<T2>> p2, Expression<Func<T3>> p3, Expression<Func<T4>> p4, Expression<Func<T5>> p5, Expression<Func<T6>> p6, Expression<Func<T1, T2, T3, T4, T5, T6, T7>> expr)
{
return Expression.Lambda<Func<T7>>(
ExpressionReplacer.
Search(expr.Body).
When(expr.Parameters[0], p1.Body).
When(expr.Parameters[1], p2.Body).
When(expr.Parameters[2], p3.Body).
When(expr.Parameters[3], p4.Body).
When(expr.Parameters[4], p5.Body).
When(expr.Parameters[5], p6.Body).
GetResult()
);
}
public Expression<Func<T8>> FromFunc<T1, T2, T3, T4, T5, T6, T7, T8>(Expression<Func<T1>> p1, Expression<Func<T2>> p2, Expression<Func<T3>> p3, Expression<Func<T4>> p4, Expression<Func<T5>> p5, Expression<Func<T6>> p6, Expression<Func<T7>> p7, Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8>> expr)
{
return Expression.Lambda<Func<T8>>(
ExpressionReplacer.
Search(expr.Body).
When(expr.Parameters[0], p1.Body).
When(expr.Parameters[1], p2.Body).
When(expr.Parameters[2], p3.Body).
When(expr.Parameters[3], p4.Body).
When(expr.Parameters[4], p5.Body).
When(expr.Parameters[5], p6.Body).
When(expr.Parameters[6], p7.Body).
GetResult()
);
}
public Expression<Func<T9>> FromFunc<T1, T2, T3, T4, T5, T6, T7, T8, T9>(Expression<Func<T1>> p1, Expression<Func<T2>> p2, Expression<Func<T3>> p3, Expression<Func<T4>> p4, Expression<Func<T5>> p5, Expression<Func<T6>> p6, Expression<Func<T7>> p7, Expression<Func<T8>> p8, Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9>> expr)
{
return Expression.Lambda<Func<T9>>(
ExpressionReplacer.
Search(expr.Body).
When(expr.Parameters[0], p1.Body).
When(expr.Parameters[1], p2.Body).
When(expr.Parameters[2], p3.Body).
When(expr.Parameters[3], p4.Body).
When(expr.Parameters[4], p5.Body).
When(expr.Parameters[5], p6.Body).
When(expr.Parameters[6], p7.Body).
When(expr.Parameters[7], p8.Body).
GetResult()
);
}
public Expression<Func<T10>> FromFunc<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(Expression<Func<T1>> p1, Expression<Func<T2>> p2, Expression<Func<T3>> p3, Expression<Func<T4>> p4, Expression<Func<T5>> p5, Expression<Func<T6>> p6, Expression<Func<T7>> p7, Expression<Func<T8>> p8, Expression<Func<T9>> p9, Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>> expr)
{
return Expression.Lambda<Func<T10>>(
ExpressionReplacer.
Search(expr.Body).
When(expr.Parameters[0], p1.Body).
When(expr.Parameters[1], p2.Body).
When(expr.Parameters[2], p3.Body).
When(expr.Parameters[3], p4.Body).
When(expr.Parameters[4], p5.Body).
When(expr.Parameters[5], p6.Body).
When(expr.Parameters[6], p7.Body).
When(expr.Parameters[7], p8.Body).
When(expr.Parameters[8], p9.Body).
GetResult()
);
}
public Expression<Func<T11>> FromFunc<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(Expression<Func<T1>> p1, Expression<Func<T2>> p2, Expression<Func<T3>> p3, Expression<Func<T4>> p4, Expression<Func<T5>> p5, Expression<Func<T6>> p6, Expression<Func<T7>> p7, Expression<Func<T8>> p8, Expression<Func<T9>> p9, Expression<Func<T10>> p10, Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>> expr)
{
return Expression.Lambda<Func<T11>>(
ExpressionReplacer.
Search(expr.Body).
When(expr.Parameters[0], p1.Body).
When(expr.Parameters[1], p2.Body).
When(expr.Parameters[2], p3.Body).
When(expr.Parameters[3], p4.Body).
When(expr.Parameters[4], p5.Body).
When(expr.Parameters[5], p6.Body).
When(expr.Parameters[6], p7.Body).
When(expr.Parameters[7], p8.Body).
When(expr.Parameters[8], p9.Body).
When(expr.Parameters[9], p10.Body).
GetResult()
);
}
public Expression<Func<T12>> FromFunc<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(Expression<Func<T1>> p1, Expression<Func<T2>> p2, Expression<Func<T3>> p3, Expression<Func<T4>> p4, Expression<Func<T5>> p5, Expression<Func<T6>> p6, Expression<Func<T7>> p7, Expression<Func<T8>> p8, Expression<Func<T9>> p9, Expression<Func<T10>> p10, Expression<Func<T11>> p11, Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>> expr)
{
return Expression.Lambda<Func<T12>>(
ExpressionReplacer.
Search(expr.Body).
When(expr.Parameters[0], p1.Body).
When(expr.Parameters[1], p2.Body).
When(expr.Parameters[2], p3.Body).
When(expr.Parameters[3], p4.Body).
When(expr.Parameters[4], p5.Body).
When(expr.Parameters[5], p6.Body).
When(expr.Parameters[6], p7.Body).
When(expr.Parameters[7], p8.Body).
When(expr.Parameters[8], p9.Body).
When(expr.Parameters[9], p10.Body).
When(expr.Parameters[10], p11.Body).
GetResult()
);
}
public Expression<Func<T13>> FromFunc<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(Expression<Func<T1>> p1, Expression<Func<T2>> p2, Expression<Func<T3>> p3, Expression<Func<T4>> p4, Expression<Func<T5>> p5, Expression<Func<T6>> p6, Expression<Func<T7>> p7, Expression<Func<T8>> p8, Expression<Func<T9>> p9, Expression<Func<T10>> p10, Expression<Func<T11>> p11, Expression<Func<T12>> p12, Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>> expr)
{
return Expression.Lambda<Func<T13>>(
ExpressionReplacer.
Search(expr.Body).
When(expr.Parameters[0], p1.Body).
When(expr.Parameters[1], p2.Body).
When(expr.Parameters[2], p3.Body).
When(expr.Parameters[3], p4.Body).
When(expr.Parameters[4], p5.Body).
When(expr.Parameters[5], p6.Body).
When(expr.Parameters[6], p7.Body).
When(expr.Parameters[7], p8.Body).
When(expr.Parameters[8], p9.Body).
When(expr.Parameters[9], p10.Body).
When(expr.Parameters[10], p11.Body).
When(expr.Parameters[11], p12.Body).
GetResult()
);
}
public Expression<Func<T14>> FromFunc<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(Expression<Func<T1>> p1, Expression<Func<T2>> p2, Expression<Func<T3>> p3, Expression<Func<T4>> p4, Expression<Func<T5>> p5, Expression<Func<T6>> p6, Expression<Func<T7>> p7, Expression<Func<T8>> p8, Expression<Func<T9>> p9, Expression<Func<T10>> p10, Expression<Func<T11>> p11, Expression<Func<T12>> p12, Expression<Func<T13>> p13, Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>> expr)
{
return Expression.Lambda<Func<T14>>(
ExpressionReplacer.
Search(expr.Body).
When(expr.Parameters[0], p1.Body).
When(expr.Parameters[1], p2.Body).
When(expr.Parameters[2], p3.Body).
When(expr.Parameters[3], p4.Body).
When(expr.Parameters[4], p5.Body).
When(expr.Parameters[5], p6.Body).
When(expr.Parameters[6], p7.Body).
When(expr.Parameters[7], p8.Body).
When(expr.Parameters[8], p9.Body).
When(expr.Parameters[9], p10.Body).
When(expr.Parameters[10], p11.Body).
When(expr.Parameters[11], p12.Body).
When(expr.Parameters[12], p13.Body).
GetResult()
);
}
public Expression<Func<T15>> FromFunc<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(Expression<Func<T1>> p1, Expression<Func<T2>> p2, Expression<Func<T3>> p3, Expression<Func<T4>> p4, Expression<Func<T5>> p5, Expression<Func<T6>> p6, Expression<Func<T7>> p7, Expression<Func<T8>> p8, Expression<Func<T9>> p9, Expression<Func<T10>> p10, Expression<Func<T11>> p11, Expression<Func<T12>> p12, Expression<Func<T13>> p13, Expression<Func<T14>> p14, Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>> expr)
{
return Expression.Lambda<Func<T15>>(
ExpressionReplacer.
Search(expr.Body).
When(expr.Parameters[0], p1.Body).
When(expr.Parameters[1], p2.Body).
When(expr.Parameters[2], p3.Body).
When(expr.Parameters[3], p4.Body).
When(expr.Parameters[4], p5.Body).
When(expr.Parameters[5], p6.Body).
When(expr.Parameters[6], p7.Body).
When(expr.Parameters[7], p8.Body).
When(expr.Parameters[8], p9.Body).
When(expr.Parameters[9], p10.Body).
When(expr.Parameters[10], p11.Body).
When(expr.Parameters[11], p12.Body).
When(expr.Parameters[12], p13.Body).
When(expr.Parameters[13], p14.Body).
GetResult()
);
}
public Expression<Func<T16>> FromFunc<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(Expression<Func<T1>> p1, Expression<Func<T2>> p2, Expression<Func<T3>> p3, Expression<Func<T4>> p4, Expression<Func<T5>> p5, Expression<Func<T6>> p6, Expression<Func<T7>> p7, Expression<Func<T8>> p8, Expression<Func<T9>> p9, Expression<Func<T10>> p10, Expression<Func<T11>> p11, Expression<Func<T12>> p12, Expression<Func<T13>> p13, Expression<Func<T14>> p14, Expression<Func<T15>> p15, Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>> expr)
{
return Expression.Lambda<Func<T16>>(
ExpressionReplacer.
Search(expr.Body).
When(expr.Parameters[0], p1.Body).
When(expr.Parameters[1], p2.Body).
When(expr.Parameters[2], p3.Body).
When(expr.Parameters[3], p4.Body).
When(expr.Parameters[4], p5.Body).
When(expr.Parameters[5], p6.Body).
When(expr.Parameters[6], p7.Body).
When(expr.Parameters[7], p8.Body).
When(expr.Parameters[8], p9.Body).
When(expr.Parameters[9], p10.Body).
When(expr.Parameters[10], p11.Body).
When(expr.Parameters[11], p12.Body).
When(expr.Parameters[12], p13.Body).
When(expr.Parameters[13], p14.Body).
When(expr.Parameters[14], p15.Body).
GetResult()
);
}
public Expression<Func<T17>> FromFunc<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17>(Expression<Func<T1>> p1, Expression<Func<T2>> p2, Expression<Func<T3>> p3, Expression<Func<T4>> p4, Expression<Func<T5>> p5, Expression<Func<T6>> p6, Expression<Func<T7>> p7, Expression<Func<T8>> p8, Expression<Func<T9>> p9, Expression<Func<T10>> p10, Expression<Func<T11>> p11, Expression<Func<T12>> p12, Expression<Func<T13>> p13, Expression<Func<T14>> p14, Expression<Func<T15>> p15, Expression<Func<T16>> p16, Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17>> expr)
{
return Expression.Lambda<Func<T17>>(
ExpressionReplacer.
Search(expr.Body).
When(expr.Parameters[0], p1.Body).
When(expr.Parameters[1], p2.Body).
When(expr.Parameters[2], p3.Body).
When(expr.Parameters[3], p4.Body).
When(expr.Parameters[4], p5.Body).
When(expr.Parameters[5], p6.Body).
When(expr.Parameters[6], p7.Body).
When(expr.Parameters[7], p8.Body).
When(expr.Parameters[8], p9.Body).
When(expr.Parameters[9], p10.Body).
When(expr.Parameters[10], p11.Body).
When(expr.Parameters[11], p12.Body).
When(expr.Parameters[12], p13.Body).
When(expr.Parameters[13], p14.Body).
When(expr.Parameters[14], p15.Body).
When(expr.Parameters[15], p16.Body).
GetResult()
);
}
}
}
| |
//
// MessageIdList.cs
//
// Author: Jeffrey Stedfast <[email protected]>
//
// Copyright (c) 2013 Jeffrey Stedfast
//
// 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;
using System.Collections.Generic;
using MimeKit.Utils;
namespace MimeKit {
/// <summary>
/// A list of Message-Ids, as found in the References header.
/// </summary>
public sealed class MessageIdList : IList<string>
{
readonly List<string> references;
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.MessageIdList"/> class.
/// </summary>
public MessageIdList ()
{
references = new List<string> ();
}
#region IList implementation
/// <summary>
/// Gets the index of the requested Message-Id, if it exists.
/// </summary>
/// <returns>The index of the requested Message-Id; otherwise <value>-1</value>.</returns>
/// <param name="messageId">The Message-Id.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="messageId"/> is <c>null</c>.
/// </exception>
public int IndexOf (string messageId)
{
if (messageId == null)
throw new ArgumentNullException ("messageId");
return references.IndexOf (messageId);
}
static string ValidateMessageId (string messageId)
{
var buffer = Encoding.ASCII.GetBytes (messageId);
InternetAddress addr;
int index = 0;
if (!InternetAddress.TryParse (ParserOptions.Default, buffer, ref index, buffer.Length, false, out addr) || !(addr is MailboxAddress))
throw new ArgumentException ("Invalid Message-Id format.", "messageId");
return "<" + ((MailboxAddress) addr).Address + ">";
}
/// <summary>
/// Insert the Message-Id at the specified index.
/// </summary>
/// <param name="index">The index to insert the Message-Id.</param>
/// <param name="messageId">The Message-Id to insert.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="messageId"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of range.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="messageId"/> is improperly formatted.
/// </exception>
public void Insert (int index, string messageId)
{
if (messageId == null)
throw new ArgumentNullException ("messageId");
references.Insert (index, ValidateMessageId (messageId));
OnChanged ();
}
/// <summary>
/// Removes the Message-Id at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of range.
/// </exception>
public void RemoveAt (int index)
{
references.RemoveAt (index);
OnChanged ();
}
/// <summary>
/// Gets or sets the <see cref="MimeKit.MessageIdList"/> at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="value"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of range.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="value"/> is improperly formatted.
/// </exception>
public string this [int index] {
get { return references[index]; }
set {
if (value == null)
throw new ArgumentNullException ("value");
if (references[index] == value)
return;
references[index] = ValidateMessageId (value);
OnChanged ();
}
}
#endregion
#region ICollection implementation
/// <summary>
/// Add the specified Message-Id.
/// </summary>
/// <param name="messageId">The Message-Id.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="messageId"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="messageId"/> is improperly formatted.
/// </exception>
public void Add (string messageId)
{
if (messageId == null)
throw new ArgumentNullException ("messageId");
references.Add (ValidateMessageId (messageId));
OnChanged ();
}
/// <summary>
/// Clears the Message-Id list.
/// </summary>
public void Clear ()
{
references.Clear ();
OnChanged ();
}
/// <summary>
/// Checks if the <see cref="MessageIdList"/> contains the specified Message-Id.
/// </summary>
/// <returns><value>true</value> if the specified Message-Id is contained;
/// otherwise <value>false</value>.</returns>
/// <param name="messageId">The Message-Id.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="messageId"/> is <c>null</c>.
/// </exception>
public bool Contains (string messageId)
{
if (messageId == null)
throw new ArgumentNullException ("messageId");
return references.Contains (messageId);
}
/// <summary>
/// Copies all of the Message-Ids in the <see cref="MimeKit.MessageIdList"/> to the specified array.
/// </summary>
/// <param name="array">The array to copy the Message-Ids to.</param>
/// <param name="arrayIndex">The index into the array.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="array"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="arrayIndex"/> is out of range.
/// </exception>
public void CopyTo (string[] array, int arrayIndex)
{
references.CopyTo (array, arrayIndex);
}
/// <summary>
/// Removes the specified Message-Id.
/// </summary>
/// <returns><value>true</value> if the specified Message-Id was removed;
/// otherwise <value>false</value>.</returns>
/// <param name="messageId">The Message-Id.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="messageId"/> is <c>null</c>.
/// </exception>
public bool Remove (string messageId)
{
if (messageId == null)
throw new ArgumentNullException ("messageId");
if (references.Remove (messageId)) {
OnChanged ();
return true;
}
return false;
}
/// <summary>
/// Gets the number of Message-Ids in the <see cref="MimeKit.MessageIdList"/>.
/// </summary>
/// <value>The number of Message-Ids.</value>
public int Count {
get { return references.Count; }
}
/// <summary>
/// Gets a value indicating whether this instance is read only.
/// </summary>
/// <value><c>true</c> if this instance is read only; otherwise, <c>false</c>.</value>
public bool IsReadOnly {
get { return false; }
}
#endregion
#region IEnumerable implementation
/// <summary>
/// Gets an enumerator for the list of Message-Ids.
/// </summary>
/// <returns>The enumerator.</returns>
public IEnumerator<string> GetEnumerator ()
{
return references.GetEnumerator ();
}
#endregion
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator ()
{
return references.GetEnumerator ();
}
#endregion
/// <summary>
/// Serializes the <see cref="MimeKit.MessageIdList"/> to a string.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents the current <see cref="MimeKit.MessageIdList"/>.</returns>
public override string ToString ()
{
StringBuilder builder = new StringBuilder ();
for (int i = 0; i < references.Count; i++) {
if (builder.Length > 0)
builder.Append (' ');
builder.Append (references[i]);
}
return builder.ToString ();
}
internal event EventHandler Changed;
void OnChanged ()
{
if (Changed != null)
Changed (this, EventArgs.Empty);
}
}
}
| |
#region Copyright Notice
// Copyright 2011-2013 Eleftherios Aslanoglou
//
// 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
namespace NBA_Stats_Tracker.Data.Players
{
#region Using Directives
using System.Collections.Generic;
using System.Linq;
#endregion
/// <summary>Lists and dictionaries to help access and create lists of player stats.</summary>
public static class PlayerStatsHelper
{
public static readonly Dictionary<int, string> Totals = new Dictionary<int, string>
{
{ 0, "GP" },
{ 1, "GS" },
{ 2, "MINS" },
{ 3, "PTS" },
{ 4, "DREB" },
{ 5, "OREB" },
{ 6, "AST" },
{ 7, "STL" },
{ 8, "BLK" },
{ 9, "TOS" },
{ 10, "FOUL" },
{ 11, "FGM" },
{ 12, "FGA" },
{ 13, "3PM" },
{ 14, "3PA" },
{ 15, "FTM" },
{ 16, "FTA" }
};
public static readonly Dictionary<int, string> CHTotals = new Dictionary<int, string>
{
{ 0, "GP" },
{ 1, "GS" },
{ 2, "MINS" },
{ 3, "PTS" },
{ 4, "DREB" },
{ 5, "OREB" },
{ 6, "AST" },
{ 7, "STL" },
{ 8, "BLK" },
{ 9, "TOS" },
{ 10, "FOUL" },
{ 11, "FGM" },
{ 12, "FGA" },
{ 13, "3PM" },
{ 14, "3PA" },
{ 15, "FTM" },
{ 16, "FTA" },
{ 17, "REB" }
};
public static readonly Dictionary<int, string> PerGame = new Dictionary<int, string>
{
{ 0, "MPG" },
{ 1, "PPG" },
{ 2, "DRPG" },
{ 3, "ORPG" },
{ 4, "APG" },
{ 5, "SPG" },
{ 6, "BPG" },
{ 7, "TPG" },
{ 8, "FPG" },
{ 9, "FG%" },
{ 10, "FGeff" },
{ 11, "3P%" },
{ 12, "3Peff" },
{ 13, "FT%" },
{ 14, "FTeff" },
{ 15, "RPG" }
};
public static readonly Dictionary<string, string> TotalsToPerGame = new Dictionary<string, string>
{
{ "PTS", "PPG" },
{ "FGM", "FGMPG" },
{ "FGA", "FGAPG" },
{ "TPM", "TPMPG" },
{ "TPA", "TPAPG" },
{ "FTM", "FTMPG" },
{ "FTA", "FTAPG" },
{ "REB", "RPG" },
{ "OREB", "ORPG" },
{ "DREB", "DRPG" },
{ "STL", "SPG" },
{ "BLK", "BPG" },
{ "TOS", "TPG" },
{ "AST", "APG" },
{ "FOUL", "FPG" },
{ "MINS", "MPG" }
};
public static readonly List<string> ExtendedTotals = new List<string>
{
"GP",
"GS",
"PTS",
"FGM",
"FGA",
"3PM",
"3PA",
"FTM",
"FTA",
"REB",
"OREB",
"DREB",
"AST",
"STL",
"BLK",
"TO",
"FOUL",
"MINS"
};
public static readonly List<string> ExtendedPerGame = new List<string>
{
"PPG",
"FGMPG",
"FGAPG",
"FG%",
"FGeff",
"3PMPG",
"3PAPG",
"3P%",
"3Peff",
"FTMPG",
"FTAPG",
"FT%",
"FTeff",
"RPG",
"ORPG",
"DRPG",
"APG",
"SPG",
"BPG",
"TPG",
"FPG",
"MPG"
};
public static readonly List<string> MetricsNames = new List<string>
{
"PER",
"EFF",
"ORTG",
"DRTG",
"RTGd",
"GmSc",
"GmScE",
"TS%",
"EFG%",
"Floor%",
"AST%",
"PPR",
"STL%",
"TO%",
"USG%",
"BLK%",
"DREB%",
"OREB%",
"REB%",
"PTSR",
"REBR",
"OREBR",
"ASTR",
"BLKR",
"STLR",
"TOR",
"FTR",
"FTAR",
"aPER"
};
public static readonly Dictionary<string, double> MetricsDict =
MetricsNames.Select(name => new KeyValuePair<string, double>(name, double.NaN))
.ToDictionary(pair => pair.Key, pair => pair.Value);
}
// Unlike TeamStats which was designed before REDitor implemented such stats,
// PlayerStats were made according to REDitor's standards, to make life
// easier when importing/exporting from REDitor's CSV
}
| |
#region License
// Copyright (c) 2010-2019, Mark Final
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of BuildAMation nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion // License
using Bam.Core;
using System.Linq;
namespace Python
{
[Bam.Core.ModuleGroup("Thirdparty/Python/libffi")]
[Bam.Core.PlatformFilter(Bam.Core.EPlatform.Linux)]
class libffiheader :
C.ProceduralHeaderFile
{
protected override void
Init()
{
base.Init();
this.Macros.Add("templateConfig", this.CreateTokenizedString("$(packagedir)/Modules/_ctypes/libffi/include/ffi.h.in"));
}
protected override Bam.Core.TokenizedString OutputPath => this.CreateTokenizedString("$(packagebuilddir)/$(config)/PublicHeaders/ffi.h");
protected override string GuardString => null; // the template file already has one
protected override bool UseSystemIncludeSearchPaths => true;
protected override string Contents
{
get
{
var contents = new System.Text.StringBuilder();
using (System.IO.TextReader reader = new System.IO.StreamReader(this.Macros["templateConfig"].ToString()))
{
contents.Append(reader.ReadToEnd());
}
// macro replacements
contents.Replace("@TARGET@", "xX86_64");
contents.Replace("@HAVE_LONG_DOUBLE@", "0");
contents.Replace("@FFI_EXEC_TRAMPOLINE_TABLE@", "0");
return contents.ToString();
}
}
}
[Bam.Core.ModuleGroup("Thirdparty/Python/libffi")]
[Bam.Core.PlatformFilter(Bam.Core.EPlatform.Linux)]
class libfficonfig :
C.ProceduralHeaderFile
{
protected override void
Init()
{
base.Init();
}
protected override Bam.Core.TokenizedString OutputPath => this.CreateTokenizedString("$(packagebuilddir)/$(config)/fficonfig.h"); // not public
protected override bool UseSystemIncludeSearchPaths => true;
protected override string Contents
{
get
{
var contents = new System.Text.StringBuilder();
contents.AppendLine("#define STDC_HEADERS 1");
contents.AppendLine("#ifdef LIBFFI_ASM");
contents.AppendLine("#define FFI_HIDDEN(name) .hidden name");
contents.AppendLine("#define EH_FRAME_FLAGS \"aw\"");
contents.AppendLine("#else");
contents.AppendLine("#define FFI_HIDDEN __attribute__ ((visibility (\"hidden\")))");
contents.AppendLine("#endif");
return contents.ToString();
}
}
}
[Bam.Core.ModuleGroup("Thirdparty/Python/libffi")]
[Bam.Core.PlatformFilter(Bam.Core.EPlatform.Linux)]
class CopyNonPublicHeadersToPublic :
Publisher.Collation
{
protected override void
Init()
{
base.Init();
var publishRoot = this.CreateTokenizedString("$(packagebuilddir)/$(config)/PublicHeaders");
this.PublicPatch((settings, appliedTo) =>
{
if (settings is C.ICommonPreprocessorSettings preprocessor)
{
preprocessor.IncludePaths.AddUnique(publishRoot);
}
});
var headerPaths = new Bam.Core.StringArray
{
"src/x86/ffitarget.h",
"include/ffi_common.h"
};
foreach (var header in headerPaths)
{
this.IncludeFiles<CopyNonPublicHeadersToPublic>("$(packagedir)/Modules/_ctypes/libffi/" + header, publishRoot, null);
}
}
}
[Bam.Core.ModuleGroup("Thirdparty/Python/libffi")]
class ffi :
C.StaticLibrary
{
protected override void
Init()
{
base.Init();
var source = this.CreateCSourceCollection();
var asmSource = this.CreateAssemblerSourceCollection();
if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Linux))
{
source.AddFiles("$(packagedir)/Modules/_ctypes/libffi/src/*.c");
if (this.BitDepth == C.EBit.ThirtyTwo)
{
source.AddFiles("$(packagedir)/Modules/_ctypes/libffi/src/x86/ffi.c");
asmSource.AddFiles("$(packagedir)/Modules/_ctypes/libffi/src/x86/sysv.S");
asmSource.AddFiles("$(packagedir)/Modules/_ctypes/libffi/src/x86/win32.S");
}
else
{
var ffi64 = source.AddFiles("$(packagedir)/Modules/_ctypes/libffi/src/x86/ffi64.c");
ffi64.First().PrivatePatch(settings =>
{
// TODO: Gcc 7+
if (settings is GccCommon.ICommonCompilerSettings)
{
var compiler = settings as C.ICommonCompilerSettings;
compiler.DisableWarnings.AddUnique("implicit-fallthrough");
}
});
asmSource.AddFiles("$(packagedir)/Modules/_ctypes/libffi/src/x86/unix64.S");
}
var copyheaders = Bam.Core.Graph.Instance.FindReferencedModule<CopyNonPublicHeadersToPublic>();
source.DependsOn(copyheaders);
source.UsePublicPatches(copyheaders);
var ffiHeader = Bam.Core.Graph.Instance.FindReferencedModule<libffiheader>();
this.UsePublicPatches(ffiHeader);
source.DependsOn(ffiHeader);
var ffiConfig = Bam.Core.Graph.Instance.FindReferencedModule<libfficonfig>();
source.UsePublicPatches(ffiConfig);
source.DependsOn(ffiConfig);
asmSource.UsePublicPatches(ffiConfig);
asmSource.DependsOn(ffiConfig);
}
else if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.OSX))
{
var ffi = source.AddFiles("$(packagedir)/Modules/_ctypes/libffi_osx/ffi.c");
ffi.First().PrivatePatch(settings =>
{
if (settings is ClangCommon.ICommonCompilerSettings)
{
var compiler = settings as C.ICommonCompilerSettings;
compiler.DisableWarnings.AddUnique("unused-function"); // Python-3.5.1/Modules/_ctypes/libffi_osx/ffi.c:108:1: error: unused function 'struct_on_stack' [-Werror,-Wunused-function]
}
});
if (this.BitDepth == C.EBit.ThirtyTwo)
{
source.AddFiles("$(packagedir)/Modules/_ctypes/libffi_osx/x86/x86-ffi_darwin.c");
asmSource.AddFiles("$(packagedir)/Modules/_ctypes/libffi_osx/x86/x86-darwin.S");
}
else
{
source.AddFiles("$(packagedir)/Modules/_ctypes/libffi_osx/x86/x86-ffi64.c");
asmSource.AddFiles("$(packagedir)/Modules/_ctypes/libffi_osx/x86/darwin64.S");
}
}
else if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Windows))
{
var ffi = source.AddFiles("$(packagedir)/Modules/_ctypes/libffi_msvc/ffi.c");
ffi.First().PrivatePatch(settings =>
{
if (settings is VisualCCommon.ICommonCompilerSettings)
{
var compiler = settings as C.ICommonCompilerSettings;
compiler.DisableWarnings.AddUnique("4244"); // Python-3.5.1\Modules\_ctypes\libffi_msvc\ffi.c(293): warning C4244: '=': conversion from 'unsigned int' to 'unsigned short', possible loss of data
compiler.DisableWarnings.AddUnique("4054"); // Python-3.5.1\Modules\_ctypes\libffi_msvc\ffi.c(466): warning C4054: 'type cast': from function pointer 'void (__cdecl *)()' to data pointer 'void *'
compiler.DisableWarnings.AddUnique("4100"); // Python-3.5.1\Modules\_ctypes\libffi_msvc\ffi.c(416): warning C4100: 'codeloc': unreferenced formal parameter
}
});
var prep_cif = source.AddFiles("$(packagedir)/Modules/_ctypes/libffi_msvc/prep_cif.c");
prep_cif.First().PrivatePatch(settings =>
{
if (settings is VisualCCommon.ICommonCompilerSettings)
{
var compiler = settings as C.ICommonCompilerSettings;
compiler.DisableWarnings.AddUnique("4267"); // Python-3.5.1\Modules\_ctypes\libffi_msvc\prep_cif.c(170): warning C4267: '+=': conversion from 'size_t' to 'unsigned int', possible loss of data
}
});
if (this.BitDepth == C.EBit.ThirtyTwo)
{
var win32 = source.AddFiles("$(packagedir)/Modules/_ctypes/libffi_msvc/win32.c");
win32.First().PrivatePatch(settings =>
{
if (settings is VisualCCommon.ICommonCompilerSettings)
{
var compiler = settings as C.ICommonCompilerSettings;
compiler.DisableWarnings.AddUnique("4100"); // Python-3.5.1\Modules\_ctypes\libffi_msvc\win32.c(46): warning C4100: 'fn': unreferenced formal parameter
}
});
}
else
{
asmSource.AddFiles("$(packagedir)/Modules/_ctypes/libffi_msvc/win64.asm");
}
}
source.PrivatePatch(settings =>
{
if (settings is GccCommon.ICommonCompilerSettings gccCompiler)
{
gccCompiler.AllWarnings = true;
gccCompiler.ExtraWarnings = true;
gccCompiler.Pedantic = false; // Python-3.5.1/Modules/_ctypes/libffi/src/x86/ffi.c:867:0: error: ISO C forbids an empty translation unit [-Werror=pedantic]
var preprocessor = settings as C.ICommonPreprocessorSettings;
preprocessor.IncludePaths.AddUnique(this.CreateTokenizedString("$(packagedir)/Modules/_ctypes/libffi/include"));
var compiler = settings as C.ICommonCompilerSettings;
compiler.DisableWarnings.AddUnique("unused-parameter"); // Python-3.5.1/Modules/_ctypes/libffi/src/debug.c:50:30: error: unused parameter 'a' [-Werror=unused-parameter]
compiler.DisableWarnings.AddUnique("empty-body"); // Python-3.5.1/Modules/_ctypes/libffi/src/debug.c:50:30: error: unused parameter 'a' [-Werror=unused-parameter]
compiler.DisableWarnings.AddUnique("sign-compare"); // Python-3.5.1/Modules/_ctypes/libffi/src/debug.c:50:30: error: unused parameter 'a' [-Werror=unused-parameter]
if (this.BuildEnvironment.Configuration != Bam.Core.EConfiguration.Debug)
{
compiler.DisableWarnings.AddUnique("unused-result"); // Python-3.5.1/Modules/_ctypes/libffi/src/closures.c:460:17: error: ignoring return value of 'ftruncate', declared with attribute warn_unused_result [-Werror=unused-result]
}
var cOnly = settings as C.ICOnlyCompilerSettings;
cOnly.LanguageStandard = C.ELanguageStandard.C99; // for C++ style comments, etc
gccCompiler.PositionIndependentCode = true; // since it's being included into a dynamic library
}
if (settings is ClangCommon.ICommonCompilerSettings clangCompiler)
{
clangCompiler.AllWarnings = true;
clangCompiler.ExtraWarnings = true;
clangCompiler.Pedantic = false; // Python-3.5.1/Modules/_ctypes/libffi_osx/x86/x86-ffi64.c:602:30: error: assigning to 'void *volatile' from 'void (void)' converts between void pointer and function pointer [-Werror,-Wpedantic]
var preprocessor = settings as C.ICommonPreprocessorSettings;
preprocessor.PreprocessorDefines.Add("MACOSX");
var cOnly = settings as C.ICOnlyCompilerSettings;
cOnly.LanguageStandard = C.ELanguageStandard.C99; // for C++ style comments, etc
}
if (settings is VisualCCommon.ICommonCompilerSettings vcCompiler)
{
vcCompiler.WarningLevel = VisualCCommon.EWarningLevel.Level4;
}
});
asmSource.PrivatePatch(settings =>
{
if (settings is GccCommon.ICommonAssemblerSettings)
{
var assembler = settings as C.ICommonAssemblerSettings;
assembler.PreprocessorDefines.Add("HAVE_AS_X86_PCREL", "1");
if (this.BitDepth == C.EBit.ThirtyTwo)
{
assembler.PreprocessorDefines.Add("HAVE_AS_ASCII_PSEUDO_OP", "1");
}
}
if (settings is ClangCommon.ICommonAssemblerSettings)
{
var assembler = settings as C.ICommonAssemblerSettings;
assembler.IncludePaths.AddUnique(settings.Module.CreateTokenizedString("$(packagedir)/Modules/_ctypes/libffi_osx/include"));
assembler.PreprocessorDefines.Add("MACOSX");
}
});
this.PublicPatch((settings, appliedTo) =>
{
if (settings is ClangCommon.ICommonCompilerSettings)
{
var preprocessor = settings as C.ICommonPreprocessorSettings;
preprocessor.SystemIncludePaths.AddUnique(this.CreateTokenizedString("$(packagedir)/Modules/_ctypes/libffi_osx/include"));
preprocessor.PreprocessorDefines.Add("MACOSX");
var compiler = settings as C.ICommonCompilerSettings;
compiler.DisableWarnings.AddUnique("comment"); // Python-3.5.1/Modules/_ctypes/libffi_osx/include/x86-ffitarget.h:74:8: error: // comments are not allowed in this language [-Werror,-Wcomment]
compiler.DisableWarnings.AddUnique("newline-eof"); // Python-3.5.1/Modules/_ctypes/libffi_osx/include/x86-ffitarget.h:88:34: error: no newline at end of file [-Werror,-Wnewline-eof]
}
if (settings is VisualCCommon.ICommonCompilerSettings)
{
var preprocessor = settings as C.ICommonPreprocessorSettings;
preprocessor.IncludePaths.AddUnique(this.CreateTokenizedString("$(packagedir)/Modules/_ctypes/libffi_msvc"));
}
});
}
}
}
| |
// Copyright (C) Kirill Osenkov, www.osenkov.com
// Feel free to use and reuse in any projects.
// Please do not remove this comment.
using System;
using System.Collections.Generic;
using System.Drawing; // needed for System.Drawing.Color
using System.IO;
using System.Xml;
namespace GuiLabs.Utils
{
public interface ISupportMemento
{
Memento CreateSnapshot();
}
/// <summary>
/// Each Memento object corresponds to a single XML node in memory.
/// It can be serialized and deserialized into XML.
/// * NodeType corresponds to XML node tag name.
/// * Attributes corresponds to the XML node attributes
/// * Children corresponds to subnodes
/// </summary>
public class Memento
{
#region ctors
public Memento()
{
}
public Memento(XmlNode node)
: this()
{
ReadFromXmlNode(node);
}
#endregion
#region this
public string this[string attributeName]
{
get
{
return Get<string>(attributeName);
}
set
{
Attributes[attributeName] = value;
}
}
#endregion
#region NodeType
private string mNodeType;
/// <summary>
/// Tag name in the resulting XML
/// </summary>
public string NodeType
{
get
{
return mNodeType;
}
set
{
mNodeType = value;
}
}
#endregion
#region Attributes
private Dictionary<string, object> mAttributes = new Dictionary<string, object>(0);
/// <summary>
/// Attributes in the resulting XML node
/// </summary>
internal IDictionary<string, object> Attributes
{
get
{
return mAttributes;
}
}
#region Get / Put
public T Get<T>(string attributeName)
{
object val;
this.Attributes.TryGetValue(attributeName, out val);
T result = default(T);
if (typeof(T).IsEnum)
{
result = (T)Enum.Parse(typeof(T), val as string, true);
return result;
}
try
{
result = (T)val;
}
catch (Exception)
{
}
return result;
}
public void Put(string attributeName, Color colorValue)
{
if (colorValue != Color.Transparent)
{
this[attributeName] = colorValue.ToArgb().ToString();
}
}
public void Put(string attributeName, int intValue)
{
if (intValue != 0)
{
this[attributeName] = intValue.ToString();
}
}
public void Put(string attributeName, bool boolValue)
{
if (boolValue)
{
this[attributeName] = boolValue.ToString();
}
}
public int GetInt(string attributeName)
{
string str = this[attributeName];
if (string.IsNullOrEmpty(str))
{
return 0;
}
int val = 0;
int.TryParse(this[attributeName], out val);
return val;
}
public bool GetBool(string attributeName)
{
bool b = false;
string str = this[attributeName];
if (string.IsNullOrEmpty(str))
{
return false;
}
bool.TryParse(str, out b);
return b;
}
private static readonly int ColorTransparentArgb = Color.Transparent.ToArgb();
public Color GetColor(string attributeName)
{
string str = this[attributeName];
if (string.IsNullOrEmpty(str) || str == "-1")
{
return Color.Transparent;
}
int val = ColorTransparentArgb;
int.TryParse(str, out val);
return Color.FromArgb(val);
}
#endregion
#endregion
#region Children
public void Add(Memento child)
{
if (child != null)
{
Children.Add(child);
}
}
public void Add(ISupportMemento objectToSerialize)
{
if (objectToSerialize != null)
{
Add(objectToSerialize.CreateSnapshot());
}
}
public Memento FindChild(string name)
{
foreach (Memento child in this.Children)
{
if (child.NodeType == name)
{
return child;
}
}
return null;
}
private List<Memento> mChildren = new List<Memento>(0);
public ICollection<Memento> Children
{
get
{
return mChildren;
}
}
#endregion
#region Factory methods
public static Memento ReadFromString(string contents)
{
XmlDocument doc = new XmlDocument();
doc.Load(new StringReader(contents));
Memento result = new Memento(doc.DocumentElement);
return result;
}
public static Memento ReadFromFile(string fileName)
{
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
Memento result = new Memento();
result.ReadFromXmlNode(doc.DocumentElement);
return result;
}
#endregion
#region Read
public void ReadFromXmlNode(XmlNode node)
{
this.NodeType = node.Name;
if (node.Attributes != null)
{
foreach (XmlAttribute attr in node.Attributes)
{
Attributes.Add(attr.Name, attr.Value);
}
}
if (node.ChildNodes != null)
{
foreach (XmlNode child in node.ChildNodes)
{
Children.Add(new Memento(child));
}
}
}
#endregion
#region Write
public void SaveToFile(string fileName)
{
using (StreamWriter w = new StreamWriter(fileName))
{
using (XmlTextWriter writer = new XmlTextWriter(w))
{
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
WriteToXml(writer);
writer.WriteEndDocument();
}
}
}
public void WriteToXml(XmlTextWriter writer)
{
writer.WriteStartElement(NodeType);
foreach (KeyValuePair<string, object> pair in Attributes)
{
writer.WriteAttributeString(pair.Key, pair.Value.ToString());
}
foreach (Memento child in this.Children)
{
child.WriteToXml(writer);
}
writer.WriteEndElement();
}
public void Write(TextWriter writer)
{
using (XmlTextWriter x = new XmlTextWriter(writer))
{
x.Formatting = Formatting.Indented;
WriteToXml(x);
}
}
public string WriteToString()
{
using (StringWriter sw = new StringWriter())
{
Write(sw);
return sw.ToString();
}
}
#endregion
}
}
| |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Runtime.InteropServices;
namespace SharpDX.DirectWrite
{
public partial class TextAnalyzer
{
/// <summary>
/// Returns an interface for performing text analysis.
/// </summary>
/// <param name="factory">A reference to a DirectWrite factory <see cref="Factory"/></param>
/// <unmanaged>HRESULT IDWriteFactory::CreateTextAnalyzer([Out] IDWriteTextAnalyzer** textAnalyzer)</unmanaged>
public TextAnalyzer(Factory factory)
{
factory.CreateTextAnalyzer(this);
}
/// <summary>
/// Analyzes a text range for script boundaries, reading text attributes from the source and reporting the Unicode script ID to the sink callback {{SetScript}}.
/// </summary>
/// <param name="analysisSource">A reference to the source object to analyze.</param>
/// <param name="textPosition">The starting text position within the source object.</param>
/// <param name="textLength">The text length to analyze.</param>
/// <param name="analysisSink">A reference to the sink callback object that receives the text analysis.</param>
/// <returns>
/// If the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.
/// </returns>
/// <unmanaged>HRESULT IDWriteTextAnalyzer::AnalyzeScript([None] IDWriteTextAnalysisSource* analysisSource,[None] int textPosition,[None] int textLength,[None] IDWriteTextAnalysisSink* analysisSink)</unmanaged>
public void AnalyzeScript(TextAnalysisSource analysisSource, int textPosition, int textLength, TextAnalysisSink analysisSink)
{
AnalyzeScript__(TextAnalysisSourceShadow.ToIntPtr(analysisSource), textPosition, textLength, TextAnalysisSinkShadow.ToIntPtr(analysisSink));
}
/// <summary>
/// Analyzes a text range for script directionality, reading attributes from the source and reporting levels to the sink callback {{SetBidiLevel}}.
/// </summary>
/// <param name="analysisSource">A reference to a source object to analyze.</param>
/// <param name="textPosition">The starting text position within the source object.</param>
/// <param name="textLength">The text length to analyze.</param>
/// <param name="analysisSink">A reference to the sink callback object that receives the text analysis.</param>
/// <returns>
/// If the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.
/// </returns>
/// <unmanaged>HRESULT IDWriteTextAnalyzer::AnalyzeBidi([None] IDWriteTextAnalysisSource* analysisSource,[None] int textPosition,[None] int textLength,[None] IDWriteTextAnalysisSink* analysisSink)</unmanaged>
/// <remarks>
/// While the function can handle multiple paragraphs, the text range should not arbitrarily split the middle of paragraphs. Otherwise, the returned levels may be wrong, because the Bidi algorithm is meant to apply to the paragraph as a whole.
/// </remarks>
public void AnalyzeBidi(TextAnalysisSource analysisSource, int textPosition, int textLength, TextAnalysisSink analysisSink)
{
AnalyzeBidi__(TextAnalysisSourceShadow.ToIntPtr(analysisSource), textPosition, textLength, TextAnalysisSinkShadow.ToIntPtr(analysisSink));
}
/// <summary>
/// Analyzes a text range for spans where number substitution is applicable, reading attributes from the source and reporting substitutable ranges to the sink callback {{SetNumberSubstitution}}.
/// </summary>
/// <param name="analysisSource">The source object to analyze.</param>
/// <param name="textPosition">The starting position within the source object.</param>
/// <param name="textLength">The length to analyze.</param>
/// <param name="analysisSink">A reference to the sink callback object that receives the text analysis.</param>
/// <returns>
/// If the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.
/// </returns>
/// <unmanaged>HRESULT IDWriteTextAnalyzer::AnalyzeNumberSubstitution([None] IDWriteTextAnalysisSource* analysisSource,[None] int textPosition,[None] int textLength,[None] IDWriteTextAnalysisSink* analysisSink)</unmanaged>
/// <remarks>
/// Although the function can handle multiple ranges of differing number substitutions, the text ranges should not arbitrarily split the middle of numbers. Otherwise, it will treat the numbers separately and will not translate any intervening punctuation.
/// </remarks>
public void AnalyzeNumberSubstitution(TextAnalysisSource analysisSource, int textPosition, int textLength, TextAnalysisSink analysisSink)
{
AnalyzeNumberSubstitution__(TextAnalysisSourceShadow.ToIntPtr(analysisSource), textPosition, textLength, TextAnalysisSinkShadow.ToIntPtr(analysisSink));
}
/// <summary>
/// Analyzes a text range for potential breakpoint opportunities, reading attributes from the source and reporting breakpoint opportunities to the sink callback {{SetLineBreakpoints}}.
/// </summary>
/// <param name="analysisSource">A reference to the source object to analyze.</param>
/// <param name="textPosition">The starting text position within the source object.</param>
/// <param name="textLength">The text length to analyze.</param>
/// <param name="analysisSink">A reference to the sink callback object that receives the text analysis.</param>
/// <returns>
/// If the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.
/// </returns>
/// <unmanaged>HRESULT IDWriteTextAnalyzer::AnalyzeLineBreakpoints([None] IDWriteTextAnalysisSource* analysisSource,[None] int textPosition,[None] int textLength,[None] IDWriteTextAnalysisSink* analysisSink)</unmanaged>
/// <remarks>
/// Although the function can handle multiple paragraphs, the text range should not arbitrarily split the middle of paragraphs, unless the specified text span is considered a whole unit. Otherwise, the returned properties for the first and last characters will inappropriately allow breaks.
/// </remarks>
public void AnalyzeLineBreakpoints(TextAnalysisSource analysisSource, int textPosition, int textLength, TextAnalysisSink analysisSink)
{
AnalyzeLineBreakpoints__(TextAnalysisSourceShadow.ToIntPtr(analysisSource), textPosition, textLength, TextAnalysisSinkShadow.ToIntPtr(analysisSink));
}
/// <summary>
/// Gets the glyphs (TODO doc)
/// </summary>
/// <param name="textString">The text string.</param>
/// <param name="textLength">Length of the text.</param>
/// <param name="fontFace">The font face.</param>
/// <param name="isSideways">if set to <c>true</c> [is sideways].</param>
/// <param name="isRightToLeft">if set to <c>true</c> [is right to left].</param>
/// <param name="scriptAnalysis">The script analysis.</param>
/// <param name="localeName">Name of the locale.</param>
/// <param name="numberSubstitution">The number substitution.</param>
/// <param name="features">The features.</param>
/// <param name="featureRangeLengths">The feature range lengths.</param>
/// <param name="maxGlyphCount">The max glyph count.</param>
/// <param name="clusterMap">The cluster map.</param>
/// <param name="textProps">The text props.</param>
/// <param name="glyphIndices">The glyph indices.</param>
/// <param name="glyphProps">The glyph props.</param>
/// <param name="actualGlyphCount">The actual glyph count.</param>
/// <returns>
/// If the method succeeds, it returns <see cref="Result.Ok"/>.
/// </returns>
/// <unmanaged>HRESULT IDWriteTextAnalyzer::GetGlyphs([In, Buffer] const wchar_t* textString,[In] unsigned int textLength,[In] IDWriteFontFace* fontFace,[In] BOOL isSideways,[In] BOOL isRightToLeft,[In] const DWRITE_SCRIPT_ANALYSIS* scriptAnalysis,[In, Buffer, Optional] const wchar_t* localeName,[In, Optional] IDWriteNumberSubstitution* numberSubstitution,[In, Optional] const void** features,[In, Buffer, Optional] const unsigned int* featureRangeLengths,[In] unsigned int featureRanges,[In] unsigned int maxGlyphCount,[Out, Buffer] unsigned short* clusterMap,[Out, Buffer] DWRITE_SHAPING_TEXT_PROPERTIES* textProps,[Out, Buffer] unsigned short* glyphIndices,[Out, Buffer] DWRITE_SHAPING_GLYPH_PROPERTIES* glyphProps,[Out] unsigned int* actualGlyphCount)</unmanaged>
public void GetGlyphs(string textString, int textLength, SharpDX.DirectWrite.FontFace fontFace, bool isSideways, bool isRightToLeft, SharpDX.DirectWrite.ScriptAnalysis scriptAnalysis, string localeName, SharpDX.DirectWrite.NumberSubstitution numberSubstitution, FontFeature[][] features, int[] featureRangeLengths, int maxGlyphCount, short[] clusterMap, SharpDX.DirectWrite.ShapingTextProperties[] textProps, short[] glyphIndices, SharpDX.DirectWrite.ShapingGlyphProperties[] glyphProps, out int actualGlyphCount)
{
var pFeatures = AllocateFeatures(features);
try
{
GetGlyphs(
textString,
textLength,
fontFace,
isSideways,
isRightToLeft,
scriptAnalysis,
localeName,
numberSubstitution,
pFeatures,
featureRangeLengths,
featureRangeLengths == null ? 0 : featureRangeLengths.Length,
maxGlyphCount,
clusterMap,
textProps,
glyphIndices,
glyphProps,
out actualGlyphCount);
} finally
{
if (pFeatures != IntPtr.Zero) Marshal.FreeHGlobal(pFeatures);
}
}
/// <summary>
/// Gets the glyph placements.
/// </summary>
/// <param name="textString">The text string.</param>
/// <param name="clusterMap">The cluster map.</param>
/// <param name="textProps">The text props.</param>
/// <param name="textLength">Length of the text.</param>
/// <param name="glyphIndices">The glyph indices.</param>
/// <param name="glyphProps">The glyph props.</param>
/// <param name="glyphCount">The glyph count.</param>
/// <param name="fontFace">The font face.</param>
/// <param name="fontEmSize">Size of the font in ems.</param>
/// <param name="isSideways">if set to <c>true</c> [is sideways].</param>
/// <param name="isRightToLeft">if set to <c>true</c> [is right to left].</param>
/// <param name="scriptAnalysis">The script analysis.</param>
/// <param name="localeName">Name of the locale.</param>
/// <param name="features">The features.</param>
/// <param name="featureRangeLengths">The feature range lengths.</param>
/// <param name="glyphAdvances">The glyph advances.</param>
/// <param name="glyphOffsets">The glyph offsets.</param>
/// <returns>
/// If the method succeeds, it returns <see cref="Result.Ok"/>.
/// </returns>
/// <unmanaged>HRESULT IDWriteTextAnalyzer::GetGlyphPlacements([In, Buffer] const wchar_t* textString,[In, Buffer] const unsigned short* clusterMap,[In, Buffer] DWRITE_SHAPING_TEXT_PROPERTIES* textProps,[In] unsigned int textLength,[In, Buffer] const unsigned short* glyphIndices,[In, Buffer] const DWRITE_SHAPING_GLYPH_PROPERTIES* glyphProps,[In] unsigned int glyphCount,[In] IDWriteFontFace* fontFace,[In] float fontEmSize,[In] BOOL isSideways,[In] BOOL isRightToLeft,[In] const DWRITE_SCRIPT_ANALYSIS* scriptAnalysis,[In, Buffer, Optional] const wchar_t* localeName,[In, Optional] const void** features,[In, Buffer, Optional] const unsigned int* featureRangeLengths,[In] unsigned int featureRanges,[Out, Buffer] float* glyphAdvances,[Out, Buffer] DWRITE_GLYPH_OFFSET* glyphOffsets)</unmanaged>
public void GetGlyphPlacements(string textString, short[] clusterMap, SharpDX.DirectWrite.ShapingTextProperties[] textProps, int textLength, short[] glyphIndices, SharpDX.DirectWrite.ShapingGlyphProperties[] glyphProps, int glyphCount, SharpDX.DirectWrite.FontFace fontFace, float fontEmSize, bool isSideways, bool isRightToLeft, SharpDX.DirectWrite.ScriptAnalysis scriptAnalysis, string localeName, FontFeature[][] features, int[] featureRangeLengths, float[] glyphAdvances, SharpDX.DirectWrite.GlyphOffset[] glyphOffsets)
{
var pFeatures = AllocateFeatures(features);
try
{
GetGlyphPlacements(
textString,
clusterMap,
textProps,
textLength,
glyphIndices,
glyphProps,
glyphCount,
fontFace,
fontEmSize,
isSideways,
isRightToLeft,
scriptAnalysis,
localeName,
pFeatures,
featureRangeLengths,
featureRangeLengths == null ? 0 : featureRangeLengths.Length,
glyphAdvances,
glyphOffsets
);
}
finally
{
if (pFeatures != IntPtr.Zero) Marshal.FreeHGlobal(pFeatures);
}
}
/// <summary>
/// Gets the GDI compatible glyph placements.
/// </summary>
/// <param name="textString">The text string.</param>
/// <param name="clusterMap">The cluster map.</param>
/// <param name="textProps">The text props.</param>
/// <param name="textLength">Length of the text.</param>
/// <param name="glyphIndices">The glyph indices.</param>
/// <param name="glyphProps">The glyph props.</param>
/// <param name="glyphCount">The glyph count.</param>
/// <param name="fontFace">The font face.</param>
/// <param name="fontEmSize">Size of the font em.</param>
/// <param name="pixelsPerDip">The pixels per dip.</param>
/// <param name="transform">The transform.</param>
/// <param name="useGdiNatural">if set to <c>true</c> [use GDI natural].</param>
/// <param name="isSideways">if set to <c>true</c> [is sideways].</param>
/// <param name="isRightToLeft">if set to <c>true</c> [is right to left].</param>
/// <param name="scriptAnalysis">The script analysis.</param>
/// <param name="localeName">Name of the locale.</param>
/// <param name="features">The features.</param>
/// <param name="featureRangeLengths">The feature range lengths.</param>
/// <param name="glyphAdvances">The glyph advances.</param>
/// <param name="glyphOffsets">The glyph offsets.</param>
/// <returns>
/// If the method succeeds, it returns <see cref="Result.Ok"/>.
/// </returns>
/// <unmanaged>HRESULT IDWriteTextAnalyzer::GetGdiCompatibleGlyphPlacements([In, Buffer] const wchar_t* textString,[In, Buffer] const unsigned short* clusterMap,[In, Buffer] DWRITE_SHAPING_TEXT_PROPERTIES* textProps,[In] unsigned int textLength,[In, Buffer] const unsigned short* glyphIndices,[In, Buffer] const DWRITE_SHAPING_GLYPH_PROPERTIES* glyphProps,[In] unsigned int glyphCount,[In] IDWriteFontFace* fontFace,[In] float fontEmSize,[In] float pixelsPerDip,[In, Optional] const DWRITE_MATRIX* transform,[In] BOOL useGdiNatural,[In] BOOL isSideways,[In] BOOL isRightToLeft,[In] const DWRITE_SCRIPT_ANALYSIS* scriptAnalysis,[In, Buffer, Optional] const wchar_t* localeName,[In, Optional] const void** features,[In, Buffer, Optional] const unsigned int* featureRangeLengths,[In] unsigned int featureRanges,[Out, Buffer] float* glyphAdvances,[Out, Buffer] DWRITE_GLYPH_OFFSET* glyphOffsets)</unmanaged>
public void GetGdiCompatibleGlyphPlacements(string textString, short[] clusterMap, SharpDX.DirectWrite.ShapingTextProperties[] textProps, int textLength, short[] glyphIndices, SharpDX.DirectWrite.ShapingGlyphProperties[] glyphProps, int glyphCount, SharpDX.DirectWrite.FontFace fontFace, float fontEmSize, float pixelsPerDip, SharpDX.DirectWrite.Matrix? transform, bool useGdiNatural, bool isSideways, bool isRightToLeft, SharpDX.DirectWrite.ScriptAnalysis scriptAnalysis, string localeName, FontFeature[][] features, int[] featureRangeLengths, float[] glyphAdvances, SharpDX.DirectWrite.GlyphOffset[] glyphOffsets)
{
var pFeatures = AllocateFeatures(features);
try
{
GetGdiCompatibleGlyphPlacements(
textString,
clusterMap,
textProps,
textLength,
glyphIndices,
glyphProps,
glyphCount,
fontFace,
fontEmSize,
pixelsPerDip,
transform,
useGdiNatural,
isSideways,
isRightToLeft,
scriptAnalysis,
localeName,
pFeatures,
featureRangeLengths,
featureRangeLengths == null ? 0 : featureRangeLengths.Length,
glyphAdvances,
glyphOffsets
);
}
finally
{
if (pFeatures != IntPtr.Zero) Marshal.FreeHGlobal(pFeatures);
}
}
/// <summary>
/// Allocates the features from the jagged array..
/// </summary>
/// <param name="features">The features.</param>
/// <returns>A pointer to the allocated native features or 0 if features is null or empty.</returns>
private static IntPtr AllocateFeatures(FontFeature[][] features)
{
unsafe
{
var pFeatures = (byte*)0;
if (features != null && features.Length > 0)
{
// Calculate the total size of the buffer to allocate:
// (0) (1) (2)
// -------------------------------------------------------------
// | array | TypographicFeatures || FontFeatures ||
// | ptr to (1) | | | || ||
// | | ptr to FontFeatures || ||
// -------------------------------------------------------------
// Offset in bytes to (1)
int offsetToTypographicFeatures = sizeof(IntPtr) * features.Length;
// Add offset (1) and Size in bytes to (1)
int calcSize = offsetToTypographicFeatures + sizeof(TypographicFeatures) * features.Length;
// Calculate size (2)
foreach (var fontFeature in features)
{
if (fontFeature == null)
throw new ArgumentNullException("FontFeature[] inside features array cannot be null", "features");
// calcSize += typographicFeatures.Length * sizeof(FontFeature)
calcSize += sizeof(FontFeature) * fontFeature.Length;
}
// Allocate the whole buffer
pFeatures = (byte*)Marshal.AllocHGlobal(calcSize);
// Pointer to (1)
var pTypographicFeatures = (TypographicFeatures*)(pFeatures + offsetToTypographicFeatures);
// Pointer to (2)
var pFontFeatures = (FontFeature*)(pTypographicFeatures + features.Length);
// Iterate on features and copy them to (2)
for (int i = 0; i < features.Length; i++)
{
// Write array pointers in (0)
((void**)pFeatures)[i] = pTypographicFeatures;
var featureSet = features[i];
// Write TypographicFeatures in (1)
pTypographicFeatures->Features = (IntPtr)pFontFeatures;
pTypographicFeatures->FeatureCount = featureSet.Length;
pTypographicFeatures++;
// Write FontFeatures in (2)
for (int j = 0; j < featureSet.Length; j++)
{
*pFontFeatures = featureSet[j];
pFontFeatures++;
}
}
}
return (IntPtr)pFeatures;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Chill;
using FluentAssertions.Equivalency;
using Xunit;
using Xunit.Sdk;
namespace FluentAssertions.Specs
{
/// <summary>
/// Test Class containing specs over the extensibility points of ShouldBeEquivalentTo
/// </summary>
public class ExtensibilityRelatedEquivalencySpecs
{
#region Selection Rules
[Fact]
public void When_a_selection_rule_is_added_it_should_be_evaluated_after_all_existing_rules()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
NameId = "123",
SomeValue = "hello"
};
var expected = new
{
SomeValue = "hello"
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(
expected,
options => options.Using(new ExcludeForeignKeysSelectionRule()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[Fact]
public void When_a_selection_rule_is_added_it_should_appear_in_the_exception_message()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
Name = "123",
};
var expected = new
{
SomeValue = "hello"
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(
expected,
options => options.Using(new ExcludeForeignKeysSelectionRule()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<XunitException>()
.WithMessage(string.Format("*{0}*", typeof(ExcludeForeignKeysSelectionRule).Name));
}
internal class ExcludeForeignKeysSelectionRule : IMemberSelectionRule
{
public bool OverridesStandardIncludeRules
{
get { return false; }
}
public IEnumerable<SelectedMemberInfo> SelectMembers(IEnumerable<SelectedMemberInfo> selectedMembers, ISubjectInfo context, IEquivalencyAssertionOptions config)
{
return selectedMembers.Where(pi => !pi.Name.EndsWith("Id")).ToArray();
}
bool IMemberSelectionRule.IncludesMembers
{
get { return OverridesStandardIncludeRules; }
}
}
#endregion
#region Matching Rules
[Fact]
public void When_a_matching_rule_is_added_it_should_preceed_all_existing_rules()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
NameId = "123",
SomeValue = "hello"
};
var expected = new
{
Name = "123",
SomeValue = "hello"
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(
expected,
options => options.Using(new ForeignKeyMatchingRule()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[Fact]
public void When_a_matching_rule_is_added_it_should_appear_in_the_exception_message()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
NameId = "123",
SomeValue = "hello"
};
var expected = new
{
Name = "1234",
SomeValue = "hello"
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(
expected,
options => options.Using(new ForeignKeyMatchingRule()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<XunitException>()
.WithMessage(string.Format("*{0}*", typeof(ForeignKeyMatchingRule).Name));
}
internal class ForeignKeyMatchingRule : IMemberMatchingRule
{
public SelectedMemberInfo Match(SelectedMemberInfo subjectMember, object expectation, string memberPath, IEquivalencyAssertionOptions config)
{
string name = subjectMember.Name;
if (name.EndsWith("Id"))
{
name = name.Replace("Id", "");
}
#if !WINRT && !WINDOWS_PHONE_APP
return SelectedMemberInfo.Create(expectation.GetType().GetProperty(name));
#else
return SelectedMemberInfo.Create(expectation.GetType()
.GetRuntimeProperty(name));
#endif
}
}
#endregion
#region Assertion Rules
[Fact]
public void When_equally_named_properties_are_type_incompatible_and_assertion_rule_exists_it_should_not_throw()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
Type = typeof(String),
};
var other = new
{
Type = typeof(String).AssemblyQualifiedName,
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(other,
o => o
.Using<object>(c => ((Type)c.Subject).AssemblyQualifiedName.Should().Be((string)c.Expectation))
.When(si => si.SelectedMemberPath == "Type"));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[Fact]
public void When_an_assertion_is_overridden_for_a_predicate_it_should_use_the_provided_action()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
Date = 14.July(2012).At(12, 59, 59)
};
var expectation = new
{
Date = 14.July(2012).At(13, 0, 0)
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(expectation, options => options
.Using<DateTime>(ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation, 1000))
.When(info => info.SelectedMemberPath.EndsWith("Date")));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[Fact]
public void When_an_assertion_is_overridden_for_all_types_it_should_use_the_provided_action_for_all_properties()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
Date = 21.July(2012).At(11, 8, 59),
Nested = new
{
NestedDate = 14.July(2012).At(12, 59, 59)
}
};
var expectation = new
{
Date = 21.July(2012).At(11, 9, 0),
Nested = new
{
NestedDate = 14.July(2012).At(13, 0, 0)
}
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(expectation, options =>
options
.Using<DateTime>(ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation, 1000))
.WhenTypeIs<DateTime>());
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[Fact]
public void When_a_nullable_property_is_overriden_with_a_custom_asserrtion_it_should_use_it()
{
var actual = new SimpleWithNullable
{
nullableIntegerProperty = 1,
strProperty = "I haz a string!"
};
var expected = new SimpleWithNullable
{
strProperty = "I haz a string!"
};
actual.ShouldBeEquivalentTo(expected,
opt => opt.Using<Int64>(c => c.Subject.Should().BeInRange(0, 10)).WhenTypeIs<Int64>());
}
internal class SimpleWithNullable
{
public Int64? nullableIntegerProperty { get; set; }
public string strProperty { get; set; }
}
[Fact]
public void When_an_assertion_rule_is_added_it_should_preceed_all_existing_rules()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
Created = 8.July(2012).At(22, 9)
};
var expected = new
{
Created = 8.July(2012).At(22, 10)
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(
expected,
options => options.Using(new RelaxingDateTimeAssertionRule()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[Fact]
public void When_an_assertion_rule_is_added_it_appear_in_the_exception_message()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = 8.July(2012).At(22, 9);
var expected = 8.July(2012).At(22, 10);
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(
expected,
options => options.Using(new RelaxingDateTimeAssertionRule()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<XunitException>()
.WithMessage(string.Format("*{0}*", typeof(RelaxingDateTimeAssertionRule).Name));
}
[Fact]
public void When_an_assertion_rule_matches_the_root_object_the_assertion_rule_should_not_apply_to_the_root_object()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = 8.July(2012).At(22, 9);
var expected = 8.July(2012).At(22, 10);
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(
expected,
options => options.Using(new RelaxingDateTimeAssertionRule()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<XunitException>();
}
[Fact]
public void When_multiple_asertion_rules_are_added__they_should_be_executed_from_right_to_left()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
Created = 8.July(2012).At(22, 9)
};
var expected = new
{
Created = 8.July(2012).At(22, 10)
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act =
() =>
subject.ShouldBeEquivalentTo(expected,
opts => opts.Using(new AlwaysFailAssertionRule()).Using(new RelaxingDateTimeAssertionRule()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow(
"a different assertion rule should handle the comparision before the exception throwing assertion rule is hit");
}
[Fact]
public void When_an_assertion_rule_added_with_the_fluent_api_matches_the_root_object_the_assertion_rule_should_not_apply_to_the_root_object()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = 8.July(2012).At(22, 9);
var expected = 8.July(2012).At(22, 10);
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act =
() =>
subject.ShouldBeEquivalentTo(
expected,
options =>
options.Using<DateTime>(
context => context.Subject.Should().BeCloseTo(context.Expectation, 1000 * 60))
.WhenTypeIs<DateTime>());
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<XunitException>();
}
internal class AlwaysFailAssertionRule : IAssertionRule
{
public bool AssertEquality(IEquivalencyValidationContext context)
{
throw new Exception("Failed");
}
}
internal class RelaxingDateTimeAssertionRule : IAssertionRule
{
public bool AssertEquality(IEquivalencyValidationContext context)
{
if (context.Subject is DateTime)
{
((DateTime)context.Subject).Should().BeCloseTo((DateTime)context.Expectation, 1000 * 60);
return true;
}
return false;
}
}
[Fact]
public void When_multiple_asertion_rules_are_added_with_the_fluent_api_they_should_be_executed_from_right_to_left()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new ClassWithOnlyAProperty();
var expected = new ClassWithOnlyAProperty();
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act =
() =>
subject.ShouldBeEquivalentTo(expected,
opts =>
opts.Using<object>(context => { throw new Exception(); })
.When(s => true)
.Using<object>(context => { })
.When(s => true));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow(
"a different assertion rule should handle the comparision before the exception throwing assertion rule is hit");
}
#endregion
#region Equivalency Steps
[Fact]
public void When_an_equivalency_step_handles_the_comparison_later_equivalency_steps_should_not_be_ran()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new ClassWithOnlyAProperty();
var expected = new ClassWithOnlyAProperty();
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act =
() =>
subject.ShouldBeEquivalentTo(expected,
opts =>
opts.Using(new AlwayHandleEquivalencyStep())
.Using(new ThrowExceptionEquivalencyStep<InvalidOperationException>()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[Fact]
public void When_a_user_equivalency_step_is_registered_it_should_run_before_the_built_in_steps()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var actual = new
{
Property = 123
};
var expected = new
{
Property = "123"
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => actual.ShouldBeEquivalentTo(expected, options => options
.Using(new EqualityEquivalencyStep()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<XunitException>()
.WithMessage("Expected*123*123*");
}
[Fact]
public void When_an_equivalency_does_not_handle_the_comparison_later_equivalency_steps_should_stil_be_ran()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new ClassWithOnlyAProperty();
var expected = new ClassWithOnlyAProperty();
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act =
() =>
subject.ShouldBeEquivalentTo(expected,
opts =>
opts.Using(new NeverHandleEquivalencyStep())
.Using(new ThrowExceptionEquivalencyStep<InvalidOperationException>()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<InvalidOperationException>();
}
[Fact]
public void When_multiple_equivalency_steps_are_added_they_should_be_executed_in_registration_order()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new ClassWithOnlyAProperty();
var expected = new ClassWithOnlyAProperty();
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act =
() =>
subject.ShouldBeEquivalentTo(expected,
opts =>
opts.Using(new ThrowExceptionEquivalencyStep<NotSupportedException>())
.Using(new ThrowExceptionEquivalencyStep<InvalidOperationException>()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<NotSupportedException>();
}
internal class ThrowExceptionEquivalencyStep<TException> : CanHandleAnythingEquivalencyStep where TException : Exception, new()
{
public override bool Handle(IEquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config)
{
throw new TException();
}
}
internal class AlwayHandleEquivalencyStep : CanHandleAnythingEquivalencyStep
{
public override bool Handle(IEquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config)
{
return true;
}
}
internal class NeverHandleEquivalencyStep : CanHandleAnythingEquivalencyStep
{
public override bool Handle(IEquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config)
{
return false;
}
}
private class EqualityEquivalencyStep : CanHandleAnythingEquivalencyStep
{
public override bool Handle(IEquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config)
{
context.Subject.Should().Be(context.Expectation, context.Because, context.BecauseArgs);
return true;
}
}
internal class DoEquivalencyStep : CanHandleAnythingEquivalencyStep
{
private readonly Action doAction;
public DoEquivalencyStep(Action doAction)
{
this.doAction = doAction;
}
public override bool Handle(IEquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config)
{
doAction();
return true;
}
}
internal abstract class CanHandleAnythingEquivalencyStep : IEquivalencyStep
{
public bool CanHandle(IEquivalencyValidationContext context, IEquivalencyAssertionOptions config)
{
return true;
}
public abstract bool Handle(IEquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config);
}
#endregion
}
}
| |
using System;
using ChainUtils.BouncyCastle.Crypto.Parameters;
namespace ChainUtils.BouncyCastle.Crypto.Modes
{
/**
* implements a Cipher-FeedBack (CFB) mode on top of a simple cipher.
*/
public class CfbBlockCipher
: IBlockCipher
{
private byte[] IV;
private byte[] cfbV;
private byte[] cfbOutV;
private bool encrypting;
private readonly int blockSize;
private readonly IBlockCipher cipher;
/**
* Basic constructor.
*
* @param cipher the block cipher to be used as the basis of the
* feedback mode.
* @param blockSize the block size in bits (note: a multiple of 8)
*/
public CfbBlockCipher(
IBlockCipher cipher,
int bitBlockSize)
{
this.cipher = cipher;
blockSize = bitBlockSize / 8;
IV = new byte[cipher.GetBlockSize()];
cfbV = new byte[cipher.GetBlockSize()];
cfbOutV = new byte[cipher.GetBlockSize()];
}
/**
* return the underlying block cipher that we are wrapping.
*
* @return the underlying block cipher that we are wrapping.
*/
public IBlockCipher GetUnderlyingCipher()
{
return cipher;
}
/**
* Initialise the cipher and, possibly, the initialisation vector (IV).
* If an IV isn't passed as part of the parameter, the IV will be all zeros.
* An IV which is too short is handled in FIPS compliant fashion.
*
* @param forEncryption if true the cipher is initialised for
* encryption, if false for decryption.
* @param param the key and other data required by the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
encrypting = forEncryption;
if (parameters is ParametersWithIV)
{
var ivParam = (ParametersWithIV) parameters;
var iv = ivParam.GetIV();
var diff = IV.Length - iv.Length;
Array.Copy(iv, 0, IV, diff, iv.Length);
Array.Clear(IV, 0, diff);
parameters = ivParam.Parameters;
}
Reset();
// if it's null, key is to be reused.
if (parameters != null)
{
cipher.Init(true, parameters);
}
}
/**
* return the algorithm name and mode.
*
* @return the name of the underlying algorithm followed by "/CFB"
* and the block size in bits.
*/
public string AlgorithmName
{
get { return cipher.AlgorithmName + "/CFB" + (blockSize * 8); }
}
public bool IsPartialBlockOkay
{
get { return true; }
}
/**
* return the block size we are operating at.
*
* @return the block size we are operating at (in bytes).
*/
public int GetBlockSize()
{
return blockSize;
}
/**
* Process one block of input from the array in and write it to
* the out array.
*
* @param in the array containing the input data.
* @param inOff offset into the in array the data starts at.
* @param out the array the output data will be copied into.
* @param outOff the offset into the out array the output will start at.
* @exception DataLengthException if there isn't enough data in in, or
* space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
* @return the number of bytes processed and produced.
*/
public int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
return (encrypting)
? EncryptBlock(input, inOff, output, outOff)
: DecryptBlock(input, inOff, output, outOff);
}
/**
* Do the appropriate processing for CFB mode encryption.
*
* @param in the array containing the data to be encrypted.
* @param inOff offset into the in array the data starts at.
* @param out the array the encrypted data will be copied into.
* @param outOff the offset into the out array the output will start at.
* @exception DataLengthException if there isn't enough data in in, or
* space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
* @return the number of bytes processed and produced.
*/
public int EncryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
if ((inOff + blockSize) > input.Length)
{
throw new DataLengthException("input buffer too short");
}
if ((outOff + blockSize) > outBytes.Length)
{
throw new DataLengthException("output buffer too short");
}
cipher.ProcessBlock(cfbV, 0, cfbOutV, 0);
//
// XOR the cfbV with the plaintext producing the ciphertext
//
for (var i = 0; i < blockSize; i++)
{
outBytes[outOff + i] = (byte)(cfbOutV[i] ^ input[inOff + i]);
}
//
// change over the input block.
//
Array.Copy(cfbV, blockSize, cfbV, 0, cfbV.Length - blockSize);
Array.Copy(outBytes, outOff, cfbV, cfbV.Length - blockSize, blockSize);
return blockSize;
}
/**
* Do the appropriate processing for CFB mode decryption.
*
* @param in the array containing the data to be decrypted.
* @param inOff offset into the in array the data starts at.
* @param out the array the encrypted data will be copied into.
* @param outOff the offset into the out array the output will start at.
* @exception DataLengthException if there isn't enough data in in, or
* space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
* @return the number of bytes processed and produced.
*/
public int DecryptBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
if ((inOff + blockSize) > input.Length)
{
throw new DataLengthException("input buffer too short");
}
if ((outOff + blockSize) > outBytes.Length)
{
throw new DataLengthException("output buffer too short");
}
cipher.ProcessBlock(cfbV, 0, cfbOutV, 0);
//
// change over the input block.
//
Array.Copy(cfbV, blockSize, cfbV, 0, cfbV.Length - blockSize);
Array.Copy(input, inOff, cfbV, cfbV.Length - blockSize, blockSize);
//
// XOR the cfbV with the ciphertext producing the plaintext
//
for (var i = 0; i < blockSize; i++)
{
outBytes[outOff + i] = (byte)(cfbOutV[i] ^ input[inOff + i]);
}
return blockSize;
}
/**
* reset the chaining vector back to the IV and reset the underlying
* cipher.
*/
public void Reset()
{
Array.Copy(IV, 0, cfbV, 0, IV.Length);
cipher.Reset();
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Activities.Validation
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime;
using System.Text;
using System.Threading;
using System.Linq;
public static class ActivityValidationServices
{
internal static readonly ReadOnlyCollection<Activity> EmptyChildren = new ReadOnlyCollection<Activity>(new Activity[0]);
static ValidationSettings defaultSettings = new ValidationSettings();
internal static ReadOnlyCollection<ValidationError> EmptyValidationErrors = new ReadOnlyCollection<ValidationError>(new List<ValidationError>(0));
public static ValidationResults Validate(Activity toValidate)
{
return Validate(toValidate, defaultSettings);
}
public static ValidationResults Validate(Activity toValidate, ValidationSettings settings)
{
if (toValidate == null)
{
throw FxTrace.Exception.ArgumentNull("toValidate");
}
if (settings == null)
{
throw FxTrace.Exception.ArgumentNull("settings");
}
if (toValidate.HasBeenAssociatedWithAnInstance)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.RootActivityAlreadyAssociatedWithInstance(toValidate.DisplayName)));
}
if (settings.PrepareForRuntime && (settings.SingleLevel || settings.SkipValidatingRootConfiguration || settings.OnlyUseAdditionalConstraints))
{
throw FxTrace.Exception.Argument("settings", SR.InvalidPrepareForRuntimeValidationSettings);
}
InternalActivityValidationServices validator = new InternalActivityValidationServices(settings, toValidate);
return validator.InternalValidate();
}
public static Activity Resolve(Activity root, string id)
{
return WorkflowInspectionServices.Resolve(root, id);
}
internal static void ThrowIfViolationsExist(IList<ValidationError> validationErrors, ExceptionReason reason = ExceptionReason.InvalidTree)
{
Exception exception = CreateExceptionFromValidationErrors(validationErrors, reason);
if (exception != null)
{
throw FxTrace.Exception.AsError(exception);
}
}
static Exception CreateExceptionFromValidationErrors(IList<ValidationError> validationErrors, ExceptionReason reason)
{
if (validationErrors != null && validationErrors.Count > 0)
{
string exceptionString = GenerateExceptionString(validationErrors, reason);
if (exceptionString != null)
{
return new InvalidWorkflowException(exceptionString);
}
else
{
return null;
}
}
else
{
return null;
}
}
internal static List<Activity> GetChildren(ActivityUtilities.ChildActivity root, ActivityUtilities.ActivityCallStack parentChain, ProcessActivityTreeOptions options)
{
ActivityUtilities.FinishCachingSubtree(root, parentChain, options);
List<Activity> listOfChildren = new List<Activity>();
foreach (Activity activity in WorkflowInspectionServices.GetActivities(root.Activity))
{
listOfChildren.Add(activity);
}
int toProcessIndex = 0;
while (toProcessIndex < listOfChildren.Count)
{
foreach (Activity activity in WorkflowInspectionServices.GetActivities(listOfChildren[toProcessIndex]))
{
listOfChildren.Add(activity);
}
toProcessIndex++;
}
return listOfChildren;
}
internal static void ValidateRootInputs(Activity rootActivity, IDictionary<string, object> inputs)
{
IList<ValidationError> validationErrors = null;
ValidationHelper.ValidateArguments(rootActivity, rootActivity.EquivalenceInfo, rootActivity.OverloadGroups, rootActivity.RequiredArgumentsNotInOverloadGroups, inputs, ref validationErrors);
// Validate if there are any extra arguments passed in the input dictionary
if (inputs != null)
{
List<string> unusedArguments = null;
IEnumerable<RuntimeArgument> arguments = rootActivity.RuntimeArguments.Where((a) => ArgumentDirectionHelper.IsIn(a.Direction));
foreach (string key in inputs.Keys)
{
bool found = false;
foreach (RuntimeArgument argument in arguments)
{
if (argument.Name == key)
{
found = true;
// Validate if the input argument type matches the expected argument type.
object inputArgumentValue = null;
if (inputs.TryGetValue(key, out inputArgumentValue))
{
if (!TypeHelper.AreTypesCompatible(inputArgumentValue, argument.Type))
{
ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.InputParametersTypeMismatch(argument.Type, argument.Name), rootActivity));
}
}
// The ValidateArguments will validate Required in-args and hence not duplicating that validation if the key is not found.
break;
}
}
if (!found)
{
if (unusedArguments == null)
{
unusedArguments = new List<string>();
}
unusedArguments.Add(key);
}
}
if (unusedArguments != null)
{
ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.UnusedInputArguments(unusedArguments.AsCommaSeparatedValues()), rootActivity));
}
}
if (validationErrors != null && validationErrors.Count > 0)
{
string parameterName = "rootArgumentValues";
ExceptionReason reason = ExceptionReason.InvalidNonNullInputs;
if (inputs == null)
{
parameterName = "program";
reason = ExceptionReason.InvalidNullInputs;
}
string exceptionString = GenerateExceptionString(validationErrors, reason);
if (exceptionString != null)
{
throw FxTrace.Exception.Argument(parameterName, exceptionString);
}
}
}
internal static void ValidateArguments(Activity activity, bool isRoot, ref IList<ValidationError> validationErrors)
{
Fx.Assert(activity != null, "Activity to validate should not be null.");
Dictionary<string, List<RuntimeArgument>> overloadGroups;
List<RuntimeArgument> requiredArgumentsNotInOverloadGroups;
ValidationHelper.OverloadGroupEquivalenceInfo equivalenceInfo;
if (ValidationHelper.GatherAndValidateOverloads(activity, out overloadGroups, out requiredArgumentsNotInOverloadGroups, out equivalenceInfo, ref validationErrors))
{
// If we're not the root and the overload groups are valid
// then we validate the arguments
if (!isRoot)
{
ValidationHelper.ValidateArguments(activity, equivalenceInfo, overloadGroups, requiredArgumentsNotInOverloadGroups, null, ref validationErrors);
}
}
// If we are the root, regardless of whether the groups are
// valid or not, we cache the group information
if (isRoot)
{
activity.OverloadGroups = overloadGroups;
activity.RequiredArgumentsNotInOverloadGroups = requiredArgumentsNotInOverloadGroups;
activity.EquivalenceInfo = equivalenceInfo;
}
}
static string GenerateExceptionString(IList<ValidationError> validationErrors, ExceptionReason reason)
{
// 4096 is an arbitrary constant. Currently clipped by character count (not bytes).
const int maxExceptionStringSize = 4096;
StringBuilder exceptionMessageBuilder = null;
for (int i = 0; i < validationErrors.Count; i++)
{
ValidationError validationError = validationErrors[i];
if (!validationError.IsWarning)
{
// create the common exception string
if (exceptionMessageBuilder == null)
{
exceptionMessageBuilder = new StringBuilder();
switch (reason)
{
case ExceptionReason.InvalidTree:
exceptionMessageBuilder.Append(SR.ErrorsEncounteredWhileProcessingTree);
break;
case ExceptionReason.InvalidNonNullInputs:
exceptionMessageBuilder.Append(SR.RootArgumentViolationsFound);
break;
case ExceptionReason.InvalidNullInputs:
exceptionMessageBuilder.Append(SR.RootArgumentViolationsFoundNoInputs);
break;
}
}
string activityName = null;
if (validationError.Source != null)
{
activityName = validationError.Source.DisplayName;
}
else
{
activityName = "<UnknownActivity>";
}
exceptionMessageBuilder.AppendLine();
exceptionMessageBuilder.Append(string.Format(SR.Culture, "'{0}': {1}", activityName, validationError.Message));
if (exceptionMessageBuilder.Length > maxExceptionStringSize)
{
break;
}
}
}
string exceptionString = null;
if (exceptionMessageBuilder != null)
{
exceptionString = exceptionMessageBuilder.ToString();
if (exceptionString.Length > maxExceptionStringSize)
{
string snipNotification = SR.TooManyViolationsForExceptionMessage;
exceptionString = exceptionString.Substring(0, maxExceptionStringSize - snipNotification.Length);
exceptionString += snipNotification;
}
}
return exceptionString;
}
static internal string GenerateValidationErrorPrefix(Activity toValidate, ActivityUtilities.ActivityCallStack parentChain, ProcessActivityTreeOptions options, out Activity source)
{
bool parentVisible = true;
string prefix = "";
source = toValidate;
// Processing for implementation of activity
// during build time
if (options.SkipRootConfigurationValidation)
{
// Check if the activity is a implementation child
if (toValidate.MemberOf.Parent != null)
{
// Check if activity is an immediate implementation child
// of x:class activity. This means that the activity is
// being designed and hence we do not want to add the
// prefix at build time
if (toValidate.MemberOf.Parent.Parent == null)
{
prefix = "";
source = toValidate;
}
else
{
// This means the activity is a child of immediate implementation child
// of x:class activity which means the activity is not visible.
// The source points to the first visible parent activity in the
// parent chain.
while (source.MemberOf.Parent.Parent != null)
{
source = source.Parent;
}
prefix = SR.ValidationErrorPrefixForHiddenActivity(source);
}
return prefix;
}
}
// Find out if any of the parents of the activity are not publicly visible
for (int i = 0; i < parentChain.Count; i++)
{
if (parentChain[i].Activity.MemberOf.Parent != null)
{
parentVisible = false;
break;
}
}
// Figure out the source of validation error:
// - For hidden activity - source will be closest visible public parent
// - For visible activity - source will be the activity itself
// In current design an activity is visible only if it is in the root id space.
// In future, if we provide a knob for the user to specify the
// id spaces that are visible, then this check needs to be changed
// to iterate over the parentChain and find the closest parent activity that
// is in the visible id spaces.
while (source.MemberOf.Parent != null)
{
source = source.Parent;
}
if (toValidate.MemberOf.Parent != null)
{
// Activity itself is hidden
prefix = SR.ValidationErrorPrefixForHiddenActivity(source);
}
else
{
if (!parentVisible)
{
// Activity itself is public but has a private parent
prefix = SR.ValidationErrorPrefixForPublicActivityWithHiddenParent(source.Parent, source);
}
}
return prefix;
}
internal static void RunConstraints(ActivityUtilities.ChildActivity childActivity, ActivityUtilities.ActivityCallStack parentChain, IList<Constraint> constraints, ProcessActivityTreeOptions options, bool suppressGetChildrenViolations, ref IList<ValidationError> validationErrors)
{
if (constraints != null)
{
Activity toValidate = childActivity.Activity;
LocationReferenceEnvironment environment = toValidate.GetParentEnvironment();
Dictionary<string, object> inputDictionary = new Dictionary<string, object>(2);
for (int constraintIndex = 0; constraintIndex < constraints.Count; constraintIndex++)
{
Constraint constraint = constraints[constraintIndex];
// there may be null entries here
if (constraint == null)
{
continue;
}
inputDictionary[Constraint.ToValidateArgumentName] = toValidate;
ValidationContext validationContext = new ValidationContext(childActivity, parentChain, options, environment);
inputDictionary[Constraint.ToValidateContextArgumentName] = validationContext;
IDictionary<string, object> results = null;
try
{
results = WorkflowInvoker.Invoke(constraint, inputDictionary);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
ValidationError constraintExceptionValidationError = new ValidationError(SR.InternalConstraintException(constraint.DisplayName, toValidate.GetType().FullName, toValidate.DisplayName, e.ToString()), false)
{
Source = toValidate,
Id = toValidate.Id
};
ActivityUtilities.Add(ref validationErrors, constraintExceptionValidationError);
}
if (results != null)
{
object resultValidationErrors;
if (results.TryGetValue(Constraint.ValidationErrorListArgumentName, out resultValidationErrors))
{
IList<ValidationError> validationErrorList = (IList<ValidationError>)resultValidationErrors;
if (validationErrorList.Count > 0)
{
if (validationErrors == null)
{
validationErrors = new List<ValidationError>();
}
Activity source;
string prefix = ActivityValidationServices.GenerateValidationErrorPrefix(childActivity.Activity, parentChain, options, out source);
for (int validationErrorIndex = 0; validationErrorIndex < validationErrorList.Count; validationErrorIndex++)
{
ValidationError validationError = validationErrorList[validationErrorIndex];
validationError.Source = source;
validationError.Id = source.Id;
if (!string.IsNullOrEmpty(prefix))
{
validationError.Message = prefix + validationError.Message;
}
validationErrors.Add(validationError);
}
}
}
}
if (!suppressGetChildrenViolations)
{
validationContext.AddGetChildrenErrors(ref validationErrors);
}
}
}
}
internal static bool HasErrors(IList<ValidationError> validationErrors)
{
if (validationErrors != null && validationErrors.Count > 0)
{
for (int i = 0; i < validationErrors.Count; i++)
{
if (!validationErrors[i].IsWarning)
{
return true;
}
}
}
return false;
}
class InternalActivityValidationServices
{
ValidationSettings settings;
Activity rootToValidate;
IList<ValidationError> errors;
ProcessActivityTreeOptions options;
Activity expressionRoot;
LocationReferenceEnvironment environment;
internal InternalActivityValidationServices(ValidationSettings settings, Activity toValidate)
{
this.settings = settings;
this.rootToValidate = toValidate;
this.environment = settings.Environment;
}
internal ValidationResults InternalValidate()
{
this.options = ProcessActivityTreeOptions.GetValidationOptions(this.settings);
if (this.settings.OnlyUseAdditionalConstraints)
{
// We don't want the errors from CacheMetadata so we send those to a "dummy" list.
IList<ValidationError> suppressedErrors = null;
ActivityUtilities.CacheRootMetadata(this.rootToValidate, this.environment, this.options, new ActivityUtilities.ProcessActivityCallback(ValidateElement), ref suppressedErrors);
}
else
{
// We want to add the CacheMetadata errors to our errors collection
ActivityUtilities.CacheRootMetadata(this.rootToValidate, this.environment, this.options, new ActivityUtilities.ProcessActivityCallback(ValidateElement), ref this.errors);
}
return new ValidationResults(this.errors);
}
void ValidateElement(ActivityUtilities.ChildActivity childActivity, ActivityUtilities.ActivityCallStack parentChain)
{
Activity toValidate = childActivity.Activity;
if (!this.settings.SingleLevel || object.ReferenceEquals(toValidate, this.rootToValidate))
{
// 0. Open time violations are captured by the CacheMetadata walk.
// 1. Argument validations are done by the CacheMetadata walk.
// 2. Build constraints are done by the CacheMetadata walk.
// 3. Then do policy constraints
if (this.settings.HasAdditionalConstraints && childActivity.CanBeExecuted && parentChain.WillExecute)
{
bool suppressGetChildrenViolations = this.settings.OnlyUseAdditionalConstraints || this.settings.SingleLevel;
Type currentType = toValidate.GetType();
while (currentType != null)
{
IList<Constraint> policyConstraints;
if (this.settings.AdditionalConstraints.TryGetValue(currentType, out policyConstraints))
{
RunConstraints(childActivity, parentChain, policyConstraints, this.options, suppressGetChildrenViolations, ref this.errors);
}
if (currentType.IsGenericType)
{
Type genericDefinitionType = currentType.GetGenericTypeDefinition();
if (genericDefinitionType != null)
{
IList<Constraint> genericTypePolicyConstraints;
if (this.settings.AdditionalConstraints.TryGetValue(genericDefinitionType, out genericTypePolicyConstraints))
{
RunConstraints(childActivity, parentChain, genericTypePolicyConstraints, this.options, suppressGetChildrenViolations, ref this.errors);
}
}
}
currentType = currentType.BaseType;
}
}
//4. Validate if the argument expression subtree contains an activity that can induce idle.
if (childActivity.Activity.IsExpressionRoot)
{
if (childActivity.Activity.HasNonEmptySubtree)
{
this.expressionRoot = childActivity.Activity;
// Back-compat: In Dev10 we always used ProcessActivityTreeOptions.FullCachingOptions here, and ignored this.options.
// So we need to continue to do that, unless the new Dev11 flag SkipRootConfigurationValidation is passed.
ProcessActivityTreeOptions options = this.options.SkipRootConfigurationValidation ? this.options : ProcessActivityTreeOptions.FullCachingOptions;
ActivityUtilities.FinishCachingSubtree(childActivity, parentChain, options, ValidateExpressionSubtree);
this.expressionRoot = null;
}
else if (childActivity.Activity.InternalCanInduceIdle)
{
Activity activity = childActivity.Activity;
RuntimeArgument runtimeArgument = GetBoundRuntimeArgument(activity);
ValidationError error = new ValidationError(SR.CanInduceIdleActivityInArgumentExpression(runtimeArgument.Name, activity.Parent.DisplayName, activity.DisplayName), true, runtimeArgument.Name, activity.Parent);
ActivityUtilities.Add(ref this.errors, error);
}
}
}
}
void ValidateExpressionSubtree(ActivityUtilities.ChildActivity childActivity, ActivityUtilities.ActivityCallStack parentChain)
{
Fx.Assert(this.expressionRoot != null, "This callback should be called activities in the expression subtree only.");
if (childActivity.Activity.InternalCanInduceIdle)
{
Activity activity = childActivity.Activity;
Activity expressionRoot = this.expressionRoot;
RuntimeArgument runtimeArgument = GetBoundRuntimeArgument(expressionRoot);
ValidationError error = new ValidationError(SR.CanInduceIdleActivityInArgumentExpression(runtimeArgument.Name, expressionRoot.Parent.DisplayName, activity.DisplayName), true, runtimeArgument.Name, expressionRoot.Parent);
ActivityUtilities.Add(ref this.errors, error);
}
}
}
// Iterate through all runtime arguments on the configured activity
// and find the one that binds to expressionActivity.
static RuntimeArgument GetBoundRuntimeArgument(Activity expressionActivity)
{
Activity configuredActivity = expressionActivity.Parent;
Fx.Assert(configuredActivity != null, "Configured activity should not be null.");
RuntimeArgument boundRuntimeArgument = null;
for (int i = 0; i < configuredActivity.RuntimeArguments.Count; i++)
{
boundRuntimeArgument = configuredActivity.RuntimeArguments[i];
if (object.ReferenceEquals(boundRuntimeArgument.BoundArgument.Expression, expressionActivity))
{
break;
}
}
Fx.Assert(boundRuntimeArgument != null, "We should always be able to find the runtime argument!");
return boundRuntimeArgument;
}
// This method checks for duplicate evaluation order entries in a collection that is
// sorted in ascendng order of evaluation order values.
internal static void ValidateEvaluationOrder(IList<RuntimeArgument> runtimeArguments, Activity referenceActivity, ref IList<ValidationError> validationErrors)
{
for (int i = 0; i < runtimeArguments.Count - 1; i++)
{
RuntimeArgument argument = runtimeArguments[i];
RuntimeArgument nextArgument = runtimeArguments[i + 1];
if (argument.IsEvaluationOrderSpecified && nextArgument.IsEvaluationOrderSpecified)
{
if (argument.BoundArgument.EvaluationOrder == nextArgument.BoundArgument.EvaluationOrder)
{
ActivityUtilities.Add(ref validationErrors, new ValidationError(SR.DuplicateEvaluationOrderValues(referenceActivity.DisplayName, argument.BoundArgument.EvaluationOrder), false, argument.Name, referenceActivity));
}
}
}
}
internal enum ExceptionReason
{
InvalidTree,
InvalidNullInputs,
InvalidNonNullInputs,
}
}
}
| |
//
// Authors:
// Christian Hergert <[email protected]>
// Ben Motmans <[email protected]>
//
// Copyright (C) 2005 Mosaix Communications, Inc.
// Copyright (c) 2007 Ben Motmans
//
// 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 Gtk;
using System;
using System.Data;
using System.Threading;
using System.Collections.Generic;
using MonoDevelop.Database.Sql;
using SQL = MonoDevelop.Database.Sql;
using MonoDevelop.Core;
using MonoDevelop.Ide;
using MonoDevelop.Ide.Gui.Pads;
using MonoDevelop.Database.Query;
using MonoDevelop.Database.Components;
using MonoDevelop.Database.Designer;
using MonoDevelop.Components.Commands;
using MonoDevelop.Ide.Gui.Components;
namespace MonoDevelop.Database.ConnectionManager
{
public class TableNodeBuilder : TypeNodeBuilder
{
public TableNodeBuilder ()
: base ()
{
}
public override Type NodeDataType {
get { return typeof (TableNode); }
}
public override string ContextMenuAddinPath {
get { return "/MonoDevelop/Database/ContextMenu/ConnectionManagerPad/TableNode"; }
}
public override Type CommandHandlerType {
get { return typeof (TableNodeCommandHandler); }
}
public override void GetNodeAttributes (ITreeNavigator treeNavigator, object dataObject, ref NodeAttributes attributes)
{
attributes |= NodeAttributes.AllowRename;
}
public override string GetNodeName (ITreeNavigator thisNode, object dataObject)
{
TableNode node = dataObject as TableNode;
return node.Table.Name;
}
public override void BuildNode (ITreeBuilder builder, object dataObject, NodeInfo nodeInfo)
{
TableNode node = dataObject as TableNode;
nodeInfo.Label = node.Table.Name;
nodeInfo.Icon = Context.GetIcon ("md-db-table");
}
public override void BuildChildNodes (ITreeBuilder builder, object dataObject)
{
ThreadPool.QueueUserWorkItem (new WaitCallback (BuildChildNodesThreaded), dataObject);
}
private void BuildChildNodesThreaded (object state)
{
TableNode node = state as TableNode;
ITreeBuilder builder = Context.GetTreeBuilder (state);
ISchemaProvider provider = node.ConnectionContext.SchemaProvider;
if (provider.IsSchemaActionSupported (SQL.SchemaType.TableColumn, SchemaActions.Schema))
DispatchService.GuiDispatch (delegate {
builder.AddChild (new ColumnsNode (node.ConnectionContext, node.Table));
});
if (provider.IsSchemaActionSupported (SQL.SchemaType.Constraint, SchemaActions.Schema))
DispatchService.GuiDispatch (delegate {
builder.AddChild (new ConstraintsNode (node.ConnectionContext, node.Table));
});
if (provider.IsSchemaActionSupported (SQL.SchemaType.Trigger, SchemaActions.Schema))
DispatchService.GuiDispatch (delegate {
builder.AddChild (new TriggersNode (node.ConnectionContext));
});
//TODO: rules
DispatchService.GuiDispatch (delegate {
builder.Expanded = true;
});
}
public override bool HasChildNodes (ITreeBuilder builder, object dataObject)
{
return true;
}
}
public class TableNodeCommandHandler : NodeCommandHandler
{
public override DragOperation CanDragNode ()
{
return DragOperation.None;
}
public override void ActivateItem ()
{
OnQueryCommand ();
}
public override void RenameItem (string newName)
{
TableNode node = (TableNode)CurrentNode.DataItem;
if (node.Table.Name != newName)
ThreadPool.QueueUserWorkItem (new WaitCallback (RenameItemThreaded), new object[]{ node, newName });
}
private void RenameItemThreaded (object state)
{
object[] objs = state as object[];
TableNode node = objs[0] as TableNode;
string newName = objs[1] as string;
IEditSchemaProvider provider = (IEditSchemaProvider)node.Table.SchemaProvider;
if (provider.IsValidName (newName)) {
provider.RenameTable (node.Table, newName);
node.Refresh ();
} else {
DispatchService.GuiDispatch (delegate () {
MessageService.ShowError (String.Format (
"Unable to rename table '{0}' to '{1}'!",
node.Table.Name, newName
));
});
}
node.Refresh ();
}
[CommandHandler (ConnectionManagerCommands.Query)]
protected void OnQueryCommand ()
{
TableNode node = (TableNode)CurrentNode.DataItem;
IdentifierExpression tableId = new IdentifierExpression (node.Table.Name);
SelectStatement sel = new SelectStatement (new FromTableClause (tableId));
SqlQueryView view = new SqlQueryView ();
view.SelectedConnectionContext = node.ConnectionContext;
IDbFactory fac = DbFactoryService.GetDbFactory (node.ConnectionContext.ConnectionSettings);
view.Text = fac.Dialect.GetSql (sel);
IdeApp.Workbench.OpenDocument (view, true);
}
[CommandHandler (ConnectionManagerCommands.SelectColumns)]
protected void OnSelectColumnsCommand ()
{
ThreadPool.QueueUserWorkItem (new WaitCallback (OnSelectColumnsCommandGetColumns), CurrentNode.DataItem);
}
private void OnSelectColumnsCommandGetColumns (object state)
{
TableNode node = (TableNode)state;
ColumnSchemaCollection columns = node.Table.Columns; //this can invoke the schema provider, so it must be in bg thread
DispatchService.GuiDispatch (delegate () {
SelectColumnDialog dlg = new SelectColumnDialog (true, columns);
if (dlg.Run () == (int)Gtk.ResponseType.Ok) {
IdentifierExpression tableId = new IdentifierExpression (node.Table.Name);
List<IdentifierExpression> cols = new List<IdentifierExpression> ();
foreach (ColumnSchema schema in dlg.CheckedColumns)
cols.Add (new IdentifierExpression (schema.Name));
SelectStatement sel = new SelectStatement (new FromTableClause (tableId), cols);
IPooledDbConnection conn = node.ConnectionContext.ConnectionPool.Request ();
IDbCommand command = conn.CreateCommand (sel);
conn.ExecuteTableAsync (command, new ExecuteCallback<DataTable> (OnSelectCommandThreaded), null);
}
dlg.Destroy ();
});
}
[CommandHandler (ConnectionManagerCommands.SelectAll)]
protected void OnSelectAllCommand ()
{
TableNode node = (TableNode)CurrentNode.DataItem;
IdentifierExpression tableId = new IdentifierExpression (node.Table.Name);
SelectStatement sel = new SelectStatement (new FromTableClause (tableId));
IPooledDbConnection conn = node.ConnectionContext.ConnectionPool.Request ();
IDbCommand command = conn.CreateCommand (sel);
conn.ExecuteTableAsync (command, new ExecuteCallback<DataTable> (OnSelectCommandThreaded), null);
}
private void OnSelectCommandThreaded (IPooledDbConnection connection, DataTable table, object state)
{
connection.Release ();
DispatchService.GuiDispatch (delegate () {
QueryResultView view = new QueryResultView (table);
IdeApp.Workbench.OpenDocument (view, true);
});
}
[CommandHandler (ConnectionManagerCommands.EmptyTable)]
protected void OnEmptyTable ()
{
TableNode node = (TableNode)CurrentNode.DataItem;
AlertButton emptyButton = new AlertButton (AddinCatalog.GetString ("Empty Table"));
if (MessageService.Confirm (
AddinCatalog.GetString ("Are you sure you want to empty table '{0}'", node.Table.Name),
emptyButton
)) {
IdentifierExpression tableId = new IdentifierExpression (node.Table.Name);
DeleteStatement del = new DeleteStatement (new FromTableClause (tableId));
IPooledDbConnection conn = node.ConnectionContext.ConnectionPool.Request ();
IDbCommand command = conn.CreateCommand (del);
conn.ExecuteNonQueryAsync (command, new ExecuteCallback<int> (OnEmptyTableCallback), null);
}
}
private void OnEmptyTableCallback (IPooledDbConnection connection, int result, object state)
{
connection.Release ();
DispatchService.GuiDispatch (delegate () {
IdeApp.Workbench.StatusBar.ShowMessage (AddinCatalog.GetString ("Table emptied"));
});
}
[CommandHandler (ConnectionManagerCommands.DropTable)]
protected void OnDropTable ()
{
TableNode node = (TableNode)CurrentNode.DataItem;
AlertButton dropButton = new AlertButton (AddinCatalog.GetString ("Drop"), Gtk.Stock.Delete);
if (MessageService.Confirm (
AddinCatalog.GetString ("Are you sure you want to drop table '{0}'", node.Table.Name),
dropButton
)) {
ThreadPool.QueueUserWorkItem (new WaitCallback (OnDropTableThreaded), CurrentNode.DataItem);
}
}
private void OnDropTableThreaded (object state)
{
TableNode node = (TableNode)state;
IEditSchemaProvider provider = (IEditSchemaProvider)node.ConnectionContext.SchemaProvider;
provider.DropTable (node.Table);
OnRefreshParent ();
}
protected void OnRefreshParent ()
{
if (CurrentNode.MoveToParent ()) {
BaseNode node = CurrentNode.DataItem as BaseNode;
node.Refresh ();
}
}
[CommandHandler (ConnectionManagerCommands.AlterTable)]
protected void OnAlterTable ()
{
TableNode node = CurrentNode.DataItem as TableNode;
IDbFactory fac = node.ConnectionContext.DbFactory;
IEditSchemaProvider schemaProvider = (IEditSchemaProvider)node.ConnectionContext.SchemaProvider;
if (fac.GuiProvider.ShowTableEditorDialog (schemaProvider, node.Table, false))
ThreadPool.QueueUserWorkItem (new WaitCallback (OnAlterTableThreaded), CurrentNode.DataItem);
}
private void OnAlterTableThreaded (object state)
{
// TableNode node = (TableNode)state;
// IEditSchemaProvider provider = (IEditSchemaProvider)node.ConnectionContext.SchemaProvider;
//
// provider.AlterTable (node.Table);
}
[CommandHandler (MonoDevelop.Ide.Commands.EditCommands.Rename)]
protected void OnRenameTable ()
{
Tree.StartLabelEdit ();
}
[CommandUpdateHandler (ConnectionManagerCommands.DropTable)]
protected void OnUpdateDropTable (CommandInfo info)
{
BaseNode node = (BaseNode)CurrentNode.DataItem;
info.Enabled = node.ConnectionContext.SchemaProvider.IsSchemaActionSupported (SQL.SchemaType.Table, SchemaActions.Drop);
}
[CommandUpdateHandler (MonoDevelop.Ide.Commands.EditCommands.Rename)]
protected void OnUpdateRenameTable (CommandInfo info)
{
BaseNode node = (BaseNode)CurrentNode.DataItem;
info.Enabled = node.ConnectionContext.SchemaProvider.IsSchemaActionSupported (SQL.SchemaType.Table, SchemaActions.Rename);
}
[CommandUpdateHandler (ConnectionManagerCommands.AlterTable)]
protected void OnUpdateAlterTable (CommandInfo info)
{
BaseNode node = (BaseNode)CurrentNode.DataItem;
info.Enabled = node.ConnectionContext.SchemaProvider.IsSchemaActionSupported (SQL.SchemaType.Table, SchemaActions.Alter);
}
[CommandHandler (ConnectionManagerCommands.QuerySelectInNewWindow)]
protected void OnSelectQueryOnNewWindow ()
{
TableNode node = CurrentNode.DataItem as TableNode;
IEditSchemaProvider schemaProvider = (IEditSchemaProvider)node.ConnectionContext.SchemaProvider;
SqlQueryView view = new SqlQueryView ();
view.SelectedConnectionContext = node.ConnectionContext;
view.TextEditor.Insert (0, schemaProvider.GetSelectQuery (node.Table));
IdeApp.Workbench.OpenDocument (view, true);
}
[CommandHandler (ConnectionManagerCommands.QuerySelectInClipboard)]
protected void OnSelectQueryOnClipboard ()
{
TableNode node = CurrentNode.DataItem as TableNode;
IEditSchemaProvider schemaProvider = (IEditSchemaProvider)node.ConnectionContext.SchemaProvider;
Gtk.Clipboard clp = Clipboard.Get (Gdk.Selection.Clipboard);
clp.Text = schemaProvider.GetSelectQuery (node.Table);
MessageService.ShowMessage (AddinCatalog.GetString ("SELECT statement has been copied to Clipboard."));
}
[CommandHandler (ConnectionManagerCommands.QueryUpdateInNewWindow)]
protected void OnUpdateQueryOnNewWindow ()
{
TableNode node = CurrentNode.DataItem as TableNode;
IEditSchemaProvider schemaProvider = (IEditSchemaProvider)node.ConnectionContext.SchemaProvider;
SqlQueryView view = new SqlQueryView ();
view.SelectedConnectionContext = node.ConnectionContext;
view.TextEditor.Insert (0, schemaProvider.GetUpdateQuery (node.Table));
IdeApp.Workbench.OpenDocument (view, true);
}
[CommandHandler (ConnectionManagerCommands.QueryUpdateInClipboard)]
protected void OnUpdateQueryOnClipboard ()
{
TableNode node = CurrentNode.DataItem as TableNode;
IEditSchemaProvider schemaProvider = (IEditSchemaProvider)node.ConnectionContext.SchemaProvider;
Gtk.Clipboard clp = Clipboard.Get (Gdk.Selection.Clipboard);
clp.Text = schemaProvider.GetUpdateQuery (node.Table);
MessageService.ShowMessage (AddinCatalog.GetString ("UPDATE Statement has been copied to Clipboard."));
}
[CommandHandler (ConnectionManagerCommands.QueryInsertInNewWindow)]
protected void OnInsertQueryOnNewWindow ()
{
TableNode node = CurrentNode.DataItem as TableNode;
IEditSchemaProvider schemaProvider = (IEditSchemaProvider)node.ConnectionContext.SchemaProvider;
SqlQueryView view = new SqlQueryView ();
view.SelectedConnectionContext = node.ConnectionContext;
view.TextEditor.Insert (0, schemaProvider.GetInsertQuery (node.Table));
IdeApp.Workbench.OpenDocument (view, true);
}
[CommandHandler (ConnectionManagerCommands.QueryInsertInClipboard)]
protected void OnInsertQueryOnClipboard ()
{
TableNode node = CurrentNode.DataItem as TableNode;
IEditSchemaProvider schemaProvider = (IEditSchemaProvider)node.ConnectionContext.SchemaProvider;
Gtk.Clipboard clp = Clipboard.Get (Gdk.Selection.Clipboard);
clp.Text = schemaProvider.GetInsertQuery (node.Table);
MessageService.ShowMessage (AddinCatalog.GetString ("INSERT INTO Statement has been copied to Clipboard."));
}
[CommandHandler (ConnectionManagerCommands.QueryDeleteInNewWindow)]
protected void OnDeleteQueryOnNewWindow ()
{
TableNode node = CurrentNode.DataItem as TableNode;
IEditSchemaProvider schemaProvider = (IEditSchemaProvider)node.ConnectionContext.SchemaProvider;
SqlQueryView view = new SqlQueryView ();
view.SelectedConnectionContext = node.ConnectionContext;
view.TextEditor.Insert (0, schemaProvider.GetDeleteQuery (node.Table));
IdeApp.Workbench.OpenDocument (view, true);
}
[CommandHandler (ConnectionManagerCommands.QueryDeleteInClipboard)]
protected void OnDeleteQueryOnClipboard ()
{
TableNode node = CurrentNode.DataItem as TableNode;
IEditSchemaProvider schemaProvider = (IEditSchemaProvider)node.ConnectionContext.SchemaProvider;
Gtk.Clipboard clp = Clipboard.Get (Gdk.Selection.Clipboard);
clp.Text = schemaProvider.GetDeleteQuery (node.Table);
MessageService.ShowMessage (AddinCatalog.GetString ("DELETE Statement has been copied to Clipboard."));
}
[CommandHandler (ConnectionManagerCommands.ShowTableDefinitionInNewWindow)]
protected void OnShowDefinitionOnNewWindow ()
{
TableNode node = CurrentNode.DataItem as TableNode;
IEditSchemaProvider schemaProvider = (IEditSchemaProvider)node.ConnectionContext.SchemaProvider;
SqlQueryView view = new SqlQueryView ();
view.SelectedConnectionContext = node.ConnectionContext;
view.TextEditor.Insert (0, schemaProvider.GetTableCreateStatement (node.Table));
IdeApp.Workbench.OpenDocument (view, true);
}
[CommandHandler (ConnectionManagerCommands.ShowTableDefinitionInClipboard)]
protected void OnShowDefinitionOnClipboard ()
{
TableNode node = CurrentNode.DataItem as TableNode;
IEditSchemaProvider schemaProvider = (IEditSchemaProvider)node.ConnectionContext.SchemaProvider;
Gtk.Clipboard clp = Clipboard.Get (Gdk.Selection.Clipboard);
clp.Text = schemaProvider.GetTableCreateStatement (node.Table);
MessageService.ShowMessage (AddinCatalog.GetString ("CREATE Statement has been copied to Clipboard."));
}
}
}
| |
using System.Linq;
using System.Threading.Tasks;
using OmniSharp.Models;
using OmniSharp.Roslyn.CSharp.Services.Signatures;
using OmniSharp.Tests;
using Xunit;
namespace OmniSharp.Roslyn.CSharp.Tests
{
public class SignatureHelpFacts
{
[Fact]
public async Task NoInvocationNoHelp()
{
var source =
@"class Program
{
public static void Ma$in(){
System.Console.Clear();
}
}";
var actual = await GetSignatureHelp(source);
Assert.Null(actual);
source =
@"class Program
{
public static void Main(){
System.Cons$ole.Clear();
}
}";
actual = await GetSignatureHelp(source);
Assert.Null(actual);
source =
@"class Program
{
public static void Main(){
System.Console.Clear()$;
}
}";
actual = await GetSignatureHelp(source);
Assert.Null(actual);
}
[Fact]
public async Task NoTypeNoHelp()
{
var source =
@"class Program
{
public static void Main(){
System.Console.Foo$Bar();
}
}";
var actual = await GetSignatureHelp(source);
Assert.Null(actual);
}
[Fact]
public async Task NoMethodNoHelp()
{
var source =
@"class Program
{
public static void Main(){
System.Conso$le;
}
}";
var actual = await GetSignatureHelp(source);
Assert.Null(actual);
}
[Fact]
public async Task SimpleSignatureHelp()
{
var source =
@"class Program
{
public static void Main(){
System.Console.Clear($);
}
}";
var actual = await GetSignatureHelp(source);
Assert.Equal(1, actual.Signatures.Count());
Assert.Equal(0, actual.ActiveParameter);
Assert.Equal(0, actual.ActiveSignature);
Assert.Equal("Clear", actual.Signatures.ElementAt(0).Name);
Assert.Equal(0, actual.Signatures.ElementAt(0).Parameters.Count());
}
[Fact]
public async Task TestForParameterLabels()
{
var source =
@"class Program
{
public static void Main(){
Foo($);
}
pubic static Foo(bool b, int n = 1234)
{
}
}";
var actual = await GetSignatureHelp(source);
Assert.Equal(1, actual.Signatures.Count());
Assert.Equal(0, actual.ActiveParameter);
Assert.Equal(0, actual.ActiveSignature);
var signature = actual.Signatures.ElementAt(0);
Assert.Equal(2, signature.Parameters.Count());
Assert.Equal("b", signature.Parameters.ElementAt(0).Name);
Assert.Equal("bool b", signature.Parameters.ElementAt(0).Label);
Assert.Equal("n", signature.Parameters.ElementAt(1).Name);
Assert.Equal("int n = 1234", signature.Parameters.ElementAt(1).Label);
}
[Fact]
public async Task ActiveParameterIsBasedOnComma()
{
// 1st position, a
var source =
@"class Program
{
public static void Main(){
new Program().Foo(1$2,
}
/// foo1
private int Foo(int one, int two, int three)
{
return 3;
}
}";
var actual = await GetSignatureHelp(source);
Assert.Equal(0, actual.ActiveParameter);
// 1st position, b
source =
@"class Program
{
public static void Main(){
new Program().Foo(12 $)
}
/// foo1
private int Foo(int one, int two, int three)
{
return 3;
}
}";
actual = await GetSignatureHelp(source);
Assert.Equal(0, actual.ActiveParameter);
// 2nd position, a
source =
@"class Program
{
public static void Main(){
new Program().Foo(12, $
}
/// foo1
private int Foo(int one, int two, int three)
{
return 3;
}
}";
actual = await GetSignatureHelp(source);
Assert.Equal(1, actual.ActiveParameter);
// 2nd position, b
source =
@"class Program
{
public static void Main(){
new Program().Foo(12, 1$
}
/// foo1
private int Foo(int one, int two, int three)
{
return 3;
}
}";
actual = await GetSignatureHelp(source);
Assert.Equal(1, actual.ActiveParameter);
// 3rd position, a
source =
@"class Program
{
public static void Main(){
new Program().Foo(12, 1, $
}
/// foo1
private int Foo(int one, int two, int three)
{
return 3;
}
}";
actual = await GetSignatureHelp(source);
Assert.Equal(2, actual.ActiveParameter);
}
[Fact]
public async Task ActiveSignatureIsBasedOnTypes()
{
var source =
@"class Program
{
public static void Main(){
new Program().Foo(12, $
}
/// foo1
private int Foo()
{
return 3;
}
/// foo2
private int Foo(int m, int n)
{
return m * Foo() * n;
}
/// foo3
private int Foo(string m, int n)
{
return Foo(m.length, n);
}
}";
var actual = await GetSignatureHelp(source);
Assert.Equal(3, actual.Signatures.Count());
Assert.True(actual.Signatures.ElementAt(actual.ActiveSignature).Documentation.Contains("foo2"));
source =
@"class Program
{
public static void Main(){
new Program().Foo(""d"", $
}
/// foo1
private int Foo()
{
return 3;
}
/// foo2
private int Foo(int m, int n)
{
return m * Foo() * n;
}
/// foo3
private int Foo(string m, int n)
{
return Foo(m.length, n);
}
}";
actual = await GetSignatureHelp(source);
Assert.Equal(3, actual.Signatures.Count());
Assert.True(actual.Signatures.ElementAt(actual.ActiveSignature).Documentation.Contains("foo3"));
source =
@"class Program
{
public static void Main(){
new Program().Foo($)
}
/// foo1
private int Foo()
{
return 3;
}
/// foo2
private int Foo(int m, int n)
{
return m * Foo() * n;
}
/// foo3
private int Foo(string m, int n)
{
return Foo(m.length, n);
}
}";
actual = await GetSignatureHelp(source);
Assert.Equal(3, actual.Signatures.Count());
Assert.True(actual.Signatures.ElementAt(actual.ActiveSignature).Documentation.Contains("foo1"));
}
[Fact]
public async Task SigantureHelpForCtor()
{
var source =
@"class Program
{
public static void Main()
{
new Program($)
}
public Program()
{
}
public Program(bool b)
{
}
public Program(Program p)
{
}
}";
var actual = await GetSignatureHelp(source);
Assert.Equal(3, actual.Signatures.Count());
}
[Fact]
public async Task SigantureHelpForCtorWithOverloads()
{
var source =
@"class Program
{
public static void Main()
{
new Program(true, 12$3)
}
public Program()
{
}
/// ctor2
public Program(bool b, int n)
{
}
public Program(Program p, int n)
{
}
}";
var actual = await GetSignatureHelp(source);
Assert.Equal(3, actual.Signatures.Count());
Assert.Equal(1, actual.ActiveParameter);
Assert.True(actual.Signatures.ElementAt(actual.ActiveSignature).Documentation.Contains("ctor2"));
}
[Fact]
public async Task SkipReceiverOfExtensionMethods()
{
var source =
@"class Program
{
public static void Main()
{
new Program().B($);
}
public Program()
{
}
public bool B(this Program p, int n)
{
return p.Foo() > n;
}
}";
var actual = await GetSignatureHelp(source);
Assert.Equal(1, actual.Signatures.Count());
Assert.Equal(1, actual.Signatures.ElementAt(actual.ActiveSignature).Parameters.Count());
Assert.Equal("n", actual.Signatures.ElementAt(actual.ActiveSignature).Parameters.ElementAt(0).Name);
}
private async Task<SignatureHelp> GetSignatureHelp(string source)
{
var lineColumn = TestHelpers.GetLineAndColumnFromDollar(source);
source = source.Replace("$", string.Empty);
var request = new SignatureHelpRequest()
{
FileName = "dummy.cs",
Line = lineColumn.Line,
Column = lineColumn.Column,
Buffer = source
};
var workspace = await TestHelpers.CreateSimpleWorkspace(source);
var controller = new SignatureHelpService(workspace);
return await controller.Handle(request);
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
namespace KERBALISM
{
public static class DB
{
public static void Load(ConfigNode node)
{
// get version (or use current one for new savegames)
string versionStr = Lib.ConfigValue(node, "version", Lib.KerbalismVersion.ToString());
// sanitize old saves (pre 3.1) format (X.X.X.X) to new format (X.X)
if (versionStr.Split('.').Length > 2) versionStr = versionStr.Split('.')[0] + "." + versionStr.Split('.')[1];
version = new Version(versionStr);
// if this is an unsupported version, print warning
if (version <= new Version(1, 2)) Lib.Log("loading save from unsupported version " + version);
// get unique id (or generate one for new savegames)
uid = Lib.ConfigValue(node, "uid", Lib.RandomInt(int.MaxValue));
// load kerbals data
kerbals = new Dictionary<string, KerbalData>();
if (node.HasNode("kerbals"))
{
foreach (var kerbal_node in node.GetNode("kerbals").GetNodes())
{
kerbals.Add(From_safe_key(kerbal_node.name), new KerbalData(kerbal_node));
}
}
// load the science database, has to be before vessels are loaded
ScienceDB.Load(node);
UnityEngine.Profiling.Profiler.BeginSample("Kerbalism.DB.Load.Vessels");
vessels.Clear();
// flightstate will be null when first creating the game
if (HighLogic.CurrentGame.flightState != null)
{
ConfigNode vesselsNode = node.GetNode("vessels2");
if (vesselsNode == null)
vesselsNode = new ConfigNode();
// HighLogic.CurrentGame.flightState.protoVessels is what is used by KSP to persist vessels
// It is always available and synchronized in OnLoad, no matter the scene, excepted on the first OnLoad in a new game
foreach (ProtoVessel pv in HighLogic.CurrentGame.flightState.protoVessels)
{
if (pv.vesselID == Guid.Empty)
{
// It seems flags are saved with an empty GUID. skip them.
Lib.LogDebug("Skipping VesselData load for vessel with empty GUID :" + pv.vesselName);
continue;
}
VesselData vd = new VesselData(pv, vesselsNode.GetNode(pv.vesselID.ToString()));
vessels.Add(pv.vesselID, vd);
Lib.LogDebug("VesselData loaded for vessel " + pv.vesselName);
}
}
UnityEngine.Profiling.Profiler.EndSample();
// for compatibility with old saves, convert drives data (it's now saved in PartData)
if (node.HasNode("drives"))
{
Dictionary<uint, PartData> allParts = new Dictionary<uint, PartData>();
foreach (VesselData vesselData in vessels.Values)
{
foreach (PartData partData in vesselData.PartDatas)
{
// we had a case of someone having a save with multiple parts having the same flightID
// 5 duplicates, all were asteroids.
if (!allParts.ContainsKey(partData.FlightId))
{
allParts.Add(partData.FlightId, partData);
}
}
}
foreach (var drive_node in node.GetNode("drives").GetNodes())
{
uint driveId = Lib.Parse.ToUInt(drive_node.name);
if (allParts.ContainsKey(driveId))
{
allParts[driveId].Drive = new Drive(drive_node);
}
}
}
// load bodies data
storms = new Dictionary<string, StormData>();
if (node.HasNode("bodies"))
{
foreach (var body_node in node.GetNode("bodies").GetNodes())
{
storms.Add(From_safe_key(body_node.name), new StormData(body_node));
}
}
// load landmark data
if (node.HasNode("landmarks"))
{
landmarks = new LandmarkData(node.GetNode("landmarks"));
}
else
{
landmarks = new LandmarkData();
}
// load ui data
if (node.HasNode("ui"))
{
ui = new UIData(node.GetNode("ui"));
}
else
{
ui = new UIData();
}
// if an old savegame was imported, log some debug info
if (version != Lib.KerbalismVersion) Lib.Log("savegame converted from version " + version + " to " + Lib.KerbalismVersion);
}
public static void Save(ConfigNode node)
{
// save version
node.AddValue("version", Lib.KerbalismVersion.ToString());
// save unique id
node.AddValue("uid", uid);
// save kerbals data
var kerbals_node = node.AddNode("kerbals");
foreach (var p in kerbals)
{
p.Value.Save(kerbals_node.AddNode(To_safe_key(p.Key)));
}
// only persist vessels that exists in KSP own vessel persistence
// this prevent creating junk data without going into the mess of using gameevents
UnityEngine.Profiling.Profiler.BeginSample("Kerbalism.DB.Save.Vessels");
ConfigNode vesselsNode = node.AddNode("vessels2");
foreach (ProtoVessel pv in HighLogic.CurrentGame.flightState.protoVessels)
{
if (pv.vesselID == Guid.Empty)
{
// It seems flags are saved with an empty GUID. skip them.
Lib.LogDebug("Skipping VesselData save for vessel with empty GUID :" + pv.vesselName);
continue;
}
VesselData vd = pv.KerbalismData();
ConfigNode vesselNode = vesselsNode.AddNode(pv.vesselID.ToString());
vd.Save(vesselNode);
}
UnityEngine.Profiling.Profiler.EndSample();
// save the science database
ScienceDB.Save(node);
// save bodies data
var bodies_node = node.AddNode("bodies");
foreach (var p in storms)
{
p.Value.Save(bodies_node.AddNode(To_safe_key(p.Key)));
}
// save landmark data
landmarks.Save(node.AddNode("landmarks"));
// save ui data
ui.Save(node.AddNode("ui"));
}
public static KerbalData Kerbal(string name)
{
if (!kerbals.ContainsKey(name))
{
kerbals.Add(name, new KerbalData());
}
return kerbals[name];
}
public static VesselData KerbalismData(this Vessel vessel)
{
VesselData vd;
if (!vessels.TryGetValue(vessel.id, out vd))
{
Lib.LogDebug("Creating Vesseldata for new vessel " + vessel.vesselName);
vd = new VesselData(vessel);
vessels.Add(vessel.id, vd);
}
return vd;
}
public static VesselData KerbalismData(this ProtoVessel protoVessel)
{
VesselData vd;
if (!vessels.TryGetValue(protoVessel.vesselID, out vd))
{
Lib.Log("VesselData for protovessel " + protoVessel.vesselName + ", ID=" + protoVessel.vesselID + " doesn't exist !", Lib.LogLevel.Warning);
vd = new VesselData(protoVessel, null);
vessels.Add(protoVessel.vesselID, vd);
}
return vd;
}
/// <summary>shortcut for VesselData.IsValid. False in the following cases : asteroid, debris, flag, deployed ground part, dead eva, rescue</summary>
public static bool KerbalismIsValid(this Vessel vessel)
{
return KerbalismData(vessel).IsSimulated;
}
public static Dictionary<Guid, VesselData>.ValueCollection VesselDatas => vessels.Values;
public static StormData Storm(string name)
{
if (!storms.ContainsKey(name))
{
storms.Add(name, new StormData(null));
}
return storms[name];
}
public static Boolean ContainsKerbal(string name)
{
return kerbals.ContainsKey(name);
}
/// <summary>
/// Remove a Kerbal and his lifetime data from the database
/// </summary>
public static void KillKerbal(String name, bool reallyDead)
{
if (reallyDead)
{
kerbals.Remove(name);
}
else
{
// called when a vessel is destroyed. don't remove the kerbal just yet,
// check with the roster if the kerbal is dead or not
Kerbal(name).Recover();
}
}
/// <summary>
/// Resets all process data of a kerbal, except lifetime data
/// </summary>
public static void RecoverKerbal(string name)
{
if (ContainsKerbal(name))
{
if (Kerbal(name).eva_dead)
{
kerbals.Remove(name);
}
else
{
Kerbal(name).Recover();
}
}
}
public static Dictionary<string, KerbalData> Kerbals()
{
return kerbals;
}
public static string To_safe_key(string key) { return key.Replace(" ", "___"); }
public static string From_safe_key(string key) { return key.Replace("___", " "); }
public static Version version; // savegame version
public static int uid; // savegame unique id
private static Dictionary<string, KerbalData> kerbals; // store data per-kerbal
private static Dictionary<Guid, VesselData> vessels = new Dictionary<Guid, VesselData>(); // store data per-vessel
public static Dictionary<string, StormData> storms; // store data per-body
public static LandmarkData landmarks; // store landmark data
public static UIData ui; // store ui data
}
} // KERBALISM
| |
// 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 Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public class SqlBulkCopyTest
{
private string srcConstr = null;
private string dstConstr = null;
private static bool IsAzureServer() => DataTestUtility.IsAzureSqlServer(new SqlConnectionStringBuilder((DataTestUtility.TcpConnStr)).DataSource);
private static bool AreConnectionStringsSetup() => DataTestUtility.AreConnStringsSetup();
public SqlBulkCopyTest()
{
srcConstr = DataTestUtility.TcpConnStr;
dstConstr = (new SqlConnectionStringBuilder(srcConstr) { InitialCatalog = "tempdb" }).ConnectionString;
}
public string AddGuid(string stringin)
{
stringin += "_" + Guid.NewGuid().ToString().Replace('-', '_');
return stringin;
}
[ConditionalFact(nameof(AreConnectionStringsSetup), nameof(IsAzureServer))]
public void AzureDistributedTransactionTest()
{
AzureDistributedTransaction.Test();
}
[CheckConnStrSetupFact]
public void CopyAllFromReaderTest()
{
CopyAllFromReader.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopyAllFromReader"));
}
[CheckConnStrSetupFact]
public void CopyAllFromReader1Test()
{
CopyAllFromReader1.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopyAllFromReader1"));
}
[CheckConnStrSetupFact]
public void CopyMultipleReadersTest()
{
CopyMultipleReaders.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopyMultipleReaders"));
}
[CheckConnStrSetupFact]
public void CopySomeFromReaderTest()
{
CopySomeFromReader.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopySomeFromReader"));
}
[CheckConnStrSetupFact]
public void CopySomeFromDataTableTest()
{
CopySomeFromDataTable.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopySomeFromDataTable"));
}
[CheckConnStrSetupFact]
public void CopySomeFromRowArrayTest()
{
CopySomeFromRowArray.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopySomeFromRowArray"));
}
[CheckConnStrSetupFact]
public void CopyWithEventTest()
{
CopyWithEvent.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopyWithEvent"));
}
[CheckConnStrSetupFact]
public void CopyWithEvent1Test()
{
CopyWithEvent1.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_CopyWithEvent1"));
}
[CheckConnStrSetupFact]
public void InvalidAccessFromEventTest()
{
InvalidAccessFromEvent.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_InvalidAccessFromEvent"));
}
[CheckConnStrSetupFact]
public void Bug84548Test()
{
Bug84548.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Bug84548"));
}
[CheckConnStrSetupFact]
public void MissingTargetTableTest()
{
MissingTargetTable.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_MissingTargetTable"));
}
[CheckConnStrSetupFact]
public void MissingTargetColumnTest()
{
MissingTargetColumn.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_MissingTargetColumn"));
}
[CheckConnStrSetupFact]
public void Bug85007Test()
{
Bug85007.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Bug85007"));
}
[CheckConnStrSetupFact]
public void CheckConstraintsTest()
{
CheckConstraints.Test(dstConstr, AddGuid("SqlBulkCopyTest_Extensionsrc"), AddGuid("SqlBulkCopyTest_Extensiondst"));
}
[CheckConnStrSetupFact]
public void TransactionTest()
{
Transaction.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Transaction0"));
}
[CheckConnStrSetupFact]
public void Transaction1Test()
{
Transaction1.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Transaction1"));
}
[CheckConnStrSetupFact]
public void Transaction2Test()
{
Transaction2.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Transaction2"));
}
[CheckConnStrSetupFact]
public void Transaction3Test()
{
Transaction3.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Transaction3"));
}
[CheckConnStrSetupFact]
public void Transaction4Test()
{
Transaction4.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_Transaction4"));
}
[CheckConnStrSetupFact]
public void CopyVariantsTest()
{
CopyVariants.Test(dstConstr, AddGuid("SqlBulkCopyTest_Variants"));
}
[CheckConnStrSetupFact]
public void Bug98182Test()
{
Bug98182.Test(dstConstr, AddGuid("SqlBulkCopyTest_Bug98182 "));
}
[CheckConnStrSetupFact]
public void FireTriggerTest()
{
FireTrigger.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_FireTrigger"));
}
[CheckConnStrSetupFact]
public void ErrorOnRowsMarkedAsDeletedTest()
{
ErrorOnRowsMarkedAsDeleted.Test(dstConstr, AddGuid("SqlBulkCopyTest_ErrorOnRowsMarkedAsDeleted"));
}
[CheckConnStrSetupFact]
public void SpecialCharacterNamesTest()
{
SpecialCharacterNames.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_SpecialCharacterNames"));
}
[CheckConnStrSetupFact]
public void Bug903514Test()
{
Bug903514.Test(dstConstr, AddGuid("SqlBulkCopyTest_Bug903514"));
}
[CheckConnStrSetupFact]
public void ColumnCollationTest()
{
ColumnCollation.Test(dstConstr, AddGuid("SqlBulkCopyTest_ColumnCollation"));
}
[CheckConnStrSetupFact]
public void CopyAllFromReaderAsyncTest()
{
CopyAllFromReaderAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest1")); //Async + Reader
}
[CheckConnStrSetupFact]
public void CopySomeFromRowArrayAsyncTest()
{
CopySomeFromRowArrayAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest2")); //Async + Some Rows
}
[CheckConnStrSetupFact]
public void CopySomeFromDataTableAsyncTest()
{
CopySomeFromDataTableAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest3")); //Async + Some Table
}
[CheckConnStrSetupFact]
public void CopyWithEventAsyncTest()
{
CopyWithEventAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest4")); //Async + Rows + Notification
}
[CheckConnStrSetupFact]
public void CopyAllFromReaderCancelAsyncTest()
{
CopyAllFromReaderCancelAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest5")); //Async + Reader + cancellation token
}
[CheckConnStrSetupFact]
public void CopyAllFromReaderConnectionClosedAsyncTest()
{
CopyAllFromReaderConnectionClosedAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest6")); //Async + Reader + Connection closed
}
[CheckConnStrSetupFact]
public void CopyAllFromReaderConnectionClosedOnEventAsyncTest()
{
CopyAllFromReaderConnectionClosedOnEventAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_AsyncTest7")); //Async + Reader + Connection closed during the event
}
[CheckConnStrSetupFact]
public void TransactionTestAsyncTest()
{
TransactionTestAsync.Test(srcConstr, dstConstr, AddGuid("SqlBulkCopyTest_TransactionTestAsync")); //Async + Transaction rollback
}
}
}
| |
namespace AgileObjects.AgileMapper.Members
{
using System;
using System.Collections.Generic;
using System.Linq;
#if NET35
using Microsoft.Scripting.Ast;
#else
using System.Linq.Expressions;
#endif
using Caching;
using Extensions;
using Extensions.Internal;
using NetStandardPolyfills;
using ReadableExpressions;
using ReadableExpressions.Extensions;
internal class ConfiguredSourceMember : IQualifiedMember
{
private readonly Expression _rootValue;
private readonly IList<string> _matchedTargetMemberJoinedNames;
private readonly MapperContext _mapperContext;
private readonly Member[] _childMembers;
private readonly ICache<Member, ConfiguredSourceMember> _childMemberCache;
private readonly bool _isMatchedToRootTarget;
private IQualifiedMemberContext _context;
public ConfiguredSourceMember(Expression value, IQualifiedMemberContext context)
: this(
value,
value.Type,
value.Type.IsEnumerable(),
value.Type.IsSimple(),
value.ToReadableString(),
context.TargetMember.JoinedNames,
context.MapperContext,
GetConfiguredMemberChainOrNull(value, context))
{
_isMatchedToRootTarget = context.TargetMember.IsRoot;
}
private static Member[] GetConfiguredMemberChainOrNull(Expression value, IMapperContextOwner contextOwner)
=> value.ToSourceMemberOrNull(contextOwner.MapperContext)?.MemberChain;
private ConfiguredSourceMember(ConfiguredSourceMember parent, Member childMember)
: this(
parent._rootValue,
childMember.Type,
childMember.IsEnumerable,
childMember.IsSimple,
parent.Name + childMember.JoiningName,
parent._matchedTargetMemberJoinedNames.ExtendWith(
parent._mapperContext.Naming.GetMatchingNamesFor(childMember, parent._context),
parent._mapperContext),
parent._mapperContext,
parent._childMembers.Append(childMember))
{
}
private ConfiguredSourceMember(
Expression rootValue,
Type type,
bool isEnumerable,
bool isSimple,
string name,
IList<string> matchedTargetMemberJoinedNames,
MapperContext mapperContext,
Member[] childMembers = null)
{
_rootValue = rootValue;
Type = type;
IsEnumerable = isEnumerable;
IsSimple = isSimple;
Name = name;
_matchedTargetMemberJoinedNames = matchedTargetMemberJoinedNames;
_mapperContext = mapperContext;
_childMembers = childMembers ?? new[] { Member.RootSource(name, type) };
if (isSimple)
{
return;
}
if (isEnumerable)
{
ElementType = (childMembers != null)
? childMembers.Last().ElementType
: type.GetEnumerableElementType();
}
_childMemberCache = mapperContext.Cache
.CreateNewWithHashCodes<Member, ConfiguredSourceMember>();
}
public bool IsRoot => false;
public Type Type { get; }
public Type RootType => _childMembers[0].Type;
public Type ElementType { get; }
public string GetFriendlyTypeName() => Type.GetFriendlyName();
public bool IsEnumerable { get; }
public bool IsSimple { get; }
public string Name { get; }
public string GetPath() => _childMembers.GetFullName();
IQualifiedMember IQualifiedMember.GetElementMember() => this.GetElementMember();
public IQualifiedMember Append(Member childMember)
=> _childMemberCache.GetOrAdd(childMember, cm => new ConfiguredSourceMember(this, cm));
public IQualifiedMember RelativeTo(IQualifiedMember otherMember)
{
if (!(otherMember is ConfiguredSourceMember otherConfiguredMember))
{
return this;
}
var relativeMemberChain = _childMembers.RelativeTo(otherConfiguredMember._childMembers);
if ((relativeMemberChain == _childMembers) ||
relativeMemberChain.SequenceEqual(_childMembers))
{
return this;
}
return new ConfiguredSourceMember(
_rootValue,
Type,
IsEnumerable,
IsSimple,
Name,
_matchedTargetMemberJoinedNames,
_mapperContext,
relativeMemberChain);
}
public bool HasCompatibleType(Type type) => false;
public bool CouldMatch(QualifiedMember otherMember)
=> _matchedTargetMemberJoinedNames.CouldMatch(otherMember.JoinedNames);
public bool Matches(IQualifiedMember otherMember)
{
if (otherMember is QualifiedMember otherQualifiedMember)
{
return _matchedTargetMemberJoinedNames.Match(otherQualifiedMember.JoinedNames);
}
if (otherMember is ConfiguredSourceMember otherConfiguredMember)
{
return _matchedTargetMemberJoinedNames.Match(otherConfiguredMember._matchedTargetMemberJoinedNames);
}
return false;
}
public Expression GetQualifiedAccess(Expression parentInstance)
{
if (_isMatchedToRootTarget && _childMembers.HasOne())
{
return _rootValue;
}
return _childMembers.GetQualifiedAccess(parentInstance);
}
public IQualifiedMember SetContext(IQualifiedMemberContext context)
{
_context = context;
return this;
}
public IQualifiedMember WithType(Type runtimeType)
{
if (runtimeType == Type)
{
return this;
}
var isEnumerable = IsEnumerable || runtimeType.IsEnumerable();
var isSimple = !isEnumerable && (IsSimple || runtimeType.IsSimple());
return new ConfiguredSourceMember(
_rootValue,
runtimeType,
isEnumerable,
isSimple,
Name,
_matchedTargetMemberJoinedNames,
_mapperContext,
_childMembers);
}
#region ExcludeFromCodeCoverage
#if DEBUG
[ExcludeFromCodeCoverage]
#endif
#endregion
public override string ToString() => GetPath() + ": " + Type.GetFriendlyName();
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
namespace NuGet.OneGet {
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Reflection;
using System.Security.Principal;
using System.Xml.Linq;
using System.Xml.XPath;
using global::OneGet.ProviderSDK;
using Microsoft.Win32;
using ErrorCategory = global::OneGet.ProviderSDK.ErrorCategory;
public abstract class ChocolateyRequest : BaseRequest {
internal static ImplictLazy<string> ChocolateyModuleFolder = new ImplictLazy<string>(() => Path.GetFullPath(Assembly.GetExecutingAssembly().Location));
internal static ImplictLazy<string> ChocolateyModuleFile = new ImplictLazy<string>(() => Path.Combine(ChocolateyModuleFolder, "Chocolatey.psd1"));
internal static ImplictLazy<string> EtcPath = new ImplictLazy<string>(() => Path.Combine(ChocolateyModuleFolder, "etc"));
internal static ImplictLazy<string> ChocolateyConfigPath = new ImplictLazy<string>(() => Path.Combine(RootInstallationPath, "chocolateyinstall", "Chocolatey.config"));
internal static ImplictLazy<string> SystemDrive = new ImplictLazy<string>(() => {
var drive = Environment.GetEnvironmentVariable("SystemDrive");
if (string.IsNullOrEmpty(drive)) {
return "c:\\";
}
return drive + "\\";
});
internal static ImplictLazy<string> RootInstallationPath = new ImplictLazy<string>(() => {
var rip = Environment.GetEnvironmentVariable("ChocolateyPath");
if (string.IsNullOrEmpty(rip)) {
// current default
rip = Path.Combine(SystemDrive, @"\", "Chocolatey");
// store it.
Environment.SetEnvironmentVariable("ChocolateyPath", rip, EnvironmentVariableTarget.User);
Environment.SetEnvironmentVariable("ChocolateyPath", rip, EnvironmentVariableTarget.Process);
}
if (!rip.DirectoryHasDriveLetter()) {
rip = rip.TrimStart('\\');
rip = Path.Combine(SystemDrive, rip);
Environment.SetEnvironmentVariable("ChocolateyPath", rip, EnvironmentVariableTarget.User);
Environment.SetEnvironmentVariable("ChocolateyPath", rip, EnvironmentVariableTarget.Process);
}
if (!Directory.Exists(rip)) {
Directory.CreateDirectory(rip);
}
return rip;
});
internal static ImplictLazy<string> HelperModuleText = new ImplictLazy<string>(() => {
var asm = Assembly.GetExecutingAssembly();
var resource = asm.GetManifestResourceNames().FirstOrDefault(each => each.EndsWith("ChocolateyHelpers.psm1", StringComparison.OrdinalIgnoreCase));
if (resource != null) {
return asm.GetManifestResourceStream(resource).ReadToEnd();
}
return string.Empty;
});
public static ImplictLazy<bool> IsElevated = new ImplictLazy<bool>(() => {
var id = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(id);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
});
public override string ProviderName {
get {
return "Chocolatey";
}
}
internal bool ForceX86 {
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required.")]
get {
return GetOptionValue("ForceX86").IsTrue();
}
}
internal override string Destination {
get {
return PackageInstallationPath;
}
}
internal override IDictionary<string, PackageSource> RegisteredPackageSources {
get {
try {
return Config.XPathSelectElements("/chocolatey/sources/source")
.Where(each => each.Attribute("id") != null && each.Attribute("value") != null)
.ToDictionaryNicely(each => each.Attribute("id").Value, each => new PackageSource {
Name = each.Attribute("id").Value,
Location = each.Attribute("value").Value,
Trusted = each.Attributes("trusted").Any() && each.Attribute("trusted").Value.IsTrue(),
IsRegistered = true,
IsValidated = each.Attributes("validated").Any() && each.Attribute("validated").Value.IsTrue(),
}, StringComparer.OrdinalIgnoreCase);
} catch (Exception e) {
e.Dump(this);
}
return new Dictionary<string, PackageSource>(StringComparer.OrdinalIgnoreCase) {
{
"chocolatey", new PackageSource {
Name = "chocolatey",
Location = "http://chocolatey.org/api/v2/",
Trusted = false,
IsRegistered = false,
IsValidated = true,
}
}
};
}
}
internal XDocument Config {
get {
try {
var doc = XDocument.Load(ChocolateyConfigPath);
if (doc.Root != null && doc.Root.Name == "chocolatey") {
return doc;
}
// doc root isn't right. make a new one!
} catch {
// bad doc
}
return XDocument.Load(new MemoryStream(@"<?xml version=""1.0""?>
<chocolatey>
<useNuGetForSources>false</useNuGetForSources>
<sources>
<source id=""chocolatey"" value=""http://chocolatey.org/api/v2/"" />
</sources>
</chocolatey>
".ToByteArray()));
}
set {
Verbose("Saving Chocolatey Config", ChocolateyConfigPath);
if (value == null) {
return;
}
CreateFolder(Path.GetDirectoryName(ChocolateyConfigPath), this.REQ);
value.Save(ChocolateyConfigPath);
}
}
internal string PackageInstallationPath {
get {
var path = Path.Combine(RootInstallationPath, "lib");
if (!Directory.Exists(path)) {
CreateFolder(path, this.REQ);
}
return path;
}
}
internal string PackageExePath {
get {
var path = Path.Combine(RootInstallationPath, "bin");
if (!Directory.Exists(path)) {
CreateFolder(path, this.REQ);
}
return Path.Combine(RootInstallationPath, "bin");
}
}
protected override string ConfigurationFileLocation {
get {
return ChocolateyConfigPath;
}
}
internal override void RemovePackageSource(string id) {
var config = Config;
var source = config.XPathSelectElements(string.Format("/chocolatey/sources/source[@id='{0}']", id)).FirstOrDefault();
if (source != null) {
source.Remove();
Config = config;
}
}
internal override void AddPackageSource(string name, string location, bool isTrusted, bool isValidated) {
if (SkipValidate || ValidateSourceLocation(location)) {
var config = Config;
var sources = config.XPathSelectElements("/chocolatey/sources").FirstOrDefault();
if (sources == null) {
config.Root.Add(sources = new XElement("sources"));
}
var source = new XElement("source");
source.SetAttributeValue("id", name);
source.SetAttributeValue("value", location);
if (isValidated) {
source.SetAttributeValue("validated", true);
}
if (isTrusted) {
source.SetAttributeValue("trusted", true);
}
sources.Add(source);
Config = config;
// Yield this from the provider object.
//YieldPackageSource(name, location, isTrusted, true, isValidated);
}
}
public bool GenerateBins(string pkgPath) {
var exes = Directory.EnumerateFiles(pkgPath, "*.exe", SearchOption.AllDirectories);
foreach (var exe in exes) {
if (File.Exists((exe + ".ignore"))) {
continue;
}
if (File.Exists(exe + ".gui")) {
GenerateGuiBin(exe);
continue;
}
GenerateConsoleBin(exe);
}
return true;
}
internal override bool PostInstall(PackageItem packageItem) {
// run the install script
var pkgPath = packageItem.FullPath;
var scripts = Directory.EnumerateFiles(pkgPath, "chocolateyInstall.ps1", SearchOption.AllDirectories);
var script = scripts.FirstOrDefault();
if (script != null) {
try {
Environment.SetEnvironmentVariable("chocolateyPackageFolder", pkgPath);
Environment.SetEnvironmentVariable("chocolateyInstallArguments", "");
Environment.SetEnvironmentVariable("chocolateyInstallOverride", "");
InvokeChocolateyScript(script, pkgPath);
} catch (Exception e) {
e.Dump(this);
return false;
} finally {
Environment.SetEnvironmentVariable("chocolateyPackageFolder", null);
Environment.SetEnvironmentVariable("chocolateyInstallArguments", null);
Environment.SetEnvironmentVariable("chocolateyInstallOverride", null);
}
}
// Now handle 'bins'
return GenerateBins(pkgPath);
}
internal override bool PostUninstall(PackageItem packageItem) {
// run the uninstall script
return true;
}
internal override bool PreInstall(PackageItem packageItem) {
// run the install script
return true;
}
internal override bool PreUninstall(PackageItem packageItem) {
// run the uninstall script
return true;
}
internal bool Invoke(string script) {
using (var p = PowerShell.Create(RunspaceMode.NewRunspace)) {
p.Runspace.SessionStateProxy.SetVariable("request", this);
p.AddScript(HelperModuleText, false);
p.AddScript(script);
foreach (var result in p.Invoke().Where(result => result != null)) {
try {
Verbose(result.ToString());
} catch {
// no worries.
}
}
// todo: I'm seeing cases here were we're getting 'HadErrors == true' but can't find
// the error.
// disabling until I can find out why, or replace it with DynamicPowerShell and deal with the errors
/*
if (p.HadErrors ) {
return false;
}*
*/
}
return true;
}
internal bool InvokeChocolateyScript(string path, string workingDirectory) {
var pwd = Directory.GetCurrentDirectory();
try {
workingDirectory = string.IsNullOrEmpty(workingDirectory) ? pwd : workingDirectory;
if (Directory.Exists(workingDirectory)) {
Directory.SetCurrentDirectory(workingDirectory);
}
if (File.Exists(path)) {
path = Path.GetFullPath(path);
return Invoke(path);
}
} catch (Exception e) {
e.Dump(this);
} finally {
Directory.SetCurrentDirectory(pwd);
}
return false;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required.")]
public bool GetChocolateyWebFile(string packageName, string fileFullPath, string url, string url64bit) {
if (!string.IsNullOrEmpty(url64bit) && Environment.Is64BitOperatingSystem && !ForceX86) {
url = url64bit;
}
Verbose("GetChocolateyWebFile {0} => {1}", packageName, url);
var uri = new Uri(url);
DownloadFile(uri, fileFullPath, this.REQ);
if (string.IsNullOrEmpty(fileFullPath) || !FileExists(fileFullPath)) {
throw new Exception("Failed to download file {0}".format(url));
}
return true;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required.")]
public bool InstallChocolateyInstallPackage(string packageName, string fileType, string silentArgs, string file, int[] validExitCodes, string workingDirectory) {
Verbose("InstallChocolateyInstallPackage", "{0}", packageName);
switch (fileType.ToLowerInvariant()) {
case "msi":
case "msu":
return Install(file, silentArgs, this.REQ);
case "exe":
return StartChocolateyProcessAsAdmin("{0}".format(silentArgs), file, true, true, validExitCodes, workingDirectory);
}
return false;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required.")]
public bool InstallChocolateyPackage(string packageName, string fileType, string silentArgs, string url, string url64bit, int[] validExitCodes, string workingDirectory) {
try {
var tempFolder = Path.GetTempPath();
;
var chocTempDir = Path.Combine(tempFolder, "chocolatey");
var pkgTempDir = Path.Combine(chocTempDir, packageName);
Delete(pkgTempDir, this.REQ);
CreateFolder(pkgTempDir, this.REQ);
if (!string.IsNullOrEmpty(url64bit) && Environment.Is64BitOperatingSystem && !ForceX86) {
url = url64bit;
}
var localFile = CanonicalizePath(url, workingDirectory);
// check to see if the url is a local file
if (!FileExists(localFile)) {
localFile = null;
}
if (string.IsNullOrEmpty(localFile)) {
localFile = Path.Combine(pkgTempDir, "{0}install.{1}".format(packageName, fileType));
if (!GetChocolateyWebFile(packageName, localFile, url, url64bit)) {
throw new Exception(string.Format("Download failed {0} {1} {2}", url, url64bit, localFile));
}
}
if (InstallChocolateyInstallPackage(packageName, fileType, silentArgs, localFile, validExitCodes, workingDirectory)) {
Verbose("Package Successfully Installed", packageName);
return true;
}
throw new Exception("Failed Install.");
} catch (Exception e) {
e.Dump(this);
Error(ErrorCategory.InvalidResult, packageName, Constants.Messages.DependentPackageFailedInstall, packageName);
throw new Exception("Failed Installation");
}
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required.")]
public Snapshot SnapshotFolder(string locationToMonitor) {
return new Snapshot(this, locationToMonitor);
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required.")]
public bool InstallChocolateyPath(string pathToInstall, string context) {
if (context.Equals("machine", StringComparison.InvariantCultureIgnoreCase)) {
if (IsElevated) {
EnvironmentUtility.SystemPath = EnvironmentUtility.SystemPath.Append(pathToInstall).RemoveMissingFolders();
EnvironmentUtility.Path = EnvironmentUtility.Path.Append(pathToInstall).RemoveMissingFolders();
return true;
}
Verbose("Elevation Required--May not modify system path without elevation");
return false;
}
EnvironmentUtility.UserPath = EnvironmentUtility.UserPath.Append(pathToInstall).RemoveMissingFolders();
EnvironmentUtility.Path = EnvironmentUtility.Path.Append(pathToInstall).RemoveMissingFolders();
return true;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required.")]
public void UpdateSessionEnvironment() {
Verbose("Reloading Environment", "");
EnvironmentUtility.Rehash();
}
public string GetBatFileLocation(string exe, string name) {
if (string.IsNullOrEmpty(name)) {
return Path.Combine(PackageExePath, Path.GetFileNameWithoutExtension(exe) + ".bat");
} else {
return Path.Combine(PackageExePath, Path.GetFileNameWithoutExtension(name) + ".bat");
}
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Can be called from powershell")]
public void GeneratePS1ScriptBin(string ps1, string name = null) {
File.WriteAllText(GetBatFileLocation(ps1, name), @"@echo off
powershell -NoProfile -ExecutionPolicy unrestricted -Command ""& '{0}' %*""".format(ps1));
}
public void GenerateConsoleBin(string exe, string name = null) {
File.WriteAllText(GetBatFileLocation(exe, name), @"@echo off
SET DIR=%~dp0%
cmd /c ""%DIR%{0} %*""
exit /b %ERRORLEVEL%".format(PackageExePath.RelativePathTo(exe)));
}
public void GenerateGuiBin(string exe, string name = null) {
File.WriteAllText(GetBatFileLocation(exe, name), @"@echo off
SET DIR=%~dp0%
start """" ""%DIR%{0}"" %*".format(PackageExePath.RelativePathTo(exe)));
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required.")]
public bool RemoveBins(string pkgPath) {
var exes = Directory.EnumerateFiles(pkgPath, "*.exe", SearchOption.AllDirectories);
foreach (var exe in exes) {
if (File.Exists(exe + ".ignore")) {
continue;
}
if (File.Exists(exe + ".gui")) {
RemoveGuiBin(exe);
continue;
}
RemoveConsoleBin(exe);
}
return true;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required.")]
public void RemoveConsoleBin(string exe, string name = null) {
Delete(GetBatFileLocation(exe, name), this.REQ);
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required.")]
public void RemoveGuiBin(string exe, string name = null) {
Delete(GetBatFileLocation(exe, name), this.REQ);
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required.")]
public bool InstallChocolateyPowershellCommand(string packageName, string psFileFullPath, string url, string url64bit, string workingDirectory) {
if (GetChocolateyWebFile(packageName, psFileFullPath, url, url64bit)) {
if (File.Exists(psFileFullPath)) {
GeneratePS1ScriptBin(psFileFullPath);
return true;
}
}
Verbose("Unable to download script {0}", url);
return false;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required.")]
public bool InstallChocolateyVsixPackage(string packageName, string vsixUrl, string vsVersion) {
Verbose("InstallChocolateyVsixPackage", packageName);
var vs = Registry.LocalMachine.OpenSubKey(@"Software\Wow6432Node\Microsoft\VisualStudio");
var versions = vs.GetSubKeyNames().Select(each => {
float f;
if (!float.TryParse(each, out f)) {
return null;
}
if (f < 10.0) {
return null;
}
var vsv = vs.OpenSubKey(each);
if (vsv.GetValueNames().Contains("InstallDir", StringComparer.OrdinalIgnoreCase)) {
return new {
Version = f,
InstallDir = vsv.GetValue("InstallDir").ToString()
};
}
return null;
}).Where(each => each != null).OrderByDescending(each => each.Version);
var reqVsVersion = versions.FirstOrDefault();
if (!string.IsNullOrEmpty(vsVersion)) {
float f;
if (!float.TryParse(vsVersion, out f)) {
throw new Exception("Unable to parse version number");
}
reqVsVersion = versions.FirstOrDefault(each => each.Version == f);
}
if (reqVsVersion == null) {
throw new Exception("Required Visual Studio Version is not installed");
}
var vsixInstller = Path.Combine(reqVsVersion.InstallDir, "VsixInstaller.exe");
if (!File.Exists(vsixInstller)) {
throw new Exception("Can't find Visual Studio VSixInstaller.exe {0}".format(vsixInstller));
}
var file = Path.Combine(Path.GetTempPath(), packageName.MakeSafeFileName());
DownloadFile(new Uri(vsixUrl), file, this.REQ);
if (string.IsNullOrEmpty(file) || !File.Exists(file)) {
throw new Exception("Unable to download file {0}".format(vsixUrl));
}
var process = AsyncProcess.Start(new ProcessStartInfo {
FileName = vsixInstller,
Arguments = @"/q ""{0}""".format(file),
});
process.WaitForExit();
if (process.ExitCode > 0 && process.ExitCode != 1001) {
Verbose("VsixInstall Failure {0}", file);
throw new Exception("Install failure");
}
return false;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required.")]
public bool InstallChocolateyExplorerMenuItem(string menuKey, string menuLabel, string command, string type) {
Verbose("InstallChocolateyExplorerMenuItem", "{0}/{1}/{2}/{3}", menuKey, menuLabel, command, type);
var key = type == "file" ? "*" : (type == "directory" ? "directory" : null);
if (key == null) {
return false;
}
if (!IsElevated) {
return StartChocolateyProcessAsAdmin("Install-ChocolateyExplorerMenuItem '{0}' '{1}' '{2}' '{3}'".format(menuKey, menuLabel, command, type), "powershell", false, false, new[] {
0
}, Environment.CurrentDirectory);
}
var k = Registry.ClassesRoot.CreateSubKey(@"{0}\shell\{1}".format(key, menuKey));
k.SetValue(null, menuLabel);
var c = k.CreateSubKey("command");
c.SetValue(null, @"{0} ""%1""");
return true;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required.")]
public bool UninstallChocolateyPackage(string packageName, string fileType, string silentArgs, string file, int[] validExitCodes, string workingDirectory) {
Verbose("UninstallChocolateyPackage", packageName);
switch (fileType.ToLowerInvariant()) {
case "msi":
return StartChocolateyProcessAsAdmin("/x {0} {1}".format(file, silentArgs), "msiexec.exe", true, true, validExitCodes, workingDirectory);
case "exe":
return StartChocolateyProcessAsAdmin("{0}".format(silentArgs), file, true, true, validExitCodes, workingDirectory);
default:
Verbose("Unsupported Uninstall Type {0}", fileType);
break;
}
return false;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required.")]
public string GetChocolateyUnzip(string fileFullPath, string destination, string specificFolder, string packageName) {
Verbose("GetChocolateyUnzip", fileFullPath);
try {
var zipfileFullPath = fileFullPath;
if (!string.IsNullOrEmpty(specificFolder)) {
fileFullPath = Path.Combine(fileFullPath, specificFolder);
}
if (!string.IsNullOrEmpty(packageName)) {
var packageLibPath = Environment.GetEnvironmentVariable("ChocolateyPackageFolder");
CreateFolder(packageLibPath, this.REQ);
var zipFileName = Path.GetFileName(zipfileFullPath);
var zipExtractLogFullPath = Path.Combine(packageLibPath, "{0}.txt".format(zipFileName));
var snapshot = new Snapshot(this, destination);
// UnZip(fileFullPath, destination);
var files = UnpackArchive(fileFullPath, destination, this.REQ).ToArray();
snapshot.WriteFileDiffLog(zipExtractLogFullPath);
} else {
var files = UnpackArchive(fileFullPath, destination, this.REQ).ToArray();
}
return destination;
} catch (Exception e) {
e.Dump(this);
Verbose("PackageInstallation Failed {0}", packageName);
throw new Exception("Failed Installation");
}
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required.")]
public bool InstallChocolateyZipPackage(string packageName, string url, string unzipLocation, string url64bit, string specificFolder, string workingDirectory) {
Verbose("InstallChocolateyZipPackage", packageName);
try {
var tempFolder = Path.GetTempPath();
;
var chocTempDir = Path.Combine(tempFolder, "chocolatey");
var pkgTempDir = Path.Combine(chocTempDir, packageName);
Delete(pkgTempDir, this.REQ);
CreateFolder(pkgTempDir, this.REQ);
var file = Path.Combine(pkgTempDir, "{0}install.{1}".format(packageName, "zip"));
if (GetChocolateyWebFile(packageName, file, url, url64bit)) {
if (GetChocolateyUnzip(file, unzipLocation, specificFolder, packageName).Is()) {
Verbose("Package Successfully Installed", packageName);
return true;
}
throw new Exception("Failed Install.");
}
throw new Exception("Failed Download.");
} catch (Exception e) {
e.Dump(this);
Verbose("PackageInstallation Failed {0}", packageName);
throw new Exception("Failed Installation");
}
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required.")]
public bool UnInstallChocolateyZipPackage(string packageName, string zipFileName) {
Verbose("UnInstallChocolateyZipPackage", "Package '{0}', ZipFile '{1}'", packageName, zipFileName);
try {
var packageLibPath = Environment.GetEnvironmentVariable("ChocolateyPackageFolder");
var zipContentFile = Path.Combine(packageLibPath, "{0}.txt".format(Path.GetFileName(zipFileName)));
if (File.Exists(zipContentFile)) {
foreach (var file in File.ReadAllLines(zipContentFile).Where(each => !string.IsNullOrEmpty(each) && File.Exists(each))) {
DeleteFile(file, this.REQ);
}
}
} catch (Exception e) {
e.Dump(this);
Verbose("uninstall failure {0}", packageName);
}
return true;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required.")]
public bool InstallChocolateyFileAssociation(string extension, string executable) {
Verbose("InstallChocolateyFileAssociation", "{0} with executable {1}", extension, executable);
if (string.IsNullOrEmpty(executable)) {
throw new ArgumentNullException("executable");
}
if (string.IsNullOrEmpty(extension)) {
throw new ArgumentNullException("extension");
}
executable = Path.GetFullPath(executable);
if (!File.Exists(executable)) {
throw new FileNotFoundException("Executable not found", executable);
}
extension = "." + extension.Trim().Trim('.');
var fileType = Path.GetFileName(executable).Replace(' ', '_');
return StartChocolateyProcessAsAdmin(@"/c assoc {0}={1} & ftype {1}={2} ""%1"" %*".format(extension, fileType, executable), "cmd.exe", false, false, new[] {
0
}, Environment.CurrentDirectory);
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required.")]
public bool InstallChocolateyPinnedTaskBarItem(string targetFilePath) {
Verbose("InstallChocolateyPinnedTaskBarItem", targetFilePath);
if (string.IsNullOrEmpty(targetFilePath)) {
Verbose("Failed InstallChocolateyPinnedTaskBarItem -- Empty path");
throw new Exception("Failed.");
}
AddPinnedItemToTaskbar(Path.GetFullPath(targetFilePath), this.REQ);
return true;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Required.")]
public bool StartChocolateyProcessAsAdmin(string statements, string exeToRun, bool minimized, bool noSleep, int[] validExitCodes, string workingDirectory) {
Verbose("StartChocolateyProcessAsAdmin", "Exe '{0}', Args '{1}'", exeToRun, statements);
if (exeToRun.EqualsIgnoreCase("powershell")) {
// run as a powershell script
if (IsElevated) {
Verbose("Already Elevated", "Running PowerShell script in process");
// in proc, we're already good.
return Invoke(statements);
}
Verbose("Not Elevated", "Running PowerShell script in new process");
// otherwise setup a new proc
if (!ExecuteElevatedAction(ProviderName, statements, this.REQ)) {
Debug("Error during elevation");
return false;
}
return true;
}
// just a straight exec from here.
try {
Verbose("Launching Process", "EXE :'{0}'", exeToRun);
var process = AsyncProcess.Start(new ProcessStartInfo {
FileName = exeToRun,
Arguments = statements,
WorkingDirectory = workingDirectory,
WindowStyle = minimized ? ProcessWindowStyle.Hidden : ProcessWindowStyle.Normal,
Verb = IsElevated ? "" : "runas",
});
while (!process.WaitForExit(1)) {
if (IsCanceled) {
process.Kill();
Verbose("Process Killed", "Host requested cancellation");
throw new Exception("Killed Process {0}".format(exeToRun));
}
}
if (validExitCodes.Contains(process.ExitCode)) {
Verbose("Process Exited Successfully.", "{0}", exeToRun);
return true;
}
Verbose("Process Failed {0}", exeToRun);
throw new Exception("Process Exited with non-successful exit code {0} : {1} ".format(exeToRun, process.ExitCode));
} catch (Exception e) {
e.Dump(this);
Error("Process Execution Failed", "'{0}' -- {1}", exeToRun, e.Message);
throw e;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Bond.Expressions
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
public class TaggedParser<R> : IParser
{
delegate Expression TypeHandlerCompiletime(BondDataType type);
delegate Expression TypeHandlerRuntime(Expression type);
readonly TaggedReader<R> reader = new TaggedReader<R>();
readonly TaggedParser<R> baseParser;
readonly TaggedParser<R> fieldParser;
readonly bool isBase;
public TaggedParser(RuntimeSchema schema)
{
isBase = false;
baseParser = new TaggedParser<R>(this, isBase: true);
fieldParser = this;
}
public TaggedParser(Type type)
{
isBase = false;
baseParser = new TaggedParser<R>(this, isBase: true);
fieldParser = this;
}
private TaggedParser(TaggedParser<R> that, bool isBase)
{
this.isBase = isBase;
reader = that.reader;
baseParser = this;
fieldParser = that;
}
public ParameterExpression ReaderParam { get { return reader.Param; } }
public Expression ReaderValue { get { return reader.Param; } }
public int HierarchyDepth { get { return 0; } }
public bool IsBonded { get { return false; } }
public Expression Apply(ITransform transform)
{
var fieldId = Expression.Variable(typeof(UInt16), "fieldId");
var fieldType = Expression.Variable(typeof(BondDataType), "fieldType");
var endLabel = Expression.Label("end");
var breakLoop = Expression.Break(endLabel);
// (int)fieldType > (int)BT_STOP_BASE
var notEndOrEndBase = Expression.GreaterThan(
Expression.Convert(fieldType, typeof(int)),
Expression.Constant((int)BondDataType.BT_STOP_BASE));
var notEnd = isBase ? notEndOrEndBase : Expression.NotEqual(fieldType, Expression.Constant(BondDataType.BT_STOP));
var isEndBase = Expression.Equal(fieldType, Expression.Constant(BondDataType.BT_STOP_BASE));
var body = new List<Expression>
{
isBase ? reader.ReadBaseBegin() : reader.ReadStructBegin(),
transform.Begin,
transform.Base(baseParser),
reader.ReadFieldBegin(fieldType, fieldId)
};
// known fields
body.AddRange(
from f in transform.Fields select
Expression.Loop(
Expression.IfThenElse(notEndOrEndBase,
Expression.Block(
Expression.IfThenElse(
Expression.Equal(fieldId, Expression.Constant(f.Id)),
Expression.Block(
f.Value(fieldParser, fieldType),
reader.ReadFieldEnd(),
reader.ReadFieldBegin(fieldType, fieldId),
breakLoop),
Expression.IfThenElse(
Expression.GreaterThan(fieldId, Expression.Constant(f.Id)),
Expression.Block(
f.Omitted,
breakLoop),
transform.UnknownField(fieldParser, fieldType, fieldId) ?? Skip(fieldType))),
reader.ReadFieldEnd(),
reader.ReadFieldBegin(fieldType, fieldId),
Expression.IfThen(
Expression.GreaterThan(fieldId, Expression.Constant(f.Id)),
breakLoop)),
Expression.Block(
f.Omitted,
breakLoop)),
endLabel));
// unknown fields
body.Add(
ControlExpression.While(notEnd,
Expression.Block(
Expression.IfThenElse(
isEndBase,
transform.UnknownEnd,
Expression.Block(
transform.UnknownField(fieldParser, fieldType, fieldId) ?? Skip(fieldType),
reader.ReadFieldEnd())),
reader.ReadFieldBegin(fieldType, fieldId))));
body.Add(isBase ? reader.ReadBaseEnd() : reader.ReadStructEnd());
body.Add(transform.End);
return Expression.Block(
new[] { fieldType, fieldId },
body);
}
public Expression Container(BondDataType? expectedType, ContainerHandler handler)
{
var count = Expression.Variable(typeof(int), "count");
var elementType = Expression.Variable(typeof(BondDataType), "elementType");
var next = Expression.GreaterThan(Expression.PostDecrementAssign(count), Expression.Constant(0));
var loops = MatchOrCompatible(
elementType,
expectedType,
type => handler(this, type, next, count));
return Expression.Block(
new[] { count, elementType },
reader.ReadContainerBegin(count, elementType),
loops,
reader.ReadContainerEnd());
}
public Expression Map(BondDataType? expectedKeyType, BondDataType? expectedValueType, MapHandler handler)
{
var count = Expression.Variable(typeof(int), "count");
var keyType = Expression.Variable(typeof(BondDataType), "keyType");
var valueType = Expression.Variable(typeof(BondDataType), "valueType");
var next = Expression.GreaterThan(Expression.PostDecrementAssign(count), Expression.Constant(0));
var loops = MatchOrCompatible(keyType, expectedKeyType, constantKeyType =>
MatchOrCompatible(valueType, expectedValueType, constantValueType =>
handler(this, this, constantKeyType, constantValueType, next, Expression.Empty(), count)));
return Expression.Block(
new[] { count, keyType, valueType },
reader.ReadContainerBegin(count, keyType, valueType),
loops,
reader.ReadContainerEnd());
}
public Expression Blob(Expression count)
{
return reader.ReadBytes(count);
}
public Expression Scalar(Expression valueType, BondDataType expectedType, ValueHandler handler)
{
return MatchOrCompatible(valueType, expectedType,
type => handler(reader.Read(type)));
}
public Expression Bonded(ValueHandler handler)
{
var bondedCtor = typeof(BondedVoid<>).MakeGenericType(typeof(R)).GetConstructor(typeof(R));
return Expression.Block(
handler(Expression.New(bondedCtor, reader.Param)),
reader.Skip(Expression.Constant(BondDataType.BT_STRUCT)));
}
public Expression Skip(Expression type)
{
return reader.Skip(type);
}
private static Expression MatchOrCompatible(Expression valueType, BondDataType? expectedType, TypeHandlerRuntime handler)
{
return (expectedType == null) ?
handler(valueType) :
MatchOrCompatible(valueType, expectedType.Value, type => handler(Expression.Constant(type)));
}
// Generate expression to handle exact match or compatible type
private static Expression MatchOrCompatible(Expression valueType, BondDataType expectedType, TypeHandlerCompiletime handler)
{
return MatchOrElse(valueType, expectedType, handler,
TryCompatible(valueType, expectedType, handler));
}
// valueType maybe a ConstantExpression and then Prune optimizes unreachable branches out
private static Expression MatchOrElse(Expression valueType, BondDataType expectedType, TypeHandlerCompiletime handler, Expression orElse)
{
return PrunedExpression.IfThenElse(
Expression.Equal(valueType, Expression.Constant(expectedType)),
handler(expectedType),
orElse);
}
// Generates expression to handle value of type that is different but compatible with expected type
private static Expression TryCompatible(Expression valueType, BondDataType expectedType, TypeHandlerCompiletime handler)
{
if (expectedType == BondDataType.BT_DOUBLE)
{
return MatchOrElse(valueType, BondDataType.BT_FLOAT, handler,
InvalidType(expectedType, valueType));
}
if (expectedType == BondDataType.BT_UINT64)
{
return MatchOrElse(valueType, BondDataType.BT_UINT32, handler,
MatchOrElse(valueType, BondDataType.BT_UINT16, handler,
MatchOrElse(valueType, BondDataType.BT_UINT8, handler,
InvalidType(expectedType, valueType))));
}
if (expectedType == BondDataType.BT_UINT32)
{
return MatchOrElse(valueType, BondDataType.BT_UINT16, handler,
MatchOrElse(valueType, BondDataType.BT_UINT8, handler,
InvalidType(expectedType, valueType)));
}
if (expectedType == BondDataType.BT_UINT16)
{
return MatchOrElse(valueType, BondDataType.BT_UINT8, handler,
InvalidType(expectedType, valueType));
}
if (expectedType == BondDataType.BT_INT64)
{
return MatchOrElse(valueType, BondDataType.BT_INT32, handler,
MatchOrElse(valueType, BondDataType.BT_INT16, handler,
MatchOrElse(valueType, BondDataType.BT_INT8, handler,
InvalidType(expectedType, valueType))));
}
if (expectedType == BondDataType.BT_INT32)
{
return MatchOrElse(valueType, BondDataType.BT_INT16, handler,
MatchOrElse(valueType, BondDataType.BT_INT8, handler,
InvalidType(expectedType, valueType)));
}
if (expectedType == BondDataType.BT_INT16)
{
return MatchOrElse(valueType, BondDataType.BT_INT8, handler,
InvalidType(expectedType, valueType));
}
return InvalidType(expectedType, valueType);
}
private static Expression InvalidType(BondDataType expectedType, Expression valueType)
{
return ThrowExpression.InvalidTypeException(Expression.Constant(expectedType), valueType);
}
}
}
| |
// Copyright (c) 2003, Paul Welter
// All rights reserved.
// Modified by Joerg Krause ([email protected]) to adapt usage in Netrix component
using System;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Windows.Forms.Design;
using System.Drawing;
using System.Drawing.Design;
using System.Globalization;
using GuruComponents.Netrix.SpellChecker.NetSpell.Dictionary;
using GuruComponents.Netrix.SpellChecker.NetSpell.Dictionary.Affix;
using GuruComponents.Netrix.SpellChecker.NetSpell.Dictionary.Phonetic;
using System.Windows.Forms;
using System.Collections.Generic;
#pragma warning disable 414
namespace GuruComponents.Netrix.SpellChecker.NetSpell
{
/// <summary>
/// The Spelling class encapsulates the functions necessary to check
/// the spelling of inputted text.
/// </summary>
[ToolboxItem(false)]
internal class Spelling : ISpelling
{
#region Global Regex
// Regex are class scope and compiled to improve performance on reuse
private Regex _digitRegex = new Regex(@"^\d", RegexOptions.Compiled);
private Regex _htmlRegex = new Regex(@"</[c-g\d]+>|</[i-o\d]+>|</[a\d]+>|</[q-z\d]+>|<[cg]+[^>]*>|<[i-o]+[^>]*>|<[q-z]+[^>]*>|<[a]+[^>]*>|<(\[^\]*\|'[^']*'|[^'\>])*>", RegexOptions.IgnoreCase & RegexOptions.Compiled);
private MatchCollection _htmlTags;
private Regex _letterRegex = new Regex(@"\D", RegexOptions.Compiled);
private Regex _upperRegex = new Regex(@"[^A-Z]", RegexOptions.Compiled);
// Unicode support added to asian and non-latin languages
private Regex _wordEx = new Regex(@"\b[A-Za-z0-9_\u00A0-\uFFFF]+\b", RegexOptions.Compiled);
private MatchCollection _words;
#endregion
#region private variables
private System.ComponentModel.Container components = null;
#endregion
#region Events
/// <summary>
/// This event is fired when a word is deleted
/// </summary>
/// <remarks>
/// Use this event to update the parent text
/// </remarks>
public event DeletedWordEventHandler DeletedWord;
/// <summary>
/// This event is fired when word is detected two times in a row
/// </summary>
public event DoubledWordEventHandler DoubledWord;
/// <summary>
/// This event is fired when the spell checker reaches the end of
/// the text in the Text property
/// </summary>
public event EndOfTextEventHandler EndOfText;
/// <summary>
/// This event is fired when a word is skipped
/// </summary>
public event IgnoredWordEventHandler IgnoredWord;
/// <summary>
/// This event is fired when the spell checker finds a word that
/// is not in the dictionaries
/// </summary>
public event MisspelledWordEventHandler MisspelledWord;
/// <summary>
/// This event is fired when a word is replace
/// </summary>
/// <remarks>
/// Use this event to update the parent text
/// </remarks>
public event ReplacedWordEventHandler ReplacedWord;
/// <summary>
/// This represents the delegate method prototype that
/// event receivers must implement
/// </summary>
public delegate void DeletedWordEventHandler(object sender, SpellingEventArgs e);
/// <summary>
/// This represents the delegate method prototype that
/// event receivers must implement
/// </summary>
public delegate void DoubledWordEventHandler(object sender, SpellingEventArgs e);
/// <summary>
/// This represents the delegate method prototype that
/// event receivers must implement
/// </summary>
public delegate void EndOfTextEventHandler(object sender, System.EventArgs e);
/// <summary>
/// This represents the delegate method prototype that
/// event receivers must implement
/// </summary>
public delegate void IgnoredWordEventHandler(object sender, SpellingEventArgs e);
/// <summary>
/// This represents the delegate method prototype that
/// event receivers must implement
/// </summary>
public delegate void MisspelledWordEventHandler(object sender, SpellingEventArgs e);
/// <summary>
/// This represents the delegate method prototype that
/// event receivers must implement
/// </summary>
public delegate void ReplacedWordEventHandler(object sender, ReplaceWordEventArgs e);
/// <summary>
/// This is the method that is responsible for notifying
/// receivers that the event occurred
/// </summary>
protected virtual void OnDeletedWord(SpellingEventArgs e)
{
if (DeletedWord != null)
{
DeletedWord(this, e);
}
}
/// <summary>
/// This is the method that is responsible for notifying
/// receivers that the event occurred
/// </summary>
protected virtual void OnDoubledWord(SpellingEventArgs e)
{
if (DoubledWord != null)
{
DoubledWord(this, e);
}
}
/// <summary>
/// This is the method that is responsible for notifying
/// receivers that the event occurred
/// </summary>
protected virtual void OnEndOfText(System.EventArgs e)
{
if (EndOfText != null)
{
EndOfText(this, e);
}
}
/// <summary>
/// This is the method that is responsible for notifying
/// receivers that the event occurred
/// </summary>
protected virtual void OnIgnoredWord(SpellingEventArgs e)
{
if (IgnoredWord != null)
{
IgnoredWord(this, e);
}
}
/// <summary>
/// This is the method that is responsible for notifying
/// receivers that the event occurred
/// </summary>
protected virtual void OnMisspelledWord(SpellingEventArgs e)
{
if (MisspelledWord != null)
{
MisspelledWord(this, e);
}
}
/// <summary>
/// This is the method that is responsible for notifying
/// receivers that the event occurred
/// </summary>
protected virtual void OnReplacedWord(ReplaceWordEventArgs e)
{
if (ReplacedWord != null)
{
ReplacedWord(this, e);
}
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the SpellCheck class
/// </summary>
public Spelling()
{
}
#endregion
#region private methods
/// <summary>
/// Calculates the words from the Text property
/// </summary>
private void CalculateWords()
{
// splits the text into words
_words = _wordEx.Matches(_text.ToString());
// remark html
this.MarkHtml();
}
/// <summary>
/// Determines if the string should be spell checked
/// </summary>
/// <param name="characters" type="string">
/// <para>
/// The Characters to check
/// </para>
/// </param>
/// <returns>
/// Returns true if the string should be spell checked
/// </returns>
private bool CheckString(string characters)
{
if(_ignoreAllCapsWords && !_upperRegex.IsMatch(characters))
{
return false;
}
if(_ignoreWordsWithDigits && _digitRegex.IsMatch(characters))
{
return false;
}
if(!_letterRegex.IsMatch(characters))
{
return false;
}
if(_ignoreHtml)
{
int startIndex = _words[this.WordIndex].Index;
foreach (Match item in _htmlTags)
{
if (startIndex >= item.Index && startIndex <= item.Index + item.Length - 1)
{
return false;
}
}
}
return true;
}
private void Initialize()
{
if(_dictionary == null)
_dictionary = new WordDictionary();
if(!_dictionary.Initialized)
_dictionary.Initialize();
}
/// <summary>
/// Calculates the position of html tags in the Text property
/// </summary>
private void MarkHtml()
{
// splits the text into words
_htmlTags = _htmlRegex.Matches(_text.ToString());
}
/// <summary>
/// Resets the public properties
/// </summary>
private void Reset()
{
_wordIndex = 0; // reset word index
_replacementWord = "";
_suggestions.Clear();
}
#endregion
#region ISpell Near Miss Suggetion methods
/// <summary>
/// swap out each char one by one and try all the tryme
/// chars in its place to see if that makes a good word
/// </summary>
private void BadChar(ref ArrayList tempSuggestion)
{
for (int i = 0; i < this.CurrentWord.Length; i++)
{
StringBuilder tempWord = new StringBuilder(this.CurrentWord);
char[] tryme = this.Dictionary.TryCharacters.ToCharArray();
for (int x = 0; x < tryme.Length; x++)
{
tempWord[i] = tryme[x];
if (this.TestWord(tempWord.ToString()))
{
Word ws = new Word();
ws.Text = tempWord.ToString().ToLower();
ws.EditDistance = this.EditDistance(this.CurrentWord, tempWord.ToString());
tempSuggestion.Add(ws);
}
}
}
}
/// <summary>
/// try omitting one char of word at a time
/// </summary>
private void ExtraChar(ref ArrayList tempSuggestion)
{
if (this.CurrentWord.Length > 1)
{
for (int i = 0; i < this.CurrentWord.Length; i++)
{
StringBuilder tempWord = new StringBuilder(this.CurrentWord);
tempWord.Remove(i, 1);
if (this.TestWord(tempWord.ToString()))
{
Word ws = new Word();
ws.Text = tempWord.ToString().ToLower(CultureInfo.CurrentUICulture);
ws.EditDistance = this.EditDistance(this.CurrentWord, tempWord.ToString());
tempSuggestion.Add(ws);
}
}
}
}
/// <summary>
/// try inserting a tryme character before every letter
/// </summary>
private void ForgotChar(ref ArrayList tempSuggestion)
{
char[] tryme = this.Dictionary.TryCharacters.ToCharArray();
for (int i = 0; i <= this.CurrentWord.Length; i++)
{
for (int x = 0; x < tryme.Length; x++)
{
StringBuilder tempWord = new StringBuilder(this.CurrentWord);
tempWord.Insert(i, tryme[x]);
if (this.TestWord(tempWord.ToString()))
{
Word ws = new Word();
ws.Text = tempWord.ToString().ToLower();
ws.EditDistance = this.EditDistance(this.CurrentWord, tempWord.ToString());
tempSuggestion.Add(ws);
}
}
}
}
/// <summary>
/// suggestions for a typical fault of spelling, that
/// differs with more, than 1 letter from the right form.
/// </summary>
private void ReplaceChars(ref ArrayList tempSuggestion)
{
List<string> replacementChars = this.Dictionary.ReplaceCharacters;
for (int i = 0; i < replacementChars.Count; i++)
{
int split = ((string)replacementChars[i]).IndexOf(' ');
string key = ((string)replacementChars[i]).Substring(0, split);
string replacement = ((string)replacementChars[i]).Substring(split+1);
int pos = this.CurrentWord.IndexOf(key);
while (pos > -1)
{
string tempWord = this.CurrentWord.Substring(0, pos);
tempWord += replacement;
tempWord += this.CurrentWord.Substring(pos + key.Length);
if (this.TestWord(tempWord))
{
Word ws = new Word();
ws.Text = tempWord.ToString().ToLower();
ws.EditDistance = this.EditDistance(this.CurrentWord, tempWord.ToString());
tempSuggestion.Add(ws);
}
pos = this.CurrentWord.IndexOf(key, pos+1);
}
}
}
/// <summary>
/// try swapping adjacent chars one by one
/// </summary>
private void SwapChar(ref ArrayList tempSuggestion)
{
for (int i = 0; i < this.CurrentWord.Length - 1; i++)
{
StringBuilder tempWord = new StringBuilder(this.CurrentWord);
char swap = tempWord[i];
tempWord[i] = tempWord[i+1];
tempWord[i+1] = swap;
if (this.TestWord(tempWord.ToString()))
{
Word ws = new Word();
ws.Text = tempWord.ToString().ToLower();
ws.EditDistance = this.EditDistance(this.CurrentWord, tempWord.ToString());
tempSuggestion.Add(ws);
}
}
}
/// <summary>
/// split the string into two pieces after every char
/// if both pieces are good words make them a suggestion
/// </summary>
private void TwoWords(ref ArrayList tempSuggestion)
{
for (int i = 1; i < this.CurrentWord.Length - 1; i++)
{
string firstWord = this.CurrentWord.Substring(0,i);
string secondWord = this.CurrentWord.Substring(i);
if (this.TestWord(firstWord) && this.TestWord(secondWord))
{
string tempWord = firstWord + " " + secondWord;
Word ws = new Word();
ws.Text = tempWord.ToString().ToLower();
ws.EditDistance = this.EditDistance(this.CurrentWord, tempWord.ToString());
tempSuggestion.Add(ws);
}
}
}
#endregion
#region public methods
/// <summary>
/// Deletes the CurrentWord from the Text Property
/// </summary>
/// <remarks>
/// Note, calling ReplaceWord with the ReplacementWord property set to
/// an empty string has the same behavior as DeleteWord.
/// </remarks>
public void DeleteWord()
{
if (_words == null || _words.Count == 0)
{
System.Diagnostics.Debug.WriteLine("No Words to Delete");
return;
}
string replacedWord = this.CurrentWord;
int replacedIndex = this.WordIndex;
int index = _words[replacedIndex].Index;
int length = _words[replacedIndex].Length;
// adjust length to remove extra white space after first word
if (index == 0
&& index + length < _text.Length
&& _text[index+length] == ' ')
{
length++; //removing trailing space
}
// adjust length to remove double white space
else if (index > 0
&& index + length < _text.Length
&& _text[index-1] == ' '
&& _text[index+length] == ' ')
{
length++; //removing trailing space
}
// adjust index to remove extra white space before punctuation
else if (index > 0
&& index + length < _text.Length
&& _text[index-1] == ' '
&& char.IsPunctuation(_text[index+length]))
{
index--;
length++;
}
// adjust index to remove extra white space before last word
else if (index > 0
&& index + length == _text.Length
&& _text[index-1] == ' ')
{
index--;
length++;
}
string deletedWord = _text.ToString(index, length);
_text.Remove(index, length);
this.CalculateWords();
this.OnDeletedWord(new SpellingEventArgs(deletedWord, replacedIndex, index, null));
}
/// <summary>
/// Calculates the minimum number of change, inserts or deletes
/// required to change firstWord into secondWord
/// </summary>
/// <param name="source" type="string">
/// <para>
/// The first word to calculate
/// </para>
/// </param>
/// <param name="target" type="string">
/// <para>
/// The second word to calculate
/// </para>
/// </param>
/// <param name="positionPriority" type="bool">
/// <para>
/// set to true if the first and last char should have priority
/// </para>
/// </param>
/// <returns>
/// The number of edits to make firstWord equal secondWord
/// </returns>
public int EditDistance(string source, string target, bool positionPriority)
{
// i.e. 2-D array
Array matrix = Array.CreateInstance(typeof(int), source.Length+1, target.Length+1);
// boundary conditions
matrix.SetValue(0, 0, 0);
for(int j=1; j <= target.Length; j++)
{
// boundary conditions
int val = (int)matrix.GetValue(0,j-1);
matrix.SetValue(val+1, 0, j);
}
// outer loop
for(int i=1; i <= source.Length; i++)
{
// boundary conditions
int val = (int)matrix.GetValue(i-1, 0);
matrix.SetValue(val+1, i, 0);
// inner loop
for(int j=1; j <= target.Length; j++)
{
int diag = (int)matrix.GetValue(i-1, j-1);
if(source.Substring(i-1, 1) != target.Substring(j-1, 1))
{
diag++;
}
int deletion = (int)matrix.GetValue(i-1, j);
int insertion = (int)matrix.GetValue(i, j-1);
int match = Math.Min(deletion+1, insertion+1);
matrix.SetValue(Math.Min(diag, match), i, j);
}//for j
}//for i
int dist = (int)matrix.GetValue(source.Length, target.Length);
// extra edit on first and last chars
if (positionPriority)
{
if (source[0] != target[0]) dist++;
if (source[source.Length-1] != target[target.Length-1]) dist++;
}
return dist;
}
/// <summary>
/// Calculates the minimum number of change, inserts or deletes
/// required to change firstWord into secondWord
/// </summary>
/// <param name="source" type="string">
/// <para>
/// The first word to calculate
/// </para>
/// </param>
/// <param name="target" type="string">
/// <para>
/// The second word to calculate
/// </para>
/// </param>
/// <returns>
/// The number of edits to make firstWord equal secondWord
/// </returns>
/// <remarks>
/// This method automatically gives priority to matching the first and last char
/// </remarks>
public int EditDistance(string source, string target)
{
return this.EditDistance(source, target, true);
}
/// <summary>
/// Gets the word index from the text index. Use this method to
/// find a word based on the text position.
/// </summary>
/// <param name="textIndex">
/// <para>
/// The index to search for
/// </para>
/// </param>
/// <returns>
/// The word index that the text index falls on
/// </returns>
public int GetWordIndexFromTextIndex(int textIndex)
{
if (_words == null || _words.Count == 0 || textIndex < 1)
{
System.Diagnostics.Debug.WriteLine("No words to get text index from.");
return 0;
}
if(_words.Count == 1)
return 0;
int low=0;
int high=_words.Count-1;
// binary search
while(low<=high)
{
int mid=(low+high)/2;
int wordStartIndex = _words[mid].Index;
int wordEndIndex = _words[mid].Index + _words[mid].Length - 1;
// add white space to end of word by finding the start of the next word
if ((mid+1) < _words.Count)
wordEndIndex = _words[mid+1].Index - 1;
if(textIndex < wordStartIndex)
high=mid-1;
else if(textIndex > wordEndIndex)
low=mid+1;
else if(wordStartIndex <= textIndex && textIndex <= wordEndIndex)
return mid;
}
// return last word if not found
return _words.Count-1;
}
/// <summary>
/// Ignores all instances of the CurrentWord in the Text Property
/// </summary>
public void IgnoreAllWord()
{
if (this.CurrentWord.Length == 0)
{
System.Diagnostics.Debug.WriteLine("No current word");
return;
}
// Add current word to ignore list
_ignoreList.Add(this.CurrentWord);
this.IgnoreWord();
}
/// <summary>
/// Ignores the instances of the CurrentWord in the Text Property.
/// </summary>
/// <remarks>
/// Must call SpellCheck after call this method to resume spell checking.
/// Forces the IgnoredWord event on Speller plug-in. Host application must handle.
/// </remarks>
public void IgnoreWord()
{
if (_words == null || _words.Count == 0 || this.CurrentWord.Length == 0)
{
System.Diagnostics.Debug.WriteLine("No text or current word");
return;
}
this.OnIgnoredWord(new SpellingEventArgs(
this.CurrentWord,
this.WordIndex,
_words[this.WordIndex].Index,
null));
// increment Word Index to skip over this word
_wordIndex++;
}
/// <summary>
/// Replaces all instances of the CurrentWord in the Text Property
/// </summary>
public void ReplaceAllWord()
{
if (this.CurrentWord.Length == 0)
{
System.Diagnostics.Debug.WriteLine("No current word");
return;
}
// if not in list and replacement word has length
if(!_replaceList.ContainsKey(this.CurrentWord) && _replacementWord.Length > 0)
{
_replaceList.Add(this.CurrentWord, _replacementWord);
}
this.ReplaceWord();
}
/// <summary>
/// Replaces all instances of the CurrentWord in the Text Property
/// </summary>
/// <param name="replacementWord" type="string">
/// <para>
/// The word to replace the CurrentWord with
/// </para>
/// </param>
public void ReplaceAllWord(string replacementWord)
{
this.ReplacementWord = replacementWord;
this.ReplaceAllWord();
}
/// <summary>
/// Replaces the instances of the CurrentWord in the Text Property
/// </summary>
public void ReplaceWord()
{
if (_words == null || _words.Count == 0 || this.CurrentWord.Length == 0)
{
System.Diagnostics.Debug.WriteLine("No text or current word");
return;
}
if (_replacementWord.Length == 0)
{
this.DeleteWord();
return;
}
string replacedWord = this.CurrentWord;
int replacedIndex = this.WordIndex;
int index = _words[replacedIndex].Index;
int length = _words[replacedIndex].Length;
_text.Remove(index, length);
// if first letter upper case, match case for replacement word
if (char.IsUpper(_words[replacedIndex].ToString(), 0))
{
_replacementWord = _replacementWord.Substring(0,1).ToUpper(CultureInfo.CurrentUICulture)
+ _replacementWord.Substring(1);
}
_text.Insert(index, _replacementWord);
this.CalculateWords();
this.OnReplacedWord(new ReplaceWordEventArgs(
_replacementWord,
replacedWord,
replacedIndex,
index));
}
/// <summary>
/// Replaces the instances of the CurrentWord in the Text Property
/// </summary>
/// <param name="replacementWord" type="string">
/// <para>
/// The word to replace the CurrentWord with
/// </para>
/// </param>
public void ReplaceWord(string replacementWord)
{
this.ReplacementWord = replacementWord;
this.ReplaceWord();
}
/// <summary>
/// Spell checks the words in the <see cref="Text"/> property starting
/// at the <see cref="WordIndex"/> position.
/// </summary>
/// <returns>
/// Returns true if there is a word found in the text
/// that is not in the dictionaries
/// </returns>
/// <seealso cref="CurrentWord"/>
/// <seealso cref="WordIndex"/>
public bool SpellCheck()
{
return SpellCheck(_wordIndex, this.WordCount-1);
}
/// <summary>
/// Spell checks the words in the <see cref="Text"/> property starting
/// at the <see cref="WordIndex"/> position. This overload takes in the
/// WordIndex to start checking from.
/// </summary>
/// <param name="startWordIndex" type="int">
/// <para>
/// The index of the word to start checking from.
/// </para>
/// </param>
/// <returns>
/// Returns true if there is a word found in the text
/// that is not in the dictionaries
/// </returns>
/// <seealso cref="CurrentWord"/>
/// <seealso cref="WordIndex"/>
public bool SpellCheck(int startWordIndex)
{
_wordIndex = startWordIndex;
return SpellCheck();
}
/// <summary>
/// Spell checks a range of words in the <see cref="Text"/> property starting
/// at the <see cref="WordIndex"/> position and ending at endWordIndex.
/// </summary>
/// <param name="startWordIndex" type="int">
/// <para>
/// The index of the word to start checking from.
/// </para>
/// </param>
/// <param name="endWordIndex" type="int">
/// <para>
/// The index of the word to end checking with.
/// </para>
/// </param>
/// <returns>
/// Returns true if there is a word found in the text
/// that is not in the dictionaries
/// </returns>
/// <seealso cref="CurrentWord"/>
/// <seealso cref="WordIndex"/>
public bool SpellCheck(int startWordIndex, int endWordIndex)
{
if(startWordIndex > endWordIndex || _words == null || _words.Count == 0)
{
// make sure end index is not greater then word count
this.OnEndOfText(System.EventArgs.Empty); //raise event
return false;
}
this.Initialize();
string currentWord = "";
bool misspelledWord = false;
for (int i = startWordIndex; i <= endWordIndex; i++)
{
_wordIndex = i; // saving the current word index
currentWord = this.CurrentWord;
if(CheckString(currentWord))
{
if(!TestWord(currentWord))
{
if(_replaceList.ContainsKey(currentWord))
{
this.ReplacementWord = _replaceList[currentWord].ToString();
this.ReplaceWord();
}
else if(!_ignoreList.Contains(currentWord))
{
misspelledWord = true;
this.OnMisspelledWord(new SpellingEventArgs(currentWord, i, _words[i].Index, Suggestions)); //raise event
break;
}
}
else if(i > 0 && _words[i-1].Value.ToString() == currentWord
&& (_words[i-1].Index + _words[i-1].Length + 1) == _words[i].Index)
{
misspelledWord = true;
this.OnDoubledWord(new SpellingEventArgs(currentWord, i, _words[i].Index, Suggestions)); //raise event
break;
}
}
} // for
if(_wordIndex >= _words.Count-1 && !misspelledWord)
{
this.OnEndOfText(System.EventArgs.Empty); //raise event
}
return misspelledWord;
} // SpellCheck
/// <summary>
/// Spell checks the words in the <see cref="Text"/> property starting
/// at the <see cref="WordIndex"/> position. This overload takes in the
/// text to spell check
/// </summary>
/// <param name="text" type="string">
/// <para>
/// The text to spell check
/// </para>
/// </param>
/// <returns>
/// Returns true if there is a word found in the text
/// that is not in the dictionaries
/// </returns>
/// <seealso cref="CurrentWord"/>
/// <seealso cref="WordIndex"/>
public bool SpellCheck(string text)
{
this.Text = text;
return SpellCheck();
}
/// <summary>
/// Spell checks the words in the <see cref="Text"/> property starting
/// at the <see cref="WordIndex"/> position. This overload takes in
/// the text to check and the WordIndex to start checking from.
/// </summary>
/// <param name="text" type="string">
/// <para>
/// The text to spell check
/// </para>
/// </param>
/// <param name="startWordIndex" type="int">
/// <para>
/// The index of the word to start checking from
/// </para>
/// </param>
/// <returns>
/// Returns true if there is a word found in the text
/// that is not in the dictionaries
/// </returns>
/// <seealso cref="CurrentWord"/>
/// <seealso cref="WordIndex"/>
public bool SpellCheck(string text, int startWordIndex)
{
this.WordIndex = startWordIndex;
this.Text = text;
return SpellCheck();
}
/// <summary>
/// Populates the <see cref="Suggestions"/> property with word suggestions
/// for the word
/// </summary>
/// <param name="word" type="string">
/// <para>
/// The word to generate suggestions on
/// </para>
/// </param>
/// <remarks>
/// This method sets the <see cref="Text"/> property to the word.
/// Then calls <see cref="TestWord"/> on the word to generate the need
/// information for suggestions. Note that the Text, CurrentWord and WordIndex
/// properties are set when calling this method.
/// </remarks>
/// <seealso cref="CurrentWord"/>
/// <seealso cref="Suggestions"/>
/// <seealso cref="TestWord"/>
public void Suggest(string word)
{
this.Text = word;
if(!this.TestWord(word))
this.Suggest();
}
/// <summary>
/// Populates the <see cref="Suggestions"/> property with word suggestions
/// for the <see cref="CurrentWord"/>
/// </summary>
/// <remarks>
/// <see cref="TestWord"/> must have been called before calling this method
/// </remarks>
/// <seealso cref="CurrentWord"/>
/// <seealso cref="Suggestions"/>
/// <seealso cref="TestWord"/>
public void Suggest()
{
// can't generate suggestions with out current word
if (this.CurrentWord.Length == 0)
{
System.Diagnostics.Debug.WriteLine("No current word");
return;
}
this.Initialize();
ArrayList tempSuggestion = new ArrayList();
if ((_suggestionMode == SuggestionEnum.PhoneticNearMiss
|| _suggestionMode == SuggestionEnum.Phonetic)
&& _dictionary.PhoneticRules.Count > 0)
{
// generate phonetic code for possible root word
Hashtable codes = new Hashtable();
foreach (string tempWord in _dictionary.PossibleBaseWords)
{
string tempCode = _dictionary.PhoneticCode(tempWord);
if (tempCode.Length > 0 && !codes.ContainsKey(tempCode))
{
codes.Add(tempCode, tempCode);
}
}
if (codes.Count > 0)
{
// search root words for phonetic codes
foreach (Word word in _dictionary.BaseWords.Values)
{
if (codes.ContainsKey(word.PhoneticCode))
{
ArrayList words = _dictionary.ExpandWord(word);
// add expanded words
foreach (string expandedWord in words)
{
Word newWord = new Word();
newWord.Text = expandedWord;
newWord.EditDistance = this.EditDistance(this.CurrentWord, expandedWord);
tempSuggestion.Add(newWord);
}
}
}
}
System.Diagnostics.Debug.WriteLine(tempSuggestion.Count, "Suggestiongs Found with Phonetic Stratagy: ");
}
if (_suggestionMode == SuggestionEnum.PhoneticNearMiss
|| _suggestionMode == SuggestionEnum.NearMiss)
{
// suggestions for a typical fault of spelling, that
// differs with more, than 1 letter from the right form.
this.ReplaceChars(ref tempSuggestion);
// swap out each char one by one and try all the tryme
// chars in its place to see if that makes a good word
this.BadChar(ref tempSuggestion);
// try omitting one char of word at a time
this.ExtraChar(ref tempSuggestion);
// try inserting a tryme character before every letter
this.ForgotChar(ref tempSuggestion);
// split the string into two pieces after every char
// if both pieces are good words make them a suggestion
this.TwoWords(ref tempSuggestion);
// try swapping adjacent chars one by one
this.SwapChar(ref tempSuggestion);
}
System.Diagnostics.Debug.WriteLine(tempSuggestion.Count, "Total Suggestiongs Found: ");
tempSuggestion.Sort(); // sorts by edit score
_suggestions.Clear();
for (int i = 0; i < tempSuggestion.Count; i++)
{
string word = ((Word)tempSuggestion[i]).Text;
// looking for duplicates
if (!_suggestions.Contains(word))
{
// populating the suggestion list
_suggestions.Add(word);
}
if (_suggestions.Count >= _maxSuggestions && _maxSuggestions > 0)
{
break;
}
}
} // suggest
/// <summary>
/// Checks to see if the word is in the dictionary
/// </summary>
/// <param name="word" type="string">
/// <para>
/// The word to check
/// </para>
/// </param>
/// <returns>
/// Returns true if word is found in dictionary
/// </returns>
public bool TestWord(string word)
{
this.Initialize();
if (this.Dictionary.Contains(word))
{
return true;
}
else if (this.Dictionary.Contains(word.ToLower()))
{
return true;
}
return false;
}
#endregion
#region public properties
private bool _alertComplete = true;
private WordDictionary _dictionary;
private bool _ignoreAllCapsWords = true;
private bool _ignoreHtml = true;
private List<string> _ignoreList = new List<string>();
private bool _ignoreWordsWithDigits = false;
private int _maxSuggestions = 25;
private Dictionary<string, string> _replaceList = new Dictionary<string, string>();
private string _replacementWord = "";
private bool _showDialog = false;
private Form _spellcheckerForm;
private SuggestionEnum _suggestionMode = SuggestionEnum.PhoneticNearMiss;
private List<string> _suggestions = new List<string>();
private StringBuilder _text = new StringBuilder();
internal int _wordIndex = 0;
/// <summary>
/// Display the 'Spell Check Complete' alert.
/// </summary>
[Browsable(true)]
[DefaultValue(true)]
[CategoryAttribute("Options")]
[Description("Display the 'Spell Check Complete' alert.")]
public bool AlertComplete
{
get { return _alertComplete; }
set { _alertComplete = value; }
}
/// <summary>
/// The current word being spell checked from the text property
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string CurrentWord
{
get
{
if(_words == null || _words.Count == 0)
return string.Empty;
else
return _words[this.WordIndex].Value;
}
}
/// <summary>
/// The WordDictionary object to use when spell checking
/// </summary>
[Browsable(false)]
[CategoryAttribute("Dictionary")]
[Description("The WordDictionary object to use when spell checking")]
public WordDictionary Dictionary
{
get
{
if(_dictionary == null)
_dictionary = new WordDictionary();
return _dictionary;
}
set
{
if (value != null)
_dictionary = value;
}
}
/// <summary>
/// Ignore words with all capital letters when spell checking
/// </summary>
[DefaultValue(true)]
[CategoryAttribute("Options")]
[Description("Ignore words with all capital letters when spell checking")]
public bool IgnoreAllCapsWords
{
get {return _ignoreAllCapsWords;}
set {_ignoreAllCapsWords = value;}
}
/// <summary>
/// Ignore html tags when spell checking
/// </summary>
[DefaultValue(true)]
[CategoryAttribute("Options")]
[Description("Ignore html tags when spell checking")]
public bool IgnoreHtml
{
get {return _ignoreHtml;}
set {_ignoreHtml = value;}
}
/// <summary>
/// List of words to automatically ignore
/// </summary>
/// <remarks>
/// When <see cref="IgnoreAllWord"/> is clicked, the <see cref="CurrentWord"/> is added to this list
/// </remarks>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public List<string> IgnoreList
{
get {return _ignoreList;}
}
/// <summary>
/// Ignore words with digits when spell checking
/// </summary>
[DefaultValue(false)]
[CategoryAttribute("Options")]
[Description("Ignore words with digits when spell checking")]
public bool IgnoreWordsWithDigits
{
get {return _ignoreWordsWithDigits;}
set {_ignoreWordsWithDigits = value;}
}
/// <summary>
/// The maximum number of suggestions to generate
/// </summary>
[DefaultValue(25)]
[CategoryAttribute("Options")]
[Description("The maximum number of suggestions to generate")]
public int MaxSuggestions
{
get {return _maxSuggestions;}
set {_maxSuggestions = value;}
}
/// <summary>
/// List of words and replacement values to automatically replace
/// </summary>
/// <remarks>
/// When <see cref="ReplaceAllWord()"/> is clicked, the <see cref="CurrentWord"/> is added to this list
/// </remarks>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Dictionary<string,string> ReplaceList
{
get {return _replaceList;}
}
/// <summary>
/// The word to used when replacing the misspelled word
/// </summary>
/// <seealso cref="ReplaceAllWord()"/>
/// <seealso cref="ReplaceWord()"/>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string ReplacementWord
{
get {return _replacementWord;}
set {_replacementWord = value.Trim();}
}
/// <summary>
/// Determines if the spell checker should use an attached dialog.
/// </summary>
[DefaultValue(true)]
[CategoryAttribute("Options")]
[Description("Determines if the spell checker should use attached dialogs.")]
public bool ShowDialog
{
get {return _showDialog;}
set
{
_showDialog = value;
}
}
/// <summary>
/// Gets or sets the dialog form that is shown internally.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Form SpellcheckerForm
{
get
{
return _spellcheckerForm;
}
set
{
_spellcheckerForm = value;
}
}
/// <summary>
/// The suggestion strategy to use when generating suggestions
/// </summary>
[DefaultValue(SuggestionEnum.PhoneticNearMiss)]
[CategoryAttribute("Options")]
[Description("The suggestion strategy to use when generating suggestions")]
public SuggestionEnum SuggestionMode
{
get {return _suggestionMode;}
set {_suggestionMode = value;}
}
/// <summary>
/// An array of word suggestions for the correct spelling of the misspelled word
/// </summary>
/// <seealso cref="Suggest()"/>
/// <seealso cref="SpellCheck(string)"/>
/// <seealso cref="MaxSuggestions"/>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public List<string> Suggestions
{
get {return _suggestions;}
}
/// <summary>
/// The text to spell check
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Text
{
get {return _text.ToString();}
set
{
_text = new StringBuilder(value);
this.CalculateWords();
this.Reset();
}
}
/// <summary>
/// TextIndex is the index of the current text being spell checked
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int TextIndex
{
get
{
if (_words == null || _words.Count == 0)
return 0;
return _words[this.WordIndex].Index;
}
}
/// <summary>
/// The number of words being spell checked
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int WordCount
{
get
{
if(_words == null)
return 0;
return _words.Count;
}
}
/// <summary>
/// WordIndex is the index of the current word being spell checked
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int WordIndex
{
get
{
if(_words == null)
return 0;
// make sure word index can't be higher then word count
return Math.Max(0, Math.Min(_wordIndex, (this.WordCount-1)));
}
set
{
_wordIndex = value;
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace postalcodefinder.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/* ====================================================================
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 NPOI.Util;
using NPOI.OpenXml4Net.OPC;
using System;
using NUnit.Framework;
using TestCases.OpenXml4Net;
using System.IO;
using System.Net;
using System.Web;
using System.Text.RegularExpressions;
using NPOI.XWPF.UserModel;
namespace TestCases.OPC
{
[TestFixture]
public class TestRelationships {
private static String HYPERLINK_REL_TYPE =
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink";
private static String COMMENTS_REL_TYPE =
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments";
private static String SHEET_WITH_COMMENTS =
"/xl/worksheets/sheet1.xml";
private static POILogger logger = POILogFactory.GetLogger(typeof(TestPackageCoreProperties));
/**
* Test relationships are correctly loaded. This at the moment fails (as of r499)
* whenever a document is loaded before its correspondig .rels file has been found.
* The code in this case assumes there are no relationships defined, but it should
* really look also for not yet loaded parts.
*/
[Test]
public void TestLoadRelationships() {
Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("sample.xlsx");
OPCPackage pkg = OPCPackage.Open(is1);
logger.Log(POILogger.DEBUG, "1: " + pkg);
PackageRelationshipCollection rels = pkg.GetRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT);
PackageRelationship coreDocRelationship = rels.GetRelationship(0);
PackagePart corePart = pkg.GetPart(coreDocRelationship);
String[] relIds = { "rId1", "rId2", "rId3" };
foreach (String relId in relIds) {
PackageRelationship rel = corePart.GetRelationship(relId);
Assert.IsNotNull(rel);
PackagePartName relName = PackagingUriHelper.CreatePartName(rel.TargetUri);
PackagePart sheetPart = pkg.GetPart(relName);
Assert.AreEqual(1, sheetPart.Relationships.Size, "Number of relationships1 for " + sheetPart.PartName);
}
}
/**
* Checks that we can fetch a collection of relations by
* type, then grab from within there by id
*/
[Test]
public void TestFetchFromCollection() {
Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("ExcelWithHyperlinks.xlsx");
OPCPackage pkg = OPCPackage.Open(is1);
PackagePart sheet = pkg.GetPart(
PackagingUriHelper.CreatePartName(SHEET_WITH_COMMENTS));
Assert.IsNotNull(sheet);
Assert.IsTrue(sheet.HasRelationships);
Assert.AreEqual(6, sheet.Relationships.Size);
// Should have three hyperlinks, and one comment
PackageRelationshipCollection hyperlinks =
sheet.GetRelationshipsByType(HYPERLINK_REL_TYPE);
PackageRelationshipCollection comments =
sheet.GetRelationshipsByType(COMMENTS_REL_TYPE);
Assert.AreEqual(3, hyperlinks.Size);
Assert.AreEqual(1, comments.Size);
// Check we can Get bits out by id
// Hyperlinks are rId1, rId2 and rId3
// Comment is rId6
Assert.IsNotNull(hyperlinks.GetRelationshipByID("rId1"));
Assert.IsNotNull(hyperlinks.GetRelationshipByID("rId2"));
Assert.IsNotNull(hyperlinks.GetRelationshipByID("rId3"));
Assert.IsNull(hyperlinks.GetRelationshipByID("rId6"));
Assert.IsNull(comments.GetRelationshipByID("rId1"));
Assert.IsNull(comments.GetRelationshipByID("rId2"));
Assert.IsNull(comments.GetRelationshipByID("rId3"));
Assert.IsNotNull(comments.GetRelationshipByID("rId6"));
Assert.IsNotNull(sheet.GetRelationship("rId1"));
Assert.IsNotNull(sheet.GetRelationship("rId2"));
Assert.IsNotNull(sheet.GetRelationship("rId3"));
Assert.IsNotNull(sheet.GetRelationship("rId6"));
}
/**
* Excel uses relations on sheets to store the details of
* external hyperlinks. Check we can load these ok.
*/
[Test]
public void TestLoadExcelHyperlinkRelations() {
Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("ExcelWithHyperlinks.xlsx");
OPCPackage pkg = OPCPackage.Open(is1);
PackagePart sheet = pkg.GetPart(
PackagingUriHelper.CreatePartName(SHEET_WITH_COMMENTS));
Assert.IsNotNull(sheet);
// rId1 is url
PackageRelationship url = sheet.GetRelationship("rId1");
Assert.IsNotNull(url);
Assert.AreEqual("rId1", url.Id);
Assert.AreEqual("/xl/worksheets/sheet1.xml", url.SourceUri.ToString());
Assert.AreEqual("http://poi.apache.org/", url.TargetUri.ToString());
// rId2 is file
PackageRelationship file = sheet.GetRelationship("rId2");
Assert.IsNotNull(file);
Assert.AreEqual("rId2", file.Id);
Assert.AreEqual("/xl/worksheets/sheet1.xml", file.SourceUri.ToString());
Assert.AreEqual("WithVariousData.xlsx", file.TargetUri.ToString());
// rId3 is mailto
PackageRelationship mailto = sheet.GetRelationship("rId3");
Assert.IsNotNull(mailto);
Assert.AreEqual("rId3", mailto.Id);
Assert.AreEqual("/xl/worksheets/sheet1.xml", mailto.SourceUri.ToString());
Assert.AreEqual("mailto:[email protected]?subject=XSSF%20Hyperlinks", mailto.TargetUri.AbsoluteUri);
}
/*
* Excel uses relations on sheets to store the details of
* external hyperlinks. Check we can create these OK,
* then still read them later
*/
[Test]
public void TestCreateExcelHyperlinkRelations() {
String filepath = OpenXml4NetTestDataSamples.GetSampleFileName("ExcelWithHyperlinks.xlsx");
OPCPackage pkg = OPCPackage.Open(filepath, PackageAccess.READ_WRITE);
PackagePart sheet = pkg.GetPart(
PackagingUriHelper.CreatePartName(SHEET_WITH_COMMENTS));
Assert.IsNotNull(sheet);
Assert.AreEqual(3, sheet.GetRelationshipsByType(HYPERLINK_REL_TYPE).Size);
// Add three new ones
PackageRelationship openxml4j =
sheet.AddExternalRelationship("http://www.Openxml4j.org/", HYPERLINK_REL_TYPE);
PackageRelationship sf =
sheet.AddExternalRelationship("http://openxml4j.sf.net/", HYPERLINK_REL_TYPE);
PackageRelationship file =
sheet.AddExternalRelationship("MyDocument.docx", HYPERLINK_REL_TYPE);
// Check they were Added properly
Assert.IsNotNull(openxml4j);
Assert.IsNotNull(sf);
Assert.IsNotNull(file);
Assert.AreEqual(6, sheet.GetRelationshipsByType(HYPERLINK_REL_TYPE).Size);
Assert.AreEqual("http://www.openxml4j.org/", openxml4j.TargetUri.ToString());
Assert.AreEqual("/xl/worksheets/sheet1.xml", openxml4j.SourceUri.ToString());
Assert.AreEqual(HYPERLINK_REL_TYPE, openxml4j.RelationshipType);
Assert.AreEqual("http://openxml4j.sf.net/", sf.TargetUri.ToString());
Assert.AreEqual("/xl/worksheets/sheet1.xml", sf.SourceUri.ToString());
Assert.AreEqual(HYPERLINK_REL_TYPE, sf.RelationshipType);
Assert.AreEqual("MyDocument.docx", file.TargetUri.ToString());
Assert.AreEqual("/xl/worksheets/sheet1.xml", file.SourceUri.ToString());
Assert.AreEqual(HYPERLINK_REL_TYPE, file.RelationshipType);
// Will Get ids 7, 8 and 9, as we already have 1-6
Assert.AreEqual("rId7", openxml4j.Id);
Assert.AreEqual("rId8", sf.Id);
Assert.AreEqual("rId9", file.Id);
// Write out and re-load
MemoryStream baos = new MemoryStream();
pkg.Save(baos);
MemoryStream bais = new MemoryStream(baos.ToArray());
pkg = OPCPackage.Open(bais);
// use revert to not re-write the input file
pkg.Revert();
// Check again
sheet = pkg.GetPart(
PackagingUriHelper.CreatePartName(SHEET_WITH_COMMENTS));
Assert.AreEqual(6, sheet.GetRelationshipsByType(HYPERLINK_REL_TYPE).Size);
Assert.AreEqual("http://poi.apache.org/",
sheet.GetRelationship("rId1").TargetUri.ToString());
Assert.AreEqual("mailto:[email protected]?subject=XSSF Hyperlinks",
sheet.GetRelationship("rId3").TargetUri.ToString());
Assert.AreEqual("http://www.openxml4j.org/",
sheet.GetRelationship("rId7").TargetUri.ToString());
Assert.AreEqual("http://openxml4j.sf.net/",
sheet.GetRelationship("rId8").TargetUri.ToString());
Assert.AreEqual("MyDocument.docx",
sheet.GetRelationship("rId9").TargetUri.ToString());
}
[Test]
public void TestCreateRelationsFromScratch() {
MemoryStream baos = new MemoryStream();
OPCPackage pkg = OPCPackage.Create(baos);
PackagePart partA =
pkg.CreatePart(PackagingUriHelper.CreatePartName("/partA"), "text/plain");
PackagePart partB =
pkg.CreatePart(PackagingUriHelper.CreatePartName("/partB"), "image/png");
Assert.IsNotNull(partA);
Assert.IsNotNull(partB);
// Internal
partA.AddRelationship(partB.PartName, TargetMode.Internal, "http://example/Rel");
// External
partA.AddExternalRelationship("http://poi.apache.org/", "http://example/poi");
partB.AddExternalRelationship("http://poi.apache.org/ss/", "http://example/poi/ss");
// Check as expected currently
Assert.AreEqual("/partB", partA.GetRelationship("rId1").TargetUri.ToString());
Assert.AreEqual("http://poi.apache.org/",
partA.GetRelationship("rId2").TargetUri.ToString());
Assert.AreEqual("http://poi.apache.org/ss/",
partB.GetRelationship("rId1").TargetUri.ToString());
// Save, and re-load
pkg.Close();
MemoryStream bais = new MemoryStream(baos.ToArray());
pkg = OPCPackage.Open(bais);
partA = pkg.GetPart(PackagingUriHelper.CreatePartName("/partA"));
partB = pkg.GetPart(PackagingUriHelper.CreatePartName("/partB"));
// Check the relations
Assert.AreEqual(2, partA.Relationships.Size);
Assert.AreEqual(1, partB.Relationships.Size);
Assert.AreEqual("/partB", partA.GetRelationship("rId1").TargetUri.OriginalString);
Assert.AreEqual("http://poi.apache.org/",
partA.GetRelationship("rId2").TargetUri.ToString());
Assert.AreEqual("http://poi.apache.org/ss/",
partB.GetRelationship("rId1").TargetUri.ToString());
// Check core too
Assert.AreEqual("/docProps/core.xml",
pkg.GetRelationshipsByType(
"http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties").GetRelationship(0).TargetUri.ToString());
// Add some more
partB.AddExternalRelationship("http://poi.apache.org/new", "http://example/poi/new");
partB.AddExternalRelationship("http://poi.apache.org/alt", "http://example/poi/alt");
// Check the relations
Assert.AreEqual(2, partA.Relationships.Size);
Assert.AreEqual(3, partB.Relationships.Size);
Assert.AreEqual("/partB", partA.GetRelationship("rId1").TargetUri.OriginalString);
Assert.AreEqual("http://poi.apache.org/",
partA.GetRelationship("rId2").TargetUri.OriginalString);
Assert.AreEqual("http://poi.apache.org/ss/",
partB.GetRelationship("rId1").TargetUri.OriginalString);
Assert.AreEqual("http://poi.apache.org/new",
partB.GetRelationship("rId2").TargetUri.OriginalString);
Assert.AreEqual("http://poi.apache.org/alt",
partB.GetRelationship("rId3").TargetUri.OriginalString);
}
[Test]
public void TestTargetWithSpecialChars()
{
OPCPackage pkg;
String filepath = OpenXml4NetTestDataSamples.GetSampleFileName("50154.xlsx");
pkg = OPCPackage.Open(filepath);
Assert_50154(pkg);
MemoryStream baos = new MemoryStream();
pkg.Save(baos);
// use revert to not re-write the input file
pkg.Revert();
MemoryStream bais = new MemoryStream(baos.ToArray());
pkg = OPCPackage.Open(bais);
Assert_50154(pkg);
}
public void Assert_50154(OPCPackage pkg) {
Uri drawingUri = new Uri("/xl/drawings/drawing1.xml",UriKind.Relative);
PackagePart drawingPart = pkg.GetPart(PackagingUriHelper.CreatePartName(drawingUri));
PackageRelationshipCollection drawingRels = drawingPart.Relationships;
Assert.AreEqual(6, drawingRels.Size);
// expected one image
Assert.AreEqual(1, drawingPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image").Size);
// and three hyperlinks
Assert.AreEqual(5, drawingPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink").Size);
PackageRelationship rId1 = drawingPart.GetRelationship("rId1");
Uri parent = drawingPart.PartName.URI;
Uri rel1 = new Uri(Path.Combine(parent.ToString(),rId1.TargetUri.ToString()),UriKind.Relative);
Uri rel11 = PackagingUriHelper.RelativizeUri(drawingPart.PartName.URI, rId1.TargetUri);
Assert.AreEqual("'Another Sheet'!A1", WebUtility.UrlDecode(rel1.ToString().Split(new char[]{'#'})[1]));
Assert.AreEqual("'Another Sheet'!A1", WebUtility.UrlDecode(rel11.ToString().Split(new char[] { '#' })[1]));
PackageRelationship rId2 = drawingPart.GetRelationship("rId2");
Uri rel2 = PackagingUriHelper.RelativizeUri(drawingPart.PartName.URI, rId2.TargetUri);
Assert.AreEqual("../media/image1.png", rel2.OriginalString);
PackageRelationship rId3 = drawingPart.GetRelationship("rId3");
Uri rel3 = new Uri(Path.Combine(parent.ToString(), rId3.TargetUri.ToString()), UriKind.Relative);
Assert.AreEqual("#ThirdSheet!A1", rel3.OriginalString.Split(new char[] { '/' })[3]);
PackageRelationship rId4 = drawingPart.GetRelationship("rId4");
Uri rel4 = new Uri(Path.Combine(parent.ToString(), rId4.TargetUri.ToString()), UriKind.Relative);
Assert.AreEqual("#'\u0410\u043F\u0430\u0447\u0435 \u041F\u041E\u0418'!A1", WebUtility.UrlDecode(rel4.OriginalString.Split(new char[] { '/' })[3]));
PackageRelationship rId5 = drawingPart.GetRelationship("rId5");
Uri rel5 = new Uri(Path.Combine(parent.ToString(), rId5.TargetUri.ToString()), UriKind.Relative);
// back slashed have been Replaced with forward
//Assert.AreEqual("file:///D:/chan-chan.mp3", rel5.ToString());
PackageRelationship rId6 = drawingPart.GetRelationship("rId6");
Uri rel6 = new Uri(ResolveRelativePath(parent.ToString(), WebUtility.UrlDecode(rId6.TargetUri.ToString())), UriKind.Relative);
//Assert.AreEqual("../../../../../../../cygwin/home/yegor/dinom/&&&[access].2010-10-26.log", rel6.OriginalString);
//Assert.AreEqual("#'\u0410\u043F\u0430\u0447\u0435 \u041F\u041E\u0418'!A5", HttpUtility.UrlDecode(rel6.OriginalString.Split(new char[] { '/' })[3]));
}
public static string ResolveRelativePath(string referencePath, string relativePath)
{
return Path.GetFullPath(Path.Combine(referencePath, relativePath));
}
[Test]
public void TestSelfRelations_bug51187()
{
MemoryStream baos = new MemoryStream();
OPCPackage pkg = OPCPackage.Create(baos);
PackagePart partA =
pkg.CreatePart(PackagingUriHelper.CreatePartName("/partA"), "text/plain");
Assert.IsNotNull(partA);
// reference itself
PackageRelationship rel1 = partA.AddRelationship(partA.PartName, TargetMode.Internal, "partA");
// Save, and re-load
pkg.Close();
MemoryStream bais = new MemoryStream(baos.ToArray());
pkg = OPCPackage.Open(bais);
partA = pkg.GetPart(PackagingUriHelper.CreatePartName("/partA"));
// Check the relations
Assert.AreEqual(1, partA.Relationships.Size);
PackageRelationship rel2 = partA.Relationships.GetRelationship(0);
Assert.AreEqual(rel1.RelationshipType, rel2.RelationshipType);
Assert.AreEqual(rel1.Id, rel2.Id);
Assert.AreEqual(rel1.SourceUri, rel2.SourceUri);
Assert.AreEqual(rel1.TargetUri, rel2.TargetUri);
Assert.AreEqual(rel1.TargetMode, rel2.TargetMode);
}
[Test]
public void TestTrailingSpacesInURI_53282()
{
OPCPackage pkg = null;
using (Stream stream = OpenXml4NetTestDataSamples.OpenSampleStream("53282.xlsx"))
{
pkg = OPCPackage.Open(stream);
}
PackageRelationshipCollection sheetRels = pkg.GetPartsByName(new Regex("/xl/worksheets/sheet1.xml"))[0].Relationships;
Assert.AreEqual(3, sheetRels.Size);
PackageRelationship rId1 = sheetRels.GetRelationshipByID("rId1");
Assert.AreEqual(TargetMode.External, rId1.TargetMode);
Uri targetUri = rId1.TargetUri;
Assert.AreEqual("mailto:[email protected]%C2%A0", targetUri.OriginalString);
//Assert.AreEqual("[email protected]\u00A0", targetUri.OriginalString);
Console.WriteLine("how to get string \"[email protected]\\u00A0\"");
MemoryStream out1 = new MemoryStream();
pkg.Save(out1);
pkg = OPCPackage.Open(new ByteArrayInputStream(out1.ToArray()));
out1.Close();
sheetRels = pkg.GetPartsByName(new Regex("/xl/worksheets/sheet1.xml"))[(0)].Relationships;
Assert.AreEqual(3, sheetRels.Size);
rId1 = sheetRels.GetRelationshipByID("rId1");
Assert.AreEqual(TargetMode.External, rId1.TargetMode);
targetUri = rId1.TargetUri;
Assert.AreEqual("mailto:[email protected]%C2%A0", targetUri.OriginalString);
//Assert.AreEqual("[email protected]\u00A0", targetUri.Scheme);
}
[Test]
public void TestEntitiesInRels_56164()
{
Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("PackageRelsHasEntities.ooxml");
OPCPackage p = OPCPackage.Open(is1);
is1.Close();
// Should have 3 root relationships
bool foundDocRel = false, foundCorePropRel = false, foundExtPropRel = false;
foreach (PackageRelationship pr in p.Relationships)
{
if (pr.RelationshipType.Equals(PackageRelationshipTypes.CORE_DOCUMENT))
foundDocRel = true;
if (pr.RelationshipType.Equals(PackageRelationshipTypes.CORE_PROPERTIES))
foundCorePropRel = true;
if (pr.RelationshipType.Equals(PackageRelationshipTypes.EXTENDED_PROPERTIES))
foundExtPropRel = true;
}
Assert.IsTrue(foundDocRel, "Core/Doc Relationship not found in " + p.Relationships);
Assert.IsTrue(foundCorePropRel, "Core Props Relationship not found in " + p.Relationships);
Assert.IsTrue(foundExtPropRel, "Ext Props Relationship not found in " + p.Relationships);
// Should have normal work parts
bool foundCoreProps = false, foundDocument = false, foundTheme1 = false;
foreach (PackagePart part in p.GetParts())
{
if (part.PartName.ToString().Equals("/docProps/core.xml"))
{
Assert.AreEqual(ContentTypes.CORE_PROPERTIES_PART, part.ContentType);
foundCoreProps = true;
}
if (part.PartName.ToString().Equals("/word/document.xml"))
{
Assert.AreEqual(XWPFRelation.DOCUMENT.ContentType, part.ContentType);
foundDocument = true;
}
if (part.PartName.ToString().Equals("/word/theme/theme1.xml"))
{
Assert.AreEqual(XWPFRelation.THEME.ContentType, part.ContentType);
foundTheme1 = true;
}
}
Assert.IsTrue(foundCoreProps, "Core not found in " + Arrays.ToString(p.GetParts().ToArray()));
Assert.IsTrue(foundDocument, "Document not found in " + Arrays.ToString(p.GetParts().ToArray()));
Assert.IsTrue(foundTheme1, "Theme1 not found in " + Arrays.ToString(p.GetParts().ToArray()));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
namespace SpaceExplorers {
/// <summary>
/// Modified version of code written by Laurent Cozic, obtained from https://www.codeproject.com/Articles/15573/D-Polygon-Collision-Detection
/// Modified version of code written by codeproject user fgshen, obtained from https://www.codeproject.com/Articles/8238/Polygon-Triangulation-in-C
/// </summary>
public class Polygon {
public enum VertexType
{
ErrorPoint,
ConvexPoint,
ConcavePoint
}
public enum PolygonType
{
Unknown,
Convex,
Concave
}
public enum PointPosition
{
Inside,
Above,
Below,
Left,
Right,
None
}
public List<Vector> Points = new List<Vector>();
private List<Vector> edges = new List<Vector>();
public void BuildEdges() {
Vector p1;
Vector p2;
edges.Clear();
for (int i = 0; i < Points.Count; i++) {
p1 = Points[i];
if (i + 1 >= Points.Count) {
p2 = Points[0];
} else {
p2 = Points[i + 1];
}
edges.Add(p2 - p1);
}
}
public List<Vector> Edges {
get { return edges; }
}
public Vector Center {
get {
float totalX = 0;
float totalY = 0;
for (int i = 0; i < Points.Count; i++) {
totalX += Points[i].X;
totalY += Points[i].Y;
}
return new Vector(totalX / Points.Count, totalY / Points.Count);
}
}
public Polygon Copy()
{
Polygon copy = new Polygon();
foreach (var point in Points)
{
copy.Points.Add(point.Copy());
}
copy.BuildEdges();
return copy;
}
public void Offset(Vector v) {
Offset(v.X, v.Y);
}
public void Offset(float x, float y) {
for (int i = 0; i < Points.Count; i++) {
Vector p = Points[i];
Points[i] = new Vector(p.X + x, p.Y + y);
}
}
public override string ToString() {
string result = "";
for (int i = 0; i < Points.Count; i++) {
if (result != "") result += " ";
result += "{" + Points[i].ToString(true) + "}";
}
return result;
}
// Structure that stores the results of the PolygonCollision function
public struct PolygonCollisionResult
{
public bool WillIntersect; // Are the polygons going to intersect forward in time?
public bool Intersect; // Are the polygons currently intersecting
public Vector MinimumTranslationVector; // The translation to apply to polygon A to push the polygons apart.
}
// Check if polygon A is going to collide with polygon B for the given velocity
public PolygonCollisionResult PolygonCollision(Polygon polygon, Vector velocity)
{
PolygonCollisionResult result = new PolygonCollisionResult();
result.Intersect = true;
result.WillIntersect = true;
int edgeCountA = Edges.Count;
int edgeCountB = polygon.Edges.Count;
float minIntervalDistance = float.PositiveInfinity;
Vector translationAxis = new Vector();
Vector edge;
// Loop through all the edges of both polygons
for (int edgeIndex = 0; edgeIndex < edgeCountA + edgeCountB; edgeIndex++)
{
if (edgeIndex < edgeCountA)
{
edge = Edges[edgeIndex];
}
else
{
edge = polygon.Edges[edgeIndex - edgeCountA];
}
// ===== 1. Find if the polygons are currently intersecting =====
// Find the axis perpendicular to the current edge
Vector axis = new Vector(-edge.Y, edge.X);
axis.Normalize();
// Find the projection of the polygon on the current axis
float minA = 0; float minB = 0; float maxA = 0; float maxB = 0;
ProjectPolygon(axis, this, ref minA, ref maxA);
ProjectPolygon(axis, polygon, ref minB, ref maxB);
// Check if the polygon projections are currentlty intersecting
if (IntervalDistance(minA, maxA, minB, maxB) > 0) result.Intersect = false;
// ===== 2. Now find if the polygons *will* intersect =====
// Project the velocity on the current axis
float velocityProjection = axis.DotProduct(velocity);
// Get the projection of polygon A during the movement
if (velocityProjection < 0)
{
minA += velocityProjection;
}
else
{
maxA += velocityProjection;
}
// Do the same test as above for the new projection
float intervalDistance = IntervalDistance(minA, maxA, minB, maxB);
if (intervalDistance > 0) result.WillIntersect = false;
// If the polygons are not intersecting and won't intersect, exit the loop
if (!result.Intersect && !result.WillIntersect) break;
// Check if the current interval distance is the minimum one. If so store
// the interval distance and the current distance.
// This will be used to calculate the minimum translation vector
intervalDistance = Math.Abs(intervalDistance);
if (intervalDistance < minIntervalDistance)
{
minIntervalDistance = intervalDistance;
translationAxis = axis;
Vector d = Center - polygon.Center;
if (d.DotProduct(translationAxis) < 0) translationAxis = -translationAxis;
}
}
// The minimum translation vector can be used to push the polygons appart.
// First moves the polygons by their velocity
// then move polygonA by MinimumTranslationVector.
if (result.WillIntersect) result.MinimumTranslationVector = translationAxis * minIntervalDistance;
return result;
}
// Calculate the distance between [minA, maxA] and [minB, maxB]
// The distance will be negative if the intervals overlap
public float IntervalDistance(float minA, float maxA, float minB, float maxB)
{
if (minA < minB)
{
return minB - maxA;
}
else
{
return minA - maxB;
}
}
// Calculate the projection of a polygon on an axis and returns it as a [min, max] interval
public void ProjectPolygon(Vector axis, Polygon polygon, ref float min, ref float max)
{
// To project a point on an axis use the dot product
float d = axis.DotProduct(polygon.Points[0]);
min = d;
max = d;
for (int i = 0; i < polygon.Points.Count; i++)
{
d = polygon.Points[i].DotProduct(axis);
if (d < min)
{
min = d;
}
else
{
if (d > max)
{
max = d;
}
}
}
}
/// <summary>
/// Returns Above if the point is directly above the polygon or Below if it is directly below,
/// Inside if it is inside the polygon or None if it is to the left or right of the polygon.
/// </summary>
/// <param name="point">The point to compare to the polygon</param>
/// <returns>Above, Below, Inside, or None</returns>
public PointPosition PointYRelation(Vector point)
{
PointPosition ret = PointPosition.None;
for (int i = 0; i < Points.Count; i++)
{
LineSegment line = new LineSegment(Points[i], Points[Utility.ValueWrap(i + 1, Points.Count)]);
if (line.PointWithinXBounds(point))
{ //Point is above, below, or in given line
int relation = line.GetPointLocation(point);
if (relation == -1)
{
if (ret == PointPosition.Below)
{
return PointPosition.Inside;
}
else
{
ret = PointPosition.Above;
}
}
else if (relation == 1)
{
if (ret == PointPosition.Above)
{
return PointPosition.Inside;
}
else
{
ret = PointPosition.Below;
}
}
else
{
return PointPosition.Inside;
}
}
}
return ret;
}
public List<Polygon> MakeConvex()
{
List<Polygon> ret;
if (GetPolygonType() == PolygonType.Convex)
{
ret = new List<Polygon>
{
this
};
}
else
{
ret = new List<Polygon>();
Polygon copy = Copy();
bool done = false;
if (copy.Points.Count == 3) //triangle, don't have to cut ear
{
done = true;
ret.Add(this);
}
int i;
while (done == false) //UpdatedPolygon
{
i = 0;
bool notFound = true;
while (notFound
&& (i < copy.Points.Count)) //loop till find an ear
{
if (copy.IsEar(i))
notFound = false; //got one, pt is an ear
else
i++;
} //bNotFound
//An ear found:}
if (copy.Points[i] != null)
{
Polygon triangle = new Polygon();
triangle.Points.Add(copy.Points[i].Copy());
triangle.Points.Add(copy.Points[Utility.ValueWrap(i + 1, copy.Points.Count)].Copy());
triangle.Points.Add(copy.Points[Utility.ValueWrap(i - 1, copy.Points.Count)].Copy());
triangle.BuildEdges();
ret.Add(triangle);
copy.Points.RemoveAt(i);
}
if (copy.GetPolygonType() == PolygonType.Convex)
{
done = true;
copy.BuildEdges();
ret.Add(copy);
}
}
}
return ret;
}
public List<Polygon> Triangulate()
{
List<Polygon> ret = new List<Polygon>();
Polygon copy = Copy();
bool done = false;
if (copy.Points.Count == 3) //triangle, don't have to cut ear
{
done = true;
ret.Add(this);
}
int i;
while (done == false) //UpdatedPolygon
{
i = 0;
bool notFound = true;
while (notFound
&& (i < copy.Points.Count)) //loop till find an ear
{
if (copy.IsEar(i))
notFound = false; //got one, pt is an ear
else
i++;
} //bNotFound
//An ear found:}
if (copy.Points[i] != null)
{
Polygon triangle = new Polygon();
triangle.Points.Add(copy.Points[i].Copy());
triangle.Points.Add(copy.Points[Utility.ValueWrap(i + 1, copy.Points.Count)].Copy());
triangle.Points.Add(copy.Points[Utility.ValueWrap(i - 1, copy.Points.Count)].Copy());
triangle.BuildEdges();
ret.Add(triangle);
copy.Points.RemoveAt(i);
}
if (copy.Points.Count == 3)
{
done = true;
copy.BuildEdges();
ret.Add(copy);
}
}
return ret;
}
/// <summary>
/// Checks to see if a polygon is convex or concave, does not work on self-intersecting polygons.
/// </summary>
/// <returns>An enum for the type of the polygon.</returns>
public PolygonType GetPolygonType()
{
int numOfVertices = Points.Count;
bool signChanged = false;
int count = 0;
int j = 0, k = 0;
for (int i = 0; i < numOfVertices; i++)
{
j = (i + 1) % numOfVertices; //j:=i+1;
k = (i + 2) % numOfVertices; //k:=i+2;
double crossProduct = (Points[j].X - Points[i].X)
* (Points[k].Y - Points[j].Y);
crossProduct = crossProduct - (
(Points[j].Y - Points[i].Y)
* (Points[k].X - Points[j].X)
);
//change the value of nCount
if ((crossProduct > 0) && (count == 0))
count = 1;
else if ((crossProduct < 0) && (count == 0))
count = -1;
if (((count == 1) && (crossProduct < 0))
|| ((count == -1) && (crossProduct > 0)))
signChanged = true;
}
if (signChanged)
return PolygonType.Concave;
else
return PolygonType.Convex;
}
/****************************************************************
To check whether the Vertex is an ear or not based updated Polygon vertices
ref. www-cgrl.cs.mcgill.ca/~godfried/teaching/cg-projects/97/Ian
/algorithm1.html
If it is an ear, return true,
If it is not an ear, return false;
*****************************************************************/
private bool IsEar(int index)
{
bool ear = true;
if (PolygonVertexType(index) == VertexType.ConvexPoint)
{
List<Vector> trianglePoints = new List<Vector>();
trianglePoints.Add(Points[index]);
trianglePoints.Add(Points[Utility.ValueWrap(index - 1, Points.Count)]);
trianglePoints.Add(Points[Utility.ValueWrap(index + 1, Points.Count)]);
for (int i = 0; i < Points.Count; i++)
{
Vector point = Points[i];
if (!(point.EqualsThreshold(trianglePoints[0]) || point.EqualsThreshold(trianglePoints[1]) || point.EqualsThreshold(trianglePoints[2])))
{
if (TriangleContainsPoint(trianglePoints, point))
ear = false;
}
}
} //ThePolygon.getVertexType(Vertex)=ConvexPt
else //concave point
ear = false; //not an ear/
return ear;
}
/***********************************************
To check a vertex concave point or a convex point
-----------------------------------------------------------
The out polygon is in count clock-wise direction
************************************************/
public VertexType PolygonVertexType(int index)
{
VertexType vertexType = VertexType.ErrorPoint;
List<Vector> trianglePoints = new List<Vector>();
trianglePoints.Add(Points[Utility.ValueWrap(index - 1, Points.Count)]);
trianglePoints.Add(Points[index]);
trianglePoints.Add(Points[Utility.ValueWrap(index + 1, Points.Count)]);
double area = PolygonArea(trianglePoints);
if (area < 0)
vertexType = VertexType.ConvexPoint;
else if (area > 0)
vertexType = VertexType.ConcavePoint;
return vertexType;
}
/******************************************
To calculate the area of polygon made by given points
Good for polygon with holes, but the vertices make the
hole should be in different direction with bounding
polygon.
Restriction: the polygon is not self intersecting
ref: www.swin.edu.au/astronomy/pbourke/
geometry/polyarea/
As polygon in different direction, the result could be
in different sign:
If dblArea>0 : polygon in clock wise to the user
If dblArea<0: polygon in count clock wise to the user
*******************************************/
public static double PolygonArea(List<Vector> points)
{
double dblArea = 0;
int numPts = points.Count;
int j;
for (int i = 0; i < numPts; i++)
{
j = (i + 1) % numPts;
dblArea += points[i].X * points[j].Y;
dblArea -= (points[i].Y * points[j].X);
}
dblArea = dblArea / 2;
return dblArea;
}
/**********************************************************
To check the Pt is in the Triangle or not.
If the Pt is in the line or is a vertex, then return true.
If the Pt is out of the Triangle, then return false.
This method is used for triangle only.
***********************************************************/
private bool TriangleContainsPoint(List<Vector> trianglePoints, Vector point)
{
if (trianglePoints.Count != 3)
return false;
foreach (Vector trianglePoint in trianglePoints)
{
if (point.EqualsThreshold(trianglePoint))
return true;
}
bool ret = false;
LineSegment line0 = new LineSegment(trianglePoints[0], trianglePoints[1]);
LineSegment line1 = new LineSegment(trianglePoints[1], trianglePoints[2]);
LineSegment line2 = new LineSegment(trianglePoints[2], trianglePoints[0]);
if (line0.InLine(point) || line1.InLine(point)
|| line2.InLine(point))
ret = true;
else //point is not in the lines
{
List<Vector> triangle0 = new List<Vector>();
triangle0.Add(trianglePoints[0]);
triangle0.Add(trianglePoints[1]);
triangle0.Add(point);
double dblArea0 = Polygon.PolygonArea(triangle0);
List<Vector> triangle1 = new List<Vector>();
triangle1.Add(trianglePoints[1]);
triangle1.Add(trianglePoints[2]);
triangle1.Add(point);
double dblArea1 = Polygon.PolygonArea(triangle1);
List<Vector> triangle2 = new List<Vector>();
triangle2.Add(trianglePoints[2]);
triangle2.Add(trianglePoints[0]);
triangle2.Add(point);
double dblArea2 = Polygon.PolygonArea(triangle2);
if (dblArea0 > 0)
{
if ((dblArea1 > 0) && (dblArea2 > 0))
ret = true;
}
else if (dblArea0 < 0)
{
if ((dblArea1 < 0) && (dblArea2 < 0))
ret = true;
}
}
return ret;
}
}
}
| |
namespace BookingApp.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Modelupdates : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Accommodations",
c => new
{
Id = c.Int(nullable: false, identity: true),
Address = c.String(),
Approved = c.Boolean(nullable: false),
AverageGrade = c.Single(nullable: false),
Description = c.String(),
ImageURL = c.String(),
Latitude = c.Double(nullable: false),
Longitude = c.Double(nullable: false),
Name = c.String(),
owner_Id = c.Int(nullable: false),
place_Id = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AppUsers", t => t.owner_Id, cascadeDelete: false)
.ForeignKey("dbo.Places", t => t.place_Id, cascadeDelete: false)
.Index(t => t.owner_Id)
.Index(t => t.place_Id);
CreateTable(
"dbo.AppUsers",
c => new
{
Id = c.Int(nullable: false, identity: true),
Email = c.String(),
Password = c.String(),
Username = c.String(),
Approved = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Places",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
region_Id = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Regions", t => t.region_Id, cascadeDelete: false)
.Index(t => t.region_Id);
CreateTable(
"dbo.Regions",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
country_Id = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Countries", t => t.country_Id, cascadeDelete: false)
.Index(t => t.country_Id);
CreateTable(
"dbo.Countries",
c => new
{
Id = c.Int(nullable: false, identity: true),
Code = c.Int(nullable: false),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AccommodationTypes",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Comments",
c => new
{
Id = c.Int(nullable: false, identity: true),
Grade = c.Int(nullable: false),
Text = c.String(),
accomodation_Id = c.Int(nullable: false),
user_Id = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Accommodations", t => t.accomodation_Id, cascadeDelete: false)
.ForeignKey("dbo.AppUsers", t => t.user_Id, cascadeDelete: false)
.Index(t => t.accomodation_Id)
.Index(t => t.user_Id);
CreateTable(
"dbo.AspNetRoles",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Name = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.Index(t => t.Name, unique: true, name: "RoleNameIndex");
CreateTable(
"dbo.AspNetUserRoles",
c => new
{
UserId = c.String(nullable: false, maxLength: 128),
RoleId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.UserId, t.RoleId })
.ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: false)
.ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: false)
.Index(t => t.UserId)
.Index(t => t.RoleId);
CreateTable(
"dbo.RoomReservations",
c => new
{
Id = c.Int(nullable: false, identity: true),
EndDate = c.DateTime(),
StartDate = c.DateTime(),
Timestamp = c.DateTime(),
AppUser_Id = c.Int(nullable: false),
Room_Id = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AppUsers", t => t.AppUser_Id, cascadeDelete: false)
.ForeignKey("dbo.Rooms", t => t.Room_Id, cascadeDelete: false)
.Index(t => t.AppUser_Id)
.Index(t => t.Room_Id);
CreateTable(
"dbo.Rooms",
c => new
{
Id = c.Int(nullable: false, identity: true),
BedCount = c.Int(nullable: false),
Description = c.String(),
PricePerNight = c.Int(nullable: false),
RoomNumber = c.Int(nullable: false),
accomodation_Id = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Accommodations", t => t.accomodation_Id, cascadeDelete: false)
.Index(t => t.accomodation_Id);
CreateTable(
"dbo.AspNetUsers",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
appUserId = c.Int(nullable: false),
Email = c.String(maxLength: 256),
EmailConfirmed = c.Boolean(nullable: false),
PasswordHash = c.String(),
SecurityStamp = c.String(),
PhoneNumber = c.String(),
PhoneNumberConfirmed = c.Boolean(nullable: false),
TwoFactorEnabled = c.Boolean(nullable: false),
LockoutEndDateUtc = c.DateTime(),
LockoutEnabled = c.Boolean(nullable: false),
AccessFailedCount = c.Int(nullable: false),
UserName = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AppUsers", t => t.appUserId, cascadeDelete: false)
.Index(t => t.appUserId)
.Index(t => t.UserName, unique: true, name: "UserNameIndex");
CreateTable(
"dbo.AspNetUserClaims",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserId = c.String(nullable: false, maxLength: 128),
ClaimType = c.String(),
ClaimValue = c.String(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: false)
.Index(t => t.UserId);
CreateTable(
"dbo.AspNetUserLogins",
c => new
{
LoginProvider = c.String(nullable: false, maxLength: 128),
ProviderKey = c.String(nullable: false, maxLength: 128),
UserId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId })
.ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: false)
.Index(t => t.UserId);
}
public override void Down()
{
DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.AspNetUsers", "appUserId", "dbo.AppUsers");
DropForeignKey("dbo.RoomReservations", "Room_Id", "dbo.Rooms");
DropForeignKey("dbo.Rooms", "accomodation_Id", "dbo.Accommodations");
DropForeignKey("dbo.RoomReservations", "AppUser_Id", "dbo.AppUsers");
DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles");
DropForeignKey("dbo.Comments", "user_Id", "dbo.AppUsers");
DropForeignKey("dbo.Comments", "accomodation_Id", "dbo.Accommodations");
DropForeignKey("dbo.Accommodations", "place_Id", "dbo.Places");
DropForeignKey("dbo.Places", "region_Id", "dbo.Regions");
DropForeignKey("dbo.Regions", "country_Id", "dbo.Countries");
DropForeignKey("dbo.Accommodations", "owner_Id", "dbo.AppUsers");
DropIndex("dbo.AspNetUserLogins", new[] { "UserId" });
DropIndex("dbo.AspNetUserClaims", new[] { "UserId" });
DropIndex("dbo.AspNetUsers", "UserNameIndex");
DropIndex("dbo.AspNetUsers", new[] { "appUserId" });
DropIndex("dbo.Rooms", new[] { "accomodation_Id" });
DropIndex("dbo.RoomReservations", new[] { "Room_Id" });
DropIndex("dbo.RoomReservations", new[] { "AppUser_Id" });
DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" });
DropIndex("dbo.AspNetUserRoles", new[] { "UserId" });
DropIndex("dbo.AspNetRoles", "RoleNameIndex");
DropIndex("dbo.Comments", new[] { "user_Id" });
DropIndex("dbo.Comments", new[] { "accomodation_Id" });
DropIndex("dbo.Regions", new[] { "country_Id" });
DropIndex("dbo.Places", new[] { "region_Id" });
DropIndex("dbo.Accommodations", new[] { "place_Id" });
DropIndex("dbo.Accommodations", new[] { "owner_Id" });
DropTable("dbo.AspNetUserLogins");
DropTable("dbo.AspNetUserClaims");
DropTable("dbo.AspNetUsers");
DropTable("dbo.Rooms");
DropTable("dbo.RoomReservations");
DropTable("dbo.AspNetUserRoles");
DropTable("dbo.AspNetRoles");
DropTable("dbo.Comments");
DropTable("dbo.AccommodationTypes");
DropTable("dbo.Countries");
DropTable("dbo.Regions");
DropTable("dbo.Places");
DropTable("dbo.AppUsers");
DropTable("dbo.Accommodations");
}
}
}
| |
using Plugin.MobileFirst.Abstractions;
using System;
using System.Collections.Generic;
using System.Json;
using System.Threading.Tasks;
using Worklight;
namespace Plugin.MobileFirst
{
/// <summary>
/// Implementation for Feature
/// </summary>
public class MobileFirstImplementation : IMobileFirst
{
#region Fields
/// <summary>
/// Name of the connector for Push Notifications managed from the MFP Server
/// </summary>
string _pushAlias { get; set; }
/// <summary>
/// Name of the App managed from the MFP Server
/// </summary>
string _appRealm { get; set; }
/// <summary>
/// Object for the MFP understand the client call
/// </summary>
JsonObject _metadata = (JsonObject)JsonValue.Parse(" {\"platform\" : \"Xamarin\" } ");
#endregion
#region Properties
/// <summary>
/// Set up the Name for the App
/// </summary>
/// <param name="appRealm"></param>
public void SetAppRealm(string appRealm) => _appRealm = appRealm;
/// <summary>
/// Set up the Name for the Push Notification alias
/// </summary>
/// <param name="pushAlias"></param>
public void SetPushAlias(string pushAlias) => _pushAlias = pushAlias;
/// <summary>
/// Interface for the service
/// </summary>
public IWorklightClient _client { get; private set; }
/// <summary>
/// Gets a value indicating whether this instance is push supported.
/// </summary>
/// <value><c>true</c> if this instance is push supported; otherwise, <c>false</c>.</value>
public bool IsPushSupported
{
get
{
try
{
return _client.PushService.IsPushSupported;
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets a value indicating whether this instance is subscribed.
/// </summary>
/// <value><c>true</c> if this instance is subscribed; otherwise, <c>false</c>.</value>
public bool IsSubscribed
{
get
{
try
{
return _client.PushService.IsAliasSubscribed(_pushAlias);
}
catch
{
return false;
}
}
}
#endregion
#region Constuctors
/// <summary>
/// Default constructor
/// </summary>
public MobileFirstImplementation()
{
}
#endregion
#region Public Functions
/// <summary>
/// Init Method
/// </summary>
public void Init() { }
/// <summary>
/// Configures the Client Instances For the Xamarin Forms App
/// </summary>
/// <param name="activity">The Android Activity</param>
public void Init(object activity) => _client = Worklight.Xamarin.Android.WorklightClient.CreateInstance((Android.App.Activity)activity);
/// <summary>
/// Make a async connection with the Server
/// </summary>
/// <returns></returns>
public async Task<WorklightResult> ConnectAsync()
{
var result = new WorklightResult();
try
{
var resp = await Connect();
result.Success = resp.Success;
result.Message = (resp.Success) ? "Connected" : resp.Message;
result.Response = resp.ResponseText;
}
catch (Exception ex)
{
result.Success = false;
result.Message = ex.Message;
}
return result;
}
/// <summary>
/// Make a REST call to the Adapter on the Server
/// </summary>
/// <param name="adapterName">The name of the adapter</param>
/// <param name="adapterProcedureName">The name of the procedure</param>
/// <param name="methodType">The HTTP verb used to call the procedure</param>
/// <param name="parameters">JSON parameters</param>
/// <returns></returns>
public async Task<WorklightResult> RestInvokeAsync(string adapterName, string adapterProcedureName, string methodType, object[] parameters)
{
var result = new WorklightResult();
try
{
var uriBuilder = $"{_client.ServerUrl.AbsoluteUri}/adapters/{adapterName}/{adapterProcedureName}";
WorklightResourceRequest rr = _client.ResourceRequest(new Uri(uriBuilder.ToString()), methodType);
WorklightResponse resp = await rr.Send();
result.Success = resp.Success;
result.Message = (resp.Success) ? "Connected" : resp.Message;
result.Response = resp.ResponseText;
}
catch (Exception ex)
{
result.Success = false;
result.Message = ex.Message;
}
return result;
}
/// <summary>
/// Call a procedure from Async Method
/// </summary>
/// <returns></returns>
public async Task<WorklightResult> InvokeAsync(string adapterName, string adapterProcedureName, object[] parameters)
{
var result = new WorklightResult();
try
{
var conResp = await ConnectAsync();
if (!conResp.Success)
return conResp;
result = await InvokeProc(adapterName, adapterProcedureName, parameters);
}
catch (Exception ex)
{
result.Success = false;
result.Message = ex.Message;
}
return result;
}
/// <summary>
/// Register Analytics Data to the Server
/// </summary>
/// <returns></returns>
public async Task<WorklightResult> SendActivityAsync(string data)
{
var result = new WorklightResult();
try
{
var resp = await Task.Run<string>(() =>
{
_client.Analytics.Send();
_client.LogActivity(data);
return "Activity Logged";
});
result.Success = true;
result.Message = resp;
}
catch (Exception ex)
{
result.Success = false;
result.Message = ex.Message;
}
return result;
}
/// <summary>
/// Call subscribes for Push Notifications on the Server.
/// </summary>
/// <returns></returns>
public async Task<WorklightResult> SubscribeAsync()
{
var result = new WorklightResult();
try
{
var resp = await SubscribePush();
result.Success = resp.Success;
result.Message = "Subscribed";
result.Response = resp.ResponseText;
}
catch (Exception ex)
{
result.Success = false;
result.Message = ex.Message;
}
return result;
}
/// <summary>
/// Call unsubscribes from the Push Notifications server
/// </summary>
/// <returns></returns>
public async Task<WorklightResult> UnSubscribeAsync()
{
var result = new WorklightResult();
try
{
var resp = await UnsubscribePush();
result.Success = resp.Success;
result.Message = "Unsubscribed";
result.Response = resp.ResponseText;
}
catch (Exception ex)
{
result.Success = false;
result.Message = ex.Message;
}
return result;
}
#endregion
#region Worklight Methods
/// <summary>
/// Connect to the server instance
/// </summary>
private async Task<WorklightResponse> Connect()
{
try
{
// Lets send a message to the server
_client.Analytics.Log("Trying to connect to server", _metadata);
//ChallengeHandler customCH = new CustomChallengeHandler(_appRealm);
//_client.RegisterChallengeHandler(customCH);
WorklightResponse task = await _client.Connect();
// Lets log to the local client (not server)
_client.Logger("Xamarin").Trace("Connection");
// Write to the server the connection status
_client.Analytics.Log("Connect response : " + task.Success);
return task;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Unsubscribes from push notifications
/// </summary>
/// <returns>The push.</returns>
private async Task<WorklightResponse> UnsubscribePush()
{
try
{
_client.Analytics.Log("Unsubscribing Push", _metadata);
WorklightResponse task = await _client.PushService.UnsubscribeFromEventSource(_pushAlias);
return task;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Subscribes to push notifications
/// </summary>
private async Task<WorklightResponse> SubscribePush()
{
#if DEBUG
Debug.WriteLine("Subscribing to push");
#endif
try
{
_client.PushService.ReadyToSubscribe += HandleReadyToSubscribe;
_client.PushService.InitRegistration();
return await _client.Connect();
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Handle for the subscribe method for Push Notification
/// </summary>
void HandleReadyToSubscribe(object sender, EventArgs a)
{
#if DEBUG
Debug.WriteLine("We are ready to subscribe to the notification service!!");
#endif
try
{
_client.PushService.RegisterEventSourceNotificationCallback(_pushAlias, "PushAdapter", "PushEventSource", new PushNotificationListener());
_client.PushService.SubscribeToEventSource(_pushAlias, new Dictionary<string, string>());
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Invokes the procedured
/// </summary>
/// <returns>The proc.</returns>
private async Task<WorklightResult> InvokeProc(string adapterName, string adapterProcedureName, object[] parameters)
{
var result = new WorklightResult();
try
{
_client.Analytics.Log("Trying to invoking procedure...");
#if DEBUG
Debug.WriteLine("Trying to invoke proc");
#endif
var invocationData = new WorklightProcedureInvocationData(adapterName, adapterProcedureName, parameters);
WorklightResponse task = await _client.InvokeProcedure(invocationData);
#if DEBUG
_client.Analytics.Log("Invoke Response : " + task.Success);
#endif
var retval = string.Empty;
result.Success = task.Success;
if (task.Success)
retval = task.ResponseJSON;
else
retval = $"Failure: { task.Message}";
result.Message = retval.ToString();
}
catch (Exception ex)
{
result.Success = false;
result.Message = ex.Message;
}
return result;
}
#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.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
namespace System
{
// CONTRACT with Runtime
// The UIntPtr type is one of the primitives understood by the compilers and runtime
// Data Contract: Single field of type void *
[Serializable]
[CLSCompliant(false)]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct UIntPtr : IEquatable<UIntPtr>, ISerializable
{
unsafe private void* _value; // Do not rename (binary serialization)
[Intrinsic]
public static readonly UIntPtr Zero;
[Intrinsic]
[NonVersionable]
public unsafe UIntPtr(uint value)
{
_value = (void*)value;
}
[Intrinsic]
[NonVersionable]
public unsafe UIntPtr(ulong value)
{
#if BIT64
_value = (void*)value;
#else
_value = (void*)checked((uint)value);
#endif
}
[Intrinsic]
[NonVersionable]
public unsafe UIntPtr(void* value)
{
_value = value;
}
private unsafe UIntPtr(SerializationInfo info, StreamingContext context)
{
ulong l = info.GetUInt64("value");
if (Size == 4 && l > uint.MaxValue)
throw new ArgumentException(SR.Serialization_InvalidPtrValue);
_value = (void*)l;
}
unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
info.AddValue("value", (ulong)_value);
}
[Intrinsic]
[NonVersionable]
public unsafe void* ToPointer()
{
return _value;
}
[Intrinsic]
[NonVersionable]
public unsafe uint ToUInt32()
{
#if BIT64
return checked((uint)_value);
#else
return (uint)_value;
#endif
}
[Intrinsic]
[NonVersionable]
public unsafe ulong ToUInt64()
{
return (ulong)_value;
}
[Intrinsic]
[NonVersionable]
public static explicit operator UIntPtr(uint value)
{
return new UIntPtr(value);
}
[Intrinsic]
[NonVersionable]
public static explicit operator UIntPtr(ulong value)
{
return new UIntPtr(value);
}
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator UIntPtr(void* value)
{
return new UIntPtr(value);
}
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator void* (UIntPtr value)
{
return value._value;
}
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator uint(UIntPtr value)
{
#if BIT64
return checked((uint)value._value);
#else
return (uint)value._value;
#endif
}
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator ulong(UIntPtr value)
{
return (ulong)value._value;
}
unsafe bool IEquatable<UIntPtr>.Equals(UIntPtr value)
{
return _value == value._value;
}
[Intrinsic]
[NonVersionable]
public static unsafe bool operator ==(UIntPtr value1, UIntPtr value2)
{
return value1._value == value2._value;
}
[Intrinsic]
[NonVersionable]
public static unsafe bool operator !=(UIntPtr value1, UIntPtr value2)
{
return value1._value != value2._value;
}
public static unsafe int Size
{
[Intrinsic]
[NonVersionable]
get
{
#if BIT64
return 8;
#else
return 4;
#endif
}
}
public unsafe override String ToString()
{
#if BIT64
return ((ulong)_value).ToString(CultureInfo.InvariantCulture);
#else
return ((uint)_value).ToString(CultureInfo.InvariantCulture);
#endif
}
public unsafe override bool Equals(Object obj)
{
if (obj is UIntPtr)
{
return (_value == ((UIntPtr)obj)._value);
}
return false;
}
public unsafe override int GetHashCode()
{
#if BIT64
ulong l = (ulong)_value;
return (unchecked((int)l) ^ (int)(l >> 32));
#else
return unchecked((int)_value);
#endif
}
[NonVersionable]
public static UIntPtr Add(UIntPtr pointer, int offset)
{
return pointer + offset;
}
[Intrinsic]
[NonVersionable]
public static UIntPtr operator +(UIntPtr pointer, int offset)
{
#if BIT64
return new UIntPtr(pointer.ToUInt64() + (ulong)offset);
#else
return new UIntPtr(pointer.ToUInt32() + (uint)offset);
#endif
}
[NonVersionable]
public static UIntPtr Subtract(UIntPtr pointer, int offset)
{
return pointer - offset;
}
[Intrinsic]
[NonVersionable]
public static UIntPtr operator -(UIntPtr pointer, int offset)
{
#if BIT64
return new UIntPtr(pointer.ToUInt64() - (ulong)offset);
#else
return new UIntPtr(pointer.ToUInt32() - (uint)offset);
#endif
}
}
}
| |
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using LavaLeak.Diplomata.Dictionaries;
using LavaLeak.Diplomata.Helpers;
using LavaLeak.Diplomata.Models.Submodels;
using LavaLeak.Diplomata.Persistence;
using LavaLeak.Diplomata.Persistence.Models;
using UnityEngine;
namespace LavaLeak.Diplomata.Models
{
/// <summary>
/// The item class.
/// </summary>
[Serializable]
public class Item : Data
{
[SerializeField]
private string uniqueId = Guid.NewGuid().ToString();
// TODO: Use only unique id.
public int id;
public LanguageDictionary[] name;
public LanguageDictionary[] description;
public string imagePath = string.Empty;
public string highlightImagePath = string.Empty;
public string pressedImagePath = string.Empty;
public string disabledImagePath = string.Empty;
[SerializeField]
private string category = string.Empty;
[NonSerialized]
public Texture2D image;
[NonSerialized]
public Texture2D highlightImage;
[NonSerialized]
public Texture2D pressedImage;
[NonSerialized]
public Texture2D disabledImage;
private Sprite sprite;
private Sprite highlightSprite;
private Sprite pressedSprite;
private Sprite disabledSprite;
[NonSerialized]
public bool have;
[NonSerialized]
public bool discarded;
/// <summary>
/// The item category.
/// </summary>
/// <value>The item category string.</value>
public string Category
{
get
{
return category;
}
set
{
category = value.ToLower();
}
}
/// <summary>
/// Property to get sprite after it's setted.
/// </summary>
/// <value>Sprite from image.</value>
public Sprite Sprite
{
get
{
SetImageAndSprite();
return sprite;
}
}
/// <summary>
/// Property to get sprite to highlighted, after it's setted.
/// </summary>
/// <value>Sprite from highlited image.</value>
public Sprite HighlightedSprite
{
get
{
SetHighlightedImageAndSprite();
return highlightSprite;
}
}
/// <summary>
/// Property to get sprite to pressed, after it's setted.
/// </summary>
/// <value>Sprite from pressed image.</value>
public Sprite PressedSprite
{
get
{
SetPressedImageAndSprite();
return pressedSprite;
}
}
/// <summary>
/// Property to get sprite to disabled, after it's setted.
/// </summary>
/// <value>Sprite from disabled image.</value>
public Sprite DisabledSprite
{
get
{
SetDisabledImageAndSprite();
return disabledSprite;
}
}
/// <summary>
/// Get the item unique id.
/// </summary>
/// <returns>The unique id(a string guid).</returns>
public string GetId()
{
return uniqueId;
}
/// <summary>
/// Get the item name.
/// </summary>
/// <returns>The name in the current language.</returns>
public string GetName()
{
return DictionariesHelper.ContainsKey(name, DiplomataManager.Data.options.currentLanguage).value;
}
/// <summary>
/// Get the item name.
/// </summary>
/// <returns>The name in the setted language.</returns>
public string GetName(string language)
{
return DictionariesHelper.ContainsKey(name, language).value;
}
/// <summary>
/// Get the item description.
/// </summary>
/// <returns>The description in the current language.</returns>
public string GetDescription()
{
return DictionariesHelper.ContainsKey(description, DiplomataManager.Data.options.currentLanguage).value;
}
/// <summary>
/// Get the item description.
/// </summary>
/// <returns>The description in the setted language.</returns>
public string GetDescription(string language)
{
return DictionariesHelper.ContainsKey(description, language).value;
}
/// <summary>
/// Set image and sprite from the path.
/// </summary>
public void SetImageAndSprite()
{
if (image == null || sprite == null)
{
image = (Texture2D) Resources.Load(imagePath);
if (image != null)
{
sprite = Sprite.Create(
image,
new Rect(0, 0, image.width, image.height),
new Vector2(0.5f, 0.5f)
);
}
}
}
/// <summary>
/// Set image and sprite from the path for highlight.
/// </summary>
public void SetHighlightedImageAndSprite()
{
if (highlightImage == null || highlightSprite == null)
{
highlightImage = (Texture2D) Resources.Load(highlightImagePath);
if (highlightImage != null)
{
highlightSprite = Sprite.Create(
highlightImage,
new Rect(0, 0, highlightImage.width, highlightImage.height),
new Vector2(0.5f, 0.5f)
);
}
}
}
/// <summary>
/// Set image and sprite from the path for pressed.
/// </summary>
public void SetPressedImageAndSprite()
{
if (pressedImage == null || pressedSprite == null)
{
pressedImage = (Texture2D) Resources.Load(pressedImagePath);
if (pressedImage != null)
{
pressedSprite = Sprite.Create(
pressedImage,
new Rect(0, 0, pressedImage.width, pressedImage.height),
new Vector2(0.5f, 0.5f)
);
}
}
}
/// <summary>
/// Set image and sprite from the path for disabled.
/// </summary>
public void SetDisabledImageAndSprite()
{
if (disabledImage == null || disabledSprite == null)
{
disabledImage = (Texture2D) Resources.Load(disabledImagePath);
if (disabledImage != null)
{
disabledSprite = Sprite.Create(
disabledImage,
new Rect(0, 0, disabledImage.width, disabledImage.height),
new Vector2(0.5f, 0.5f)
);
}
}
}
/// <summary>
/// Clean constructor.
/// </summary>
public Item() {}
/// <summary>
/// Instantiate a item with a id.
/// </summary>
/// <param name="id">The item id.</param>
public Item(int id, Options options)
{
SetId();
// uniqueId = Guid.NewGuid().ToString();
this.id = id;
foreach (Language language in options.languages)
{
name = ArrayHelper.Add(name, new LanguageDictionary(language.name, "[ Edit to change this name ]"));
description = ArrayHelper.Add(description, new LanguageDictionary(language.name, ""));
}
}
/// <summary>
/// Mark a item as have.
/// </summary>
public void MarkItemAsHave()
{
have = true;
}
/// <summary>
/// Set the uniqueId if it is empty or null.
/// </summary>
/// <returns>Return true if it change or false if don't.</returns>
public bool SetId()
{
if (uniqueId == string.Empty || uniqueId == null)
{
uniqueId = Guid.NewGuid().ToString();
return true;
}
return false;
}
/// <summary>
/// Find a item by id.
/// </summary>
/// <param name="array">A array of items.</param>
/// <param name="itemId">The id of the item.</param>
/// <returns>The item if found, or null.</returns>
public static Item Find(Item[] array, int itemId)
{
return (Item) Helpers.Find.In(array).Where("id", itemId).Result;
}
/// <summary>
/// Find a item by name in a specific language.
/// </summary>
/// <param name="items">A array of items.</param>
/// <param name="name">The name of the item.</param>
/// <param name="language">The specific language.</param>
/// <returns>The item if found, or null.s</returns>
public static Item Find(Item[] items, string name, string language = "English")
{
// TODO: use the Helpers.Find class here.
foreach (Item item in items)
{
LanguageDictionary itemName = DictionariesHelper.ContainsKey(item.name, language);
if (itemName.value == name && itemName != null)
{
return item;
}
}
Debug.LogError($"This item \"{name}\" doesn't exist.");
return null;
}
/// <summary>
/// Return the data of the object to save in a persistent object.
/// </summary>
/// <returns>A persistent object.</returns>
public override Persistent GetData()
{
var item = new ItemPersistent();
item.id = uniqueId;
item.have = have;
item.discarded = discarded;
return item;
}
/// <summary>
/// Store in a object data from persistent object.
/// </summary>
/// <param name="persistentData">The persistent data object.</param>
public override void SetData(Persistent persistentData)
{
var itemPersistentData = (ItemPersistent) persistentData;
uniqueId = itemPersistentData.id;
have = itemPersistentData.have;
discarded = itemPersistentData.discarded;
}
/// <summary>
/// Return the name of the item.
/// </summary>
/// <param name="language">The language of the name.</param>
/// <returns>The name of the item or empty.</returns>
public string DisplayName(string language)
{
var nameResult = DictionariesHelper.ContainsKey(name, language);
if (nameResult == null) return string.Empty;
return nameResult.value;
}
/// <summary>
/// Return the description of the item.
/// </summary>
/// <param name="language">The language of the name.</param>
/// <returns>The description of the item or empty.</returns>
public string DisplayDescription(string language)
{
var nameResult = DictionariesHelper.ContainsKey(description, language);
if (nameResult == null) return string.Empty;
return nameResult.value;
}
/// <summary>
/// Copy a item with all fields values.
/// </summary>
/// <param name="newId">the new id for the copied item.</param>
/// <param name="options">The options with languages infos.</param>
/// <returns>The new item.</returns>
public Item Copy(int newId, Options options)
{
var item = new Item(newId, options);
item.name = this.name;
item.description = this.description;
item.imagePath = this.imagePath;
item.highlightImagePath = this.highlightImagePath;
item.pressedImagePath = this.pressedImagePath;
item.disabledImagePath = this.disabledImagePath;
item.category = this.category;
return item;
}
}
}
| |
namespace Nancy.Tests.Unit.IO
{
using System;
using System.IO;
using FakeItEasy;
using Nancy.IO;
using Xunit;
public class RequestStreamFixture
{
[Fact]
public void Should_not_dispose_wrapped_stream_when_not_switched()
{
// Given
var stream = new ConfigurableMemoryStream();
var instance = RequestStream.FromStream(stream, 0, 1, true);
// When
instance.Dispose();
// Then
stream.HasBeenDisposed.ShouldBeFalse();
}
[Fact]
public void Should_move_non_seekable_stream_into_seekable_stream_when_stream_switching_is_disabled()
{
// Given
var stream = new ConfigurableMemoryStream(Seekable: false);
// When
var result = RequestStream.FromStream(stream, 0, 1, true);
// Then
result.CanSeek.ShouldBeTrue();
}
[Fact]
public void Should_move_stream_out_of_memory_if_longer_than_threshold_and_stream_switching_is_enabled()
{
// Given
var inputStream = new MemoryStream(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
// When
var result = RequestStream.FromStream(inputStream, 0, 4, false);
// Then
result.IsInMemory.ShouldBeFalse();
}
[Fact]
public void Should_not_move_stream_out_of_memory_if_longer_than_threshold_and_stream_switching_is_disabled()
{
// Given
var inputStream = new MemoryStream(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
// When
var result = RequestStream.FromStream(inputStream, 0, 4, true);
// Then
result.IsInMemory.ShouldBeTrue();
}
[Fact]
public void Should_throw_invalidoperationexception_when_created_with_non_readable_stream()
{
// Given
var stream = new ConfigurableMemoryStream(Readable: false);
// When
var exception = Record.Exception(() => RequestStream.FromStream(stream));
// Then
exception.ShouldBeOfType<InvalidOperationException>();
}
[Fact]
public void Should_throw_argumentoutofrangeexception_when_expected_lenght_is_less_than_zero()
{
// Given
var stream = new ConfigurableMemoryStream();
const int expectedLength = -1;
// When
var exception = Record.Exception(() => RequestStream.FromStream(stream, expectedLength));
// Then
exception.ShouldBeOfType<ArgumentOutOfRangeException>();
}
[Fact]
public void Should_throw_argumentoutofrangeexception_when_thresholdLength_is_less_than_zero()
{
// Given
var stream = new ConfigurableMemoryStream();
const int tresholdLength = -1;
// When
var exception = Record.Exception(() => RequestStream.FromStream(stream, 0, tresholdLength));
// Then
exception.ShouldBeOfType<ArgumentOutOfRangeException>();
}
[Fact]
public void Should_work_even_with_a_non_seekable_stream()
{
// Given
var stream = new ConfigurableMemoryStream(Seekable: false);
var request = RequestStream.FromStream(stream, 0, 1, false);
// When
var result = request.CanRead;
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_return_true_when_queried_about_supporting_reading()
{
// Given
var stream = new ConfigurableMemoryStream();
var request = RequestStream.FromStream(stream, 0, 1, false);
// When
var result = request.CanRead;
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_return_true_when_queried_about_supporting_writing()
{
// Given
var stream = new ConfigurableMemoryStream();
var request = RequestStream.FromStream(stream, 0, 1, false);
// When
var result = request.CanWrite;
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_return_true_when_queried_about_supporting_seeking()
{
// Given
var stream = new ConfigurableMemoryStream();
var request = RequestStream.FromStream(stream, 0, 1, false);
// When
var result = request.CanSeek;
// Then
result.ShouldBeTrue();
}
[Fact]
public void Should_return_false_when_queried_about_supporting_timeout()
{
// Given
var stream = new ConfigurableMemoryStream();
var request = RequestStream.FromStream(stream, 0, 1, false);
// When
var result = request.CanTimeout;
// Then
result.ShouldBeFalse();
}
[Fact]
public void Should_return_length_of_underlaying_stream()
{
// Given
var stream = new ConfigurableMemoryStream(Length: 1234L);
var request = RequestStream.FromStream(stream, 0, 1235, false);
// When
var result = request.Length;
// Then
result.ShouldEqual(1234L);
}
[Fact]
public void Should_return_position_of_underlaying_stream()
{
// Given
var stream = new ConfigurableMemoryStream();
var request = RequestStream.FromStream(stream, 0, 1, false);
stream.Position = 1234L;
// When
var result = request.Position;
// Then
result.ShouldEqual(1234L);
}
[Fact]
public void Should_set_position_of_underlaying_stream()
{
// Given
var stream = new ConfigurableMemoryStream(Length: 2000L);
var request = RequestStream.FromStream(stream, 2000L, 2001L, false);
// When
request.Position = 1234L;
// Then
stream.Position.ShouldEqual(1234L);
}
[Fact]
public void Should_throw_argumentoutofrangexception_when_setting_position_to_less_than_zero()
{
// Given
var stream = new ConfigurableMemoryStream();
var request = RequestStream.FromStream(stream, 2000L, 2001L, false);
// When
var exception = Record.Exception(() => request.Position = -1);
// Then
exception.ShouldBeOfType<InvalidOperationException>();
}
[Fact]
public void Should_throw_invalidoperationexception_when_position_is_set_to_greater_than_length_of_stream()
{
// Given
var stream = new ConfigurableMemoryStream(Length: 100L);
var request = RequestStream.FromStream(stream, 0, 1, false);
// When
var exception = Record.Exception(() => request.Position = 1000);
// Then
exception.ShouldBeOfType<InvalidOperationException>();
}
[Fact]
public void Should_flush_underlaying_stream()
{
// Given
var stream = new ConfigurableMemoryStream();
var request = RequestStream.FromStream(stream, 0, 1, false);
// When
request.Flush();
// Then
stream.HasBeenFlushed.ShouldBeTrue();
}
[Fact]
public void Should_throw_notsupportedexception_when_setting_length()
{
// Given
var stream = new ConfigurableMemoryStream();
var request = RequestStream.FromStream(stream, 0, 1, false);
// When
var exception = Record.Exception(() => request.SetLength(10L));
// Then
exception.ShouldBeOfType<NotSupportedException>();
}
[Fact]
public void Should_set_position_of_underlaying_stream_to_zero_when_created()
{
// Given
var stream = new ConfigurableMemoryStream(Position: 10L);
// When
var request = RequestStream.FromStream(stream, 0, 1, false);
// Then
stream.Position.ShouldEqual(0L);
}
[Fact]
public void Should_seek_in_the_underlaying_stream_when_seek_is_called()
{
// Given
var stream = new ConfigurableMemoryStream();
var request = RequestStream.FromStream(stream, 0, 1, false);
// When
request.Seek(10L, SeekOrigin.Current);
// Then
stream.HasBeenSeeked.ShouldBeTrue();
}
[Fact]
public void Should_return_the_new_position_of_the_underlaying_stream_when_seek_is_called()
{
// Given
var stream = CreateFakeStream();
A.CallTo(() => stream.Seek(A<long>.Ignored, A<SeekOrigin>.Ignored)).Returns(100L);
var request = RequestStream.FromStream(stream, 0, 1, false);
// When
var result = request.Seek(10L, SeekOrigin.Current);
// Then
result.ShouldEqual(100L);
}
[Fact]
public void Should_read_byte_from_underlaying_stream_when_reading_byte()
{
// Given
var stream = CreateFakeStream();
var request = RequestStream.FromStream(stream, 0, 1, false);
// When
request.ReadByte();
// Then
A.CallTo(() => stream.ReadByte()).MustHaveHappened();
}
[Fact]
public void Should_return_read_byte_from_underlaying_stream_when_readbyte_is_called()
{
// Given
var stream = CreateFakeStream();
A.CallTo(() => stream.ReadByte()).Returns(5);
var request = RequestStream.FromStream(stream, 0, 1, false);
// When
var result = request.ReadByte();
// Then
result.ShouldEqual(5);
}
[Fact]
public void Should_read_from_underlaying_stream_when_read_is_called()
{
// Given
var stream = CreateFakeStream();
var buffer = new byte[1];
var request = RequestStream.FromStream(stream, 0, 1, false);
// When
request.Read(buffer, 0, buffer.Length);
// Then
A.CallTo(() => stream.Read(buffer, 0, buffer.Length)).MustHaveHappened();
}
[Fact]
public void Should_return_result_from_reading_underlaying_stream()
{
// Given
var stream = CreateFakeStream();
var buffer = new byte[1];
var request = RequestStream.FromStream(stream, 0, 1, false);
A.CallTo(() => stream.Read(buffer, 0, buffer.Length)).Returns(3);
// When
var result = request.Read(buffer, 0, buffer.Length);
// Then
result.ShouldEqual(3);
}
[Fact]
public void Should_write_to_underlaying_stream_when_write_is_called()
{
// Given
var stream = CreateFakeStream();
var buffer = new byte[1];
var request = RequestStream.FromStream(stream, 0, 1, false);
// When
request.Write(buffer, 0, buffer.Length);
// Then
A.CallTo(() => stream.Write(buffer, 0, buffer.Length)).MustHaveHappened();
}
[Fact]
public void Should_no_longer_be_in_memory_if_expected_length_is_greater_or_equal_to_threshold_length()
{
// Given
var stream = CreateFakeStream();
// When
var request = RequestStream.FromStream(stream, 1, 0, false);
// Then
request.IsInMemory.ShouldBeFalse();
}
[Fact]
public void Should_no_longer_be_in_memory_when_more_bytes_have_been_written_to_stream_then_size_of_the_threshold_and_stream_swapping_is_enabled()
{
// Given
var stream = CreateFakeStream();
var buffer = new byte[100];
var request = RequestStream.FromStream(stream, 0, 10, false);
A.CallTo(() => stream.Length).Returns(100);
// When
request.Write(buffer, 0, buffer.Length);
// Then
request.IsInMemory.ShouldBeFalse();
}
[Fact]
public void Should_still_be_in_memory_when_more_bytes_have_been_written_to_stream_than_size_of_threshold_and_stream_swapping_is_disabled()
{
// Given
var stream = CreateFakeStream();
var buffer = new byte[100];
var request = RequestStream.FromStream(stream, 0, 10, true);
A.CallTo(() => stream.Length).Returns(100);
// When
request.Write(buffer, 0, buffer.Length);
// Then
request.IsInMemory.ShouldBeTrue();
}
#if !CORE // BeginRead, EndRead, BeginWrite, EndWrite don't exist in .NET Core
[Fact]
public void Should_call_beginread_on_underlaying_stream_when_beginread_is_called()
{
// Given
var stream = CreateFakeStream();
var buffer = new byte[10];
AsyncCallback callback = x => { };
var state = new object();
var request = RequestStream.FromStream(stream, 0, 10, true);
// When
request.BeginRead(buffer, 0, buffer.Length, callback, state);
// Then
A.CallTo(() => stream.BeginRead(buffer, 0, buffer.Length, callback, state)).MustHaveHappened();
}
[Fact]
public void Should_return_result_from_underlaying_beginread_when_beginread_is_called()
{
// Given
var stream = CreateFakeStream();
var buffer = new byte[10];
var asyncResult = A.Fake<IAsyncResult>();
AsyncCallback callback = x => { };
var state = new object();
var request = RequestStream.FromStream(stream, 0, 10, true);
A.CallTo(() => stream.BeginRead(buffer, 0, buffer.Length, callback, state)).Returns(asyncResult);
// When
var result = request.BeginRead(buffer, 0, buffer.Length, callback, state);
// Then
result.ShouldBeSameAs(asyncResult);
}
[Fact]
public void Should_call_beginwrite_on_underlaying_stream_when_beginwrite_is_called()
{
// Given
var stream = CreateFakeStream();
var buffer = new byte[10];
AsyncCallback callback = x => { };
var state = new object();
var request = RequestStream.FromStream(stream, 0, 10, true);
// When
request.BeginWrite(buffer, 0, buffer.Length, callback, state);
// Then
A.CallTo(() => stream.BeginWrite(buffer, 0, buffer.Length, callback, state)).MustHaveHappened();
}
[Fact]
public void Should_return_result_from_underlaying_beginwrite_when_beginwrite_is_called()
{
// Given
var stream = CreateFakeStream();
var buffer = new byte[10];
var asyncResult = A.Fake<IAsyncResult>();
AsyncCallback callback = x => { };
var state = new object();
var request = RequestStream.FromStream(stream, 0, 10, true);
A.CallTo(() => stream.BeginWrite(buffer, 0, buffer.Length, callback, state)).Returns(asyncResult);
// When
var result = request.BeginWrite(buffer, 0, buffer.Length, callback, state);
// Then
result.ShouldBeSameAs(asyncResult);
}
[Fact]
public void Should_call_endread_on_underlaying_stream_when_endread_is_called()
{
// Given
var stream = CreateFakeStream();
var asyncResult = A.Fake<IAsyncResult>();
var request = RequestStream.FromStream(stream, 0, 10, true);
// When
request.EndRead(asyncResult);
// Then
A.CallTo(() => stream.EndRead(asyncResult)).MustHaveHappened();
}
[Fact]
public void Should_return_result_from_underlaying_endread_when_endread_is_called()
{
// Given
var stream = CreateFakeStream();
var asyncResult = A.Fake<IAsyncResult>();
var request = RequestStream.FromStream(stream, 0, 10, true);
A.CallTo(() => stream.EndRead(A<IAsyncResult>.Ignored)).Returns(4);
// When
var result = request.EndRead(asyncResult);
// Then
result.ShouldEqual(4);
}
[Fact]
public void Should_call_endwrite_on_underlaying_stream_when_endwrite_is_called()
{
// Given
var stream = CreateFakeStream();
var asyncResult = A.Fake<IAsyncResult>();
var request = RequestStream.FromStream(stream, 0, 10, true);
// When
request.EndWrite(asyncResult);
// Then
A.CallTo(() => stream.EndWrite(asyncResult)).MustHaveHappened();
}
#endif
private static Stream CreateFakeStream()
{
var stream = A.Fake<Stream>(x =>
{
x.Implements(typeof(IDisposable));
});
A.CallTo(() => stream.CanRead).Returns(true);
A.CallTo(() => stream.CanSeek).Returns(true);
A.CallTo(() => stream.CanTimeout).Returns(true);
A.CallTo(() => stream.CanWrite).Returns(true);
return stream;
}
private class ConfigurableMemoryStream : MemoryStream
{
private readonly bool readable;
private readonly bool seekable;
private readonly bool timeoutable;
private readonly bool writable;
private readonly long length;
private long position;
public bool HasBeenDisposed { get; private set; }
public bool HasBeenFlushed { get; private set; }
public bool HasBeenSeeked { get; private set; }
public ConfigurableMemoryStream(bool Readable = true, bool Seekable = true, bool Timeoutable = true, bool Writable = true, long Length = 0, long Position = 0)
{
this.readable = Readable;
this.seekable = Seekable;
this.timeoutable = Timeoutable;
this.writable = Writable;
this.length = Length;
this.position = Position;
}
public override bool CanRead
{
get { return this.readable; }
}
public override bool CanSeek
{
get { return this.seekable; }
}
public override bool CanTimeout
{
get { return this.timeoutable; }
}
public override bool CanWrite
{
get { return this.writable; }
}
public override long Length
{
get { return this.length; }
}
public override long Position
{
get { return this.position; }
set { this.position = value ; }
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
this.HasBeenDisposed = true;
}
public override void Flush()
{
base.Flush();
this.HasBeenFlushed = true;
}
public override long Seek(long offset, SeekOrigin loc)
{
this.HasBeenSeeked = true;
return base.Seek(offset, loc);
}
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// BufferBlock.cs
//
//
// A propagator block that provides support for unbounded and bounded FIFO buffers.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Security;
using System.Threading.Tasks.Dataflow.Internal;
using System.Diagnostics.CodeAnalysis;
namespace System.Threading.Tasks.Dataflow
{
/// <summary>Provides a buffer for storing data.</summary>
/// <typeparam name="T">Specifies the type of the data buffered by this dataflow block.</typeparam>
[DebuggerDisplay("{DebuggerDisplayContent,nq}")]
[DebuggerTypeProxy(typeof(BufferBlock<>.DebugView))]
public sealed class BufferBlock<T> : IPropagatorBlock<T, T>, IReceivableSourceBlock<T>, IDebuggerDisplay
{
/// <summary>The core logic for the buffer block.</summary>
private readonly SourceCore<T> _source;
/// <summary>The bounding state for when in bounding mode; null if not bounding.</summary>
private readonly BoundingStateWithPostponedAndTask<T> _boundingState;
/// <summary>Whether all future messages should be declined on the target.</summary>
private bool _targetDecliningPermanently;
/// <summary>A task has reserved the right to run the target's completion routine.</summary>
private bool _targetCompletionReserved;
/// <summary>Gets the lock object used to synchronize incoming requests.</summary>
private object IncomingLock { get { return _source; } }
/// <summary>Initializes the <see cref="BufferBlock{T}"/>.</summary>
public BufferBlock() :
this(DataflowBlockOptions.Default)
{ }
/// <summary>Initializes the <see cref="BufferBlock{T}"/> with the specified <see cref="DataflowBlockOptions"/>.</summary>
/// <param name="dataflowBlockOptions">The options with which to configure this <see cref="BufferBlock{T}"/>.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception>
public BufferBlock(DataflowBlockOptions dataflowBlockOptions)
{
if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions));
// Ensure we have options that can't be changed by the caller
dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone();
// Initialize bounding state if necessary
Action<ISourceBlock<T>, int> onItemsRemoved = null;
if (dataflowBlockOptions.BoundedCapacity > 0)
{
onItemsRemoved = (owningSource, count) => ((BufferBlock<T>)owningSource).OnItemsRemoved(count);
_boundingState = new BoundingStateWithPostponedAndTask<T>(dataflowBlockOptions.BoundedCapacity);
}
// Initialize the source state
_source = new SourceCore<T>(this, dataflowBlockOptions,
owningSource => ((BufferBlock<T>)owningSource).Complete(),
onItemsRemoved);
// It is possible that the source half may fault on its own, e.g. due to a task scheduler exception.
// In those cases we need to fault the target half to drop its buffered messages and to release its
// reservations. This should not create an infinite loop, because all our implementations are designed
// to handle multiple completion requests and to carry over only one.
_source.Completion.ContinueWith((completed, state) =>
{
var thisBlock = ((BufferBlock<T>)state) as IDataflowBlock;
Debug.Assert(completed.IsFaulted, "The source must be faulted in order to trigger a target completion.");
thisBlock.Fault(completed.Exception);
}, this, CancellationToken.None, Common.GetContinuationOptions() | TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default);
// Handle async cancellation requests by declining on the target
Common.WireCancellationToComplete(
dataflowBlockOptions.CancellationToken, _source.Completion, owningSource => ((BufferBlock<T>)owningSource).Complete(), this);
#if FEATURE_TRACING
DataflowEtwProvider etwLog = DataflowEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.DataflowBlockCreated(this, dataflowBlockOptions);
}
#endif
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' />
DataflowMessageStatus ITargetBlock<T>.OfferMessage(DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source, bool consumeToAccept)
{
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, nameof(consumeToAccept));
lock (IncomingLock)
{
// If we've already stopped accepting messages, decline permanently
if (_targetDecliningPermanently)
{
CompleteTargetIfPossible();
return DataflowMessageStatus.DecliningPermanently;
}
// We can directly accept the message if:
// 1) we are not bounding, OR
// 2) we are bounding AND there is room available AND there are no postponed messages AND we are not currently processing.
// (If there were any postponed messages, we would need to postpone so that ordering would be maintained.)
// (We should also postpone if we are currently processing, because there may be a race between consuming postponed messages and
// accepting new ones directly into the queue.)
if (_boundingState == null
||
(_boundingState.CountIsLessThanBound && _boundingState.PostponedMessages.Count == 0 && _boundingState.TaskForInputProcessing == null))
{
// Consume the message from the source if necessary
if (consumeToAccept)
{
Debug.Assert(source != null, "We must have thrown if source == null && consumeToAccept == true.");
bool consumed;
messageValue = source.ConsumeMessage(messageHeader, this, out consumed);
if (!consumed) return DataflowMessageStatus.NotAvailable;
}
// Once consumed, pass it to the source
_source.AddMessage(messageValue);
if (_boundingState != null) _boundingState.CurrentCount++;
return DataflowMessageStatus.Accepted;
}
// Otherwise, we try to postpone if a source was provided
else if (source != null)
{
Debug.Assert(_boundingState != null && _boundingState.PostponedMessages != null,
"PostponedMessages must have been initialized during construction in bounding mode.");
_boundingState.PostponedMessages.Push(source, messageHeader);
return DataflowMessageStatus.Postponed;
}
// We can't do anything else about this message
return DataflowMessageStatus.Declined;
}
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' />
public void Complete() { CompleteCore(exception: null, storeExceptionEvenIfAlreadyCompleting: false); }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' />
void IDataflowBlock.Fault(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
CompleteCore(exception, storeExceptionEvenIfAlreadyCompleting: false);
}
private void CompleteCore(Exception exception, bool storeExceptionEvenIfAlreadyCompleting, bool revertProcessingState = false)
{
Debug.Assert(storeExceptionEvenIfAlreadyCompleting || !revertProcessingState,
"Indicating dirty processing state may only come with storeExceptionEvenIfAlreadyCompleting==true.");
lock (IncomingLock)
{
// Faulting from outside is allowed until we start declining permanently.
// Faulting from inside is allowed at any time.
if (exception != null && (!_targetDecliningPermanently || storeExceptionEvenIfAlreadyCompleting))
{
_source.AddException(exception);
}
// Revert the dirty processing state if requested
if (revertProcessingState)
{
Debug.Assert(_boundingState != null && _boundingState.TaskForInputProcessing != null,
"The processing state must be dirty when revertProcessingState==true.");
_boundingState.TaskForInputProcessing = null;
}
// Trigger completion
_targetDecliningPermanently = true;
CompleteTargetIfPossible();
}
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="LinkTo"]/*' />
public IDisposable LinkTo(ITargetBlock<T> target, DataflowLinkOptions linkOptions) { return _source.LinkTo(target, linkOptions); }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceive"]/*' />
public bool TryReceive(Predicate<T> filter, out T item) { return _source.TryReceive(filter, out item); }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceiveAll"]/*' />
public bool TryReceiveAll(out IList<T> items) { return _source.TryReceiveAll(out items); }
/// <summary>Gets the number of items currently stored in the buffer.</summary>
public int Count { get { return _source.OutputCount; } }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' />
public Task Completion { get { return _source.Completion; } }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ConsumeMessage"]/*' />
T ISourceBlock<T>.ConsumeMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target, out bool messageConsumed)
{
return _source.ConsumeMessage(messageHeader, target, out messageConsumed);
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReserveMessage"]/*' />
bool ISourceBlock<T>.ReserveMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target)
{
return _source.ReserveMessage(messageHeader, target);
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReleaseReservation"]/*' />
void ISourceBlock<T>.ReleaseReservation(DataflowMessageHeader messageHeader, ITargetBlock<T> target)
{
_source.ReleaseReservation(messageHeader, target);
}
/// <summary>Notifies the block that one or more items was removed from the queue.</summary>
/// <param name="numItemsRemoved">The number of items removed.</param>
private void OnItemsRemoved(int numItemsRemoved)
{
Debug.Assert(numItemsRemoved > 0, "A positive number of items to remove is required.");
Common.ContractAssertMonitorStatus(IncomingLock, held: false);
// If we're bounding, we need to know when an item is removed so that we
// can update the count that's mirroring the actual count in the source's queue,
// and potentially kick off processing to start consuming postponed messages.
if (_boundingState != null)
{
lock (IncomingLock)
{
// Decrement the count, which mirrors the count in the source half
Debug.Assert(_boundingState.CurrentCount - numItemsRemoved >= 0,
"It should be impossible to have a negative number of items.");
_boundingState.CurrentCount -= numItemsRemoved;
ConsumeAsyncIfNecessary();
CompleteTargetIfPossible();
}
}
}
/// <summary>Called when postponed messages may need to be consumed.</summary>
/// <param name="isReplacementReplica">Whether this call is the continuation of a previous message loop.</param>
internal void ConsumeAsyncIfNecessary(bool isReplacementReplica = false)
{
Common.ContractAssertMonitorStatus(IncomingLock, held: true);
Debug.Assert(_boundingState != null, "Must be in bounded mode.");
if (!_targetDecliningPermanently &&
_boundingState.TaskForInputProcessing == null &&
_boundingState.PostponedMessages.Count > 0 &&
_boundingState.CountIsLessThanBound)
{
// Create task and store into _taskForInputProcessing prior to scheduling the task
// so that _taskForInputProcessing will be visibly set in the task loop.
_boundingState.TaskForInputProcessing =
new Task(state => ((BufferBlock<T>)state).ConsumeMessagesLoopCore(), this,
Common.GetCreationOptionsForTask(isReplacementReplica));
#if FEATURE_TRACING
DataflowEtwProvider etwLog = DataflowEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.TaskLaunchedForMessageHandling(
this, _boundingState.TaskForInputProcessing, DataflowEtwProvider.TaskLaunchedReason.ProcessingInputMessages,
_boundingState.PostponedMessages.Count);
}
#endif
// Start the task handling scheduling exceptions
Exception exception = Common.StartTaskSafe(_boundingState.TaskForInputProcessing, _source.DataflowBlockOptions.TaskScheduler);
if (exception != null)
{
// Get out from under currently held locks. CompleteCore re-acquires the locks it needs.
Task.Factory.StartNew(exc => CompleteCore(exception: (Exception)exc, storeExceptionEvenIfAlreadyCompleting: true, revertProcessingState: true),
exception, CancellationToken.None, Common.GetCreationOptionsForTask(), TaskScheduler.Default);
}
}
}
/// <summary>Task body used to consume postponed messages.</summary>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void ConsumeMessagesLoopCore()
{
Debug.Assert(_boundingState != null && _boundingState.TaskForInputProcessing != null,
"May only be called in bounded mode and when a task is in flight.");
Debug.Assert(_boundingState.TaskForInputProcessing.Id == Task.CurrentId,
"This must only be called from the in-flight processing task.");
Common.ContractAssertMonitorStatus(IncomingLock, held: false);
try
{
int maxMessagesPerTask = _source.DataflowBlockOptions.ActualMaxMessagesPerTask;
for (int i = 0;
i < maxMessagesPerTask && ConsumeAndStoreOneMessageIfAvailable();
i++)
;
}
catch (Exception exc)
{
// Prevent the creation of new processing tasks
CompleteCore(exc, storeExceptionEvenIfAlreadyCompleting: true);
}
finally
{
lock (IncomingLock)
{
// We're no longer processing, so null out the processing task
_boundingState.TaskForInputProcessing = null;
// However, we may have given up early because we hit our own configured
// processing limits rather than because we ran out of work to do. If that's
// the case, make sure we spin up another task to keep going.
ConsumeAsyncIfNecessary(isReplacementReplica: true);
// If, however, we stopped because we ran out of work to do and we
// know we'll never get more, then complete.
CompleteTargetIfPossible();
}
}
}
/// <summary>
/// Retrieves one postponed message if there's room and if we can consume a postponed message.
/// Stores any consumed message into the source half.
/// </summary>
/// <returns>true if a message could be consumed and stored; otherwise, false.</returns>
/// <remarks>This must only be called from the asynchronous processing loop.</remarks>
private bool ConsumeAndStoreOneMessageIfAvailable()
{
Debug.Assert(_boundingState != null && _boundingState.TaskForInputProcessing != null,
"May only be called in bounded mode and when a task is in flight.");
Debug.Assert(_boundingState.TaskForInputProcessing.Id == Task.CurrentId,
"This must only be called from the in-flight processing task.");
Common.ContractAssertMonitorStatus(IncomingLock, held: false);
// Loop through the postponed messages until we get one.
while (true)
{
// Get the next item to retrieve. If there are no more, bail.
KeyValuePair<ISourceBlock<T>, DataflowMessageHeader> sourceAndMessage;
lock (IncomingLock)
{
if (_targetDecliningPermanently) return false;
if (!_boundingState.CountIsLessThanBound) return false;
if (!_boundingState.PostponedMessages.TryPop(out sourceAndMessage)) return false;
// Optimistically assume we're going to get the item. This avoids taking the lock
// again if we're right. If we're wrong, we decrement it later under lock.
_boundingState.CurrentCount++;
}
// Consume the item
bool consumed = false;
try
{
T consumedValue = sourceAndMessage.Key.ConsumeMessage(sourceAndMessage.Value, this, out consumed);
if (consumed)
{
_source.AddMessage(consumedValue);
return true;
}
}
finally
{
// We didn't get the item, so decrement the count to counteract our optimistic assumption.
if (!consumed)
{
lock (IncomingLock) _boundingState.CurrentCount--;
}
}
}
}
/// <summary>Completes the target, notifying the source, once all completion conditions are met.</summary>
private void CompleteTargetIfPossible()
{
Common.ContractAssertMonitorStatus(IncomingLock, held: true);
if (_targetDecliningPermanently &&
!_targetCompletionReserved &&
(_boundingState == null || _boundingState.TaskForInputProcessing == null))
{
_targetCompletionReserved = true;
// If we're in bounding mode and we have any postponed messages, we need to clear them,
// which means calling back to the source, which means we need to escape the incoming lock.
if (_boundingState != null && _boundingState.PostponedMessages.Count > 0)
{
Task.Factory.StartNew(state =>
{
var thisBufferBlock = (BufferBlock<T>)state;
// Release any postponed messages
List<Exception> exceptions = null;
if (thisBufferBlock._boundingState != null)
{
// Note: No locks should be held at this point
Common.ReleaseAllPostponedMessages(thisBufferBlock,
thisBufferBlock._boundingState.PostponedMessages,
ref exceptions);
}
if (exceptions != null)
{
// It is important to migrate these exceptions to the source part of the owning batch,
// because that is the completion task that is publicly exposed.
thisBufferBlock._source.AddExceptions(exceptions);
}
thisBufferBlock._source.Complete();
}, this, CancellationToken.None, Common.GetCreationOptionsForTask(), TaskScheduler.Default);
}
// Otherwise, we can just decline the source directly.
else
{
_source.Complete();
}
}
}
/// <summary>Gets the number of messages in the buffer. This must only be used from the debugger as it avoids taking necessary locks.</summary>
private int CountForDebugger { get { return _source.GetDebuggingInformation().OutputCount; } }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="ToString"]/*' />
public override string ToString() { return Common.GetNameForDebugger(this, _source.DataflowBlockOptions); }
/// <summary>The data to display in the debugger display attribute.</summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")]
private object DebuggerDisplayContent
{
get
{
return string.Format("{0}, Count={1}",
Common.GetNameForDebugger(this, _source.DataflowBlockOptions),
CountForDebugger);
}
}
/// <summary>Gets the data to display in the debugger display attribute for this instance.</summary>
object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } }
/// <summary>Provides a debugger type proxy for the BufferBlock.</summary>
private sealed class DebugView
{
/// <summary>The buffer block.</summary>
private readonly BufferBlock<T> _bufferBlock;
/// <summary>The buffer's source half.</summary>
private readonly SourceCore<T>.DebuggingInformation _sourceDebuggingInformation;
/// <summary>Initializes the debug view.</summary>
/// <param name="bufferBlock">The BufferBlock being viewed.</param>
public DebugView(BufferBlock<T> bufferBlock)
{
Debug.Assert(bufferBlock != null, "Need a block with which to construct the debug view.");
_bufferBlock = bufferBlock;
_sourceDebuggingInformation = bufferBlock._source.GetDebuggingInformation();
}
/// <summary>Gets the collection of postponed message headers.</summary>
public QueuedMap<ISourceBlock<T>, DataflowMessageHeader> PostponedMessages
{
get { return _bufferBlock._boundingState != null ? _bufferBlock._boundingState.PostponedMessages : null; }
}
/// <summary>Gets the messages in the buffer.</summary>
public IEnumerable<T> Queue { get { return _sourceDebuggingInformation.OutputQueue; } }
/// <summary>The task used to process messages.</summary>
public Task TaskForInputProcessing { get { return _bufferBlock._boundingState != null ? _bufferBlock._boundingState.TaskForInputProcessing : null; } }
/// <summary>Gets the task being used for output processing.</summary>
public Task TaskForOutputProcessing { get { return _sourceDebuggingInformation.TaskForOutputProcessing; } }
/// <summary>Gets the DataflowBlockOptions used to configure this block.</summary>
public DataflowBlockOptions DataflowBlockOptions { get { return _sourceDebuggingInformation.DataflowBlockOptions; } }
/// <summary>Gets whether the block is declining further messages.</summary>
public bool IsDecliningPermanently { get { return _bufferBlock._targetDecliningPermanently; } }
/// <summary>Gets whether the block is completed.</summary>
public bool IsCompleted { get { return _sourceDebuggingInformation.IsCompleted; } }
/// <summary>Gets the block's Id.</summary>
public int Id { get { return Common.GetBlockId(_bufferBlock); } }
/// <summary>Gets the set of all targets linked from this block.</summary>
public TargetRegistry<T> LinkedTargets { get { return _sourceDebuggingInformation.LinkedTargets; } }
/// <summary>Gets the set of all targets linked from this block.</summary>
public ITargetBlock<T> NextMessageReservedFor { get { return _sourceDebuggingInformation.NextMessageReservedFor; } }
}
}
}
| |
using System.Security;
using System;
public struct TestStruct
{
public int IntValue;
public string StringValue;
}
public class DisposableClass : IDisposable
{
public void Dispose()
{
}
}
/// <summary>
/// ctor(System.Object, System.Boolean)
/// </summary>
[SecuritySafeCritical]
public class WeakReferenceCtor1
{
#region Private Fields
private const int c_MIN_STRING_LENGTH = 8;
private const int c_MAX_STRING_LENGTH = 1024;
#endregion
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Call Ctor with valid target reference and set trackResurrection to false");
try
{
Object obj = new Object();
WeakReference reference = new WeakReference(obj, false);
if ((reference.TrackResurrection != false) || (!reference.Target.Equals(obj)) )
{
TestLibrary.TestFramework.LogError("001.1", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString() +
", obj = " + obj.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Call Ctor with valid target reference and set trackResurrection to true");
try
{
Object obj = new Object();
WeakReference reference = new WeakReference(obj, true);
if ((reference.TrackResurrection != true) || (!reference.Target.Equals(obj)))
{
TestLibrary.TestFramework.LogError("002.1", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString() +
", obj = " + obj.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Call Ctor with value type target reference");
try
{
int randValue = TestLibrary.Generator.GetInt32(-55);
WeakReference reference = new WeakReference(randValue, true);
if ((reference.TrackResurrection != true) || (!reference.Target.Equals(randValue)))
{
TestLibrary.TestFramework.LogError("003.1", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString() +
", randValue = " + randValue.ToString());
retVal = false;
}
reference = new WeakReference(randValue, false);
if ((reference.TrackResurrection != false) || (!reference.Target.Equals(randValue)))
{
TestLibrary.TestFramework.LogError("003.2", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString() +
", randValue = " + randValue.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.3", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Call Ctor with reference type target reference and set trackResurrection to true");
try
{
string randValue = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH);
WeakReference reference = new WeakReference(randValue, true);
if ((reference.TrackResurrection != true) || (!reference.Target.Equals(randValue)))
{
TestLibrary.TestFramework.LogError("004.1", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString() +
", randValue = " + randValue.ToString());
retVal = false;
}
reference = new WeakReference(randValue, false);
if ((reference.TrackResurrection != false) || (!reference.Target.Equals(randValue)))
{
TestLibrary.TestFramework.LogError("004.2", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString() +
", randValue = " + randValue.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.3", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Call Ctor with null reference and set trackResurrection to true");
try
{
WeakReference reference = new WeakReference(null, true);
if ((reference.TrackResurrection != true) || (reference.Target != null))
{
TestLibrary.TestFramework.LogError("005.1", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString());
retVal = false;
}
reference = new WeakReference(null, false);
if ((reference.TrackResurrection != false) || (reference.Target != null))
{
TestLibrary.TestFramework.LogError("005.2", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005.3", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest6: Call Ctor with IntPtr reference and set trackResurrection to true");
try
{
Object desiredValue = IntPtr.Zero;
WeakReference reference = new WeakReference(desiredValue, true);
if ((reference.TrackResurrection != true) || (!reference.Target.Equals(desiredValue)))
{
TestLibrary.TestFramework.LogError("006.1", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString() +
", desiredValue = " + desiredValue.ToString());
retVal = false;
}
desiredValue = new IntPtr(TestLibrary.Generator.GetInt32(-55));
reference = new WeakReference(desiredValue, false);
if ((reference.TrackResurrection != false) || (!reference.Target.Equals(desiredValue)))
{
TestLibrary.TestFramework.LogError("006.2", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString() +
", desiredValue = " + desiredValue.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006.3", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest7: Call Ctor with IntPtr reference and set trackResurrection to true");
try
{
TestStruct ts = new TestStruct();
ts.IntValue = TestLibrary.Generator.GetInt32(-55);
ts.StringValue = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH);
Object desiredValue = ts;
WeakReference reference = new WeakReference(desiredValue, true);
if ((reference.TrackResurrection != true) || (!reference.Target.Equals(desiredValue)))
{
TestLibrary.TestFramework.LogError("007.1", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString() +
", desiredValue = " + desiredValue.ToString());
retVal = false;
}
reference = new WeakReference(desiredValue, false);
if ((reference.TrackResurrection != false) || (!reference.Target.Equals(desiredValue)))
{
TestLibrary.TestFramework.LogError("007.2", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString() +
", desiredValue = " + desiredValue.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("007.3", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest8()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest8: Call Ctor with IntPtr reference and set trackResurrection to true");
try
{
DisposableClass dc = new DisposableClass();
Object desiredValue = dc;
WeakReference reference = new WeakReference(desiredValue, true);
if ((reference.TrackResurrection != true) || (!reference.Target.Equals(desiredValue)))
{
TestLibrary.TestFramework.LogError("008.1", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString() +
", desiredValue = " + desiredValue.ToString());
retVal = false;
}
reference = new WeakReference(desiredValue, false);
if ((reference.TrackResurrection != false) || (!reference.Target.Equals(desiredValue)))
{
TestLibrary.TestFramework.LogError("008.2", "Calling Ctor with valid target reference and set trackResurrection to false constructs wrong instance");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] reference.TrackResurrection = " + reference.TrackResurrection.ToString() +
", reference.Target = " + reference.Target.ToString() +
", desiredValue = " + desiredValue.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008.3", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
WeakReferenceCtor1 test = new WeakReferenceCtor1();
TestLibrary.TestFramework.BeginTestCase("WeakReferenceCtor1");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
using System;
using Box2D.Collision.Shapes;
using Box2D.Common;
using Box2D.Dynamics;
using Cocos2D;
namespace AngryNinjas
{
public class Enemy : BodyNode
{
b2World theWorld;
string baseImageName;
string spriteImageName;
CCPoint initialLocation;
int breaksAfterHowMuchContact; //0 will break the enemy after first contact
int damageLevel; //tracks how much damage has been done
public bool BreaksOnNextDamage { get; set; }
bool isRotationFixed; //enemy wont rotate if set to YES
float theDensity;
CreationMethod shapeCreationMethod; //same as all stack objects, check shape definitions in Constants.h
public bool DamagesFromGroundContact { get; set; }
public bool DamagesFromDamageEnabledStackObjects { get; set; } //stack objects must be enabled to damageEnemy
bool differentSpritesForDamage; //whether or not you've included different images for damage progression (recommended)
public int PointValue { get; set; }
public BreakEffect SimpleScoreVisualFX { get; set; } //defined in constants, which visual effect occurs when the enemy breaks
int currentFrame;
int framesToAnimateOnBreak; //if 0 won't show any break frames
bool enemyCantBeDamagedForShortInterval; // after damage occurs the enemy gets a moment of un-damage-abilty, which should play better ( I think)
public Enemy (b2World world,
CCPoint location,
string spriteFileName,
bool isTheRotationFixed,
bool getsDamageFromGround,
bool doesGetDamageFromDamageEnabledStackObjects,
int breaksFromHowMuchContact,
bool hasDifferentSpritesForDamage,
int numberOfFramesToAnimateOnBreak,
float density,
CreationMethod createHow,
int points,
BreakEffect simpleScoreVisualFXType )
{
InitWithWorld( world,
location,
spriteFileName,
isTheRotationFixed,
getsDamageFromGround,
doesGetDamageFromDamageEnabledStackObjects,
breaksFromHowMuchContact,
hasDifferentSpritesForDamage,
numberOfFramesToAnimateOnBreak,
density,
createHow,
points,
simpleScoreVisualFXType );
}
void InitWithWorld(b2World world,
CCPoint location,
string spriteFileName,
bool isTheRotationFixed,
bool getsDamageFromGround,
bool doesGetDamageFromDamageEnabledStackObjects,
int breaksFromHowMuchContact,
bool hasDifferentSpritesForDamage,
int numberOfFramesToAnimateOnBreak,
float density,
CreationMethod createHow,
int points,
BreakEffect simpleScoreVisualFXType )
{
this.theWorld = world;
this.initialLocation = location;
this.baseImageName = spriteFileName;
this.spriteImageName = String.Format("{0}.png", baseImageName);
this.DamagesFromGroundContact = getsDamageFromGround; // does the ground break / damage the enemy
this.damageLevel = 0; //starts at 0, if breaksAfterHowMuchContact also equals 0 then the enemy will break on first/next contact
this.breaksAfterHowMuchContact = breaksFromHowMuchContact; //contact must be made this many times before breaking, or if set to 0, the enemy will break on first/next contact
this.differentSpritesForDamage = hasDifferentSpritesForDamage; //will progress through damage frames if this is YES, for example, enemy_damage1.png, enemy_damage2.png
this.currentFrame = 0;
this.framesToAnimateOnBreak = numberOfFramesToAnimateOnBreak; //will animate through breaks frames if this is more than 0, for example, enemy_break0001.png, enemy_break0002.png
this.theDensity = density;
this.shapeCreationMethod = createHow;
this.isRotationFixed = isTheRotationFixed;
this.PointValue = points ;
this.SimpleScoreVisualFX = simpleScoreVisualFXType;
this.DamagesFromDamageEnabledStackObjects = doesGetDamageFromDamageEnabledStackObjects;
if ( damageLevel == breaksAfterHowMuchContact) {
BreaksOnNextDamage = true;
} else {
BreaksOnNextDamage = false; //duh
}
CreateEnemy();
}
void CreateEnemy ()
{
// Define the dynamic body.
var bodyDef = new b2BodyDef();
bodyDef.type = b2BodyType.b2_dynamicBody; //or you could use b2_staticBody
bodyDef.fixedRotation = isRotationFixed;
bodyDef.position.Set(initialLocation.X/Constants.PTM_RATIO, initialLocation.Y/Constants.PTM_RATIO);
b2PolygonShape shape = new b2PolygonShape();
b2CircleShape shapeCircle = new b2CircleShape();
if (shapeCreationMethod == CreationMethod.DiameterOfImageForCircle) {
var tempSprite = new CCSprite(spriteImageName);
float radiusInMeters = (tempSprite.ContentSize.Width / Constants.PTM_RATIO) * 0.5f;
shapeCircle.Radius = radiusInMeters;
}
else if ( shapeCreationMethod == CreationMethod.ShapeOfSourceImage) {
var tempSprite = new CCSprite(spriteImageName);
var num = 4;
b2Vec2[] vertices = {
new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO), //top left corner
new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom left corner
new b2Vec2( (tempSprite.ContentSize.Width / 2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 )/ Constants.PTM_RATIO), //bottom right corner
new b2Vec2( (tempSprite.ContentSize.Width / 2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO) //top right corner
};
shape.Set(vertices, num);
}
else if ( shapeCreationMethod == CreationMethod.ShapeOfSourceImageButSlightlySmaller ) {
var tempSprite = new CCSprite(spriteImageName);
var num = 4;
b2Vec2[] vertices = {
new b2Vec2( (tempSprite.ContentSize.Width / -2 ) *.8f / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 )*.8f / Constants.PTM_RATIO), //top left corner
new b2Vec2( (tempSprite.ContentSize.Width / -2 )*.8f / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 )*.8f / Constants.PTM_RATIO), //bottom left corner
new b2Vec2( (tempSprite.ContentSize.Width / 2 )*.8f / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 )*.8f / Constants.PTM_RATIO), //bottom right corner
new b2Vec2( (tempSprite.ContentSize.Width / 2 )*.8f / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 )*.8f / Constants.PTM_RATIO) //top right corner
};
shape.Set(vertices, num);
}
else if ( shapeCreationMethod == CreationMethod.Triangle) {
var tempSprite = new CCSprite(spriteImageName);
var num = 3;
b2Vec2[] vertices = {
new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom left corner
new b2Vec2( (tempSprite.ContentSize.Width / 2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom right corner
new b2Vec2( 0.0f / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 )/ Constants.PTM_RATIO) // top center of image
};
shape.Set(vertices, num);
}
else if ( shapeCreationMethod == CreationMethod.TriangleRightAngle) {
var tempSprite = new CCSprite(spriteImageName);
var num = 3;
b2Vec2[] vertices = {
new b2Vec2( (tempSprite.ContentSize.Width / 2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO), //top right corner
new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO), //top left corner
new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 )/ Constants.PTM_RATIO) //bottom left corner
};
shape.Set(vertices, num);
}
else if ( shapeCreationMethod == CreationMethod.Trapezoid) {
var tempSprite = new CCSprite(spriteImageName);
var num = 4;
b2Vec2[] vertices = {
new b2Vec2( (tempSprite.ContentSize.Width / 4 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO), //top of image, 3/4's across
new b2Vec2( (tempSprite.ContentSize.Width / -4 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO), //top of image, 1/4's across
new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom left corner
new b2Vec2( (tempSprite.ContentSize.Width / 2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom right corner
};
shape.Set(vertices, num);
}
else if ( shapeCreationMethod == CreationMethod.Hexagon) {
var tempSprite = new CCSprite(spriteImageName);
var num = 6;
b2Vec2[] vertices = {
new b2Vec2( (tempSprite.ContentSize.Width / -4 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO), //top of image, 1/4 across
new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, 0.0f / Constants.PTM_RATIO), // left, center
new b2Vec2( (tempSprite.ContentSize.Width / -4 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom of image, 1/4 across
new b2Vec2( (tempSprite.ContentSize.Width / 4 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom of image, 3/4's across
new b2Vec2( (tempSprite.ContentSize.Width / 2 ) / Constants.PTM_RATIO, 0.0f / Constants.PTM_RATIO), // right, center
new b2Vec2( (tempSprite.ContentSize.Width / 4 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO) //top of image, 3/4's across
};
shape.Set(vertices, num);
}
else if ( shapeCreationMethod == CreationMethod.Pentagon) {
var tempSprite = new CCSprite(spriteImageName);
var num = 5;
b2Vec2[] vertices = {
new b2Vec2( 0 / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO), //top of image, center
new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, 0.0f / Constants.PTM_RATIO), // left, center
new b2Vec2( (tempSprite.ContentSize.Width / -4 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom of image, 1/4 across
new b2Vec2( (tempSprite.ContentSize.Width / 4 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom of image, 3/4's across
new b2Vec2( (tempSprite.ContentSize.Width / 2 ) / Constants.PTM_RATIO, 0.0f / Constants.PTM_RATIO), // right, center
};
shape.Set(vertices, num);
}
else if ( shapeCreationMethod == CreationMethod.Octagon) {
var tempSprite = new CCSprite(spriteImageName);
var num = 8;
b2Vec2[] vertices = {
new b2Vec2( (tempSprite.ContentSize.Width / -6 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO), //use the source image octogonShape.png for reference
new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 6 ) / Constants.PTM_RATIO),
new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -6 ) / Constants.PTM_RATIO),
new b2Vec2( (tempSprite.ContentSize.Width / -6 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO),
new b2Vec2( (tempSprite.ContentSize.Width / 6 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO),
new b2Vec2( (tempSprite.ContentSize.Width / 2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -6 ) / Constants.PTM_RATIO),
new b2Vec2( (tempSprite.ContentSize.Width / 2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 6 ) / Constants.PTM_RATIO),
new b2Vec2( (tempSprite.ContentSize.Width / 6 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO)
};
shape.Set(vertices, num);
}
else if ( shapeCreationMethod == CreationMethod.Parallelogram) {
var tempSprite = new CCSprite(spriteImageName);
var num = 4;
b2Vec2[] vertices = {
new b2Vec2( (tempSprite.ContentSize.Width / -4 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO), //top of image, 1/4 across
new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom left corner
new b2Vec2( (tempSprite.ContentSize.Width / 4 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom of image, 3/4's across
new b2Vec2( (tempSprite.ContentSize.Width / 2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO) //top right corner
};
shape.Set(vertices, num);
}
else if ( shapeCreationMethod == CreationMethod.CustomCoordinates1) { //use your own custom coordinates from a program like Vertex Helper Pro
var num = 4;
b2Vec2[] vertices = {
new b2Vec2(-64.0f / Constants.PTM_RATIO, 16.0f / Constants.PTM_RATIO),
new b2Vec2(-64.0f / Constants.PTM_RATIO, -16.0f / Constants.PTM_RATIO),
new b2Vec2(64.0f / Constants.PTM_RATIO, -16.0f / Constants.PTM_RATIO),
new b2Vec2(64.0f / Constants.PTM_RATIO, 16.0f / Constants.PTM_RATIO)
};
shape.Set(vertices, num);
}
// Define the dynamic body fixture.
var fixtureDef = new b2FixtureDef();
if ( shapeCreationMethod == CreationMethod.DiameterOfImageForCircle) {
fixtureDef.shape = shapeCircle;
} else {
fixtureDef.shape = shape;
}
fixtureDef.density = theDensity;
fixtureDef.friction = 0.3f;
fixtureDef.restitution = 0.1f; //how bouncy basically
CreateBodyWithSpriteAndFixture(theWorld, bodyDef, fixtureDef, spriteImageName);
var blinkInterval = Cocos2D.CCRandom.Next(3,8); // range 3 to 8
Schedule(Blink, blinkInterval); //comment this out if you never want to show the blink
}
public void DamageEnemy() {
Unschedule(Blink);
Unschedule(OpenEyes);
if ( !enemyCantBeDamagedForShortInterval ) {
damageLevel ++;
enemyCantBeDamagedForShortInterval = true;
ScheduleOnce(EnemyCanBeDamagedAgain, 1.0f);
if ( differentSpritesForDamage ) {
//GameSounds.SharedGameSounds.PlayVoiceSoundFX("enemyGrunt.mp3"); //that sound file doesn't exist
sprite.Texture = new CCSprite(String.Format("{0}_damage{1}.png", baseImageName, damageLevel)).Texture;
}
if ( damageLevel == breaksAfterHowMuchContact ) {
BreaksOnNextDamage = true;
}
}
}
void EnemyCanBeDamagedAgain(float delta)
{
enemyCantBeDamagedForShortInterval = false;
}
public void BreakEnemy ()
{
Unschedule(Blink);
Unschedule(OpenEyes);
Schedule(StartBreakAnimation, 1.0f/30.0f);
}
void StartBreakAnimation(float delta)
{
if ( currentFrame == 0) {
RemoveBody();
}
currentFrame ++; //adds 1 every frame
if (currentFrame <= framesToAnimateOnBreak ) { //if we included frames to show for breaking and the current frame is less than the max number of frames to play
if (currentFrame < 10) {
sprite.Texture = new CCSprite(String.Format("{0}_break000{1}.png", baseImageName, currentFrame)).Texture;
} else if (currentFrame < 100) {
sprite.Texture = new CCSprite(String.Format("{0}_break00{1}.png", baseImageName, currentFrame)).Texture;
}
}
if (currentFrame > framesToAnimateOnBreak ) {
//if the currentFrame equals the number of frames to animate, we remove the sprite OR if
// the stackObject didn't include animated images for breaking
RemoveSprite();
Unschedule(StartBreakAnimation);
}
}
void Blink(float delta)
{
sprite.Texture = new CCSprite(String.Format("{0}_blink.png", baseImageName)).Texture;
Unschedule(Blink);
Schedule(OpenEyes, 0.5f);
}
void OpenEyes(float delta)
{
sprite.Texture = new CCSprite(String.Format("{0}.png", baseImageName)).Texture;
Unschedule(OpenEyes);
var blinkInterval = Cocos2D.CCRandom.Next(3,8);// random.Next(3,8); // range 3 to 8
Schedule(Blink,blinkInterval);
}
public void MakeUnScoreable() {
PointValue = 0;
CCLog.Log("points have been accumulated for this object");
}
}
}
| |
// Copyright (c) 2014 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
// Parts based on code by MJ Hutchinson http://mjhutchinson.com/journal/2010/01/25/integrating_gtk_application_mac
using System;
namespace SIL.PlatformUtilities
{
public static class Platform
{
private static readonly string UnixNameMac = "Darwin";
private static readonly string UnixNameLinux = "Linux";
private static bool? _isMono;
private static string _unixName;
private static string _sessionManager;
public static bool IsUnix
{
get { return Environment.OSVersion.Platform == PlatformID.Unix; }
}
public static bool IsLinux
{
get { return IsUnix && (UnixName == UnixNameLinux); }
}
public static bool IsMac
{
get { return IsUnix && (UnixName == UnixNameMac); }
}
public static bool IsWindows
{
get { return !IsUnix; }
}
public static bool IsMono
{
get
{
if (_isMono == null)
_isMono = Type.GetType("Mono.Runtime") != null;
return (bool)_isMono;
}
}
public static bool IsDotNet
{
get { return !IsMono; }
}
private static string UnixName
{
get
{
if (_unixName == null)
{
IntPtr buf = IntPtr.Zero;
try
{
buf = System.Runtime.InteropServices.Marshal.AllocHGlobal (8192);
// This is a hacktastic way of getting sysname from uname ()
if (uname (buf) == 0)
_unixName = System.Runtime.InteropServices.Marshal.PtrToStringAnsi (buf);
}
catch
{
_unixName = String.Empty;
}
finally {
if (buf != IntPtr.Zero)
System.Runtime.InteropServices.Marshal.FreeHGlobal (buf);
}
}
return _unixName;
}
}
public static bool IsWasta
{
get { return IsUnix && System.IO.File.Exists("/etc/wasta-release"); }
}
public static bool IsCinnamon
{
get { return IsUnix && SessionManager.StartsWith("/usr/bin/cinnamon-session"); }
}
/// <summary>
/// On a Unix machine this gets the current desktop environment (gnome/xfce/...), on
/// non-Unix machines the platform name.
/// </summary>
public static string DesktopEnvironment
{
get
{
if (!IsUnix)
return Environment.OSVersion.Platform.ToString();
// see http://unix.stackexchange.com/a/116694
// and http://askubuntu.com/a/227669
string currentDesktop = Environment.GetEnvironmentVariable("XDG_CURRENT_DESKTOP");
if (string.IsNullOrEmpty(currentDesktop))
{
var dataDirs = Environment.GetEnvironmentVariable("XDG_DATA_DIRS");
if (dataDirs != null)
{
dataDirs = dataDirs.ToLowerInvariant();
if (dataDirs.Contains("xfce"))
currentDesktop = "XFCE";
else if (dataDirs.Contains("kde"))
currentDesktop = "KDE";
else if (dataDirs.Contains("gnome"))
currentDesktop = "Gnome";
}
if (string.IsNullOrEmpty(currentDesktop))
currentDesktop = Environment.GetEnvironmentVariable("GDMSESSION") ?? string.Empty;
}
// Special case for Wasta 12
else if (currentDesktop == "GNOME" && Environment.GetEnvironmentVariable("GDMSESSION") == "cinnamon")
currentDesktop = Environment.GetEnvironmentVariable("GDMSESSION");
return currentDesktop == null ? null : currentDesktop.ToLowerInvariant();
}
}
/// <summary>
/// Get the currently running desktop environment (like Unity, Gnome shell etc)
/// </summary>
public static string DesktopEnvironmentInfoString
{
get
{
if (!IsUnix)
return string.Empty;
// see http://unix.stackexchange.com/a/116694
// and http://askubuntu.com/a/227669
string currentDesktop = DesktopEnvironment;
string mirSession = Environment.GetEnvironmentVariable("MIR_SERVER_NAME");
var additionalInfo = string.Empty;
if (!string.IsNullOrEmpty(mirSession))
additionalInfo = " [display server: Mir]";
string gdmSession = Environment.GetEnvironmentVariable("GDMSESSION") ?? "not set";
return string.Format("{0} ({1}{2})", currentDesktop, gdmSession, additionalInfo);
}
}
private static string SessionManager
{
get
{
if (_sessionManager == null)
{
IntPtr buf = IntPtr.Zero;
try
{
// This is the only way I've figured out to get the session manager: read the
// symbolic link destination value.
buf = System.Runtime.InteropServices.Marshal.AllocHGlobal(8192);
var len = readlink("/etc/alternatives/x-session-manager", buf, 8192);
if (len > 0)
{
// For some reason, Marshal.PtrToStringAnsi() sometimes returns null in Mono.
// Copying the bytes and then converting them to a string avoids that problem.
// Filenames are likely to be in UTF-8 on Linux if they are not pure ASCII.
var bytes = new byte[len];
System.Runtime.InteropServices.Marshal.Copy(buf, bytes, 0, len);
_sessionManager = System.Text.Encoding.UTF8.GetString(bytes);
}
if (_sessionManager == null)
_sessionManager = String.Empty;
}
catch
{
_sessionManager = String.Empty;
}
finally
{
if (buf != IntPtr.Zero)
System.Runtime.InteropServices.Marshal.FreeHGlobal(buf);
}
}
return _sessionManager;
}
}
[System.Runtime.InteropServices.DllImport("libc")]
private static extern int uname(IntPtr buf);
[System.Runtime.InteropServices.DllImport("libc")]
private static extern int readlink(string path, IntPtr buf, int bufsiz);
[System.Runtime.InteropServices.DllImport("__Internal", EntryPoint = "mono_get_runtime_build_info")]
private static extern string GetMonoVersion();
/// <summary>
/// Gets the version of the currently running Mono (e.g.
/// "5.0.1.1 (2017-02/5077205 Thu May 25 09:16:53 UTC 2017)"), or the empty string
/// on Windows.
/// </summary>
public static string MonoVersion
{
get { return IsMono ? GetMonoVersion() : string.Empty; }
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.BraceMatching;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.BraceMatching
{
public class CSharpBraceMatcherTests : AbstractBraceMatcherTests
{
protected override TestWorkspace CreateWorkspaceFromCode(string code, ParseOptions options)
=> TestWorkspace.CreateCSharp(code, options);
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestEmptyFile()
{
var code = @"$$";
var expected = @"";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestAtFirstPositionInFile()
{
var code = @"$$public class C { }";
var expected = @"public class C { }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestAtLastPositionInFile()
{
var code = @"public class C { }$$";
var expected = @"public class C [|{|] }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestCurlyBrace1()
{
var code = @"public class C $${ }";
var expected = @"public class C { [|}|]";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestCurlyBrace2()
{
var code = @"public class C {$$ }";
var expected = @"public class C { [|}|]";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestCurlyBrace3()
{
var code = @"public class C { $$}";
var expected = @"public class C [|{|] }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestCurlyBrace4()
{
var code = @"public class C { }$$";
var expected = @"public class C [|{|] }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestParen1()
{
var code = @"public class C { void Foo$$() { } }";
var expected = @"public class C { void Foo([|)|] { } }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestParen2()
{
var code = @"public class C { void Foo($$) { } }";
var expected = @"public class C { void Foo([|)|] { } }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestParen3()
{
var code = @"public class C { void Foo($$ ) { } }";
var expected = @"public class C { void Foo( [|)|] { } }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestParen4()
{
var code = @"public class C { void Foo( $$) { } }";
var expected = @"public class C { void Foo[|(|] ) { } }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestParen5()
{
var code = @"public class C { void Foo( )$$ { } }";
var expected = @"public class C { void Foo[|(|] ) { } }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestParen6()
{
var code = @"public class C { void Foo()$$ { } }";
var expected = @"public class C { void Foo[|(|]) { } }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestSquareBracket1()
{
var code = @"public class C { int$$[] i; }";
var expected = @"public class C { int[[|]|] i; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestSquareBracket2()
{
var code = @"public class C { int[$$] i; }";
var expected = @"public class C { int[[|]|] i; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestSquareBracket3()
{
var code = @"public class C { int[$$ ] i; }";
var expected = @"public class C { int[ [|]|] i; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestSquareBracket4()
{
var code = @"public class C { int[ $$] i; }";
var expected = @"public class C { int[|[|] ] i; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestSquareBracket5()
{
var code = @"public class C { int[ ]$$ i; }";
var expected = @"public class C { int[|[|] ] i; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestSquareBracket6()
{
var code = @"public class C { int[]$$ i; }";
var expected = @"public class C { int[|[|]] i; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestAngleBracket1()
{
var code = @"public class C { Foo$$<int> f; }";
var expected = @"public class C { Foo<int[|>|] f; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestAngleBracket2()
{
var code = @"public class C { Foo<$$int> f; }";
var expected = @"public class C { Foo<int[|>|] f; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestAngleBracket3()
{
var code = @"public class C { Foo<int$$> f; }";
var expected = @"public class C { Foo[|<|]int> f; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestAngleBracket4()
{
var code = @"public class C { Foo<int>$$ f; }";
var expected = @"public class C { Foo[|<|]int> f; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestNestedAngleBracket1()
{
var code = @"public class C { Func$$<Func<int,int>> f; }";
var expected = @"public class C { Func<Func<int,int>[|>|] f; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestNestedAngleBracket2()
{
var code = @"public class C { Func<$$Func<int,int>> f; }";
var expected = @"public class C { Func<Func<int,int>[|>|] f; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestNestedAngleBracket3()
{
var code = @"public class C { Func<Func$$<int,int>> f; }";
var expected = @"public class C { Func<Func<int,int[|>|]> f; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestNestedAngleBracket4()
{
var code = @"public class C { Func<Func<$$int,int>> f; }";
var expected = @"public class C { Func<Func<int,int[|>|]> f; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestNestedAngleBracket5()
{
var code = @"public class C { Func<Func<int,int$$>> f; }";
var expected = @"public class C { Func<Func[|<|]int,int>> f; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestNestedAngleBracket6()
{
var code = @"public class C { Func<Func<int,int>$$> f; }";
var expected = @"public class C { Func<Func[|<|]int,int>> f; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestNestedAngleBracket7()
{
var code = @"public class C { Func<Func<int,int> $$> f; }";
var expected = @"public class C { Func[|<|]Func<int,int> > f; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestNestedAngleBracket8()
{
var code = @"public class C { Func<Func<int,int>>$$ f; }";
var expected = @"public class C { Func[|<|]Func<int,int>> f; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestString1()
{
var code = @"public class C { string s = $$""Foo""; }";
var expected = @"public class C { string s = ""Foo[|""|]; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestString2()
{
var code = @"public class C { string s = ""$$Foo""; }";
var expected = @"public class C { string s = ""Foo[|""|]; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestString3()
{
var code = @"public class C { string s = ""Foo$$""; }";
var expected = @"public class C { string s = [|""|]Foo""; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestString4()
{
var code = @"public class C { string s = ""Foo""$$; }";
var expected = @"public class C { string s = [|""|]Foo""; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestString5()
{
var code = @"public class C { string s = ""Foo$$ ";
var expected = @"public class C { string s = ""Foo ";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestVerbatimString1()
{
var code = @"public class C { string s = $$@""Foo""; }";
var expected = @"public class C { string s = @""Foo[|""|]; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestVerbatimString2()
{
var code = @"public class C { string s = @$$""Foo""; }";
var expected = @"public class C { string s = @""Foo[|""|]; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestVerbatimString3()
{
var code = @"public class C { string s = @""$$Foo""; }";
var expected = @"public class C { string s = @""Foo[|""|]; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestVerbatimString4()
{
var code = @"public class C { string s = @""Foo$$""; }";
var expected = @"public class C { string s = [|@""|]Foo""; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestVerbatimString5()
{
var code = @"public class C { string s = @""Foo""$$; }";
var expected = @"public class C { string s = [|@""|]Foo""; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestInterpolatedString1()
{
var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""$${x}, {y}""; }";
var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x[|}|], {y}""; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestInterpolatedString2()
{
var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{$$x}, {y}""; }";
var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x[|}|], {y}""; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestInterpolatedString3()
{
var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x$$}, {y}""; }";
var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""[|{|]x}, {y}""; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestInterpolatedString4()
{
var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}$$, {y}""; }";
var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""[|{|]x}, {y}""; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestInterpolatedString5()
{
var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, $${y}""; }";
var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y[|}|]""; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestInterpolatedString6()
{
var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {$$y}""; }";
var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y[|}|]""; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestInterpolatedString7()
{
var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y$$}""; }";
var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, [|{|]y}""; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestInterpolatedString8()
{
var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y}$$""; }";
var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, [|{|]y}""; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestInterpolatedString9()
{
var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $$[||]$""{x}, {y}""; }";
var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y}[|""|]; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestInterpolatedString10()
{
var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $[||]$$""{x}, {y}""; }";
var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y}[|""|]; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestInterpolatedString11()
{
var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $$[||]$@""{x}, {y}""; }";
var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@""{x}, {y}[|""|]; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestInterpolatedString12()
{
var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $[||]$$@""{x}, {y}""; }";
var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@""{x}, {y}[|""|]; }";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestInterpolatedString13()
{
var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@$$""{x}, {y}""; }";
var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@""{x}, {y}[|""|]; }";
await TestAsync(code, expected);
}
[WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")]
[WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestConditionalDirectiveWithSingleMatchingDirective()
{
var code = @"
public class C
{
#if$$ CHK
#endif
}";
var expected = @"
public class C
{
#if$$ CHK
[|#endif|]
}";
await TestAsync(code, expected);
}
[WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")]
[WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestConditionalDirectiveWithTwoMatchingDirectives()
{
var code = @"
public class C
{
#if$$ CHK
#else
#endif
}";
var expected = @"
public class C
{
#if$$ CHK
[|#else|]
#endif
}";
await TestAsync(code, expected);
}
[WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")]
[WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestConditionalDirectiveWithAllMatchingDirectives()
{
var code = @"
public class C
{
#if CHK
#elif RET
#else
#endif$$
}";
var expected = @"
public class C
{
[|#if|] CHK
#elif RET
#else
#endif
}";
await TestAsync(code, expected);
}
[WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")]
[WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestRegionDirective()
{
var code = @"
public class C
{
$$#region test
#endregion
}";
var expected = @"
public class C
{
#region test
[|#endregion|]
}";
await TestAsync(code, expected);
}
[WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")]
[WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestInterleavedDirectivesInner()
{
var code = @"
#define CHK
public class C
{
void Test()
{
#if CHK
$$#region test
var x = 5;
#endregion
#else
var y = 6;
#endif
}
}";
var expected = @"
#define CHK
public class C
{
void Test()
{
#if CHK
#region test
var x = 5;
[|#endregion|]
#else
var y = 6;
#endif
}
}";
await TestAsync(code, expected);
}
[WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")]
[WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestInterleavedDirectivesOuter()
{
var code = @"
#define CHK
public class C
{
void Test()
{
#if$$ CHK
#region test
var x = 5;
#endregion
#else
var y = 6;
#endif
}
}";
var expected = @"
#define CHK
public class C
{
void Test()
{
#if CHK
#region test
var x = 5;
#endregion
[|#else|]
var y = 6;
#endif
}
}";
await TestAsync(code, expected);
}
[WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")]
[WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestUnmatchedDirective1()
{
var code = @"
public class C
{
$$#region test
}";
var expected = @"
public class C
{
#region test
}";
await TestAsync(code, expected);
}
[WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")]
[WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestUnmatchedDirective2()
{
var code = @"
#d$$efine CHK
public class C
{
}";
var expected = @"
#define CHK
public class C
{
}";
await TestAsync(code, expected);
}
[WorkItem(7534, "https://github.com/dotnet/roslyn/issues/7534")]
[WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestUnmatchedConditionalDirective()
{
var code = @"
class Program
{
static void Main(string[] args)
{#if$$
}
}";
var expected = @"
class Program
{
static void Main(string[] args)
{#if
}
}";
await TestAsync(code, expected);
}
[WorkItem(7534, "https://github.com/dotnet/roslyn/issues/7534")]
[WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task TestUnmatchedConditionalDirective2()
{
var code = @"
class Program
{
static void Main(string[] args)
{#else$$
}
}";
var expected = @"
class Program
{
static void Main(string[] args)
{#else
}
}";
await TestAsync(code, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task StartTupleDeclaration()
{
var code = @"public class C { $$(int, int, int, int, int, int, int, int) x; }";
var expected = @"public class C { (int, int, int, int, int, int, int, int[|)|] x; }";
await TestAsync(code, expected, TestOptions.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task EndTupleDeclaration()
{
var code = @"public class C { (int, int, int, int, int, int, int, int)$$ x; }";
var expected = @"public class C { [|(|]int, int, int, int, int, int, int, int) x; }";
await TestAsync(code, expected, TestOptions.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task StartTupleLiteral()
{
var code = @"public class C { var x = $$(1, 2, 3, 4, 5, 6, 7, 8); }";
var expected = @"public class C { var x = (1, 2, 3, 4, 5, 6, 7, 8[|)|]; }";
await TestAsync(code, expected, TestOptions.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task EndTupleLiteral()
{
var code = @"public class C { var x = (1, 2, 3, 4, 5, 6, 7, 8)$$; }";
var expected = @"public class C { var x = [|(|]1, 2, 3, 4, 5, 6, 7, 8); }";
await TestAsync(code, expected, TestOptions.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task StartNestedTupleLiteral()
{
var code = @"public class C { var x = $$((1, 1, 1), 2, 3, 4, 5, 6, 7, 8); }";
var expected = @"public class C { var x = ((1, 1, 1), 2, 3, 4, 5, 6, 7, 8[|)|]; }";
await TestAsync(code, expected, TestOptions.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task StartInnerNestedTupleLiteral()
{
var code = @"public class C { var x = ($$(1, 1, 1), 2, 3, 4, 5, 6, 7, 8); }";
var expected = @"public class C { var x = ((1, 1, 1[|)|], 2, 3, 4, 5, 6, 7, 8); }";
await TestAsync(code, expected, TestOptions.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task EndNestedTupleLiteral()
{
var code = @"public class C { var x = (1, 2, 3, 4, 5, 6, 7, (8, 8, 8))$$; }";
var expected = @"public class C { var x = [|(|]1, 2, 3, 4, 5, 6, 7, (8, 8, 8)); }";
await TestAsync(code, expected, TestOptions.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)]
public async Task EndInnerNestedTupleLiteral()
{
var code = @"public class C { var x = ((1, 1, 1)$$, 2, 3, 4, 5, 6, 7, 8); }";
var expected = @"public class C { var x = ([|(|]1, 1, 1), 2, 3, 4, 5, 6, 7, 8); }";
await TestAsync(code, expected, TestOptions.Regular);
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Timers;
using System.Windows.Forms;
using OpenLiveWriter.Interop.Windows;
using Timer = System.Timers.Timer;
namespace OpenLiveWriter.CoreServices
{
/// <summary>
/// Used to create temporary files and directories.
/// </summary>
/// <remarks>
/// This class is used to create temporary files and directories in a way
/// that makes them relatively cheap to delete with age.
/// </remarks>
public class TempFileManager
{
/// <summary>
/// If no pattern is given at all for the creation of a file,
/// this pattern will be used.
/// </summary>
private const string TEMP_FILE_DEFAULT_PATTERN = "p31{0}.tmp";
/// <summary>
/// If no pattern is given at all for the creation of a directory,
/// this pattern will be used.
/// </summary>
private const string TEMP_DIR_DEFAULT_PATTERN = "p31{0}";
#region singleton
private static TempFileManager singleton;
static TempFileManager()
{
string prefix = ProcessHelper.GetCurrentProcessName();
int lastDot = prefix.LastIndexOf('.');
if (lastDot > -1)
{
prefix = prefix.Substring(0, lastDot);
}
string currentDir = Environment.CurrentDirectory;
string suffix;
if (currentDir == null)
suffix = "";
else
suffix = currentDir.GetHashCode().ToString(CultureInfo.InvariantCulture);
singleton = new TempFileManager(Path.Combine(Path.GetTempPath(), prefix + suffix), true);
}
public static TempFileManager Instance
{
get
{
return singleton;
}
}
#endregion
/// <summary>
/// Returns true if the given path lies in the scope of the temp file manager.
/// </summary>
public bool IsPathContained(string path)
{
if (path == null)
return false;
else
{
string pattern = "^" + Regex.Escape(tempRoot.FullName) + Regex.Escape(@"\");
return Regex.IsMatch(path, pattern, RegexOptions.IgnoreCase);
}
}
/// <summary>
/// The root directory where temp dirs/files will be created.
/// </summary>
private readonly DirectoryInfo tempRoot;
private readonly bool deleteOnExit;
/// <summary>
/// Singleton. Use Instance property.
/// </summary>
private TempFileManager(string rootPath, bool deleteOnExit)
{
this.deleteOnExit = deleteOnExit;
tempRoot = new DirectoryInfo(rootPath);
tempRoot.Create(); // does nothing if dir already exists
}
/// <summary>
/// Call when done using this instance of TempFileManager to delete
/// all temp files (if deleteOnExit == true).
/// </summary>
public void Dispose()
{
if (deleteOnExit)
{
try
{
if (tempRoot.Exists)
DeleteAll(tempRoot);
}
catch
{
}
}
}
/// <summary>
/// Returns the root temp dir
/// </summary>
protected DirectoryInfo TempDir
{
get
{
DirectoryInfo pathInfo = new DirectoryInfo(tempRoot.FullName);
pathInfo.Create();
return pathInfo;
}
}
private void DeleteAll(DirectoryInfo dir)
{
try
{
dir.Delete(true);
}
catch
{
foreach (FileInfo file in dir.GetFiles())
{
try
{
file.Attributes = FileAttributes.Normal;
file.Delete();
}
catch (Exception e)
{
Trace.WriteLine("Unable to delete file " + file.FullName + ": " + e.GetType().FullName + ": " + e.Message);
}
}
foreach (DirectoryInfo subdir in dir.GetDirectories())
{
DeleteAll(subdir);
}
}
}
public string CreateTempFile()
{
return CreateTempFile(TEMP_FILE_DEFAULT_PATTERN);
}
public string CreateTempFile(string pattern)
{
// for now, always return exactly the right name by creating a temp dir
//return CreateNewFile(this.TempDir.FullName, pattern, false);
return CreateNewFile(CreateTempDir(), pattern, false);
}
public string CreateTempDir()
{
return CreateTempDir(Guid.NewGuid().ToString().Split('-')[4].ToUpper(CultureInfo.InvariantCulture));
}
public string CreateTempDir(string pattern)
{
return CreateNewFile(this.TempDir.FullName, pattern, true);
}
public string Duplicate(string filePath)
{
string newPath = CreateTempFile(Path.GetFileName(filePath));
File.Copy(filePath, newPath, true);
// make the copy writable
File.SetAttributes(newPath, File.GetAttributes(newPath) & ~FileAttributes.ReadOnly);
try
{
File.SetCreationTime(newPath, File.GetCreationTime(filePath));
File.SetLastWriteTime(newPath, File.GetLastWriteTime(filePath));
}
catch (Exception e)
{
// not the end of the world
Debug.WriteLine("Unable to set file creation/modification time: " + e.ToString());
}
return newPath;
}
/// <summary>
/// Creates a new file based on a pattern, dealing with
/// name collisions by using an incrementing number as
/// part of the file name. The pattern should be the
/// filename you are trying to match.
///
/// For example, the pattern "my file.txt" might result in
/// "my file.txt", "my file[1].txt", or "my file[23].txt".
/// </summary>
public static string CreateNewFile(string dir, string pattern, bool asDir)
{
// Make sure the pattern isn't too far out of whack
if (pattern == null)
throw new ArgumentNullException("pattern");
if (pattern.Trim().Length == 0)
throw new ArgumentException("Temp file pattern cannot be a zero-length string", "pattern");
if (pattern.IndexOf(Path.DirectorySeparatorChar) != -1 || pattern.IndexOfAny(Path.GetInvalidPathChars()) != -1)
throw new ArgumentException("Temp file pattern contains invalid path characters", "pattern");
// If the pattern is just a normal filename, add {0} right before the extension
pattern = pattern.Replace("{", "{{").Replace("}", "}}");
DirectoryInfo tempDir = new DirectoryInfo(dir);
string tempPath = tempDir.FullName;
string fileName = Path.GetFileNameWithoutExtension(pattern);
string fileExt = Path.GetExtension(pattern);
// Fix 597390: Watson: System.IO.PathTooLongException: The specified path, file name, or both are too long
if ((tempPath.Length + fileName.Length + fileExt.Length + 20 > Kernel32.MAX_PATH) && fileName.Length > 30)
{
fileName = StringHelper.RestrictLength(fileName, 30);
}
pattern = fileName + "{0}" + fileExt;
int suffixCounter = 0;
bool createdDir = false;
// keep trying until it succeeds or an unhandled exception is thrown
while (true)
{
// If this is our first pass through, use ""; otherwise use "[i]"
string suffix = suffixCounter == 0 ? "" : "[" + suffixCounter.ToString(CultureInfo.CurrentCulture) + "]";
suffixCounter++;
string fullFileName = Path.Combine(tempPath, string.Format(CultureInfo.InvariantCulture, pattern, suffix));
if (File.Exists(fullFileName) || Directory.Exists(fullFileName))
{
continue;
}
if (!asDir)
{
try
{
// This version of .Open will create the new file if and only if it doesn't
// exist already. If it does exist, an IOException will be thrown. I'm guessing
// that doing it this way will be atomic, which removes the need for me to do
// my own synchronization across processes.
using (FileStream fs = File.Open(fullFileName, FileMode.CreateNew, FileAccess.Write))
{
}
}
catch (DirectoryNotFoundException)
{
if (!createdDir && !Directory.Exists(tempPath))
{
createdDir = true;
Directory.CreateDirectory(tempPath);
suffixCounter--;
continue;
}
else
{
throw;
}
}
catch (IOException)
{
if (!File.Exists(fullFileName) && !Directory.Exists(fullFileName))
{
// Exception must have occurred for some reason other than
// the file already existing... so rethrow
throw;
}
else
{
// In the event of the file already existing, we want to keep
// trying until we find a number that has not been used
continue;
}
}
}
// BUG IN C# COMPILER: http://www.jelovic.com/weblog/e49.htm
// Using separate "if" (instead of "else") to avoid bug.
if (asDir)
{
// CreateDirectory succeeds even if a file OR directory already exists with the
// name we want to use. We can't do anything about the case where the directory
// has been created since the check in the if() above, but we can at least check
// that a *file* creation snuck in (since di.Exists will return false).
DirectoryInfo di = Directory.CreateDirectory(fullFileName);
if (!di.Exists)
continue;
}
return fullFileName;
}
}
}
}
| |
namespace MonoRpg.Engine.UI {
using global::System;
using global::System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using MonoRpg.Engine.GameStates;
using MonoRpg.Engine.RenderEngine;
public class Textbox : BaseStateObject {
public Vector4 Bounds { get; set; }
public Rectangle Size { get; set; }
public float TextScale { get; set; }
public Panel Panel { get; private set; }
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public Tween AppearTween { get; set; }
public bool IsDead => AppearTween.Finished && AppearTween.Value == 0;
public int Wrap { get; set; }
public List<TextboxChild> Children { get; set; }
public List<string> Chunks { get; set; }
public int ChunkIndex { get; set; }
public Sprite ContinueMark { get; set; }
public float Time { get; set; }
public Selection<string> SelectionMenu { get; set; }
public bool DoClickCallback { get; set; }
public Action OnFinish { get; set; }
public Textbox(TextboxParams args): base(args.Stack) {
args = args ?? new TextboxParams();
Chunks = args.Text;
ChunkIndex = 0;
ContinueMark = new Sprite {
Texture = System.Content.FindTexture("continue_caret.png")
};
Time = 0f;
TextScale = args.TextScale;
Panel = new Panel(args.PanelArgs) { PixelArt = true };
Size = args.Size;
Bounds = args.TextBounds;
X = (Size.Right + Size.Left) / 2;
Y = (Size.Top + Size.Bottom) / 2;
Width = Math.Abs(Size.Right - Size.Left);
Height = Math.Abs(Size.Top - Size.Bottom);
AppearTween = new Tween(0, 1, 0.4f, Tween.EaseOutCirc);
Wrap = args.Wrap;
Children = args.Children;
SelectionMenu = args.SelectionMenu;
DoClickCallback = false;
OnFinish = args.OnFinish;
}
public override bool Update(float dt) {
Time += dt;
AppearTween.Update(dt);
if (IsDead) {
Stack?.Pop();
}
return true;
}
public void OnClick() {
if (SelectionMenu != null) {
DoClickCallback = true;
}
if (ChunkIndex >= Chunks.Count - 1) {
if (!(AppearTween.Finished && AppearTween.Value == 1)) {
return;
}
AppearTween = new Tween(1, 0, 0.2f, Tween.EaseInCirc);
} else {
ChunkIndex++;
}
}
public override void HandleInput(float dt) {
if (System.Keys.WasPressed(Keys.Space)) {
OnClick();
} else {
SelectionMenu?.HandleInput();
}
}
public override void Exit() {
if (DoClickCallback) {
SelectionMenu.OnClick();
}
if (OnFinish != null) {
OnFinish();
}
}
public override void Render(Renderer renderer) {
var scale = AppearTween.Value;
renderer.AlignText(TextAlignment.Left, TextAlignment.Top);
Panel.CenterPosition(X, Y, (int)(Width * scale), (int)(Height * scale));
Panel.Render(renderer);
var left = X - (Width / 2f * scale);
var textLeft = left + (Bounds.X * scale);
var top = Y + Height / 2f * scale;
var textTop = top + Bounds.Z * scale;
var bottom = Y - Height / 2f * scale;
var bounds = new TextboxBounds {
Left = left,
Top = top,
TextLeft = textLeft,
TextTop = textTop,
Scale = scale
};
renderer.DrawText2D((int)textLeft, (int)textTop, Chunks[ChunkIndex], Color.White, TextScale * scale, (int)(Wrap * scale));
if (SelectionMenu != null) {
renderer.AlignText(TextAlignment.Left, TextAlignment.Center);
var menuX = (int)textLeft;
var menuY = (int)(bottom + SelectionMenu.GetHeight());
menuY += (int)Bounds.W;
SelectionMenu.Position = new Vector2(menuX, menuY);
SelectionMenu.Scale = scale;
SelectionMenu.TextScale = TextScale;
SelectionMenu.Render(renderer);
}
if (ChunkIndex < Chunks.Count - 1) {
var offset = 12 + (float)Math.Floor(Math.Sin(Time * 10)) * scale;
ContinueMark.Scale = new Vector2(scale, scale);
ContinueMark.Position = new Vector2(X, bottom + offset);
renderer.DrawSprite(ContinueMark);
}
foreach (var child in Children) {
child.Render(renderer, bounds, this);
}
}
}
public class TextboxBounds {
public float Left { get; set; }
public float Top { get; set; }
public float TextLeft { get; set; }
public float TextTop { get; set; }
public float Scale { get; set; }
}
public class TextboxParams {
public List<string> Text { get; set; }
public float TextScale { get; set; }
public PanelParams PanelArgs { get; set; }
public Rectangle Size { get; set; }
public Vector4 TextBounds { get; set; }
public int Wrap { get; set; }
public List<TextboxChild> Children { get; set; }
public Selection<string> SelectionMenu { get; set; }
public StateStack Stack { get; set; }
public Action OnFinish { get; set; }
public TextboxParams() {
Wrap = -1;
Children = new List<TextboxChild>();
}
}
public abstract class TextboxChild {
public int X { get; set; }
public int Y { get; set; }
public abstract void Render(Renderer renderer, TextboxBounds bounds, Textbox textbox);
}
public class TextChild : TextboxChild {
public string Text { get; set; }
public override void Render(Renderer renderer, TextboxBounds bounds, Textbox textbox) {
renderer.DrawText2D(
(int)(bounds.TextLeft + X * bounds.Scale),
(int)(bounds.TextTop + Y * bounds.Scale),
Text, Color.White, bounds.Scale * textbox.TextScale
);
}
}
public class SpriteChild : TextboxChild {
public Sprite Sprite { get; set; }
public override void Render(Renderer renderer, TextboxBounds bounds, Textbox textbox) {
Sprite.Position = new Vector2(bounds.Left + X, bounds.Top + Y);
Sprite.Scale = new Vector2(bounds.Scale, bounds.Scale);
renderer.DrawSprite(Sprite);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System
{
/// <summary>Methods for parsing numbers and strings.</summary>
internal static class ParseNumbers
{
internal const int LeftAlign = 0x0001;
internal const int RightAlign = 0x0004;
internal const int PrefixSpace = 0x0008;
internal const int PrintSign = 0x0010;
internal const int PrintBase = 0x0020;
internal const int PrintAsI1 = 0x0040;
internal const int PrintAsI2 = 0x0080;
internal const int PrintAsI4 = 0x0100;
internal const int TreatAsUnsigned = 0x0200;
internal const int TreatAsI1 = 0x0400;
internal const int TreatAsI2 = 0x0800;
internal const int IsTight = 0x1000;
internal const int NoSpace = 0x2000;
internal const int PrintRadixBase = 0x4000;
private const int MinRadix = 2;
private const int MaxRadix = 36;
public static unsafe long StringToLong(ReadOnlySpan<char> s, int radix, int flags)
{
int pos = 0;
return StringToLong(s, radix, flags, ref pos);
}
public static long StringToLong(ReadOnlySpan<char> s, int radix, int flags, ref int currPos)
{
int i = currPos;
// Do some radix checking.
// A radix of -1 says to use whatever base is spec'd on the number.
// Parse in Base10 until we figure out what the base actually is.
int r = (-1 == radix) ? 10 : radix;
if (r != 2 && r != 10 && r != 8 && r != 16)
throw new ArgumentException(SR.Arg_InvalidBase, nameof(radix));
int length = s.Length;
if (i < 0 || i >= length)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Index);
// Get rid of the whitespace and then check that we've still got some digits to parse.
if (((flags & IsTight) == 0) && ((flags & NoSpace) == 0))
{
EatWhiteSpace(s, ref i);
if (i == length)
throw new FormatException(SR.Format_EmptyInputString);
}
// Check for a sign
int sign = 1;
if (s[i] == '-')
{
if (r != 10)
throw new ArgumentException(SR.Arg_CannotHaveNegativeValue);
if ((flags & TreatAsUnsigned) != 0)
throw new OverflowException(SR.Overflow_NegativeUnsigned);
sign = -1;
i++;
}
else if (s[i] == '+')
{
i++;
}
if ((radix == -1 || radix == 16) && (i + 1 < length) && s[i] == '0')
{
if (s[i + 1] == 'x' || s[i + 1] == 'X')
{
r = 16;
i += 2;
}
}
int grabNumbersStart = i;
long result = GrabLongs(r, s, ref i, (flags & TreatAsUnsigned) != 0);
// Check if they passed us a string with no parsable digits.
if (i == grabNumbersStart)
throw new FormatException(SR.Format_NoParsibleDigits);
if ((flags & IsTight) != 0)
{
//If we've got effluvia left at the end of the string, complain.
if (i < length)
throw new FormatException(SR.Format_ExtraJunkAtEnd);
}
// Put the current index back into the correct place.
currPos = i;
// Return the value properly signed.
if ((ulong)result == 0x8000000000000000 && sign == 1 && r == 10 && ((flags & TreatAsUnsigned) == 0))
throw new OverflowException(SR.Overflow_Int64);
if (r == 10)
{
result *= sign;
}
return result;
}
public static int StringToInt(ReadOnlySpan<char> s, int radix, int flags)
{
int pos = 0;
return StringToInt(s, radix, flags, ref pos);
}
public static int StringToInt(ReadOnlySpan<char> s, int radix, int flags, ref int currPos)
{
// They're requied to tell me where to start parsing.
int i = currPos;
// Do some radix checking.
// A radix of -1 says to use whatever base is spec'd on the number.
// Parse in Base10 until we figure out what the base actually is.
int r = (-1 == radix) ? 10 : radix;
if (r != 2 && r != 10 && r != 8 && r != 16)
throw new ArgumentException(SR.Arg_InvalidBase, nameof(radix));
int length = s.Length;
if (i < 0 || i >= length)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Index);
// Get rid of the whitespace and then check that we've still got some digits to parse.
if (((flags & IsTight) == 0) && ((flags & NoSpace) == 0))
{
EatWhiteSpace(s, ref i);
if (i == length)
throw new FormatException(SR.Format_EmptyInputString);
}
// Check for a sign
int sign = 1;
if (s[i] == '-')
{
if (r != 10)
throw new ArgumentException(SR.Arg_CannotHaveNegativeValue);
if ((flags & TreatAsUnsigned) != 0)
throw new OverflowException(SR.Overflow_NegativeUnsigned);
sign = -1;
i++;
}
else if (s[i] == '+')
{
i++;
}
// Consume the 0x if we're in an unknown base or in base-16.
if ((radix == -1 || radix == 16) && (i + 1 < length) && s[i] == '0')
{
if (s[i + 1] == 'x' || s[i + 1] == 'X')
{
r = 16;
i += 2;
}
}
int grabNumbersStart = i;
int result = GrabInts(r, s, ref i, ((flags & TreatAsUnsigned) != 0));
// Check if they passed us a string with no parsable digits.
if (i == grabNumbersStart)
throw new FormatException(SR.Format_NoParsibleDigits);
if ((flags & IsTight) != 0)
{
// If we've got effluvia left at the end of the string, complain.
if (i < length)
throw new FormatException(SR.Format_ExtraJunkAtEnd);
}
// Put the current index back into the correct place.
currPos = i;
// Return the value properly signed.
if ((flags & TreatAsI1) != 0)
{
if ((uint)result > 0xFF)
throw new OverflowException(SR.Overflow_SByte);
}
else if ((flags & TreatAsI2) != 0)
{
if ((uint)result > 0xFFFF)
throw new OverflowException(SR.Overflow_Int16);
}
else if ((uint)result == 0x80000000 && sign == 1 && r == 10 && ((flags & TreatAsUnsigned) == 0))
{
throw new OverflowException(SR.Overflow_Int32);
}
if (r == 10)
{
result *= sign;
}
return result;
}
public static string IntToString(int n, int radix, int width, char paddingChar, int flags)
{
Span<char> buffer = stackalloc char[66]; // Longest possible string length for an integer in binary notation with prefix
if (radix < MinRadix || radix > MaxRadix)
throw new ArgumentException(SR.Arg_InvalidBase, nameof(radix));
// If the number is negative, make it positive and remember the sign.
// If the number is MIN_VALUE, this will still be negative, so we'll have to
// special case this later.
bool isNegative = false;
uint l;
if (n < 0)
{
isNegative = true;
// For base 10, write out -num, but other bases write out the
// 2's complement bit pattern
l = (10 == radix) ? (uint)-n : (uint)n;
}
else
{
l = (uint)n;
}
// The conversion to a uint will sign extend the number. In order to ensure
// that we only get as many bits as we expect, we chop the number.
if ((flags & PrintAsI1) != 0)
{
l &= 0xFF;
}
else if ((flags & PrintAsI2) != 0)
{
l &= 0xFFFF;
}
// Special case the 0.
int index;
if (0 == l)
{
buffer[0] = '0';
index = 1;
}
else
{
index = 0;
for (int i = 0; i < buffer.Length; i++) // for(...;i<buffer.Length;...) loop instead of do{...}while(l!=0) to help JIT eliminate span bounds checks
{
uint div = l / (uint)radix; // TODO https://github.com/dotnet/coreclr/issues/3439
uint charVal = l - (div * (uint)radix);
l = div;
buffer[i] = (charVal < 10) ?
(char)(charVal + '0') :
(char)(charVal + 'a' - 10);
if (l == 0)
{
index = i + 1;
break;
}
}
Debug.Assert(l == 0, $"Expected {l} == 0");
}
// If they want the base, append that to the string (in reverse order)
if (radix != 10 && ((flags & PrintBase) != 0))
{
if (16 == radix)
{
buffer[index++] = 'x';
buffer[index++] = '0';
}
else if (8 == radix)
{
buffer[index++] = '0';
}
}
if (10 == radix)
{
// If it was negative, append the sign, else if they requested, add the '+'.
// If they requested a leading space, put it on.
if (isNegative)
{
buffer[index++] = '-';
}
else if ((flags & PrintSign) != 0)
{
buffer[index++] = '+';
}
else if ((flags & PrefixSpace) != 0)
{
buffer[index++] = ' ';
}
}
// Figure out the size of and allocate the resulting string
string result = string.FastAllocateString(Math.Max(width, index));
unsafe
{
// Put the characters into the string in reverse order.
// Fill the remaining space, if there is any, with the correct padding character.
fixed (char* resultPtr = result)
{
char* p = resultPtr;
int padding = result.Length - index;
if ((flags & LeftAlign) != 0)
{
for (int i = 0; i < padding; i++)
{
*p++ = paddingChar;
}
for (int i = 0; i < index; i++)
{
*p++ = buffer[index - i - 1];
}
}
else
{
for (int i = 0; i < index; i++)
{
*p++ = buffer[index - i - 1];
}
for (int i = 0; i < padding; i++)
{
*p++ = paddingChar;
}
}
Debug.Assert((p - resultPtr) == result.Length, $"Expected {p - resultPtr} == {result.Length}");
}
}
return result;
}
public static string LongToString(long n, int radix, int width, char paddingChar, int flags)
{
Span<char> buffer = stackalloc char[67]; // Longest possible string length for an integer in binary notation with prefix
if (radix < MinRadix || radix > MaxRadix)
throw new ArgumentException(SR.Arg_InvalidBase, nameof(radix));
//If the number is negative, make it positive and remember the sign.
ulong ul;
bool isNegative = false;
if (n < 0)
{
isNegative = true;
// For base 10, write out -num, but other bases write out the
// 2's complement bit pattern
ul = (10 == radix) ? (ulong)(-n) : (ulong)n;
}
else
{
ul = (ulong)n;
}
if ((flags & PrintAsI1) != 0)
{
ul = ul & 0xFF;
}
else if ((flags & PrintAsI2) != 0)
{
ul = ul & 0xFFFF;
}
else if ((flags & PrintAsI4) != 0)
{
ul = ul & 0xFFFFFFFF;
}
//Special case the 0.
int index;
if (0 == ul)
{
buffer[0] = '0';
index = 1;
}
else
{
index = 0;
for (int i = 0; i < buffer.Length; i++) // for loop instead of do{...}while(l!=0) to help JIT eliminate span bounds checks
{
ulong div = ul / (ulong)radix; // TODO https://github.com/dotnet/coreclr/issues/3439
int charVal = (int)(ul - (div * (ulong)radix));
ul = div;
buffer[i] = (charVal < 10) ?
(char)(charVal + '0') :
(char)(charVal + 'a' - 10);
if (ul == 0)
{
index = i + 1;
break;
}
}
Debug.Assert(ul == 0, $"Expected {ul} == 0");
}
//If they want the base, append that to the string (in reverse order)
if (radix != 10 && ((flags & PrintBase) != 0))
{
if (16 == radix)
{
buffer[index++] = 'x';
buffer[index++] = '0';
}
else if (8 == radix)
{
buffer[index++] = '0';
}
else if ((flags & PrintRadixBase) != 0)
{
buffer[index++] = '#';
buffer[index++] = (char)((radix % 10) + '0');
buffer[index++] = (char)((radix / 10) + '0');
}
}
if (10 == radix)
{
//If it was negative, append the sign.
if (isNegative)
{
buffer[index++] = '-';
}
//else if they requested, add the '+';
else if ((flags & PrintSign) != 0)
{
buffer[index++] = '+';
}
//If they requested a leading space, put it on.
else if ((flags & PrefixSpace) != 0)
{
buffer[index++] = ' ';
}
}
// Figure out the size of and allocate the resulting string
string result = string.FastAllocateString(Math.Max(width, index));
unsafe
{
// Put the characters into the string in reverse order.
// Fill the remaining space, if there is any, with the correct padding character.
fixed (char* resultPtr = result)
{
char* p = resultPtr;
int padding = result.Length - index;
if ((flags & LeftAlign) != 0)
{
for (int i = 0; i < padding; i++)
{
*p++ = paddingChar;
}
for (int i = 0; i < index; i++)
{
*p++ = buffer[index - i - 1];
}
}
else
{
for (int i = 0; i < index; i++)
{
*p++ = buffer[index - i - 1];
}
for (int i = 0; i < padding; i++)
{
*p++ = paddingChar;
}
}
Debug.Assert((p - resultPtr) == result.Length, $"Expected {p - resultPtr} == {result.Length}");
}
}
return result;
}
private static void EatWhiteSpace(ReadOnlySpan<char> s, ref int i)
{
int localIndex = i;
for (; localIndex < s.Length && char.IsWhiteSpace(s[localIndex]); localIndex++);
i = localIndex;
}
private static long GrabLongs(int radix, ReadOnlySpan<char> s, ref int i, bool isUnsigned)
{
ulong result = 0;
ulong maxVal;
// Allow all non-decimal numbers to set the sign bit.
if (radix == 10 && !isUnsigned)
{
maxVal = 0x7FFFFFFFFFFFFFFF / 10;
// Read all of the digits and convert to a number
while (i < s.Length && IsDigit(s[i], radix, out int value))
{
// Check for overflows - this is sufficient & correct.
if (result > maxVal || ((long)result) < 0)
{
ThrowOverflowInt64Exception();
}
result = result * (ulong)radix + (ulong)value;
i++;
}
if ((long)result < 0 && result != 0x8000000000000000)
{
ThrowOverflowInt64Exception();
}
}
else
{
Debug.Assert(radix == 2 || radix == 8 || radix == 10 || radix == 16);
maxVal =
radix == 10 ? 0xffffffffffffffff / 10 :
radix == 16 ? 0xffffffffffffffff / 16 :
radix == 8 ? 0xffffffffffffffff / 8 :
0xffffffffffffffff / 2;
// Read all of the digits and convert to a number
while (i < s.Length && IsDigit(s[i], radix, out int value))
{
// Check for overflows - this is sufficient & correct.
if (result > maxVal)
{
ThrowOverflowUInt64Exception();
}
ulong temp = result * (ulong)radix + (ulong)value;
if (temp < result) // this means overflow as well
{
ThrowOverflowUInt64Exception();
}
result = temp;
i++;
}
}
return (long)result;
}
private static int GrabInts(int radix, ReadOnlySpan<char> s, ref int i, bool isUnsigned)
{
uint result = 0;
uint maxVal;
// Allow all non-decimal numbers to set the sign bit.
if (radix == 10 && !isUnsigned)
{
maxVal = (0x7FFFFFFF / 10);
// Read all of the digits and convert to a number
while (i < s.Length && IsDigit(s[i], radix, out int value))
{
// Check for overflows - this is sufficient & correct.
if (result > maxVal || (int)result < 0)
{
ThrowOverflowInt32Exception();
}
result = result * (uint)radix + (uint)value;
i++;
}
if ((int)result < 0 && result != 0x80000000)
{
ThrowOverflowInt32Exception();
}
}
else
{
Debug.Assert(radix == 2 || radix == 8 || radix == 10 || radix == 16);
maxVal =
radix == 10 ? 0xffffffff / 10 :
radix == 16 ? 0xffffffff / 16 :
radix == 8 ? 0xffffffff / 8 :
0xffffffff / 2;
// Read all of the digits and convert to a number
while (i < s.Length && IsDigit(s[i], radix, out int value))
{
// Check for overflows - this is sufficient & correct.
if (result > maxVal)
{
throw new OverflowException(SR.Overflow_UInt32);
}
uint temp = result * (uint)radix + (uint)value;
if (temp < result) // this means overflow as well
{
ThrowOverflowUInt32Exception();
}
result = temp;
i++;
}
}
return (int)result;
}
private static void ThrowOverflowInt32Exception() => throw new OverflowException(SR.Overflow_Int32);
private static void ThrowOverflowInt64Exception() => throw new OverflowException(SR.Overflow_Int64);
private static void ThrowOverflowUInt32Exception() => throw new OverflowException(SR.Overflow_UInt32);
private static void ThrowOverflowUInt64Exception() => throw new OverflowException(SR.Overflow_UInt64);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsDigit(char c, int radix, out int result)
{
int tmp;
if ((uint)(c - '0') <= 9)
{
result = tmp = c - '0';
}
else if ((uint)(c - 'A') <= 'Z' - 'A')
{
result = tmp = c - 'A' + 10;
}
else if ((uint)(c - 'a') <= 'z' - 'a')
{
result = tmp = c - 'a' + 10;
}
else
{
result = -1;
return false;
}
return tmp < radix;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Testing;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.NetCore.Analyzers.Runtime.DoNotUseReferenceEqualsWithValueTypesAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.NetCore.Analyzers.Runtime.DoNotUseReferenceEqualsWithValueTypesAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests
{
public class DoNotUseReferenceEqualsWithValueTypesTests
{
[Fact]
public async Task ReferenceTypesAreOKAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod(string test)
{
return ReferenceEquals(test, string.Empty);
}
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(test as String)
Return ReferenceEquals(string.Empty, test)
End Function
End Class
End Namespace");
}
[Fact]
public async Task LeftArgumentFailsForValueTypeAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod(string test)
{
return ReferenceEquals(IntPtr.Zero, test);
}
}
}",
GetCSharpMethodResultAt(10, 36, "System.IntPtr"));
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(test as String)
Return ReferenceEquals(IntPtr.Zero, test)
End Function
End Class
End Namespace",
GetVisualBasicMethodResultAt(7, 36, "System.IntPtr"));
}
[Fact]
public async Task RightArgumentFailsForValueTypeAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod(string test)
{
return object.ReferenceEquals(test, 4);
}
}
}",
GetCSharpMethodResultAt(10, 49, "int"));
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(test as String)
Return Object.ReferenceEquals(test, 4)
End Function
End Class
End Namespace",
GetVisualBasicMethodResultAt(7, 49, "Integer"));
}
[Fact]
public async Task NoErrorForUnconstrainedGenericAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod<T>(T test, object other)
{
return ReferenceEquals(test, other);
}
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(Of T)(test as T, other as Object)
Return ReferenceEquals(test, other)
End Function
End Class
End Namespace");
}
[Fact]
public async Task NoErrorForInterfaceConstrainedGenericAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod<T>(T test, object other)
where T : IDisposable
{
return ReferenceEquals(test, other);
}
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(Of T As IDisposable)(test as T, other as Object)
Return ReferenceEquals(test, other)
End Function
End Class
End Namespace");
}
[Fact]
public async Task ErrorForValueTypeConstrainedGenericAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod<T>(T test, object other)
where T : struct
{
return ReferenceEquals(test, other);
}
}
}",
GetCSharpMethodResultAt(11, 36, "T"));
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(Of T As Structure)(test as T, other as Object)
Return ReferenceEquals(test, other)
End Function
End Class
End Namespace",
GetVisualBasicMethodResultAt(7, 36, "T"));
}
[Fact]
public async Task TwoValueTypesProducesTwoErrorsAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod<TLeft, TRight>(TLeft test, TRight other)
where TLeft : struct
where TRight : struct
{
return ReferenceEquals(
test,
other);
}
}
}",
GetCSharpMethodResultAt(13, 17, "TLeft"),
GetCSharpMethodResultAt(14, 17, "TRight"));
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(Of TLeft As Structure, TRight As Structure)(test as TLeft, other as TRight)
Return ReferenceEquals(test, other)
End Function
End Class
End Namespace",
GetVisualBasicMethodResultAt(7, 36, "TLeft"),
GetVisualBasicMethodResultAt(7, 42, "TRight"));
}
[Fact]
public async Task LeftArgumentFailsForValueTypeWhenRightIsNullAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod()
{
return ReferenceEquals(IntPtr.Zero, null);
}
}
}",
GetCSharpMethodResultAt(10, 36, "System.IntPtr"));
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod()
Return ReferenceEquals(IntPtr.Zero, Nothing)
End Function
End Class
End Namespace",
GetVisualBasicMethodResultAt(7, 36, "System.IntPtr"));
}
[Fact]
public async Task RightArgumentFailsForValueTypeWhenLeftIsNullAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod()
{
return object.ReferenceEquals(null, 4);
}
}
}",
GetCSharpMethodResultAt(10, 49, "int"));
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod()
Return Object.ReferenceEquals(Nothing, 4)
End Function
End Class
End Namespace",
GetVisualBasicMethodResultAt(7, 52, "Integer"));
}
[Fact]
public async Task DoNotWarnForUserDefinedConversionsAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace TestNamespace
{
class CacheKey
{
public static explicit operator CacheKey(int value)
{
return null;
}
}
class TestClass
{
private static bool TestMethod()
{
return object.ReferenceEquals(null, (CacheKey)4);
}
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Namespace TestNamespace
Class CacheKey
Public Shared Narrowing Operator CType(value as Integer) as CacheKey
Return Nothing
End Operator
End Class
Class TestClass
Private Shared Function TestMethod()
Return Object.ReferenceEquals(Nothing, CType(4, CacheKey))
End Function
End Class
End Namespace");
}
[Fact]
public async Task Comparer_ReferenceTypesAreOKAsync()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections.Generic;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod(string test)
{
return ReferenceEqualityComparer.Instance.Equals(string.Empty, test);
}
}
}",
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections.Generic
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(test as String)
Return ReferenceEqualityComparer.Instance.Equals(string.Empty, test)
End Function
End Class
End Namespace",
}.RunAsync();
}
[Fact]
public async Task Comparer_LeftArgumentFailsForValueTypeAsync()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections.Generic;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod(string test)
{
return ReferenceEqualityComparer.Instance.Equals(IntPtr.Zero, test);
}
}
}",
ExpectedDiagnostics = { GetCSharpComparerResultAt(11, 62, "System.IntPtr") },
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections.Generic
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(test as String)
Return ReferenceEqualityComparer.Instance.Equals(IntPtr.Zero, test)
End Function
End Class
End Namespace",
ExpectedDiagnostics = { GetVisualBasicComparerResultAt(8, 62, "System.IntPtr") },
}.RunAsync();
}
[Fact]
public async Task Comparer_RightArgumentFailsForValueTypeAsync()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections.Generic;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod(string test)
{
return ReferenceEqualityComparer.Instance.Equals(test, 4);
}
}
}",
ExpectedDiagnostics = { GetCSharpComparerResultAt(11, 68, "int") },
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections.Generic
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(test as String)
Return ReferenceEqualityComparer.Instance.Equals(test, 4)
End Function
End Class
End Namespace",
ExpectedDiagnostics = { GetVisualBasicComparerResultAt(8, 68, "Integer") },
}.RunAsync();
}
[Fact]
public async Task Comparer_NoErrorForUnconstrainedGenericAsync()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections.Generic;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod<T>(T test, object other)
{
return ReferenceEqualityComparer.Instance.Equals(test, other);
}
}
}",
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections.Generic
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(Of T)(test as T, other as Object)
Return ReferenceEqualityComparer.Instance.Equals(test, other)
End Function
End Class
End Namespace",
}.RunAsync();
}
[Fact]
public async Task Comparer_NoErrorForInterfaceConstrainedGenericAsync()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections.Generic;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod<T>(T test, object other)
where T : IDisposable
{
return ReferenceEqualityComparer.Instance.Equals(test, other);
}
}
}",
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections.Generic
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(Of T As IDisposable)(test as T, other as Object)
Return ReferenceEqualityComparer.Instance.Equals(test, other)
End Function
End Class
End Namespace",
}.RunAsync();
}
[Fact]
public async Task Comparer_ErrorForValueTypeConstrainedGenericAsync()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections.Generic;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod<T>(T test, object other)
where T : struct
{
return ReferenceEqualityComparer.Instance.Equals(test, other);
}
}
}",
ExpectedDiagnostics = { GetCSharpComparerResultAt(12, 62, "T") },
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections.Generic
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(Of T As Structure)(test as T, other as Object)
Return ReferenceEqualityComparer.Instance.Equals(test, other)
End Function
End Class
End Namespace",
ExpectedDiagnostics = { GetVisualBasicComparerResultAt(8, 62, "T") },
}.RunAsync();
}
[Fact]
public async Task Comparer_TwoValueTypesProducesTwoErrorsAsync()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections.Generic;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod<TLeft, TRight>(TLeft test, TRight other)
where TLeft : struct
where TRight : struct
{
return ReferenceEqualityComparer.Instance.Equals(
test,
other);
}
}
}",
ExpectedDiagnostics =
{
GetCSharpComparerResultAt(14, 17, "TLeft"),
GetCSharpComparerResultAt(15, 17, "TRight"),
},
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections.Generic
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(Of TLeft As Structure, TRight As Structure)(test as TLeft, other as TRight)
Return ReferenceEqualityComparer.Instance.Equals(test, other)
End Function
End Class
End Namespace",
ExpectedDiagnostics =
{
GetVisualBasicComparerResultAt(8, 62, "TLeft"),
GetVisualBasicComparerResultAt(8, 68, "TRight"),
},
}.RunAsync();
}
[Fact]
public async Task Comparer_LeftArgumentFailsForValueTypeWhenRightIsNullAsync()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections.Generic;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod()
{
return ReferenceEqualityComparer.Instance.Equals(IntPtr.Zero, null);
}
}
}",
ExpectedDiagnostics = { GetCSharpComparerResultAt(11, 62, "System.IntPtr") },
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections.Generic
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod()
Return ReferenceEqualityComparer.Instance.Equals(IntPtr.Zero, Nothing)
End Function
End Class
End Namespace",
ExpectedDiagnostics = { GetVisualBasicComparerResultAt(8, 62, "System.IntPtr") },
}.RunAsync();
}
[Fact]
public async Task Comparer_RightArgumentFailsForValueTypeWhenLeftIsNullAsync()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections.Generic;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod()
{
return ReferenceEqualityComparer.Instance.Equals(null, 4);
}
}
}",
ExpectedDiagnostics = { GetCSharpComparerResultAt(11, 68, "int") },
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections.Generic
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod()
Return ReferenceEqualityComparer.Instance.Equals(Nothing, 4)
End Function
End Class
End Namespace",
ExpectedDiagnostics = { GetVisualBasicComparerResultAt(8, 71, "Integer") },
}.RunAsync();
}
[Fact]
public async Task Comparer_DoNotWarnForUserDefinedConversionsAsync()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections.Generic;
namespace TestNamespace
{
class CacheKey
{
public static explicit operator CacheKey(int value)
{
return null;
}
}
class TestClass
{
private static bool TestMethod()
{
return ReferenceEqualityComparer.Instance.Equals(null, (CacheKey)4);
}
}
}",
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections.Generic
Namespace TestNamespace
Class CacheKey
Public Shared Narrowing Operator CType(value as Integer) as CacheKey
Return Nothing
End Operator
End Class
Class TestClass
Private Shared Function TestMethod()
Return ReferenceEqualityComparer.Instance.Equals(Nothing, CType(4, CacheKey))
End Function
End Class
End Namespace",
}.RunAsync();
}
[Fact]
public async Task ComparerDoesNotTrackThroughInterfaceAsync()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections;
using System.Collections.Generic;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod(string test)
{
IEqualityComparer<object> generic = ReferenceEqualityComparer.Instance;
IEqualityComparer nonGeneric = ReferenceEqualityComparer.Instance;
return generic.Equals(4, 5) || nonGeneric.Equals(4, 5);
}
}
}",
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections
Imports System.Collections.Generic
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(test as String)
Dim generic as IEqualityComparer(Of object) = ReferenceEqualityComparer.Instance
Dim nonGeneric as IEqualityComparer = ReferenceEqualityComparer.Instance
Return generic.Equals(4, 5) Or nonGeneric.Equals(4, 5)
End Function
End Class
End Namespace",
}.RunAsync();
}
private DiagnosticResult GetCSharpMethodResultAt(int line, int column, string typeName)
=> GetCSharpResultAt(DoNotUseReferenceEqualsWithValueTypesAnalyzer.MethodRule, line, column, typeName);
private DiagnosticResult GetVisualBasicMethodResultAt(int line, int column, string typeName)
=> GetVisualBasicResultAt(DoNotUseReferenceEqualsWithValueTypesAnalyzer.MethodRule, line, column, typeName);
private DiagnosticResult GetCSharpComparerResultAt(int line, int column, string typeName)
=> GetCSharpResultAt(DoNotUseReferenceEqualsWithValueTypesAnalyzer.ComparerRule, line, column, typeName);
private DiagnosticResult GetVisualBasicComparerResultAt(int line, int column, string typeName)
=> GetVisualBasicResultAt(DoNotUseReferenceEqualsWithValueTypesAnalyzer.ComparerRule, line, column, typeName);
private DiagnosticResult GetCSharpResultAt(DiagnosticDescriptor rule, int line, int column, string typeName)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic(rule).WithLocation(line, column).WithArguments(typeName);
#pragma warning restore RS0030 // Do not used banned APIs
private DiagnosticResult GetVisualBasicResultAt(DiagnosticDescriptor rule, int line, int column, string typeName)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic(rule).WithLocation(line, column).WithArguments(typeName);
#pragma warning restore RS0030 // Do not used banned APIs
}
}
| |
// 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.Diagnostics.Contracts;
namespace System.Globalization
{
////////////////////////////////////////////////////////////////////////////
//
// Notes about PersianCalendar
//
////////////////////////////////////////////////////////////////////////////
// Modern Persian calendar is a solar observation based calendar. Each new year begins on the day when the vernal equinox occurs before noon.
// The epoch is the date of the vernal equinox prior to the epoch of the Islamic calendar (March 19, 622 Julian or March 22, 622 Gregorian)
// There is no Persian year 0. Ordinary years have 365 days. Leap years have 366 days with the last month (Esfand) gaining the extra day.
/*
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 0622/03/22 9999/12/31
** Persian 0001/01/01 9378/10/13
*/
[Serializable]
public class PersianCalendar : Calendar
{
public static readonly int PersianEra = 1;
internal static long PersianEpoch = new DateTime(622, 3, 22).Ticks / GregorianCalendar.TicksPerDay;
private const int ApproximateHalfYear = 180;
internal const int DatePartYear = 0;
internal const int DatePartDayOfYear = 1;
internal const int DatePartMonth = 2;
internal const int DatePartDay = 3;
internal const int MonthsPerYear = 12;
internal static int[] DaysToMonth = { 0, 31, 62, 93, 124, 155, 186, 216, 246, 276, 306, 336, 366 };
internal const int MaxCalendarYear = 9378;
internal const int MaxCalendarMonth = 10;
internal const int MaxCalendarDay = 13;
// Persian calendar (year: 1, month: 1, day:1 ) = Gregorian (year: 622, month: 3, day: 22)
// This is the minimal Gregorian date that we support in the PersianCalendar.
internal static DateTime minDate = new DateTime(622, 3, 22);
internal static DateTime maxDate = DateTime.MaxValue;
public override DateTime MinSupportedDateTime
{
get
{
return (minDate);
}
}
public override DateTime MaxSupportedDateTime
{
get
{
return (maxDate);
}
}
public override CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.SolarCalendar;
}
}
// Construct an instance of Persian calendar.
public PersianCalendar()
{
}
internal override CalendarId BaseCalendarID
{
get
{
return CalendarId.GREGORIAN;
}
}
internal override CalendarId ID
{
get
{
return CalendarId.PERSIAN;
}
}
/*=================================GetAbsoluteDatePersian==========================
**Action: Gets the Absolute date for the given Persian date. The absolute date means
** the number of days from January 1st, 1 A.D.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
private long GetAbsoluteDatePersian(int year, int month, int day)
{
if (year >= 1 && year <= MaxCalendarYear && month >= 1 && month <= 12)
{
int ordinalDay = DaysInPreviousMonths(month) + day - 1; // day is one based, make 0 based since this will be the number of days we add to beginning of year below
int approximateDaysFromEpochForYearStart = (int)(CalendricalCalculationsHelper.MeanTropicalYearInDays * (year - 1));
long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(PersianEpoch + approximateDaysFromEpochForYearStart + ApproximateHalfYear);
yearStart += ordinalDay;
return yearStart;
}
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}
internal static void CheckTicksRange(long ticks)
{
if (ticks < minDate.Ticks || ticks > maxDate.Ticks)
{
throw new ArgumentOutOfRangeException(
"time",
String.Format(
CultureInfo.InvariantCulture,
SR.ArgumentOutOfRange_CalendarRange,
minDate,
maxDate));
}
}
internal static void CheckEraRange(int era)
{
if (era != CurrentEra && era != PersianEra)
{
throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue);
}
}
internal static void CheckYearRange(int year, int era)
{
CheckEraRange(era);
if (year < 1 || year > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxCalendarYear));
}
}
internal static void CheckYearMonthRange(int year, int month, int era)
{
CheckYearRange(year, era);
if (year == MaxCalendarYear)
{
if (month > MaxCalendarMonth)
{
throw new ArgumentOutOfRangeException(
"month",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxCalendarMonth));
}
}
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException("month", SR.ArgumentOutOfRange_Month);
}
}
private static int MonthFromOrdinalDay(int ordinalDay)
{
Contract.Assert(ordinalDay <= 366);
int index = 0;
while (ordinalDay > DaysToMonth[index])
index++;
return index;
}
private static int DaysInPreviousMonths(int month)
{
Contract.Assert(1 <= month && month <= 12);
--month; // months are one based but for calculations use 0 based
return DaysToMonth[month];
}
/*=================================GetDatePart==========================
**Action: Returns a given date part of this <i>DateTime</i>. This method is used
** to compute the year, day-of-year, month, or day part.
**Returns:
**Arguments:
**Exceptions: ArgumentException if part is incorrect.
============================================================================*/
internal int GetDatePart(long ticks, int part)
{
long NumDays; // The calculation buffer in number of days.
CheckTicksRange(ticks);
//
// Get the absolute date. The absolute date is the number of days from January 1st, 1 A.D.
// 1/1/0001 is absolute date 1.
//
NumDays = ticks / GregorianCalendar.TicksPerDay + 1;
//
// Calculate the appromixate Persian Year.
//
long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(NumDays);
int y = (int)(Math.Floor(((yearStart - PersianEpoch) / CalendricalCalculationsHelper.MeanTropicalYearInDays) + 0.5)) + 1;
Contract.Assert(y >= 1);
if (part == DatePartYear)
{
return y;
}
//
// Calculate the Persian Month.
//
int ordinalDay = (int)(NumDays - CalendricalCalculationsHelper.GetNumberOfDays(this.ToDateTime(y, 1, 1, 0, 0, 0, 0, 1)));
if (part == DatePartDayOfYear)
{
return ordinalDay;
}
int m = MonthFromOrdinalDay(ordinalDay);
Contract.Assert(ordinalDay >= 1);
Contract.Assert(m >= 1 && m <= 12);
if (part == DatePartMonth)
{
return m;
}
int d = ordinalDay - DaysInPreviousMonths(m);
Contract.Assert(1 <= d);
Contract.Assert(d <= 31);
//
// Calculate the Persian Day.
//
if (part == DatePartDay)
{
return (d);
}
// Incorrect part value.
throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing);
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
"months",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
-120000,
120000));
}
Contract.EndContractBlock();
// Get the date in Persian calendar.
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
int days = GetDaysInMonth(y, m);
if (d > days)
{
d = days;
}
long ticks = GetAbsoluteDatePersian(y, m, d) * TicksPerDay + time.Ticks % TicksPerDay;
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public override DateTime AddYears(DateTime time, int years)
{
return (AddMonths(time, years * 12));
}
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public override int GetDayOfMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDay));
}
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public override int GetDayOfYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
// Returns the number of days in the month given by the year and
// month arguments.
//
public override int GetDaysInMonth(int year, int month, int era)
{
CheckYearMonthRange(year, month, era);
if ((month == MaxCalendarMonth) && (year == MaxCalendarYear))
{
return MaxCalendarDay;
}
int daysInMonth = DaysToMonth[month] - DaysToMonth[month - 1];
if ((month == MonthsPerYear) && !IsLeapYear(year))
{
Contract.Assert(daysInMonth == 30);
--daysInMonth;
}
return daysInMonth;
}
// Returns the number of days in the year given by the year argument for the current era.
//
public override int GetDaysInYear(int year, int era)
{
CheckYearRange(year, era);
if (year == MaxCalendarYear)
{
return DaysToMonth[MaxCalendarMonth - 1] + MaxCalendarDay;
}
// Common years have 365 days. Leap years have 366 days.
return (IsLeapYear(year, CurrentEra) ? 366 : 365);
}
// Returns the era for the specified DateTime value.
public override int GetEra(DateTime time)
{
CheckTicksRange(time.Ticks);
return (PersianEra);
}
public override int[] Eras
{
get
{
return (new int[] { PersianEra });
}
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public override int GetMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartMonth));
}
// Returns the number of months in the specified year and era.
public override int GetMonthsInYear(int year, int era)
{
CheckYearRange(year, era);
if (year == MaxCalendarYear)
{
return MaxCalendarMonth;
}
return (12);
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and MaxCalendarYear.
//
public override int GetYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartYear));
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public override bool IsLeapDay(int year, int month, int day, int era)
{
// The year/month/era value checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
"day",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Day,
daysInMonth,
month));
}
return (IsLeapYear(year, era) && month == 12 && day == 30);
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public override int GetLeapMonth(int year, int era)
{
CheckYearRange(year, era);
return (0);
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public override bool IsLeapMonth(int year, int month, int era)
{
CheckYearMonthRange(year, month, era);
return (false);
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public override bool IsLeapYear(int year, int era)
{
CheckYearRange(year, era);
if (year == MaxCalendarYear)
{
return false;
}
return (GetAbsoluteDatePersian(year + 1, 1, 1) - GetAbsoluteDatePersian(year, 1, 1)) == 366;
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
// The year/month/era checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
// BCLDebug.Log("year = " + year + ", month = " + month + ", day = " + day);
throw new ArgumentOutOfRangeException(
"day",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Day,
daysInMonth,
month));
}
long lDate = GetAbsoluteDatePersian(year, month, day);
if (lDate >= 0)
{
return (new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond)));
}
else
{
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 1410;
public override int TwoDigitYearMax
{
get
{
if (twoDigitYearMax == -1)
{
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
"value",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
99,
MaxCalendarYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException("year",
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
if (year < 100)
{
return (base.ToFourDigitYear(year));
}
if (year > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxCalendarYear));
}
return (year);
}
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.UseNullPropagation;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.UseNullPropagation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseNullPropagation
{
public partial class UseNullPropagationTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return Tuple.Create<DiagnosticAnalyzer, CodeFixProvider>(
new CSharpUseNullPropagationDiagnosticAnalyzer(),
new CSharpUseNullPropagationCodeFixProvider());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestLeft_Equals()
{
await TestAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o.ToString();
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestMissingOnCSharp5()
{
await TestMissingAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o.ToString();
}
}", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestRight_Equals()
{
await TestAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]null == o ? null : o.ToString();
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestLeft_NotEquals()
{
await TestAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o != null ? o.ToString() : null;
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestRight_NotEquals()
{
await TestAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]null != o ? o.ToString() : null;
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestIndexer()
{
await TestAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o[0];
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?[0];
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestConditionalAccess()
{
await TestAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o.B?.C;
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.B?.C;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestMemberAccess()
{
await TestAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o.B;
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.B;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestMissingOnSimpleMatch()
{
await TestMissingAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? null : o;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestParenthesizedCondition()
{
await TestAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||](o == null) ? null : o.ToString();
}
}",
@"using System;
class C
{
void M(object o)
{
var v = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestFixAll1()
{
await TestAsync(
@"using System;
class C
{
void M(object o)
{
var v1 = {|FixAllInDocument:o|} == null ? null : o.ToString();
var v2 = o != null ? o.ToString() : null;
}
}",
@"using System;
class C
{
void M(object o)
{
var v1 = o?.ToString();
var v2 = o?.ToString();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestFixAll2()
{
await TestAsync(
@"using System;
class C
{
void M(object o1, object o2)
{
var v1 = {|FixAllInDocument:o1|} == null ? null : o1.ToString(o2 == null ? null : o2.ToString());
}
}",
@"using System;
class C
{
void M(object o1, object o2)
{
var v1 = o1?.ToString(o2?.ToString());
}
}");
}
[WorkItem(15505, "https://github.com/dotnet/roslyn/issues/15505")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestOtherValueIsNotNull1()
{
await TestMissingAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o == null ? 0 : o.ToString();
}
}");
}
[WorkItem(15505, "https://github.com/dotnet/roslyn/issues/15505")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestOtherValueIsNotNull2()
{
await TestMissingAsync(
@"using System;
class C
{
void M(object o)
{
var v = [||]o != null ? o.ToString() : 0;
}
}");
}
[WorkItem(16287, "https://github.com/dotnet/roslyn/issues/16287")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)]
public async Task TestMethodGroup()
{
await TestMissingAsync(
@"
using System;
class D
{
void Foo()
{
var c = new C();
Action<string> a = [||]c != null ? c.M : (Action<string>)null;
}
}
class C { public void M(string s) { } }");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#if FEATURE_CUSTOM_TYPE_DESCRIPTOR
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using IronPython.Runtime.Types;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions.Calls;
namespace IronPython.Runtime.Operations {
/// <summary>
/// Helper class that all custom type descriptor implementations call for
/// the bulk of their implementation.
/// </summary>
public static class CustomTypeDescHelpers {
#region ICustomTypeDescriptor helper functions
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "self")]
public static AttributeCollection GetAttributes(object self) {
return AttributeCollection.Empty;
}
public static string GetClassName(object self) {
object cls;
if (PythonOps.TryGetBoundAttr(DefaultContext.DefaultCLS, self, "__class__", out cls)) {
return PythonOps.GetBoundAttr(DefaultContext.DefaultCLS, cls, "__name__").ToString();
}
return null;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "self")]
public static string GetComponentName(object self) {
return null;
}
public static TypeConverter GetConverter(object self) {
return new TypeConv(self);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "self")]
public static EventDescriptor GetDefaultEvent(object self) {
return null;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "self")]
public static PropertyDescriptor GetDefaultProperty(object self) {
return null;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "self"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "editorBaseType")]
public static object GetEditor(object self, Type editorBaseType) {
return null;
}
public static EventDescriptorCollection GetEvents(object self, Attribute[] attributes) {
if (attributes == null || attributes.Length == 0) return GetEvents(self);
//!!! update when we support attributes on python types
// you want things w/ attributes? we don't have attributes!
return EventDescriptorCollection.Empty;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "self")]
public static EventDescriptorCollection GetEvents(object self) {
return EventDescriptorCollection.Empty;
}
public static PropertyDescriptorCollection GetProperties(object self) {
return new PropertyDescriptorCollection(GetPropertiesImpl(self, new Attribute[0]));
}
public static PropertyDescriptorCollection GetProperties(object self, Attribute[] attributes) {
return new PropertyDescriptorCollection(GetPropertiesImpl(self, attributes));
}
static PropertyDescriptor[] GetPropertiesImpl(object self, Attribute[] attributes) {
IList<object> attrNames = PythonOps.GetAttrNames(DefaultContext.DefaultCLS, self);
List<PropertyDescriptor> descrs = new List<PropertyDescriptor>();
if (attrNames != null) {
foreach (object o in attrNames) {
if (!(o is string s)) continue;
PythonTypeSlot attrSlot = null;
object attrVal;
if (self is OldInstance) {
if (((OldInstance)self)._class.TryLookupSlot(s, out attrVal)) {
attrSlot = attrVal as PythonTypeSlot;
} else if (!((OldInstance)self).Dictionary.TryGetValue(s, out attrVal)) {
attrVal = ObjectOps.__getattribute__(DefaultContext.DefaultCLS, self, s);
}
} else {
PythonType dt = DynamicHelpers.GetPythonType(self);
dt.TryResolveSlot(DefaultContext.DefaultCLS, s, out attrSlot);
attrVal = ObjectOps.__getattribute__(DefaultContext.DefaultCLS, self, s);
}
Type attrType = (attrVal == null) ? typeof(NoneTypeOps) : attrVal.GetType();
if ((attrSlot != null && ShouldIncludeProperty(attrSlot, attributes)) ||
(attrSlot == null && ShouldIncludeInstanceMember(s, attributes))) {
descrs.Add(new SuperDynamicObjectPropertyDescriptor(s, attrType, self.GetType()));
}
}
}
return descrs.ToArray();
}
private static bool ShouldIncludeInstanceMember(string memberName, Attribute[] attributes) {
bool include = true;
foreach (Attribute attr in attributes) {
if (attr.GetType() == typeof(BrowsableAttribute)) {
if (memberName.StartsWith("__") && memberName.EndsWith("__")) {
include = false;
}
} else {
// unknown attribute, Python doesn't support attributes, so we
// say this doesn't have that attribute.
include = false;
}
}
return include;
}
private static bool ShouldIncludeProperty(PythonTypeSlot attrSlot, Attribute[] attributes) {
bool include = true;
foreach (Attribute attr in attributes) {
ReflectedProperty rp;
if ((rp = attrSlot as ReflectedProperty) != null && rp.Info != null) {
include &= rp.Info.IsDefined(attr.GetType(), true);
} else if (attr.GetType() == typeof(BrowsableAttribute)) {
if (!(attrSlot is PythonTypeUserDescriptorSlot userSlot)) {
if (!(attrSlot is PythonProperty)) {
include = false;
}
} else if (!(userSlot.Value is IPythonObject)) {
include = false;
}
} else {
// unknown attribute, Python doesn't support attributes, so we
// say this doesn't have that attribute.
include = false;
}
}
return include;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "pd")]
public static object GetPropertyOwner(object self, PropertyDescriptor pd) {
return self;
}
#endregion
class SuperDynamicObjectPropertyDescriptor : PropertyDescriptor {
string _name;
Type _propertyType;
Type _componentType;
internal SuperDynamicObjectPropertyDescriptor(
string name,
Type propertyType,
Type componentType)
: base(name, null) {
_name = name;
_propertyType = propertyType;
_componentType = componentType;
}
public override object GetValue(object component) {
return PythonOps.GetBoundAttr(DefaultContext.DefaultCLS, component, _name);
}
public override void SetValue(object component, object value) {
PythonOps.SetAttr(DefaultContext.DefaultCLS, component, _name, value);
}
public override bool CanResetValue(object component) {
return true;
}
public override Type ComponentType {
get { return _componentType; }
}
public override bool IsReadOnly {
get { return false; }
}
public override Type PropertyType {
get { return _propertyType; }
}
public override void ResetValue(object component) {
PythonOps.DeleteAttr(DefaultContext.DefaultCLS, component, _name);
}
public override bool ShouldSerializeValue(object component) {
object o;
return PythonOps.TryGetBoundAttr(component, _name, out o);
}
}
private class TypeConv : TypeConverter {
object convObj;
public TypeConv(object self) {
convObj = self;
}
#region TypeConverter overrides
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
object result;
return Converter.TryConvert(convObj, destinationType, out result);
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
return Converter.CanConvertFrom(sourceType, convObj.GetType(), NarrowingLevel.All);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) {
return Converter.Convert(value, convObj.GetType());
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) {
return Converter.Convert(convObj, destinationType);
}
public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) {
return false;
}
public override bool GetPropertiesSupported(ITypeDescriptorContext context) {
return false;
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) {
return false;
}
public override bool IsValid(ITypeDescriptorContext context, object value) {
object result;
return Converter.TryConvert(value, convObj.GetType(), out result);
}
#endregion
}
}
}
#endif
| |
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using Microsoft.Azure.Zumo.WindowsPhone8.Test;
using Microsoft.WindowsAzure.MobileServices;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Zumo.WindowsPhone8.CSharp.Test
{
public class Person
{
public long Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
[DataContract]
public class Animal
{
[DataMember(Name = "id")]
public int Id;
[DataMember(Name = "species", IsRequired = true)]
public string Species { get; set; }
[DataMember]
internal bool SoftAndFurry { get; set; }
public bool Deadly { get; set; }
}
public class Hyperlink
{
public int ID { get; set; }
[DataMemberJsonConverter(ConverterType = typeof(UriConverter))]
public Uri Href { get; set; }
public string Alt { get; set; }
internal class UriConverter : IDataMemberJsonConverter
{
public object ConvertFromJson(JToken value)
{
string text = value.AsString();
return text != null ?
new Uri(text) :
null;
}
public JToken ConvertToJson(object instance)
{
Uri uri = instance as Uri;
return new JValue(
uri != null ? uri.ToString() : "");
}
}
}
public class SimpleTree : ICustomMobileServiceTableSerialization
{
public int Id { get; set; }
public string Name { get; set; }
[IgnoreDataMember]
public List<SimpleTree> Children { get; set; }
public SimpleTree()
{
Children = new List<SimpleTree>();
}
JToken ICustomMobileServiceTableSerialization.Serialize()
{
JArray children = new JArray();
foreach (SimpleTree child in Children)
{
children.Append(MobileServiceTableSerializer.Serialize(child));
}
return new JObject()
.Set("id", Id)
.Set("name", Name)
.Set("children", children);
}
void ICustomMobileServiceTableSerialization.Deserialize(JToken value)
{
int? id = value.Get("id").AsInteger();
if (id != null)
{
Id = id.Value;
}
Name = value.Get("name").AsString();
JArray children = value["children"] as JArray;
if (children != null)
{
Children.AddRange(children.Select(MobileServiceTableSerializer.Deserialize<SimpleTree>));
}
}
}
public class ZumoSerializerTests : TestBase
{
[TestMethod]
public void BasicSerialization()
{
// Serialize an instance without an ID
JToken value = MobileServiceTableSerializer.Serialize(
new Person { Name = "John", Age = 45 });
Assert.AreEqual("John", value.Get("Name").AsString());
Assert.AreEqual(45, value.Get("Age").AsInteger());
Assert.IsNull(value.Get("id").AsInteger());
// Ensure the ID is written when provided
// Serialize an instance without an ID
value = MobileServiceTableSerializer.Serialize(
new Person { Id = 2, Name = "John", Age = 45 });
Assert.AreEqual("John", value.Get("Name").AsString());
Assert.AreEqual(45, value.Get("Age").AsInteger());
Assert.AreEqual(2, value.Get("id").AsInteger());
// Ensure other properties are included but null
value = MobileServiceTableSerializer.Serialize(new Person { Id = 12 });
string text = value.ToString();
Assert.Contains(text, "Name");
Assert.Contains(text, "Age");
Throws<ArgumentNullException>(() => MobileServiceTableSerializer.Serialize(null));
}
[TestMethod]
public void BasicDeserialization()
{
// Create a new instnace
Person p = MobileServiceTableSerializer.Deserialize<Person>(
new JObject()
.Set("Name", "Bob")
.Set("Age", 20)
.Set("id", 10));
Assert.AreEqual(10L, p.Id);
Assert.AreEqual("Bob", p.Name);
Assert.AreEqual(20, p.Age);
// Deserialize into the same instance
MobileServiceTableSerializer.Deserialize(
new JObject()
.Set("Age", 21)
.Set("Name", "Roberto"),
p);
Assert.AreEqual(10L, p.Id);
Assert.AreEqual("Roberto", p.Name);
Assert.AreEqual(21, p.Age);
Throws<ArgumentNullException>(() => MobileServiceTableSerializer.Deserialize(null, new object()));
Throws<ArgumentNullException>(() => MobileServiceTableSerializer.Deserialize(JsonExtensions.Null(), null));
}
[TestMethod]
public void DataContractSerialization()
{
// Serialize a type with a data contract
Animal bear = new Animal { Id = 1, Species = "Grizzly", Deadly = true, SoftAndFurry = true};
JToken value = MobileServiceTableSerializer.Serialize(bear);
Assert.AreEqual(1, value.Get("id").AsInteger());
Assert.AreEqual("Grizzly", value.Get("species").AsString());
Assert.IsTrue(value.Get("SoftAndFurry").AsBool().Value);
Assert.IsTrue(value.Get("Deadly").IsNull());
// Deserialize a type with a data contract
Animal donkey = MobileServiceTableSerializer.Deserialize<Animal>(
new JObject()
.Set("id", 2)
.Set("species", "Stubbornus Maximums")
.Set("Deadly", true)
.Set("SoftAndFurry", false));
Assert.AreEqual(2, donkey.Id);
Assert.AreEqual("Stubbornus Maximums", donkey.Species);
Assert.IsFalse(donkey.SoftAndFurry);
Assert.IsFalse(donkey.Deadly); // No DataMember so not serialized
// Ensure we throw if we're missing a required
Throws<SerializationException>(() => MobileServiceTableSerializer.Deserialize<Animal>(
new JObject().Set("id", 3).Set("name", "Pterodactyl").Set("Deadly", true)));
}
[TestMethod]
public void DataMemberJsonConverter()
{
// Serialize with a custom JSON converter
JToken link = MobileServiceTableSerializer.Serialize(
new Hyperlink
{
Href = new Uri("http://www.microsoft.com/"),
Alt = "Microsoft"
});
Assert.AreEqual("Microsoft", link.Get("Alt").AsString());
Assert.AreEqual("http://www.microsoft.com/", link.Get("Href").AsString());
// Deserialize with a custom JSON converter
Hyperlink azure = MobileServiceTableSerializer.Deserialize<Hyperlink>(
new JObject().Set("Alt", "Windows Azure").Set("Href", "http://windowsazure.com"));
Assert.AreEqual("Windows Azure", azure.Alt);
Assert.AreEqual("windowsazure.com", azure.Href.Host);
}
[TestMethod]
public void CustomSerialization()
{
SimpleTree tree = new SimpleTree
{
Id = 1,
Name = "John",
Children = new List<SimpleTree>
{
new SimpleTree { Id = 2, Name = "James" },
new SimpleTree
{
Id = 3,
Name = "David",
Children = new List<SimpleTree>
{
new SimpleTree { Id = 4, Name = "Jennifer" }
}
}
}
};
JToken family = MobileServiceTableSerializer.Serialize(tree);
Assert.AreEqual("Jennifer",
family.Get("children").AsArray()[1].Get("children").AsArray()[0].Get("name").AsString());
SimpleTree second = MobileServiceTableSerializer.Deserialize<SimpleTree>(family);
Assert.AreEqual(tree.Children[0].Name, second.Children[0].Name);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.