context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
namespace EIDSS.Reports.Parameterized.Uni.EventLog
{
partial class EventLogReport
{
#region Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EventLogReport));
this.tableHeader = new DevExpress.XtraReports.UI.XRTable();
this.rowHeader1 = new DevExpress.XtraReports.UI.XRTableRow();
this.cellDateTime = new DevExpress.XtraReports.UI.XRTableCell();
this.cellType = new DevExpress.XtraReports.UI.XRTableCell();
this.cellPerson = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand();
this.Detail1 = new DevExpress.XtraReports.UI.DetailBand();
this.tableData = new DevExpress.XtraReports.UI.XRTable();
this.RowData = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.sp_rep_UNI_EventLogTableAdapter1 = new EIDSS.Reports.Parameterized.Uni.EventLog.EventLogDataSetTableAdapters.sp_rep_UNI_EventLogTableAdapter();
this.eventLogDataSet1 = new EIDSS.Reports.Parameterized.Uni.EventLog.EventLogDataSet();
((System.ComponentModel.ISupportInitialize)(this.tableInterval)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableData)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.eventLogDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// tableInterval
//
resources.ApplyResources(this.tableInterval, "tableInterval");
this.tableInterval.StylePriority.UseBorders = false;
this.tableInterval.StylePriority.UseFont = false;
this.tableInterval.StylePriority.UsePadding = false;
//
// cellLanguage
//
this.cellLanguage.StylePriority.UseTextAlignment = false;
//
// lblReportName
//
resources.ApplyResources(this.lblReportName, "lblReportName");
this.lblReportName.StylePriority.UseBorders = false;
this.lblReportName.StylePriority.UseBorderWidth = false;
this.lblReportName.StylePriority.UseFont = false;
this.lblReportName.StylePriority.UseTextAlignment = false;
//
// Detail
//
resources.ApplyResources(this.Detail, "Detail");
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
//
// PageHeader
//
this.PageHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.tableHeader});
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
//
// PageFooter
//
this.PageFooter.StylePriority.UseBorders = false;
//
// ReportHeader
//
resources.ApplyResources(this.ReportHeader, "ReportHeader");
//
// xrPageInfo1
//
resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1");
this.xrPageInfo1.StylePriority.UseBorders = false;
//
// cellReportHeader
//
this.cellReportHeader.StylePriority.UseBorders = false;
this.cellReportHeader.StylePriority.UseFont = false;
this.cellReportHeader.StylePriority.UseTextAlignment = false;
this.cellReportHeader.Weight = 2.2994485515985108D;
//
// cellBaseSite
//
this.cellBaseSite.StylePriority.UseBorders = false;
this.cellBaseSite.StylePriority.UseFont = false;
this.cellBaseSite.StylePriority.UseTextAlignment = false;
this.cellBaseSite.Weight = 2.2994485515985108D;
//
// cellBaseCountry
//
this.cellBaseCountry.StylePriority.UseFont = false;
this.cellBaseCountry.Weight = 1.6891816919536407D;
//
// cellBaseLeftHeader
//
this.cellBaseLeftHeader.Weight = 1.6891816919536407D;
//
// tableBaseHeader
//
resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader");
this.tableBaseHeader.StylePriority.UseBorders = false;
this.tableBaseHeader.StylePriority.UseBorderWidth = false;
this.tableBaseHeader.StylePriority.UseFont = false;
this.tableBaseHeader.StylePriority.UsePadding = false;
this.tableBaseHeader.StylePriority.UseTextAlignment = false;
//
// tableHeader
//
this.tableHeader.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.tableHeader, "tableHeader");
this.tableHeader.Name = "tableHeader";
this.tableHeader.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.rowHeader1,
this.xrTableRow3});
this.tableHeader.StylePriority.UseBorders = false;
this.tableHeader.StylePriority.UseFont = false;
this.tableHeader.StylePriority.UseTextAlignment = false;
//
// rowHeader1
//
this.rowHeader1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.cellDateTime,
this.cellType,
this.cellPerson});
resources.ApplyResources(this.rowHeader1, "rowHeader1");
this.rowHeader1.Name = "rowHeader1";
this.rowHeader1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.rowHeader1.StylePriority.UseFont = false;
this.rowHeader1.StylePriority.UsePadding = false;
this.rowHeader1.StylePriority.UseTextAlignment = false;
this.rowHeader1.Weight = 0.4329004329004329D;
//
// cellDateTime
//
resources.ApplyResources(this.cellDateTime, "cellDateTime");
this.cellDateTime.Name = "cellDateTime";
this.cellDateTime.StylePriority.UseFont = false;
this.cellDateTime.Weight = 0.68740112079440219D;
//
// cellType
//
resources.ApplyResources(this.cellType, "cellType");
this.cellType.Name = "cellType";
this.cellType.StylePriority.UseFont = false;
this.cellType.StylePriority.UseTextAlignment = false;
this.cellType.Weight = 0.68740112079440219D;
//
// cellPerson
//
resources.ApplyResources(this.cellPerson, "cellPerson");
this.cellPerson.Name = "cellPerson";
this.cellPerson.StylePriority.UseFont = false;
this.cellPerson.StylePriority.UseTextAlignment = false;
this.cellPerson.Weight = 0.69030245026717763D;
//
// xrTableRow3
//
this.xrTableRow3.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell3,
this.xrTableCell4,
this.xrTableCell5});
this.xrTableRow3.Name = "xrTableRow3";
this.xrTableRow3.StylePriority.UseBorders = false;
this.xrTableRow3.Weight = 0.28860028860028863D;
//
// xrTableCell3
//
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
this.xrTableCell3.Name = "xrTableCell3";
this.xrTableCell3.StylePriority.UseFont = false;
this.xrTableCell3.Weight = 0.68740112079440219D;
//
// xrTableCell4
//
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.Name = "xrTableCell4";
this.xrTableCell4.StylePriority.UseFont = false;
this.xrTableCell4.Weight = 0.68740112079440219D;
//
// xrTableCell5
//
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
this.xrTableCell5.Name = "xrTableCell5";
this.xrTableCell5.StylePriority.UseFont = false;
this.xrTableCell5.Weight = 0.69030245026717763D;
//
// DetailReport
//
this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail1});
this.DetailReport.DataAdapter = this.sp_rep_UNI_EventLogTableAdapter1;
this.DetailReport.DataMember = "spRepUniEventLog";
this.DetailReport.DataSource = this.eventLogDataSet1;
this.DetailReport.Level = 0;
this.DetailReport.Name = "DetailReport";
//
// Detail1
//
this.Detail1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.tableData});
resources.ApplyResources(this.Detail1, "Detail1");
this.Detail1.Name = "Detail1";
//
// tableData
//
this.tableData.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.tableData, "tableData");
this.tableData.Name = "tableData";
this.tableData.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.RowData});
this.tableData.StylePriority.UseBorders = false;
this.tableData.StylePriority.UseFont = false;
this.tableData.StylePriority.UseTextAlignment = false;
//
// RowData
//
this.RowData.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell1,
this.xrTableCell2,
this.xrTableCell6});
resources.ApplyResources(this.RowData, "RowData");
this.RowData.Name = "RowData";
this.RowData.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.RowData.StylePriority.UseFont = false;
this.RowData.StylePriority.UsePadding = false;
this.RowData.StylePriority.UseTextAlignment = false;
this.RowData.Weight = 0.4329004329004329D;
//
// xrTableCell1
//
this.xrTableCell1.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepUniEventLog.datEventDatatime", "{0:dd/MM/yyyy}")});
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Name = "xrTableCell1";
this.xrTableCell1.StylePriority.UseFont = false;
this.xrTableCell1.Weight = 0.68740112079440219D;
//
// xrTableCell2
//
this.xrTableCell2.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepUniEventLog.strEventTypeName")});
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
this.xrTableCell2.Name = "xrTableCell2";
this.xrTableCell2.StylePriority.UseFont = false;
this.xrTableCell2.StylePriority.UseTextAlignment = false;
this.xrTableCell2.Weight = 0.68740112079440219D;
//
// xrTableCell6
//
this.xrTableCell6.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepUniEventLog.PersonName")});
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
this.xrTableCell6.Name = "xrTableCell6";
this.xrTableCell6.StylePriority.UseFont = false;
this.xrTableCell6.StylePriority.UseTextAlignment = false;
this.xrTableCell6.Weight = 0.69030245026717763D;
//
// sp_rep_UNI_EventLogTableAdapter1
//
this.sp_rep_UNI_EventLogTableAdapter1.ClearBeforeFill = true;
//
// eventLogDataSet1
//
this.eventLogDataSet1.DataSetName = "EventLogDataSet";
this.eventLogDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// EventLogReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.DetailReport,
this.ReportHeader});
this.CanWorkWithArchive = false;
this.Landscape = false;
this.PageHeight = 1169;
this.PageWidth = 827;
this.Version = "11.1";
this.Controls.SetChildIndex(this.ReportHeader, 0);
this.Controls.SetChildIndex(this.DetailReport, 0);
this.Controls.SetChildIndex(this.PageFooter, 0);
this.Controls.SetChildIndex(this.PageHeader, 0);
this.Controls.SetChildIndex(this.Detail, 0);
((System.ComponentModel.ISupportInitialize)(this.tableInterval)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableData)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.eventLogDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.XRTable tableHeader;
private DevExpress.XtraReports.UI.XRTableRow rowHeader1;
private DevExpress.XtraReports.UI.XRTableCell cellType;
private DevExpress.XtraReports.UI.XRTableCell cellPerson;
private DevExpress.XtraReports.UI.DetailReportBand DetailReport;
private DevExpress.XtraReports.UI.DetailBand Detail1;
private DevExpress.XtraReports.UI.XRTableCell cellDateTime;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTable tableData;
private DevExpress.XtraReports.UI.XRTableRow RowData;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private EventLogDataSet eventLogDataSet1;
private EventLogDataSetTableAdapters.sp_rep_UNI_EventLogTableAdapter sp_rep_UNI_EventLogTableAdapter1;
}
}
| |
// 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: Your favorite String class. Native methods
** are implemented in StringNative.cpp
**
**
===========================================================*/
namespace System
{
using System.Text;
using System;
using System.Runtime;
using System.Runtime.ConstrainedExecution;
using System.Globalization;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Microsoft.Win32;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
//
// For Information on these methods, please see COMString.cpp
//
// The String class represents a static string of characters. Many of
// the String methods perform some type of transformation on the current
// instance and return the result as a new String. All comparison methods are
// implemented as a part of String. As with arrays, character positions
// (indices) are zero-based.
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed partial class String : IComparable, ICloneable, IConvertible, IEnumerable
, IComparable<String>, IEnumerable<char>, IEquatable<String>
{
//
//NOTE NOTE NOTE NOTE
//These fields map directly onto the fields in an EE StringObject. See object.h for the layout.
//
[NonSerialized] private int m_stringLength;
// For empty strings, this will be '\0' since
// strings are both null-terminated and length prefixed
[NonSerialized] private char m_firstChar;
// The Empty constant holds the empty string value. It is initialized by the EE during startup.
// It is treated as intrinsic by the JIT as so the static constructor would never run.
// Leaving it uninitialized would confuse debuggers.
//
//We need to call the String constructor so that the compiler doesn't mark this as a literal.
//Marking this as a literal would mean that it doesn't show up as a field which we can access
//from native.
public static readonly String Empty;
internal char FirstChar { get { return m_firstChar; } }
//
// This is a helper method for the security team. They need to uppercase some strings (guaranteed to be less
// than 0x80) before security is fully initialized. Without security initialized, we can't grab resources (the nlp's)
// from the assembly. This provides a workaround for that problem and should NOT be used anywhere else.
//
internal unsafe static string SmallCharToUpper(string strIn)
{
Contract.Requires(strIn != null);
Contract.EndContractBlock();
//
// Get the length and pointers to each of the buffers. Walk the length
// of the string and copy the characters from the inBuffer to the outBuffer,
// capitalizing it if necessary. We assert that all of our characters are
// less than 0x80.
//
int length = strIn.Length;
String strOut = FastAllocateString(length);
fixed (char* inBuff = &strIn.m_firstChar, outBuff = &strOut.m_firstChar)
{
for (int i = 0; i < length; i++)
{
int c = inBuff[i];
Debug.Assert(c <= 0x7F, "string has to be ASCII");
// uppercase - notice that we need just one compare
if ((uint)(c - 'a') <= (uint)('z' - 'a')) c -= 0x20;
outBuff[i] = (char)c;
}
Debug.Assert(outBuff[length] == '\0', "outBuff[length]=='\0'");
}
return strOut;
}
// Gets the character at a specified position.
//
// Spec#: Apply the precondition here using a contract assembly. Potential perf issue.
[System.Runtime.CompilerServices.IndexerName("Chars")]
public extern char this[int index]
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
// Converts a substring of this string to an array of characters. Copies the
// characters of this string beginning at position sourceIndex and ending at
// sourceIndex + count - 1 to the character array buffer, beginning
// at destinationIndex.
//
unsafe public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
{
if (destination == null)
throw new ArgumentNullException(nameof(destination));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NegativeCount);
if (sourceIndex < 0)
throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_Index);
if (count > Length - sourceIndex)
throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_IndexCount);
if (destinationIndex > destination.Length - count || destinationIndex < 0)
throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_IndexCount);
Contract.EndContractBlock();
// Note: fixed does not like empty arrays
if (count > 0)
{
fixed (char* src = &m_firstChar)
fixed (char* dest = destination)
wstrcpy(dest + destinationIndex, src + sourceIndex, count);
}
}
// Returns the entire string as an array of characters.
unsafe public char[] ToCharArray()
{
int length = Length;
if (length > 0)
{
char[] chars = new char[length];
fixed (char* src = &m_firstChar) fixed (char* dest = chars)
{
wstrcpy(dest, src, length);
}
return chars;
}
return Array.Empty<char>();
}
// Returns a substring of this string as an array of characters.
//
unsafe public char[] ToCharArray(int startIndex, int length)
{
// Range check everything.
if (startIndex < 0 || startIndex > Length || startIndex > Length - length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
if (length > 0)
{
char[] chars = new char[length];
fixed (char* src = &m_firstChar) fixed (char* dest = chars)
{
wstrcpy(dest, src + startIndex, length);
}
return chars;
}
return Array.Empty<char>();
}
[Pure]
public static bool IsNullOrEmpty(String value)
{
return (value == null || value.Length == 0);
}
[Pure]
public static bool IsNullOrWhiteSpace(String value)
{
if (value == null) return true;
for (int i = 0; i < value.Length; i++)
{
if (!Char.IsWhiteSpace(value[i])) return false;
}
return true;
}
// Gets the length of this string
//
/// This is a EE implemented function so that the JIT can recognise is specially
/// and eliminate checks on character fetchs in a loop like:
/// for(int i = 0; i < str.Length; i++) str[i]
/// The actually code generated for this will be one instruction and will be inlined.
//
// Spec#: Add postcondition in a contract assembly. Potential perf problem.
public extern int Length
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
// Creates a new string with the characters copied in from ptr. If
// ptr is null, a 0-length string (like String.Empty) is returned.
//
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe public extern String(char* value);
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe public extern String(char* value, int startIndex, int length);
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe public extern String(sbyte* value);
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe public extern String(sbyte* value, int startIndex, int length);
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe public extern String(sbyte* value, int startIndex, int length, Encoding enc);
unsafe static private String CreateString(sbyte* value, int startIndex, int length, Encoding enc)
{
if (enc == null)
return new String(value, startIndex, length); // default to ANSI
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
if ((value + startIndex) < value)
{
// overflow check
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_PartialWCHAR);
}
byte[] b = new byte[length];
try
{
Buffer.Memcpy(b, 0, (byte*)value, startIndex, length);
}
catch (NullReferenceException)
{
// If we got a NullReferencException. It means the pointer or
// the index is out of range
throw new ArgumentOutOfRangeException(nameof(value),
SR.ArgumentOutOfRange_PartialWCHAR);
}
return enc.GetString(b);
}
// Helper for encodings so they can talk to our buffer directly
// stringLength must be the exact size we'll expect
unsafe static internal String CreateStringFromEncoding(
byte* bytes, int byteLength, Encoding encoding)
{
Contract.Requires(bytes != null);
Contract.Requires(byteLength >= 0);
// Get our string length
int stringLength = encoding.GetCharCount(bytes, byteLength, null);
Debug.Assert(stringLength >= 0, "stringLength >= 0");
// They gave us an empty string if they needed one
// 0 bytelength might be possible if there's something in an encoder
if (stringLength == 0)
return String.Empty;
String s = FastAllocateString(stringLength);
fixed (char* pTempChars = &s.m_firstChar)
{
int doubleCheck = encoding.GetChars(bytes, byteLength, pTempChars, stringLength, null);
Debug.Assert(stringLength == doubleCheck,
"Expected encoding.GetChars to return same length as encoding.GetCharCount");
}
return s;
}
// This is only intended to be used by char.ToString.
// It is necessary to put the code in this class instead of Char, since m_firstChar is a private member.
// Making m_firstChar internal would be dangerous since it would make it much easier to break String's immutability.
internal static string CreateFromChar(char c)
{
string result = FastAllocateString(1);
result.m_firstChar = c;
return result;
}
unsafe internal int GetBytesFromEncoding(byte* pbNativeBuffer, int cbNativeBuffer, Encoding encoding)
{
// encoding == Encoding.UTF8
fixed (char* pwzChar = &m_firstChar)
{
return encoding.GetBytes(pwzChar, m_stringLength, pbNativeBuffer, cbNativeBuffer);
}
}
unsafe internal int ConvertToAnsi(byte* pbNativeBuffer, int cbNativeBuffer, bool fBestFit, bool fThrowOnUnmappableChar)
{
Debug.Assert(cbNativeBuffer >= (Length + 1) * Marshal.SystemMaxDBCSCharSize, "Insufficient buffer length passed to ConvertToAnsi");
const uint CP_ACP = 0;
int nb;
const uint WC_NO_BEST_FIT_CHARS = 0x00000400;
uint flgs = (fBestFit ? 0 : WC_NO_BEST_FIT_CHARS);
uint DefaultCharUsed = 0;
fixed (char* pwzChar = &m_firstChar)
{
nb = Win32Native.WideCharToMultiByte(
CP_ACP,
flgs,
pwzChar,
this.Length,
pbNativeBuffer,
cbNativeBuffer,
IntPtr.Zero,
(fThrowOnUnmappableChar ? new IntPtr(&DefaultCharUsed) : IntPtr.Zero));
}
if (0 != DefaultCharUsed)
{
throw new ArgumentException(SR.Interop_Marshal_Unmappable_Char);
}
pbNativeBuffer[nb] = 0;
return nb;
}
// Normalization Methods
// These just wrap calls to Normalization class
public bool IsNormalized()
{
// Default to Form C
return IsNormalized(NormalizationForm.FormC);
}
public bool IsNormalized(NormalizationForm normalizationForm)
{
if (this.IsFastSort())
{
// If its FastSort && one of the 4 main forms, then its already normalized
if (normalizationForm == NormalizationForm.FormC ||
normalizationForm == NormalizationForm.FormKC ||
normalizationForm == NormalizationForm.FormD ||
normalizationForm == NormalizationForm.FormKD)
return true;
}
return Normalization.IsNormalized(this, normalizationForm);
}
public String Normalize()
{
// Default to Form C
return Normalize(NormalizationForm.FormC);
}
public String Normalize(NormalizationForm normalizationForm)
{
if (this.IsAscii())
{
// If its FastSort && one of the 4 main forms, then its already normalized
if (normalizationForm == NormalizationForm.FormC ||
normalizationForm == NormalizationForm.FormKC ||
normalizationForm == NormalizationForm.FormD ||
normalizationForm == NormalizationForm.FormKD)
return this;
}
return Normalization.Normalize(this, normalizationForm);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static String FastAllocateString(int length);
// Creates a new string from the characters in a subarray. The new string will
// be created from the characters in value between startIndex and
// startIndex + length - 1.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(char[] value, int startIndex, int length);
// Creates a new string from the characters in a subarray. The new string will be
// created from the characters in value.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(char[] value);
internal static unsafe void wstrcpy(char* dmem, char* smem, int charCount)
{
Buffer.Memcpy((byte*)dmem, (byte*)smem, charCount * 2); // 2 used everywhere instead of sizeof(char)
}
private String CtorCharArray(char[] value)
{
if (value != null && value.Length != 0)
{
String result = FastAllocateString(value.Length);
unsafe
{
fixed (char* dest = &result.m_firstChar, source = value)
{
wstrcpy(dest, source, value.Length);
}
}
return result;
}
else
return String.Empty;
}
private String CtorCharArrayStartLength(char[] value, int startIndex, int length)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
if (startIndex > value.Length - length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
if (length > 0)
{
String result = FastAllocateString(length);
unsafe
{
fixed (char* dest = &result.m_firstChar, source = value)
{
wstrcpy(dest, source + startIndex, length);
}
}
return result;
}
else
return String.Empty;
}
private String CtorCharCount(char c, int count)
{
if (count > 0)
{
String result = FastAllocateString(count);
if (c != 0)
{
unsafe
{
fixed (char* dest = &result.m_firstChar)
{
char* dmem = dest;
while (((uint)dmem & 3) != 0 && count > 0)
{
*dmem++ = c;
count--;
}
uint cc = (uint)((c << 16) | c);
if (count >= 4)
{
count -= 4;
do
{
((uint*)dmem)[0] = cc;
((uint*)dmem)[1] = cc;
dmem += 4;
count -= 4;
} while (count >= 0);
}
if ((count & 2) != 0)
{
((uint*)dmem)[0] = cc;
dmem += 2;
}
if ((count & 1) != 0)
dmem[0] = c;
}
}
}
return result;
}
else if (count == 0)
return String.Empty;
else
throw new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ArgumentOutOfRange_MustBeNonNegNum, nameof(count)));
}
internal static unsafe int wcslen(char* ptr)
{
char* end = ptr;
// First make sure our pointer is aligned on a word boundary
int alignment = IntPtr.Size - 1;
// If ptr is at an odd address (e.g. 0x5), this loop will simply iterate all the way
while (((uint)end & (uint)alignment) != 0)
{
if (*end == 0) goto FoundZero;
end++;
}
#if !BIT64
// The following code is (somewhat surprisingly!) significantly faster than a naive loop,
// at least on x86 and the current jit.
// The loop condition below works because if "end[0] & end[1]" is non-zero, that means
// neither operand can have been zero. If is zero, we have to look at the operands individually,
// but we hope this going to fairly rare.
// In general, it would be incorrect to access end[1] if we haven't made sure
// end[0] is non-zero. However, we know the ptr has been aligned by the loop above
// so end[0] and end[1] must be in the same word (and therefore page), so they're either both accessible, or both not.
while ((end[0] & end[1]) != 0 || (end[0] != 0 && end[1] != 0)) {
end += 2;
}
Debug.Assert(end[0] == 0 || end[1] == 0);
if (end[0] != 0) end++;
#else // !BIT64
// Based on https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord
// 64-bit implementation: process 1 ulong (word) at a time
// What we do here is add 0x7fff from each of the
// 4 individual chars within the ulong, using MagicMask.
// If the char > 0 and < 0x8001, it will have its high bit set.
// We then OR with MagicMask, to set all the other bits.
// This will result in all bits set (ulong.MaxValue) for any
// char that fits the above criteria, and something else otherwise.
// Note that for any char > 0x8000, this will be a false
// positive and we will fallback to the slow path and
// check each char individually. This is OK though, since
// we optimize for the common case (ASCII chars, which are < 0x80).
// NOTE: We can access a ulong a time since the ptr is aligned,
// and therefore we're only accessing the same word/page. (See notes
// for the 32-bit version above.)
const ulong MagicMask = 0x7fff7fff7fff7fff;
while (true)
{
ulong word = *(ulong*)end;
word += MagicMask; // cause high bit to be set if not zero, and <= 0x8000
word |= MagicMask; // set everything besides the high bits
if (word == ulong.MaxValue) // 0xffff...
{
// all of the chars have their bits set (and therefore none can be 0)
end += 4;
continue;
}
// at least one of them didn't have their high bit set!
// go through each char and check for 0.
if (end[0] == 0) goto EndAt0;
if (end[1] == 0) goto EndAt1;
if (end[2] == 0) goto EndAt2;
if (end[3] == 0) goto EndAt3;
// if we reached here, it was a false positive-- just continue
end += 4;
}
EndAt3: end++;
EndAt2: end++;
EndAt1: end++;
EndAt0:
#endif // !BIT64
FoundZero:
Debug.Assert(*end == 0);
int count = (int)(end - ptr);
return count;
}
private unsafe String CtorCharPtr(char* ptr)
{
if (ptr == null)
return String.Empty;
#if !FEATURE_PAL
if (ptr < (char*)64000)
throw new ArgumentException(SR.Arg_MustBeStringPtrNotAtom);
#endif // FEATURE_PAL
Debug.Assert(this == null, "this == null"); // this is the string constructor, we allocate it
try
{
int count = wcslen(ptr);
if (count == 0)
return String.Empty;
String result = FastAllocateString(count);
fixed (char* dest = &result.m_firstChar)
wstrcpy(dest, ptr, count);
return result;
}
catch (NullReferenceException)
{
throw new ArgumentOutOfRangeException(nameof(ptr), SR.ArgumentOutOfRange_PartialWCHAR);
}
}
private unsafe String CtorCharPtrStartLength(char* ptr, int startIndex, int length)
{
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
}
if (startIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
}
Contract.EndContractBlock();
Debug.Assert(this == null, "this == null"); // this is the string constructor, we allocate it
char* pFrom = ptr + startIndex;
if (pFrom < ptr)
{
// This means that the pointer operation has had an overflow
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_PartialWCHAR);
}
if (length == 0)
return String.Empty;
String result = FastAllocateString(length);
try
{
fixed (char* dest = &result.m_firstChar)
wstrcpy(dest, pFrom, length);
return result;
}
catch (NullReferenceException)
{
throw new ArgumentOutOfRangeException(nameof(ptr), SR.ArgumentOutOfRange_PartialWCHAR);
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(char c, int count);
// Returns this string.
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
return this;
}
public String ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
return this;
}
// Method required for the ICloneable interface.
// There's no point in cloning a string since they're immutable, so we simply return this.
public Object Clone()
{
Contract.Ensures(Contract.Result<Object>() != null);
Contract.EndContractBlock();
return this;
}
unsafe public static String Copy(String str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
int length = str.Length;
String result = FastAllocateString(length);
fixed (char* dest = &result.m_firstChar)
fixed (char* src = &str.m_firstChar)
{
wstrcpy(dest, src, length);
}
return result;
}
public static String Intern(String str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
Contract.Ensures(Contract.Result<String>().Length == str.Length);
Contract.Ensures(str.Equals(Contract.Result<String>()));
Contract.EndContractBlock();
return Thread.GetDomain().GetOrInternString(str);
}
[Pure]
public static String IsInterned(String str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
Contract.Ensures(Contract.Result<String>() == null || Contract.Result<String>().Length == str.Length);
Contract.EndContractBlock();
return Thread.GetDomain().IsStringInterned(str);
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.String;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(this, provider);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(this, provider);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(this, provider);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(this, provider);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(this, provider);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(this, provider);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(this, provider);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(this, provider);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(this, provider);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(this, provider);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(this, provider);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(this, provider);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(this, provider);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
return Convert.ToDateTime(this, provider);
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
// Is this a string that can be compared quickly (that is it has only characters > 0x80
// and not a - or '
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern bool IsFastSort();
// Is this a string that only contains characters < 0x80.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern bool IsAscii();
#if FEATURE_COMINTEROP
// Set extra byte for odd-sized strings that came from interop as BSTR.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void SetTrailByte(byte data);
// Try to retrieve the extra byte - returns false if not present.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern bool TryGetTrailByte(out byte data);
#endif
public CharEnumerator GetEnumerator()
{
Contract.Ensures(Contract.Result<CharEnumerator>() != null);
Contract.EndContractBlock();
BCLDebug.Perf(false, "Avoid using String's CharEnumerator until C# special cases foreach on String - use the indexed property on String instead.");
return new CharEnumerator(this);
}
IEnumerator<char> IEnumerable<char>.GetEnumerator()
{
Contract.Ensures(Contract.Result<IEnumerator<char>>() != null);
Contract.EndContractBlock();
BCLDebug.Perf(false, "Avoid using String's CharEnumerator until C# special cases foreach on String - use the indexed property on String instead.");
return new CharEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
Contract.Ensures(Contract.Result<IEnumerator>() != null);
Contract.EndContractBlock();
BCLDebug.Perf(false, "Avoid using String's CharEnumerator until C# special cases foreach on String - use the indexed property on String instead.");
return new CharEnumerator(this);
}
// Copies the source String (byte buffer) to the destination IntPtr memory allocated with len bytes.
internal unsafe static void InternalCopy(String src, IntPtr dest, int len)
{
if (len == 0)
return;
fixed (char* charPtr = &src.m_firstChar)
{
byte* srcPtr = (byte*)charPtr;
byte* dstPtr = (byte*)dest;
Buffer.Memcpy(dstPtr, srcPtr, len);
}
}
internal ref char GetRawStringData()
{
return ref m_firstChar;
}
}
}
| |
using GuruComponents.Netrix.ComInterop;
using GuruComponents.Netrix.Events;
using GuruComponents.Netrix.WebEditing.Behaviors;
using GuruComponents.Netrix.WebEditing.Styles;
using System.Collections;
namespace GuruComponents.Netrix.WebEditing.Elements
{
/// <summary>
/// The base interface for all HTML elements.
/// </summary>
public interface IElement
{
/// <summary>
/// Contains the HTML cascading-style sheets (CSS) inline style attributes for a specified HTML server control. This class cannot be inherited.
/// </summary>
System.Web.UI.CssStyleCollection Style { get; set; }
# region Events
/// <summary>
/// Fired if the user clicks on the element loses its mouse capture.
/// </summary>
event GuruComponents.Netrix.Events.DocumentEventHandler LoseCapture;
/// <summary>
/// Fired if the user clicks on the element in design mode.
/// </summary>
event DocumentEventHandler Click;
/// <summary>
/// Fired if the user double clicks on the element in design mode.
/// </summary>
event DocumentEventHandler DblClick;
/// <summary>
/// Fired if the user starts dragging the in design mode.
/// </summary>
event DocumentEventHandler DragStart;
/// <summary>
/// Fired if the elemens receives the focus.
/// </summary>
event DocumentEventHandler Focus;
/// <summary>
/// Fired if the elemens receives the focus.
/// </summary>
event DocumentEventHandler Drop;
/// <summary>
/// Fired if the elemens receives the focus.
/// </summary>
event DocumentEventHandler Blur;
/// <summary>
/// Fired if the elemens receives the focus.
/// </summary>
event DocumentEventHandler DragOver;
/// <summary>
/// Fired if the elemens receives the focus.
/// </summary>
event DocumentEventHandler DragEnter;
/// <summary>
/// Fired if the elemens receives the focus.
/// </summary>
event DocumentEventHandler DragLeave;
/// <summary>
/// Fired if the user hits a key down on the element in design mode.
/// </summary>
event DocumentEventHandler KeyDown;
/// <summary>
/// Fired if the user pressed a key element in design mode.
/// </summary>
event DocumentEventHandler KeyPress;
/// <summary>
/// Fired if the user hits and releases a key on the element in design mode.
/// </summary>
event DocumentEventHandler KeyUp;
/// <summary>
/// Fired if the user clicks a mouse button on the element in design mode.
/// </summary>
event DocumentEventHandler MouseDown;
/// <summary>
/// Sets or removes an event handler function that fires when the user begins to change the dimensions of the object.
/// </summary>
/// <remarks>
/// This event handler will not suppress the embedded resizing behavior.
/// </remarks>
event DocumentEventHandler ResizeStart;
/// <summary>
/// Sets or removes an event handler function that fires when the user has finished changing the dimensions of the object.
/// </summary>
/// <remarks>
/// This event handler will not suppress the embedded resizing behavior.
/// </remarks>
event DocumentEventHandler ResizeEnd;
/// <summary>
/// Sets or removes an event handler function that fires when the user moves the mouse pointer into the object.
/// </summary>
/// <remarks>
/// Unlike the MouseOver event, the MouseEnter event does not bubble. In other words, the MouseEnter
/// event does not fire when the user moves the mouse pointer over elements contained by the object,
/// whereas <see cref="MouseOver">MouseOver</see> does fire.
/// </remarks>
event DocumentEventHandler MouseEnter;
/// <summary>
/// Sets or retrieves a pointer to the event handler function that fires, when the user moves the mouse pointer outside
/// the boundaries of the object.</summary>
/// <remarks>Use in correspondence to OnMouseEnter.</remarks>
event DocumentEventHandler MouseLeave;
/// <summary>
/// Fired if the user moves the mouse over the element area in design mode.
/// </summary>
event DocumentEventHandler MouseMove;
/// <summary>
/// Fired if the user mouse has left the element area with the mouse in design mode.
/// </summary>
/// <example>
/// To use this event to show the content of a link the mouse pointer is over, use this code:
/// <code>
/// ArrayList anchors = this.htmlEditor2.DocumentProperties.GetElementCollection("A") as ArrayList;
/// if (anchors != null)
/// {
/// foreach (AnchorElement a in anchors)
/// {
/// a.OnMouseOver -= new GuruComponents.Netrix.Events.DocumentEventHandler(a_OnMouseOver);
/// a.OnMouseOver += new GuruComponents.Netrix.Events.DocumentEventHandler(a_OnMouseOver);
/// a.OnMouseOut -= new GuruComponents.Netrix.Events.DocumentEventHandler(a_OnMouseOut);
/// a.OnMouseOut += new GuruComponents.Netrix.Events.DocumentEventHandler(a_OnMouseOut);
/// }
/// }</code>
/// Place this code in the <see cref="GuruComponents.Netrix.IHtmlEditor.ReadyStateComplete">ReadyStateComplete</see> event.
/// The handler are now able to do something with the element.
/// <code>
///private void a_OnMouseOut(GuruComponents.Netrix.Events.DocumentEventArgs e)
///{
/// AnchorElement a = e.SrcElement as AnchorElement;
/// if (a != null)
/// {
/// this.statusBarPanelLinks.Text = "";
/// }
///}</code>
/// <code>
///private void a_OnMouseOver(GuruComponents.Netrix.Events.DocumentEventArgs e)
///{
/// AnchorElement a = e.SrcElement as AnchorElement;
/// if (a != null)
/// {
/// this.statusBarPanelLinks.Text = a.href;
/// }
///}</code>
/// </example>
event DocumentEventHandler MouseOut;
/// <summary>
/// Fired if the user has entered the element area with the mouse in design mode.
/// </summary>
/// <example>
/// To use this event to show the content of a link the mouse pointer is over, use this code:
/// <code>
/// ArrayList anchors = this.htmlEditor2.DocumentProperties.GetElementCollection("A") as ArrayList;
/// if (anchors != null)
/// {
/// foreach (AnchorElement a in anchors)
/// {
/// a.OnMouseOver -= new GuruComponents.Netrix.Events.DocumentEventHandler(a_OnMouseOver);
/// a.OnMouseOver += new GuruComponents.Netrix.Events.DocumentEventHandler(a_OnMouseOver);
/// a.OnMouseOut -= new GuruComponents.Netrix.Events.DocumentEventHandler(a_OnMouseOut);
/// a.OnMouseOut += new GuruComponents.Netrix.Events.DocumentEventHandler(a_OnMouseOut);
/// }
/// }</code>
/// Place this code in the <see cref="IHtmlEditor.ReadyStateComplete">ReadyStateComplete</see> event.
/// The handler are now able to do something with the element.
/// <code>
///private void a_OnMouseOut(GuruComponents.Netrix.Events.DocumentEventArgs e)
///{
/// AnchorElement a = e.SrcElement as AnchorElement;
/// if (a != null)
/// {
/// this.statusBarPanelLinks.Text = "";
/// }
///}</code>
/// <code>
///private void a_OnMouseOver(GuruComponents.Netrix.Events.DocumentEventArgs e)
///{
/// AnchorElement a = e.SrcElement as AnchorElement;
/// if (a != null)
/// {
/// this.statusBarPanelLinks.Text = a.href;
/// }
///}</code>
/// </example>
event DocumentEventHandler MouseOver;
/// <summary>
/// Fired if the user releases the mouse button over the element area in design mode.
/// </summary>
event DocumentEventHandler MouseUp;
/// <summary>
/// Fired if the user starts selecting the element area in design mode.
/// </summary>
event DocumentEventHandler SelectStart;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler LayoutComplete;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler Load;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler MouseWheel;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler MoveEnd;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler MoveStart;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler Activate;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler BeforeActivate;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler BeforeCopy;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler BeforeCut;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler BeforePaste;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler ContextMenu;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler Copy;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler Cut;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler Deactivate;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler Drag;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler DragEnd;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler FocusIn;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler FocusOut;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler FilterChange;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler Abort;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler Change;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler Select;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler SelectionChange;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler Stop;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler BeforeDeactivate;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler ControlSelect;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler EditFocus;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler Error;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler Move;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler Paste;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler PropertyChange;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler Resize;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler Scroll;
/// <summary>
/// Fired if the underlying event is being received.
/// </summary>
event DocumentEventHandler Paged;
# endregion
/// <summary>
/// Access to several extended properties an element can provide.
/// </summary>
IExtendedProperties ExtendedProperties { get; }
/// <summary>
/// Returns the unique name which is used to hold the element in the designer environment.
/// </summary>
string UniqueName
{
get;
}
/// <summary>
/// Returns <c>true</c> if the element is selectable.
/// </summary>
/// <returns></returns>
bool IsSelectable();
/// <summary>
/// Gets true if the element can positioned freely on the surface by using the mouse.
/// </summary>
bool IsAbsolutePositioned
{
get;
}
/// <summary>
/// Gets <c>true</c> if the element is in text editing mode.
/// </summary>
bool IsTextEdit
{
get;
}
/// <summary>
/// Inserts an element at the specified location.
/// </summary>
/// <param name="method">Specifies where to insert the HTML element.</param>
/// <param name="element">Element to be inserted adjacent to the object.</param>
void InsertAdjacentElement(InsertWhere method, IElement element);
/// <summary>
/// Inserts the given HTML text into the element at the location.
/// </summary>
/// <param name="method"></param>
/// <param name="html"></param>
void InsertAdjacentHtml(InsertWhere method, string html);
/// <summary>
/// Inserts the given text into the element at the specified location.
/// </summary>
/// <param name="method">Specifies where to insert the text.</param>
/// <param name="text"></param>
void InsertAdjacentText(InsertWhere method, string text);
/// <summary>
/// Returns the absolute coordinates of the element in pixel.
/// </summary>
/// <remarks>
/// This method works even for non absolute positioned elements. Some elements, which have no rectangle
/// dimensions, may fail returning any useful values.
/// </remarks>
/// <returns>A rectangle which describes the dimensions of the client area of the element.</returns>
System.Drawing.Rectangle GetAbsoluteArea();
/// <summary>
/// Returns the base COM element object.
/// </summary>
/// <returns></returns>
Interop.IHTMLElement GetBaseElement();
/// <summary>
/// Reference to the editor that this elements belongs to.
/// </summary>
IHtmlEditor HtmlEditor { get; set; }
/// <summary>
/// Gets or sets explicitly the design mode for this element.
/// </summary>
/// <value>Setting to true will set the attribute "contentEditable", which is visible in the documents DOM.
/// Returning the value false means that the mode is not explicitly set but may be inherited. Setting a
/// parent to ContentEditable will not change the value for the children, but in fact, they are now editable.
/// </value>
bool ContentEditable { get; set; }
/// <summary>
/// The element with this property set to TRUE will be selectable only as a unit.
/// </summary>
/// <remarks>
/// This property is only available
/// </remarks>
bool AtomicSelection { get; set; }
/// <summary>
/// Makes the element unselectable, so the user cannot activate it for resizing or moving.
/// </summary>
/// <remarks>
/// The property is ignored if the element is already an unselectable element. Only block elements
/// like DIV, TABLE, and IMG can be selectable.
/// </remarks>
bool Unselectable { get; set; }
/// <summary>
/// Access to the element's behavior
/// </summary>
IElementBehavior ElementBehaviors
{
get;
}
// /// <summary>
// /// This property contains the root of the project, where the file containing
// /// the element belongs to.
// /// </summary>
// /// <remarks>
// /// This property is set internally when the control loads either HTML from a string and the
// /// app gives the path or when it loads from a file. If none of these option happens the
// /// property is set to an empty string.
// /// </remarks>
// string AppRootPath
// {
// get;
// }
/// <summary>
/// Gets or sets inner html of the element.
/// </summary>
/// <remarks>
/// The inner html is the complete content between the opening and the closing tag.
/// If the element is not a container element the property will return <see cref="System.String.Empty">String.Empty</see>.
/// Any HTML is returned "as is", with the braces and tag names.
/// </remarks>
string InnerHtml
{
get; set;
}
/// <summary>
/// Gets or sets outer html of the element.
/// </summary>
/// <remarks>
/// The outer html is the complete content including the opening and the closing tag and their braces.
/// </remarks>
string OuterHtml
{
get; set;
}
/// <summary>
/// Gets or sets the inner text of the element.
/// </summary>
/// <remarks>
/// The inner text is the complete content between the opening and the closing tag, with any HTML tags
/// stripped out.
/// If the element is not a container element the property will return <see cref="System.String.Empty">String.Empty</see>.
/// Any HTML is returned "as is", with the braces and tag names.
/// </remarks>
string InnerText
{
get; set;
}
/// <summary>
/// The name of the element.
/// </summary>
/// <remarks>
/// Used to reference the element if it is still unknown after a insertion operation.
/// This property should work even if there is no native class available. It does not work
/// reliable if an element is not HTML 4.0 compliant.
/// </remarks>
string TagName
{
get;
}
/// <summary>
/// Gives direct access to the element object from datasource or collection based lists.
/// </summary>
/// <remarks>
/// Used for lists which needs a property to access collection members for displaying purposes. To
/// prevent such lists from deleting the object we send only a shallow copy clone. This
/// allows the caller to change all properties but deleting does not modify the DOM.
/// </remarks>
IElement TagElement
{
get;
}
/// <summary>
///
/// </summary>
string Alias
{
get;
}
/// <summary>
///
/// </summary>
string ElementName
{
get;
}
/// <overloads>This method has two overloads.</overloads>
/// <summary>
/// Returns the child at the give index. </summary>
/// <remarks>If a element has 4 children they are indexed zero based.
/// </remarks>
/// <param name="index">The Number of child in the children collection.</param>
/// <returns>Returns the base class of child element or <c>null</c>, if the index was not found.</returns>
System.Web.UI.Control GetChild(int index);
/// <summary>
/// The child of the element or null if it does not have children.
/// </summary>
/// <remarks>
/// This method will return the next child with the given tag name in the collection of children.
/// </remarks>
/// <param name="name">Tag name of the child we are searching for.</param>
/// <returns>Returns the base class of child element or <c>null</c>, if the name was not found.</returns>
System.Web.UI.Control GetChild(string name);
/// <summary>
/// Returns the collection of children of the element.
/// </summary>
/// <remarks>
/// The returned collection will always beeing created, but it could be empty if there are
/// no children.
/// </remarks>
/// <returns>Collection of elements of type IElement.</returns>
ElementCollection GetChildren();
/// <summary>
/// The parent of the current element or null if no parent.
/// </summary>
/// <returns>Returns the base class of child element or <c>null</c>, if there was no parent element.</returns>
System.Web.UI.Control GetParent();
/// <summary>
/// String represention of the element.
/// </summary>
/// <returns>Tag form of element without attributes</returns>
string ToString();
/// <summary>
/// This method return the complete CSS inline definition, which the style attribute contains.
/// </summary>
/// <remarks>
/// For easy access to specific styles it is recommended to use the
/// <see cref="GuruComponents.Netrix.WebEditing.Elements.IElement.GetStyleAttribute">GetStyleAttribute</see> and
/// <see cref="GuruComponents.Netrix.WebEditing.Elements.IElement.SetStyleAttribute">SetStyleAttribute</see>
/// methods. This and both alternative methods will check the content and cannot assign values not
/// processed by the Internet Explorer Engine. The final behavior may vary depending on the currently
/// installed IE engine.
/// </remarks>
/// <returns>Returns the complete style text (all rules) as one string.</returns>
string GetStyle();
/// <summary>
/// Set the current style by overwriting the complete content of the style attribute.
/// </summary>
/// <param name="CssText">The style text; should be CSS compliant.</param>
void SetStyle(string CssText);
/// <summary>
/// Gets a specific part of an inline style.
/// </summary>
/// <param name="styleName">The style attribute to retrieve</param>
/// <returns>The string representation of the style. Returns <see cref="System.String.Empty"/> if the
/// style does not exists.</returns>
string GetStyleAttribute(string styleName);
/// <summary>
/// Sets a specific part of an inline style.
/// </summary>
/// <remarks>
/// Setting to <seealso cref="System.String.Empty">String.Empty</seealso> does remove
/// the style name. For a more intuitive way use <see cref="RemoveStyleAttribute">RemoveStyleAttribute</see> instead.
/// Setting impossible rule texts will either ignore the command or set unexpected values.
/// </remarks>
/// <param name="styleName">The name of the style rule beeing set, e.g. "font-family".</param>
/// <param name="styleText">The rule content, like "Verdana,Arial" for the "font-family" rule.</param>
void SetStyleAttribute(string styleName, string styleText);
/// <summary>
/// Removes an style attribute and his content from the inline style string.
/// </summary>
/// <param name="styleName">Name of style to be removed</param>
void RemoveStyleAttribute(string styleName);
/// <summary>
/// Sets an attribute to a specific value.
/// </summary>
/// <remarks>
/// The command may does nothing if the value does not correspond with the attribute. E.g. it
/// is almost impossible to write a pixel value if the attribute expects a font name.
/// </remarks>
/// <param name="attribute">The name of the attribute.</param>
/// <param name="value">The value beeing written.</param>
void SetAttribute(string attribute, object value);
/// <summary>
/// Remove the give attribute from element.
/// </summary>
/// <param name="attribute">The name of the attribute which is about to be removed. Case insensitive.</param>
void RemoveAttribute(string attribute);
/// <summary>
/// Universal access to any attribute.
/// </summary>
/// <remarks>
/// The type returned may vary depended on the internal type.
/// </remarks>
/// <param name="attribute">The name of the attribute.</param>
/// <returns>The object which is the value of the attribute.</returns>
object GetAttribute(string attribute);
/// <summary>
/// Returns the DOM access to the element.
/// </summary>
/// <returns>The DOM representation of the element.</returns>
IElementDom ElementDom { get; }
/// <summary>
/// Gets the current effective style, including styles defines internally, in linked sheets as well as through HTML.
/// </summary>
/// <remarks>
/// This property shows the effective style if this element as a cascade of the global
/// and inline styles defined elsewhere. Readonly.
/// <para>
/// The property returns <c>null</c> (<c>Nothing</c> in VB.NET) if the effective style can not be retrieved.
/// <para>See implementing classes for details</para>
/// </para>
/// <seealso cref="RuntimeStyle"/>
/// <seealso cref="CurrentStyle"/>
/// </remarks>
IEffectiveStyle EffectiveStyle { get; }
/// <summary>
/// Gets the current element's runtime style definition and allows interactive access.
/// </summary>
/// <remarks>
/// This property allows access to styles not being persistent within the document. They affect only at runtime
/// and can change the current appearance of an object. One can use this to add specific effects during user
/// operation of to customize elements in particular situations.
/// <para>See implementing classes for details</para>
/// <seealso cref="EffectiveStyle"/>
/// <seealso cref="CurrentStyle"/>
/// <seealso cref="SetStyleAttribute"/>
/// <seealso cref="RemoveStyleAttribute"/>
/// <seealso cref="GetStyleAttribute"/>
/// </remarks>
IElementStyle RuntimeStyle { get; }
/// <summary>
/// Access to the style attribute in an object form.
/// </summary>
/// <para>See implementing classes for details</para>
/// <seealso cref="EffectiveStyle"/>
/// <seealso cref="RuntimeStyle"/>
/// <seealso cref="SetStyleAttribute"/>
/// <seealso cref="RemoveStyleAttribute"/>
/// <seealso cref="GetStyleAttribute"/>
IElementStyle CurrentStyle { get; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using App.Models;
using App.Models.Identity;
using App.Data;
using App.WWW.Services;
using App.WWW.ViewModels.Account;
namespace App.WWW.Controllers
{
[Authorize]
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly LibraryDbContext _applicationDbContext;
private static bool _databaseChecked;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
LibraryDbContext applicationDbContext)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_applicationDbContext = applicationDbContext;
}
//
// GET: /Account/Login
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByNameAsync(model.Email);
if(user == null)
{
user = await _userManager.FindByEmailAsync(model.Email);
}
if(user != null)
{
var result = await _signInManager.PasswordSignInAsync(user, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
}
}
else
{
ModelState.AddModelError("", "Invalid username or email.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/Register
[HttpGet]
[AllowAnonymous]
public IActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model)
{
EnsureDatabaseCreated(_applicationDbContext);
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
//var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
// "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(HomeController.Index), "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LogOff()
{
await _signInManager.SignOutAsync();
return RedirectToAction(nameof(HomeController.Index), "Home");
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
EnsureDatabaseCreated(_applicationDbContext);
// Request a redirect to the external login provider.
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return new ChallengeResult(provider, properties);
}
//
// GET: /Account/ExternalLoginCallback
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null)
{
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction(nameof(Login));
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
// If the user does not have an account, then ask the user to create an account.
ViewData["ReturnUrl"] = returnUrl;
ViewData["LoginProvider"] = info.LoginProvider;
var email = info.ExternalPrincipal.FindFirstValue(ClaimTypes.Email);
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
{
if (User.IsSignedIn())
{
return RedirectToAction(nameof(ManageController.Index),"Manage");
}
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
// GET: /Account/ConfirmEmail
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var result = await _userManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GeneratePasswordResetTokenAsync(user);
//var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Reset Password",
// "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>");
//return View("ForgotPasswordConfirmation");
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPasswordConfirmation()
{
return View();
}
//
// GET: /Account/ResetPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPassword(string code = null)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
AddErrors(result);
return View();
}
//
// GET: /Account/ResetPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPasswordConfirmation()
{
return View();
}
//
// GET: /Account/SendCode
[HttpGet]
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false)
{
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
// Generate the token and send it
var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
if (string.IsNullOrWhiteSpace(code))
{
return View("Error");
}
var message = "Your security code is: " + code;
if (model.SelectedProvider == "Email")
{
await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message);
}
else if (model.SelectedProvider == "Phone")
{
await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message);
}
return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/VerifyCode
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
{
// Require that the user has already logged in via username/password or external login
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
if (result.Succeeded)
{
return RedirectToLocal(model.ReturnUrl);
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
ModelState.AddModelError("", "Invalid code.");
return View(model);
}
}
#region Helpers
// The following code creates the database and schema if they don't exist.
// This is a temporary workaround since deploying database through EF migrations is
// not yet supported in this release.
// Please see this http://go.microsoft.com/fwlink/?LinkID=615859 for more information on how to do deploy the database
// when publishing your application.
private static void EnsureDatabaseCreated(LibraryDbContext context)
{
if (!_databaseChecked)
{
_databaseChecked = true;
context.Database.Migrate();
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private async Task<ApplicationUser> GetCurrentUserAsync()
{
return await _userManager.FindByIdAsync(HttpContext.User.GetUserId());
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
#endregion
}
}
| |
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2011-2012 openxlive.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.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace CocosSharp
{
public class CCLayer : CCNode
{
public static CCCameraProjection DefaultCameraProjection = CCCameraProjection.Projection3D;
// A delegate type for hooking up Layer Visible Bounds change notifications.
internal delegate void LayerVisibleBoundsChangedEventHandler(object sender, EventArgs e);
internal event LayerVisibleBoundsChangedEventHandler LayerVisibleBoundsChanged;
bool restoreScissor;
bool noDrawChildren;
CCCameraProjection initCameraProjection;
CCRect visibleBoundsWorldspace;
CCRenderTexture renderTexture;
CCClipMode childClippingMode;
CCCamera camera;
CCRenderCommand beforeDrawCommand;
CCRenderCommand afterDrawCommand;
#region Properties
public override CCLayer Layer
{
get { return this; }
internal set
{
}
}
public override CCCamera Camera
{
get { return camera; }
set
{
if (camera != value)
{
// Stop listening to previous camera's event
if (camera != null)
{
camera.OnCameraVisibleBoundsChanged -=
new CocosSharp.CCCamera.CameraVisibleBoundsChangedEventHandler(OnCameraVisibleBoundsChanged);
}
camera = value;
if (camera != null)
{
camera.OnCameraVisibleBoundsChanged +=
new CocosSharp.CCCamera.CameraVisibleBoundsChangedEventHandler(OnCameraVisibleBoundsChanged);
OnCameraVisibleBoundsChanged(camera, null);
}
}
}
}
/// <summary>
/// Set to true if the child drawing should be isolated in their own render target
/// </summary>
public CCClipMode ChildClippingMode
{
get { return childClippingMode; }
set
{
if (childClippingMode != value)
{
childClippingMode = value;
UpdateClipping();
}
}
}
public new CCRect VisibleBoundsWorldspace
{
get { return visibleBoundsWorldspace; }
}
public CCSize LayerSizeInPixels
{
get { return Viewport != null ? Viewport.ViewportInPixels.Size : CCSize.Zero; }
}
// Layer should have fixed size of content
public override CCSize ContentSize
{
get { return VisibleBoundsWorldspace.Size; }
set
{ }
}
public override CCAffineTransform AffineLocalTransform
{
get
{
return CCAffineTransform.Identity;
}
}
#endregion Properties
#region Constructors
public CCLayer()
: this(DefaultCameraProjection)
{
}
public CCLayer(CCSize visibleBoundsDimensions,
CCClipMode clipMode = CCClipMode.None)
: this(visibleBoundsDimensions, DefaultCameraProjection, clipMode)
{
}
public CCLayer(CCSize visibleBoundsDimensions,
CCCameraProjection cameraProjection,
CCClipMode clipMode = CCClipMode.None)
: this(new CCCamera(cameraProjection, visibleBoundsDimensions), clipMode)
{
}
public CCLayer(CCCamera camera, CCClipMode clipMode = CCClipMode.None)
: this(camera.Projection, clipMode)
{
Camera = camera;
}
public CCLayer(CCCameraProjection cameraProjection, CCClipMode clipMode = CCClipMode.None)
: base()
{
beforeDrawCommand = new CCCustomCommand(BeforeDraw);
afterDrawCommand = new CCCustomCommand(AfterDraw);
ChildClippingMode = clipMode;
IgnoreAnchorPointForPosition = true;
AnchorPoint = CCPoint.AnchorMiddle;
initCameraProjection = cameraProjection;
}
void UpdateClipping()
{
if (ChildClippingMode == CCClipMode.BoundsWithRenderTarget && Scene !=null)
{
CCRect bounds = VisibleBoundsWorldspace;
CCRect viewportRect = Viewport.ViewportInPixels;
renderTexture = new CCRenderTexture(bounds.Size, viewportRect.Size);
renderTexture.Sprite.AnchorPoint = new CCPoint(0, 0);
}
else
{
renderTexture = null;
}
}
#endregion Constructors
#region Content layout
protected override void AddedToScene()
{
base.AddedToScene();
if(Camera == null)
{
Camera = new CCCamera (initCameraProjection, Scene.DesignResolutionSize);
}
}
void OnCameraVisibleBoundsChanged(object sender, EventArgs e)
{
CCCamera camera = sender as CCCamera;
if(camera != null && camera == Camera && Scene != null)
{
VisibleBoundsChanged();
if (LayerVisibleBoundsChanged != null)
LayerVisibleBoundsChanged(this, null);
}
}
protected override void VisibleBoundsChanged()
{
base.VisibleBoundsChanged();
UpdateVisibleBoundsRect();
UpdateClipping();
}
protected override void ViewportChanged()
{
base.ViewportChanged();
UpdateVisibleBoundsRect();
UpdateClipping();
}
internal void UpdateVisibleBoundsRect()
{
if(Viewport == null || Camera == null || Viewport.ViewportInPixels == CCRect.Zero)
return;
if (Camera.Projection == CCCameraProjection.Projection2D && Camera.OrthographicViewSizeWorldspace == CCSize.Zero)
return;
var viewportRectInPixels = Viewport.ViewportInPixels;
// Want to determine worldspace bounds relative to camera target
// Need to first find z screenspace coord of target
CCPoint3 target = Camera.TargetInWorldspace;
Vector3 targetVec = new Vector3(0.0f, 0.0f, target.Z);
targetVec = Viewport.XnaViewport.Project(targetVec, Camera.ProjectionMatrix, Camera.ViewMatrix, Matrix.Identity);
Vector3 topLeft = new Vector3(viewportRectInPixels.Origin.X, viewportRectInPixels.Origin.Y, targetVec.Z);
Vector3 topRight = new Vector3(viewportRectInPixels.Origin.X + viewportRectInPixels.Size.Width, viewportRectInPixels.Origin.Y, targetVec.Z);
Vector3 bottomLeft = new Vector3(viewportRectInPixels.Origin.X, viewportRectInPixels.Origin.Y + viewportRectInPixels.Size.Height, targetVec.Z);
Vector3 bottomRight = new Vector3(viewportRectInPixels.Origin.X + viewportRectInPixels.Size.Width, viewportRectInPixels.Origin.Y + viewportRectInPixels.Size.Height, targetVec.Z);
// Convert screen space to worldspace. Note screenspace origin is in topleft part of viewport
topLeft = Viewport.XnaViewport.Unproject(topLeft, Camera.ProjectionMatrix, Camera.ViewMatrix, Matrix.Identity);
topRight = Viewport.XnaViewport.Unproject(topRight, Camera.ProjectionMatrix, Camera.ViewMatrix, Matrix.Identity);
bottomLeft = Viewport.XnaViewport.Unproject(bottomLeft, Camera.ProjectionMatrix, Camera.ViewMatrix, Matrix.Identity);
bottomRight = Viewport.XnaViewport.Unproject(bottomRight, Camera.ProjectionMatrix, Camera.ViewMatrix, Matrix.Identity);
CCPoint topLeftPoint = new CCPoint(topLeft.X, topLeft.Y);
CCPoint bottomLeftPoint = new CCPoint(bottomLeft.X, bottomLeft.Y);
CCPoint bottomRightPoint = new CCPoint(bottomRight.X, bottomRight.Y);
visibleBoundsWorldspace = new CCRect(
(float)Math.Round(bottomLeftPoint.X), (float)Math.Round(bottomLeftPoint.Y),
(float)Math.Round(bottomRightPoint.X - bottomLeftPoint.X),
(float)Math.Round(topLeftPoint.Y - bottomLeftPoint.Y));
}
#endregion Content layout
#region Visiting and drawing
public override void Visit(ref CCAffineTransform parentWorldTransform)
{
if (!Visible || Window == null)
{
return;
}
// Set camera view/proj matrix even if ChildClippingMode is None
if(Camera != null)
{
var viewMatrix = Camera.ViewMatrix;
var projMatrix = Camera.ProjectionMatrix;
Renderer.PushLayerGroup(ref viewMatrix, ref projMatrix);
}
if (ChildClippingMode == CCClipMode.None)
{
base.Visit(ref parentWorldTransform);
if(Camera != null)
Renderer.PopLayerGroup();
return;
}
beforeDrawCommand.GlobalDepth = float.MinValue;
beforeDrawCommand.WorldTransform = parentWorldTransform;
Renderer.AddCommand(beforeDrawCommand);
VisitRenderer(ref parentWorldTransform);
if(!noDrawChildren && Children != null)
{
SortAllChildren();
var elements = Children.Elements;
for(int i = 0, N = Children.Count; i < N; ++i)
{
var child = elements[i];
if (child.Visible)
child.Visit(ref parentWorldTransform);
}
}
afterDrawCommand.GlobalDepth = float.MaxValue;
afterDrawCommand.WorldTransform = parentWorldTransform;
Renderer.AddCommand(afterDrawCommand);
if(Camera != null)
Renderer.PopLayerGroup();
}
void BeforeDraw()
{
noDrawChildren = false;
CCRect visibleBounds = Layer.VisibleBoundsWorldspace;
CCRect viewportRect = Viewport.ViewportInPixels;
CCDrawManager drawManager = Window.DrawManager;
if (ChildClippingMode == CCClipMode.Bounds && Window != null)
{
drawManager.ScissorRectInPixels = viewportRect;
}
else if (ChildClippingMode == CCClipMode.BoundsWithRenderTarget)
{
restoreScissor = Window.DrawManager.ScissorRectEnabled;
Window.DrawManager.ScissorRectEnabled = false;
Window.DrawManager.PushMatrix();
Window.DrawManager.WorldMatrix = Matrix.Identity;
renderTexture.BeginWithClear(0, 0, 0, 0);
}
}
void AfterDraw()
{
if (ChildClippingMode != CCClipMode.None)
{
if (ChildClippingMode == CCClipMode.BoundsWithRenderTarget)
{
renderTexture.End();
Window.DrawManager.PopMatrix();
}
if (restoreScissor)
{
Window.DrawManager.ScissorRectEnabled = true;
restoreScissor = false;
}
else
{
Window.DrawManager.ScissorRectEnabled = false;
}
if (ChildClippingMode == CCClipMode.BoundsWithRenderTarget)
{
renderTexture.Sprite.Visit();
}
}
}
#endregion Visiting and drawing
#region Unit conversion
public CCPoint ScreenToWorldspace(CCPoint point)
{
CCRect viewportRectInPixels = Viewport.ViewportInPixels;
CCRect worldBounds = Layer.VisibleBoundsWorldspace;
point -= viewportRectInPixels.Origin;
// Note: Screen coordinates have origin in top left corner
// but world coords have origin in bottom left corner
// Therefore, Y world ratio is 1 minus Y viewport ratio
CCPoint worldPointRatio
= new CCPoint(point.X / viewportRectInPixels.Size.Width, 1 - (point.Y / viewportRectInPixels.Size.Height));
return new CCPoint (
worldBounds.Origin.X + (worldBounds.Size.Width * worldPointRatio.X),
worldBounds.Origin.Y + (worldBounds.Size.Height * worldPointRatio.Y));
}
public CCSize ScreenToWorldspace(CCSize size)
{
CCRect viewportRectInPixels = Viewport.ViewportInPixels;
CCRect worldBounds = Layer.VisibleBoundsWorldspace;
CCPoint worldSizeRatio = new CCPoint(size.Width / viewportRectInPixels.Size.Width, size.Height / viewportRectInPixels.Size.Height);
return new CCSize(worldSizeRatio.X * worldBounds.Size.Width, worldSizeRatio.Y * worldBounds.Size.Height);
}
public CCSize WorldToScreenspace(CCSize size)
{
CCRect visibleBounds = VisibleBoundsWorldspace;
CCRect viewportInPixels = Viewport.ViewportInPixels;
CCPoint worldSizeRatio = new CCPoint(size.Width / visibleBounds.Size.Width, size.Height / visibleBounds.Size.Height);
return new CCSize(worldSizeRatio.X * viewportInPixels.Size.Width, worldSizeRatio.Y * viewportInPixels.Size.Height);
}
public CCPoint WorldToScreenspace(CCPoint point)
{
CCRect worldBounds = VisibleBoundsWorldspace;
CCRect viewportRectInPixels = Viewport.ViewportInPixels;
point -= worldBounds.Origin;
CCPoint worldPointRatio
= new CCPoint(point.X / worldBounds.Size.Width, (point.Y / worldBounds.Size.Height));
return new CCPoint(viewportRectInPixels.Origin.X + viewportRectInPixels.Size.Width * worldPointRatio.X,
viewportRectInPixels.Origin.Y + viewportRectInPixels.Size.Height * (1 - worldPointRatio.Y));
}
#endregion Unit conversion
}
}
| |
// 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 1.2.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace AwesomeNamespace
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// StorageAccountsOperations operations.
/// </summary>
public partial interface IStorageAccountsOperations
{
/// <summary>
/// Checks that account name is valid and is not in use.
/// </summary>
/// <param name='name'>
/// </param>
/// <param name='type'>
/// </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<CheckNameAvailabilityResult>> CheckNameAvailabilityWithHttpMessagesAsync(string name, string type = "Microsoft.Storage/storageAccounts", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Asynchronously creates a new storage account with the specified
/// parameters. Existing accounts cannot be updated with this API and
/// should instead use the Update Storage Account API. If an account is
/// already created and subsequent PUT request is issued with exact
/// same set of properties, then HTTP 200 would be returned.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource
/// group. Storage account names must be between 3 and 24 characters in
/// length and use numbers and lower-case letters only.
/// </param>
/// <param name='location'>
/// Resource location
/// </param>
/// <param name='accountType'>
/// Gets or sets the account type. Possible values include:
/// 'Standard_LRS', 'Standard_ZRS', 'Standard_GRS', 'Standard_RAGRS',
/// 'Premium_LRS'
/// </param>
/// <param name='tags'>
/// Resource tags
/// </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<StorageAccount>> CreateWithHttpMessagesAsync(string resourceGroupName, string accountName, string location, AccountType accountType, IDictionary<string, string> tags = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a storage account in Microsoft Azure.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource
/// group. Storage account names must be between 3 and 24 characters in
/// length and use numbers and lower-case letters only.
/// </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 accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the properties for the specified storage account including
/// but not limited to name, account type, location, and account
/// status. The ListKeys operation should be used to retrieve storage
/// keys.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource
/// group. Storage account names must be between 3 and 24 characters in
/// length and use numbers and lower-case letters only.
/// </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<StorageAccount>> GetPropertiesWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the account type or tags for a storage account. It can also
/// be used to add a custom domain (note that custom domains cannot be
/// added via the Create operation). Only one custom domain is
/// supported per storage account. In order to replace a custom domain,
/// the old value must be cleared before a new value may be set. To
/// clear a custom domain, simply update the custom domain with empty
/// string. Then call update again with the new cutsom domain name. The
/// update API can only be used to update one of tags, accountType, or
/// customDomain per call. To update multiple of these properties, call
/// the API multiple times with one change per call. This call does not
/// change the storage keys for the account. If you want to change
/// storage account keys, use the RegenerateKey operation. The location
/// and name of the storage account cannot be changed after creation.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource
/// group. Storage account names must be between 3 and 24 characters in
/// length and use numbers and lower-case letters only.
/// </param>
/// <param name='tags'>
/// Resource tags
/// </param>
/// <param name='accountType'>
/// Gets or sets the account type. Note that StandardZRS and PremiumLRS
/// accounts cannot be changed to other account types, and other
/// account types cannot be changed to StandardZRS or PremiumLRS.
/// Possible values include: 'Standard_LRS', 'Standard_ZRS',
/// 'Standard_GRS', 'Standard_RAGRS', 'Premium_LRS'
/// </param>
/// <param name='customDomain'>
/// User domain assigned to the storage account. Name is the CNAME
/// source. Only one custom domain is supported per storage account at
/// this time. To clear the existing custom domain, use an empty string
/// for the custom domain name property.
/// </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<StorageAccount>> UpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, IDictionary<string, string> tags = default(IDictionary<string, string>), AccountType? accountType = default(AccountType?), CustomDomain customDomain = default(CustomDomain), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the access keys for the specified storage account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='accountName'>
/// The name of the storage account.
/// </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<StorageAccountKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all the storage accounts available under the subscription.
/// Note that storage keys are not returned; use the ListKeys operation
/// for this.
/// </summary>
/// <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<IEnumerable<StorageAccount>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all the storage accounts available under the given resource
/// group. Note that storage keys are not returned; use the ListKeys
/// operation for this.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </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<IEnumerable<StorageAccount>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Regenerates the access keys for the specified storage account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource
/// group. Storage account names must be between 3 and 24 characters in
/// length and use numbers and lower-case letters only.
/// </param>
/// <param name='keyName'>
/// </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<StorageAccountKeys>> RegenerateKeyWithHttpMessagesAsync(string resourceGroupName, string accountName, string keyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Asynchronously creates a new storage account with the specified
/// parameters. Existing accounts cannot be updated with this API and
/// should instead use the Update Storage Account API. If an account is
/// already created and subsequent PUT request is issued with exact
/// same set of properties, then HTTP 200 would be returned.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource
/// group. Storage account names must be between 3 and 24 characters in
/// length and use numbers and lower-case letters only.
/// </param>
/// <param name='location'>
/// Resource location
/// </param>
/// <param name='accountType'>
/// Gets or sets the account type. Possible values include:
/// 'Standard_LRS', 'Standard_ZRS', 'Standard_GRS', 'Standard_RAGRS',
/// 'Premium_LRS'
/// </param>
/// <param name='tags'>
/// Resource tags
/// </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<StorageAccount>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string accountName, string location, AccountType accountType, IDictionary<string, string> tags = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using MigAz.Azure.Forms;
namespace MigAz.Azure.UserControls
{
public enum AzureLoginChangeType
{
NewOrExistingContext,
NewContext,
SubscriptionChangeOnly
}
public enum AzureContextSelectedType
{
ExistingContext,
SameUserDifferentSubscription,
NewContext
}
public partial class AzureLoginContextViewer : UserControl
{
private AzureRetriever _AzureRetriever;
private AzureContext _AzureContext;
private AzureContext _ExistingContext;
private AzureLoginChangeType _ChangeType = AzureLoginChangeType.NewContext;
private AzureContextSelectedType _AzureContextSelectedType = AzureContextSelectedType.ExistingContext;
private List<AzureEnvironment> _AzureEnvironments;
private List<AzureEnvironment> _UserDefinedAzureEnvironments;
public delegate Task AfterContextChangedHandler(AzureLoginContextViewer sender);
public event AfterContextChangedHandler AfterContextChanged;
public AzureLoginContextViewer()
{
InitializeComponent();
}
public void Bind(AzureContext azureContext, AzureRetriever azureRetriever, List<AzureEnvironment> azureEnvironments, ref List<AzureEnvironment> userDefinedAzureEnvironments)
{
_AzureRetriever = azureRetriever;
_AzureEnvironments = azureEnvironments;
_UserDefinedAzureEnvironments = userDefinedAzureEnvironments;
_AzureContext = azureContext;
_AzureContext.AzureEnvironmentChanged += _AzureContext_AzureEnvironmentChanged;
_AzureContext.AfterAzureTenantChange += _AzureContext_AfterAzureTenantChange;
_AzureContext.UserAuthenticated += _AzureContext_UserAuthenticated;
_AzureContext.AfterUserSignOut += _AzureContext_AfterUserSignOut;
_AzureContext.AfterAzureSubscriptionChange += _AzureContext_AfterAzureSubscriptionChange;
}
public AzureContextSelectedType AzureContextSelectedType
{
get { return _AzureContextSelectedType; }
set
{
_AzureContextSelectedType = value;
}
}
public AzureContext ExistingContext
{
get { return _ExistingContext; }
set
{
_ExistingContext = value;
UpdateLabels();
AfterContextChanged?.Invoke(this);
}
}
private async Task _AzureContext_AfterAzureTenantChange(AzureContext sender)
{
UpdateLabels();
}
private async Task _AzureContext_AfterUserSignOut()
{
UpdateLabels();
}
private async Task _AzureContext_AzureEnvironmentChanged(AzureContext sender)
{
UpdateLabels();
}
private async Task _AzureContext_UserAuthenticated(AzureContext sender)
{
UpdateLabels();
}
private async Task _AzureContext_AfterAzureSubscriptionChange(AzureContext sender)
{
UpdateLabels();
}
public void UpdateLabels()
{
lblSourceUser.Text = "-";
lblSourceSubscriptionName.Text = "-";
lblSourceSubscriptionId.Text = "-";
lblTenantName.Text = "-";
AzureContext selectedContext = this.SelectedAzureContext;
if (selectedContext != null)
{
lblSourceEnvironment.Text = selectedContext.AzureEnvironment.ToString();
if (selectedContext.AzureTenant != null)
lblTenantName.Text = selectedContext.AzureTenant.ToString();
if (selectedContext.TokenProvider != null &&
selectedContext.TokenProvider.LastUserInfo != null)
{
lblSourceUser.Text = selectedContext.TokenProvider.LastUserInfo.DisplayableId;
}
if (selectedContext.AzureSubscription != null)
{
lblSourceSubscriptionName.Text = selectedContext.AzureSubscription.Name;
lblSourceSubscriptionId.Text = selectedContext.AzureSubscription.SubscriptionId.ToString();
}
}
}
public string Title
{
get { return this.groupSubscription.Text; }
set { this.groupSubscription.Text = value; }
}
public AzureLoginChangeType ChangeType
{
get { return _ChangeType; }
set { _ChangeType = value; }
}
public AzureContext SelectedAzureContext
{
get
{
if (this.ChangeType == AzureLoginChangeType.NewOrExistingContext)
{
if (_ExistingContext != null && _AzureContextSelectedType == AzureContextSelectedType.ExistingContext)
return _ExistingContext;
else
return _AzureContext;
}
else
return _AzureContext;
}
}
public AzureContext AzureContext
{
get { return _AzureContext; }
}
private async void btnAzureContext_Click(object sender, EventArgs e)
{
if (_AzureContext == null)
throw new ArgumentException("Azure Context not set. You must initiate the AzureLoginContextViewer control with the Bind Method.");
if (_ChangeType == AzureLoginChangeType.NewOrExistingContext)
{
if (_ExistingContext == null)
{
AzureLoginContextDialog azureLoginContextDialog = new AzureLoginContextDialog();
await azureLoginContextDialog.InitializeDialog(_AzureContext, _AzureEnvironments, _UserDefinedAzureEnvironments);
azureLoginContextDialog.ShowDialog();
azureLoginContextDialog.Dispose();
}
else
{
AzureNewOrExistingLoginContextDialog azureLoginContextDialog = new AzureNewOrExistingLoginContextDialog();
await azureLoginContextDialog.InitializeDialog(this, _AzureEnvironments, _UserDefinedAzureEnvironments);
azureLoginContextDialog.ShowDialog();
azureLoginContextDialog.Dispose();
}
}
else if (_ChangeType == AzureLoginChangeType.NewContext)
{
AzureLoginContextDialog azureLoginContextDialog = new AzureLoginContextDialog();
await azureLoginContextDialog.InitializeDialog(_AzureContext, _AzureEnvironments, _UserDefinedAzureEnvironments);
azureLoginContextDialog.ShowDialog();
azureLoginContextDialog.Dispose();
}
else
{
AzureSubscriptionContextDialog azureSubscriptionContextDialog = new AzureSubscriptionContextDialog();
await azureSubscriptionContextDialog.InitializeDialog(_AzureContext);
azureSubscriptionContextDialog.ShowDialog();
azureSubscriptionContextDialog.Dispose();
}
AfterContextChanged?.Invoke(this);
}
private void AzureLoginContextViewer_EnabledChanged(object sender, EventArgs e)
{
btnAzureContext.Enabled = this.Enabled;
}
public void ChangeAzureContext()
{
btnAzureContext_Click(this, null);
}
private void AzureLoginContextViewer_Resize(object sender, EventArgs e)
{
groupSubscription.Width = this.Width - 5;
btnAzureContext.Left = this.Width - btnAzureContext.Width - 10;
}
}
}
| |
using System;
/* [ ] recursive simple add
* [ ] recursive count
* [ ] recursive changeatpos
* [ ] recursive remove
*/
namespace ConsoleApplication {
public class Program {
public class Node {
public string value = null;
public Node nextElement = null;
}
public class VerketteteListe {
public Node head = new Node();
public Node body = new Node();
public bool debg = true;
// Simple Add
public void add_ (Node node) {
if (this.head.value == null)
this.head = node;
else if (this.head.value != null && this.body.value == null) {
this.body = node;
this.head.nextElement = node;
} else {
this.body.nextElement = node;
this.body = node;
}
if (this.debg) Console.WriteLine(this);
}
// recursive sorted add
public void _add(Node node) {
if (this.head.value == null) {
this.head = node;
} else if (this.body.value == null) {
if (this.head.value.CompareTo(this.body.value) != 1) {
this.body = node;
this.head.nextElement = this.body;
} else {
this.body = this.head;
this.head = node;
this.head.nextElement = this.body;
}
} else {
Node prevNode = this.head;
Node currNode = this.head.nextElement;
Node nextNode = currNode.nextElement;
while(true) {
if (node.value.CompareTo(currNode.value) != 1) {
prevNode.nextElement = node;
node.nextElement = nextNode;
this._add(currNode);
} else {
prevNode = currNode;
currNode = nextNode;
nextNode = nextNode.nextElement;
}
if (nextNode == null) break;
}
}
}
public void add (Node node) {
Node prevNode = new Node();
Node currNode = new Node();
Node nextNode = new Node();
if (this.head.value == null) {
this.head = node;
} else if (this.body.value == null) {
if (this.head.value.CompareTo(this.body.value) != 1) {
this.body = node;
this.head.nextElement = this.body;
} else {
this.body = this.head;
this.head = node;
this.head.nextElement = this.body;
}
} else {
if (this.head.value.CompareTo(node.value) == 1) {
currNode = this.head;
nextNode = this.body;
this.head = node;
this.body = currNode;
this.head.nextElement = currNode;
this.body.nextElement = nextNode;
//} else if (this.head.value.CompareTo(node.value) != 1) {
} else if (this.head.value.CompareTo(node.value) == 0) {
prevNode = this.head;
nextNode = this.head.nextElement;
this.head.nextElement = node;
node.nextElement = nextNode;
} else {
prevNode = this.head;
currNode = this.head.nextElement;
while(currNode.value != null) {
if (currNode.value.CompareTo(node.value) == 1) {
prevNode.nextElement = node;
node.nextElement = currNode;
if (currNode.nextElement == null)
this.body = node;
break;
} else if (currNode.nextElement == null) {
currNode.nextElement = node;
this.body = node;
break;
} else {
prevNode = currNode;
currNode = currNode.nextElement;
}
}
}
}
Console.WriteLine(this);
}
public int count () {
int c = 1;
Node tempNode = this.head;
while(tempNode.nextElement != null) {
c++;
tempNode = tempNode.nextElement;
}
return c;
}
public Node find (string value) {
Node tempNode = this.head;
while (tempNode.nextElement != null) {
if (tempNode.value == value)
return tempNode;
}
Console.WriteLine("There is no object w/ the value: '"+ value +"' in this list.");
return null;
}
public int findNodePos(Node node) {
Node tempNode = this.head;
int cunter = 0;
while (tempNode != node) {
cunter ++;
tempNode = tempNode.nextElement;
if (tempNode == null) return -1;
}
return cunter;
}
public Node returnNodeAtPos(int pos) {
Node tempNode = this.head;
if (pos == 0) return tempNode;
else if (pos >= this.count()) return null;
else {
for (int i = 1; i <= pos; i++) {
tempNode = tempNode.nextElement;
}
return tempNode;
}
}
public void changeAtPos (int pos, Node node) {
Node tempNode = this.head;
Node tempNextNode = new Node();
Node tempNextNextNode = new Node();
int cunt = this.count() - 1;
while (cunt < this.count() - 1) {
tempNode = tempNode.nextElement;
tempNextNode = tempNode.nextElement;
}
tempNextNextNode = tempNextNode.nextElement;
if (node == null) {
tempNode.nextElement = tempNextNextNode;
} else if (cunt == 0) {
node.nextElement = this.head.nextElement;
this.head = node;
} else {
tempNode.nextElement = node;
tempNextNode = node;
tempNextNode.nextElement = tempNextNextNode;
}
}
// rewrite remove :))
public void remove(Node node) {
Node oldNode = this.head;
Node tempNode = new Node();
int pos = findNodePos(node);
changeAtPos(pos, null);
}
public override string ToString() {
Node tempNode = this.head;
string tempString = this.GetType().Name.ToString() + ": [";
while (tempNode != null) {
if (tempNode.nextElement != null) {
tempString += " \"" + tempNode.value + "\", ";
} else {
tempString += " \"" + tempNode.value + "\", null ]";
}
tempNode = tempNode.nextElement;
}
return tempString;
}
}
public static void Main(string[] args) {
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface001.integeregererface001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface001.integeregererface001;
// <Title>Interfaces</Title>
// <Description>covariance between object/dynamic - implicit/explicit implementations
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public interface I
{
int Foo(object o);
int Bar(dynamic o);
}
public struct C : I
{
public int Foo(dynamic d)
{
Test.Status = 1;
return 1;
}
public int Bar(object d)
{
Test.Status = 2;
return 2;
}
}
public class CExp : I
{
int I.Foo(object d)
{
Test.Status = 3;
return 3;
}
int I.Bar(dynamic d)
{
Test.Status = 4;
return 4;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new C();
I i = d;
bool ret = 1 == i.Foo(2);
ret &= 2 == i.Bar(null);
d = new CExp();
i = d;
ret &= 3 == i.Foo(2);
ret &= 4 == i.Bar(null);
return ret ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface007.integeregererface007
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface007.integeregererface007;
// <Title>Interfaces</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public interface I
{
dynamic Foo();
}
public class C : I
{
public object Foo()
{
Test.Status = 1;
return 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
I i = new C();
i.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface008.integeregererface008
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface008.integeregererface008;
// <Title>Interfaces</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public interface I
{
dynamic Foo();
}
public class C : I
{
object I.Foo()
{
Test.Status = 1;
return 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
I i = new C();
i.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface009.integeregererface009
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface009.integeregererface009;
// <Title>Interfaces</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public interface I
{
object Foo();
}
public class C : I
{
dynamic I.Foo()
{
Test.Status = 1;
return 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
I i = new C();
i.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface010.integeregererface010
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface010.integeregererface010;
// <Title>Interfaces</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public interface I
{
int Foo(object o, int x);
}
public class C : I
{
public int Foo(dynamic d, int x)
{
Test.Status = 1;
return 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
I i = new C();
i.Foo(2, 3);
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface011.integeregererface011
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface011.integeregererface011;
// <Title>Interfaces</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public interface I
{
List<dynamic> Foo();
}
public class C : I
{
public List<dynamic> Foo()
{
Test.Status = 1;
return new List<dynamic>();
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
I i = new C();
var x = i.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface012.integeregererface012
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface012.integeregererface012;
// <Title>Interfaces</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public interface I
{
List<dynamic> Foo();
}
public class C : I
{
List<dynamic> I.Foo()
{
Test.Status = 1;
return new List<dynamic>();
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
I i = new C();
var x = i.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface013.integeregererface013
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface013.integeregererface013;
// <Title>Interfaces</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public interface I
{
List<dynamic> Foo();
}
public class C : I
{
List<object> I.Foo()
{
Test.Status = 1;
return new List<dynamic>();
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
I i = new C();
var x = i.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface014.integeregererface014
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface014.integeregererface014;
// <Title>Interfaces</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public interface I
{
List<object> Foo();
}
public class C : I
{
List<dynamic> I.Foo()
{
Test.Status = 1;
return new List<object>();
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
I i = new C();
var x = i.Foo();
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface015.integeregererface015
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface015.integeregererface015;
// <Title>Interfaces</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public interface I
{
void Foo(List<object> o);
}
public class C : I
{
void I.Foo(List<object> o)
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
I i = new C();
i.Foo(new List<dynamic>());
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface016.integeregererface016
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.integeregererfaces.integeregererface016.integeregererface016;
// <Title>Interfaces</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public interface I
{
void Foo(List<dynamic> o);
}
public class C : I
{
void I.Foo(List<object> o)
{
Test.Status = 1;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
I i = new C();
i.Foo(new List<dynamic>());
if (Test.Status != 1)
return 1;
return 0;
}
}
// </Code>
}
| |
// Copyright (c) 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
#if !NETCORE
using System;
using System.Collections;
using System.Management.Instrumentation;
namespace Alachisoft.NCache.Instrumentation
{
[InstrumentationClass(InstrumentationType.Instance)]
public class WMINodeStats : System.Management.Instrumentation.Instrumentation
{
private string _processID; //the process ID assigned to NCache Service or some user program incase of INProc Cache
//private string _nodeId; //unique id of node. In this case it will be ip address and port combined
private string _nodeName; //Name of the current node
private DateTime _nodeUpTime; //time at which the node was started
private float _addSec=0; //Avg no of items addded on current node per sec
private float _remvSec=0; //Avg no of items removed from current node per sec
private float _insertSec = 0; //Avg no of items updated on current node per sec
private float _getSec = 0; //Avg no of items retrieved from current node per sec
private ulong _hitsSec=0; //Avg no of requests recieved on current node per sec
private ulong _missesSec=0; //Avg no of requests not fullfiled on current node per sec
private int _totalClients=0; //Number of Clients connected to the current node
private Hashtable _clientnodes = new Hashtable(); //List of client nodes connected to the current server node
private float _instantAdds = 0; //Number of adds in the current sec
private float _instantGets = 0; //Number of Gets in the current sec
private float _instantUpdates = 0; //Number of Updates in the current sec
private float _instantRemoves = 0; //Number of Removes in the current sec
private float _instantHits = 0; //Number of Hits in the current sec
private float _instantMisses = 0; //Number of Misses in the current sec
private float _clusterOpsPerSec = 0;
private float _bytesSentPerSec = 0;
private float _bytesRecievedPerSec = 0;
private float _requestSentPerSec = 0;
private float _evictionsPerSec = 0;
private float _expirationPerSec = 0;
private float _stateTransferPerSec = 0;
private float _dataBalancePerSec = 0;
private float _clientsRequestsPerSec = 0;
private float _clientsBytesSendPerSec = 0;
private float _clientsBytesRecievedPerSec = 0;
private float _mirrorQueueCount = 0;
/// operations time
private float _addTime;
private float _getTime;
private float _insertTime;
private float _removeTime;
private int _serverPort; //Current server port on which the NCache service is listening
private string _partitionId = string.Empty;
private ulong _totalNodeOperations = 0; //Total operations performed on the current node
private ulong _dataSize = 0; //Size of data stored by the current cache
/// <summary>
/// Making this Node object available to the WMI Service
/// </summary>
public WMINodeStats()
{
try
{
/* Commented to stop posting on WMI */
System.Management.Instrumentation.Instrumentation.Publish(this);
}
catch { }
}
/// <summary>
/// Initializing and making available this object to WMI service
/// </summary>
/// <param name="nodeName"></param>
/// <param name="nodeupTime"></param>
public WMINodeStats(string port, string nodeName, DateTime nodeupTime, int serverPort, bool isInproc)
{
try
{
_nodeName = nodeName + "." + port;
_nodeUpTime = nodeupTime;
_serverPort = serverPort;
if (isInproc) _partitionId = _nodeName;
else _partitionId = nodeName;
_processID = Convert.ToString(System.Diagnostics.Process.GetCurrentProcess().Id);
/* Commented to stop posting on WMI */
System.Management.Instrumentation.Instrumentation.Publish(this);
}
catch { }
}
/// <summary>
/// Initializing and making available this object to WMI service
/// </summary>
/// <param name="nodeName"></param>
/// <param name="nodeupTime"></param>
public WMINodeStats(string port, string nodeName, DateTime nodeupTime, int serverPort)
{
try
{
_nodeName = nodeName + "." + port;
_nodeUpTime = nodeupTime;
_serverPort = serverPort;
_processID = Convert.ToString(System.Diagnostics.Process.GetCurrentProcess().Id);
/* Commented to stop posting on WMI */
System.Management.Instrumentation.Instrumentation.Publish(this);
}
catch { }
}
/// <summary>
/// All the public members that are to be publised on WMI
/// </summary>
#region Public variables
[CLSCompliant(false)]
public ulong ItemCount; //Total items stored on the current node of the cluster
public string clusterName; //Name of the cluster this node is part of
public string CurrentProcessID
{
get { return _processID; }
}
/// <summary>
/// Name of the Node
/// </summary>
public string NodeName
{
get
{
return _nodeName;
}
set
{
_nodeName = value;
}
}
/// <summary>
/// The time at which the Node was started
/// </summary>
public DateTime NodeUpTime
{
get
{
return _nodeUpTime;
}
}
public float InstantAdds
{
get { return _instantAdds; }
set { _instantAdds = value; }
}
public float InstantGets
{
get { return _instantGets; }
set { _instantGets = value; }
}
public float InstantRemoves
{
get { return _instantRemoves; }
set { _instantRemoves = value; }
}
public float InstantUpdates
{
get { return _instantUpdates; }
set { _instantUpdates = value; }
}
public float InstantHits
{
get { return _instantHits; }
set { _instantHits = value; }
}
public float InstantMisses
{
get { return _instantMisses; }
set { _instantMisses = value; }
}
public float AddTime
{
get { return this._addTime; }
set { this._addTime = value; }
}
public float UpdateTime
{
get { return this._insertTime; }
set { this._insertTime = value; }
}
public float GetTime
{
get { return this._getTime; }
set { this._getTime = value; }
}
public float RemoveTime
{
get { return this._removeTime; }
set { this._removeTime = value; }
}
/// <summary>
/// Total # of Clients connected to the Cache on the current node
/// </summary>
public int TotalClients
{
get
{
return _totalClients;
}
set
{
_totalClients = value;
}
}
public float ClusterOpsPerSec
{
get { return this._clusterOpsPerSec; }
set { this._clusterOpsPerSec = value; }
}
public float ClusterBytesSentPerSec
{
get { return this._bytesSentPerSec; }
set { this._bytesSentPerSec = value; }
}
public float ClusterBytesRecievedPerSec
{
get { return this._bytesRecievedPerSec; }
set { this._bytesRecievedPerSec = value; }
}
public float EvictionsPerSec
{
get { return this._evictionsPerSec; }
set { this._evictionsPerSec = value; }
}
public float ExpirationsPerSec
{
get { return this._expirationPerSec; }
set { this._expirationPerSec = value; }
}
public float StateTransferPerSec
{
get { return this._stateTransferPerSec; }
set { this._stateTransferPerSec = value; }
}
public float DataBalancedPerSec
{
get { return this._dataBalancePerSec; }
set { this._dataBalancePerSec = value; }
}
public float ClientsBytesSentPerSec
{
get { return this._clientsBytesSendPerSec; }
set { this._clientsBytesSendPerSec = value; }
}
public float ClientsBytesRecievedPerSec
{
get { return this._clientsBytesRecievedPerSec; }
set { this._clientsBytesRecievedPerSec = value; }
}
public float ClientsRequestPerSec
{
get { return this._clientsRequestsPerSec; }
set { this._clientsRequestsPerSec = value; }
}
public float MirrorQueueCount
{
get { return this._mirrorQueueCount; }
set { this._mirrorQueueCount = value; }
}
public int ServerPort
{
set { _serverPort = value; }
get { return _serverPort; }
}
public string PartitionId
{
set { _partitionId = value; }
get { return _partitionId == null ? string.Empty : _partitionId; }
}
[CLSCompliant(false)]
public ulong TotalOperations
{
set { _totalNodeOperations = value; }
get { return _totalNodeOperations; }
}
[CLSCompliant(false)]
public ulong DataSize
{
set { _dataSize = value; }
get { return _dataSize; }
}
#endregion
/// <summary>
/// Removing the published object from the WMI repository, so that the current
/// Object may not be visible over the network anymore
/// </summary>
public void Dispose()
{
try
{
this.ClearClients();
System.Management.Instrumentation.Instrumentation.Revoke(this);
}
catch { }
}
/// <summary>
/// Called each time a new Client gets connected to the current node
/// </summary>
/// <param name="Name"></param>
public void AddClient(String Name) //ToDo Add stats parameter
{
try
{
lock (_clientnodes)
{
if (_clientnodes.Contains(Name))
this.RemoveClientStatistics(Name);
/* Commented to stop posting on WMI */
_clientnodes.Add(Name, new ClientStats(Name, _nodeName, _serverPort, clusterName));
}
}
catch { }
}
public void ClearClients()
{
try
{
//ClientStats removed;
int _clntCount = _clientnodes.Count;
lock (_clientnodes)
{
foreach (DictionaryEntry de in _clientnodes)
{
try
{
ClientStats removed = (ClientStats)de.Value;
removed.Dispose();
}
catch { }
}
_clientnodes.Clear();
}
}
catch { }
}
/// <summary>
/// Called each time a client node leaves the cluster
/// </summary>
/// <param name="Name"></param>
public void RemoveClientStatistics(String Name)
{
try
{
ClientStats remved;
lock (_clientnodes)
{
remved = (ClientStats)_clientnodes[Name];
remved.Dispose();
/* Commented to stop posting on WMI */
_clientnodes.Remove(Name);
}
}
catch { }
}
/// <summary>
/// Sets the amount data transferred by a client to the server node
/// </summary>
/// <param name="ClientID"></param>
/// <param name="DataSize"></param>
public void ClientDataRecived(string ClientID, long DataSize, IncommingOperationType OperationType, int OperationsCount)
{
try
{
_totalNodeOperations++; // Incrementing the Current node operation count
lock (_clientnodes)
{
ClientStats client;
client = (ClientStats)_clientnodes[ClientID];
client.DataTransfered += (ulong)DataSize;
client.OperationsPerformed++;
switch (OperationType)
{
case IncommingOperationType.Add:
case IncommingOperationType.AddBulk:
client.TotalAddOperations = (ulong)OperationsCount;
break;
case IncommingOperationType.Get:
case IncommingOperationType.GetBulk:
client.TotalGetOperations = (ulong)OperationsCount;
break;
case IncommingOperationType.Insert:
case IncommingOperationType.InsertBulk:
client.TotalInsertOperations = (ulong)OperationsCount;
break;
case IncommingOperationType.Remove:
case IncommingOperationType.RemoveBulk:
client.TotalRemoveOperations = (ulong)OperationsCount;
break;
}
}
}
catch { }
}
}
}
#endif
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using OpenMetaverse;
using log4net;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.Framework.Scenes
{
public abstract class SceneBase : IScene
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#region Events
public event restart OnRestart;
#endregion
#region Fields
public IConfigSource Config
{
get { return GetConfig(); }
}
protected virtual IConfigSource GetConfig()
{
return null;
}
/// <value>
/// All the region modules attached to this scene.
/// </value>
public Dictionary<string, IRegionModule> Modules
{
get { return m_modules; }
}
protected Dictionary<string, IRegionModule> m_modules = new Dictionary<string, IRegionModule>();
public Dictionary<string, IRegionModuleBase> RegionModules
{
get { return m_regionModules; }
}
private Dictionary<string, IRegionModuleBase> m_regionModules = new Dictionary<string, IRegionModuleBase>();
/// <value>
/// The module interfaces available from this scene.
/// </value>
protected Dictionary<Type, List<object>> ModuleInterfaces = new Dictionary<Type, List<object>>();
protected Dictionary<string, object> ModuleAPIMethods = new Dictionary<string, object>();
/// <value>
/// The module commanders available from this scene
/// </value>
protected Dictionary<string, ICommander> m_moduleCommanders = new Dictionary<string, ICommander>();
/// <value>
/// Registered classes that are capable of creating entities.
/// </value>
protected Dictionary<PCode, IEntityCreator> m_entityCreators = new Dictionary<PCode, IEntityCreator>();
/// <summary>
/// The last allocated local prim id. When a new local id is requested, the next number in the sequence is
/// dispensed.
/// </summary>
protected uint m_lastAllocatedLocalId = 720000;
private readonly Mutex _primAllocateMutex = new Mutex(false);
private readonly ClientManager m_clientManager = new ClientManager();
public ClientManager ClientManager
{
get { return m_clientManager; }
}
public float TimeDilation
{
get { return m_timedilation; }
}
protected float m_timedilation = 1.0f;
protected ulong m_regionHandle;
protected string m_regionName;
protected RegionInfo m_regInfo;
public ITerrainChannel Heightmap;
/// <value>
/// Allows retrieval of land information for this scene.
/// </value>
public ILandChannel LandChannel;
/// <value>
/// Manage events that occur in this scene (avatar movement, script rez, etc.). Commonly used by region modules
/// to subscribe to scene events.
/// </value>
public EventManager EventManager
{
get { return m_eventManager; }
}
protected EventManager m_eventManager;
protected ScenePermissions m_permissions;
public ScenePermissions Permissions
{
get { return m_permissions; }
}
protected string m_datastore;
/* Used by the loadbalancer plugin on GForge */
protected RegionStatus m_regStatus;
public RegionStatus RegionStatus
{
get { return m_regStatus; }
set { m_regStatus = value; }
}
#endregion
#region Update Methods
/// <summary>
/// Normally called once every frame/tick to let the world preform anything required (like running the physics simulation)
/// </summary>
public abstract void Update();
#endregion
#region Terrain Methods
/// <summary>
/// Loads the World heightmap
/// </summary>
public abstract void LoadWorldMap();
/// <summary>
/// Send the region heightmap to the client
/// </summary>
/// <param name="RemoteClient">Client to send to</param>
public virtual void SendLayerData(IClientAPI RemoteClient)
{
RemoteClient.SendLayerData(Heightmap.GetFloatsSerialised());
}
#endregion
#region Add/Remove Agent/Avatar
/// <summary>
/// Register the new client with the scene. The client starts off as a child agent - the later agent crossing
/// will promote it to a root agent during login.
/// </summary>
/// <param name="client"></param
public abstract void AddNewClient(IClientAPI client);
/// <summary>
/// Remove a client from the scene
/// </summary>
/// <param name="agentID"></param>
public abstract void RemoveClient(UUID agentID);
public abstract void CloseAllAgents(uint circuitcode);
#endregion
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual RegionInfo RegionInfo
{
get { return m_regInfo; }
}
#region admin stuff
/// <summary>
/// Region Restart - Seconds till restart.
/// </summary>
/// <param name="seconds"></param>
public virtual void Restart(int seconds)
{
m_log.Error("[REGION]: passing Restart Message up the namespace");
restart handlerPhysicsCrash = OnRestart;
if (handlerPhysicsCrash != null)
handlerPhysicsCrash(RegionInfo);
}
public virtual bool PresenceChildStatus(UUID avatarID)
{
return false;
}
public abstract bool OtherRegionUp(RegionInfo thisRegion);
public virtual string GetSimulatorVersion()
{
return "OpenSimulator Server";
}
#endregion
#region Shutdown
/// <summary>
/// Tidy before shutdown
/// </summary>
public virtual void Close()
{
// Shut down all non shared modules.
foreach (IRegionModule module in Modules.Values)
{
if (!module.IsSharedModule)
{
module.Close();
}
}
Modules.Clear();
try
{
EventManager.TriggerShutdown();
}
catch (Exception e)
{
m_log.Error("[SCENE]: SceneBase.cs: Close() - Failed with exception " + e.ToString());
}
}
#endregion
/// <summary>
/// Returns a new unallocated local ID
/// </summary>
/// <returns>A brand new local ID</returns>
protected internal uint AllocateLocalId()
{
uint myID;
_primAllocateMutex.WaitOne();
myID = ++m_lastAllocatedLocalId;
_primAllocateMutex.ReleaseMutex();
return myID;
}
#region Module Methods
/// <summary>
/// Add a module to this scene.
/// </summary>
/// <param name="name"></param>
/// <param name="module"></param>
public void AddModule(string name, IRegionModule module)
{
if (!Modules.ContainsKey(name))
{
Modules.Add(name, module);
}
}
/// <summary>
/// Add a region-module to this scene. TODO: This will replace AddModule in the future.
/// </summary>
/// <param name="name"></param>
/// <param name="module"></param>
public void AddRegionModule(string name, IRegionModuleBase module)
{
if (!RegionModules.ContainsKey(name))
{
RegionModules.Add(name, module);
}
}
public void RemoveRegionModule(string name)
{
RegionModules.Remove(name);
}
/// <summary>
/// Register a module commander.
/// </summary>
/// <param name="commander"></param>
public void RegisterModuleCommander(ICommander commander)
{
lock (m_moduleCommanders)
{
m_moduleCommanders.Add(commander.Name, commander);
}
}
/// <summary>
/// Unregister a module commander and all its commands
/// </summary>
/// <param name="name"></param>
public void UnregisterModuleCommander(string name)
{
lock (m_moduleCommanders)
{
ICommander commander;
if (m_moduleCommanders.TryGetValue(name, out commander))
m_moduleCommanders.Remove(name);
}
}
/// <summary>
/// Get a module commander
/// </summary>
/// <param name="name"></param>
/// <returns>The module commander, null if no module commander with that name was found</returns>
public ICommander GetCommander(string name)
{
lock (m_moduleCommanders)
{
if (m_moduleCommanders.ContainsKey(name))
return m_moduleCommanders[name];
}
return null;
}
public Dictionary<string, ICommander> GetCommanders()
{
return m_moduleCommanders;
}
/// <summary>
/// Register an interface to a region module. This allows module methods to be called directly as
/// well as via events. If there is already a module registered for this interface, it is not replaced
/// (is this the best behaviour?)
/// </summary>
/// <param name="mod"></param>
public void RegisterModuleInterface<M>(M mod)
{
List<Object> l = null;
if (!ModuleInterfaces.TryGetValue(typeof(M), out l))
{
l = new List<Object>();
ModuleInterfaces.Add(typeof(M), l);
}
if (l.Count > 0)
return;
l.Add(mod);
if (mod is IEntityCreator)
{
IEntityCreator entityCreator = (IEntityCreator)mod;
foreach (PCode pcode in entityCreator.CreationCapabilities)
{
m_entityCreators[pcode] = entityCreator;
}
}
}
public void UnregisterModuleInterface<M>(M mod)
{
List<Object> l;
if (ModuleInterfaces.TryGetValue(typeof(M), out l))
{
if (l.Remove(mod))
{
if (mod is IEntityCreator)
{
IEntityCreator entityCreator = (IEntityCreator)mod;
foreach (PCode pcode in entityCreator.CreationCapabilities)
{
m_entityCreators[pcode] = null;
}
}
}
}
}
public void StackModuleInterface<M>(M mod)
{
List<Object> l;
if (ModuleInterfaces.ContainsKey(typeof(M)))
l = ModuleInterfaces[typeof(M)];
else
l = new List<Object>();
if (l.Contains(mod))
return;
l.Add(mod);
if (mod is IEntityCreator)
{
IEntityCreator entityCreator = (IEntityCreator)mod;
foreach (PCode pcode in entityCreator.CreationCapabilities)
{
m_entityCreators[pcode] = entityCreator;
}
}
ModuleInterfaces[typeof(M)] = l;
}
/// <summary>
/// For the given interface, retrieve the region module which implements it.
/// </summary>
/// <returns>null if there is no registered module implementing that interface</returns>
public T RequestModuleInterface<T>()
{
if (ModuleInterfaces.ContainsKey(typeof(T)) &&
(ModuleInterfaces[typeof(T)].Count > 0))
return (T)ModuleInterfaces[typeof(T)][0];
else
return default(T);
}
/// <summary>
/// For the given interface, retrieve an array of region modules that implement it.
/// </summary>
/// <returns>an empty array if there are no registered modules implementing that interface</returns>
public T[] RequestModuleInterfaces<T>()
{
if (ModuleInterfaces.ContainsKey(typeof(T)))
{
List<T> ret = new List<T>();
foreach (Object o in ModuleInterfaces[typeof(T)])
ret.Add((T)o);
return ret.ToArray();
}
else
{
return new T[] { default(T) };
}
}
#endregion
/// <summary>
/// Shows various details about the sim based on the parameters supplied by the console command in openSimMain.
/// </summary>
/// <param name="showParams">What to show</param>
public virtual void Show(string[] showParams)
{
switch (showParams[0])
{
case "modules":
m_log.Error("The currently loaded modules in " + RegionInfo.RegionName + " are:");
foreach (IRegionModule module in Modules.Values)
{
if (!module.IsSharedModule)
{
m_log.Error("Region Module: " + module.Name);
}
}
break;
}
}
public void AddCommand(object mod, string command, string shorthelp, string longhelp, CommandDelegate callback)
{
if (MainConsole.Instance == null)
return;
string modulename = String.Empty;
bool shared = false;
if (mod != null)
{
if (mod is IRegionModule)
{
IRegionModule module = (IRegionModule)mod;
modulename = module.Name;
shared = module.IsSharedModule;
}
else if (mod is IRegionModuleBase)
{
IRegionModuleBase module = (IRegionModuleBase)mod;
modulename = module.Name;
shared = mod is ISharedRegionModule;
}
else throw new Exception("AddCommand module parameter must be IRegionModule or IRegionModuleBase");
}
MainConsole.Instance.Commands.AddCommand(modulename, shared, command, shorthelp, longhelp, callback);
}
}
}
| |
/*
'===============================================================================
' Generated From - CSharp_dOOdads_BusinessEntity.vbgen
'
' ** IMPORTANT **
' How to Generate your stored procedures:
'
' SQL = SQL_StoredProcs.vbgen
' ACCESS = Access_StoredProcs.vbgen
' ORACLE = Oracle_StoredProcs.vbgen
' FIREBIRD = FirebirdStoredProcs.vbgen
'
' The supporting base class OracleClientEntity is in the Architecture directory in "dOOdads".
'
' This object is 'abstract' which means you need to inherit from it to be able
' to instantiate it. This is very easilly done. You can override properties and
' methods in your derived class, this allows you to regenerate this class at any
' time and not worry about overwriting custom code.
'
' NEVER EDIT THIS FILE.
'
' public class YourObject : _YourObject
' {
'
' }
'
'===============================================================================
*/
// Generated by MyGeneration Version # (1.0.0.4)
using System;
using System.Data;
using System.Data.OracleClient;
using System.Collections;
using System.Collections.Specialized;
using MyGeneration.dOOdads;
namespace CSharp.ORACLE
{
public abstract class _EMPLOYEES : OracleClientEntity
{
public _EMPLOYEES()
{
this.SchemaGlobal = "HR.";
this.QuerySource = "MYEMPLOYEES";
this.MappingName = "MYEMPLOYEES";
}
//=================================================================
// public Overrides void AddNew()
//=================================================================
//
//=================================================================
public override void AddNew()
{
base.AddNew();
}
public override void FlushData()
{
this._whereClause = null;
base.FlushData();
}
//=================================================================
// public Function LoadAll() As Boolean
//=================================================================
// Loads all of the records in the database, and sets the currentRow to the first row
//=================================================================
public bool LoadAll()
{
ListDictionary parameters = null;
parameters = new ListDictionary();
OracleParameter p = new OracleParameter("outCursor", OracleType.Cursor);
p.Direction = ParameterDirection.Output;
parameters.Add(p, null);
return base.LoadFromSql(this.SchemaStoredProcedure + "PL_MYEMPLOYEES", parameters);
}
//=================================================================
// public Overridable Function LoadByPrimaryKey() As Boolean
//=================================================================
// Loads a single row of via the primary key
//=================================================================
public virtual bool LoadByPrimaryKey(decimal EMPLOYEE_ID)
{
ListDictionary parameters = new ListDictionary();
parameters.Add(Parameters.EMPLOYEE_ID, EMPLOYEE_ID);
OracleParameter p = new OracleParameter("outCursor", OracleType.Cursor);
p.Direction = ParameterDirection.Output;
parameters.Add(p, null);
return base.LoadFromSql(this.SchemaStoredProcedure + "PK_MYEMPLOYEES", parameters);
}
#region Parameters
protected class Parameters
{
public static OracleParameter EMPLOYEE_ID
{
get
{
return new OracleParameter("p_EMPLOYEE_ID", OracleType.Number, 0);
}
}
public static OracleParameter FIRST_NAME
{
get
{
return new OracleParameter("p_FIRST_NAME", OracleType.VarChar, 80);
}
}
public static OracleParameter LAST_NAME
{
get
{
return new OracleParameter("p_LAST_NAME", OracleType.VarChar, 80);
}
}
}
#endregion
#region ColumnNames
public class ColumnNames
{
public const string EMPLOYEE_ID = "EMPLOYEE_ID";
public const string FIRST_NAME = "FIRST_NAME";
public const string LAST_NAME = "LAST_NAME";
static public string ToPropertyName(string columnName)
{
if(ht == null)
{
ht = new Hashtable();
ht[EMPLOYEE_ID] = _EMPLOYEES.PropertyNames.EMPLOYEE_ID;
ht[FIRST_NAME] = _EMPLOYEES.PropertyNames.FIRST_NAME;
ht[LAST_NAME] = _EMPLOYEES.PropertyNames.LAST_NAME;
}
return (string)ht[columnName];
}
static private Hashtable ht = null;
}
#endregion
#region PropertyNames
public class PropertyNames
{
public const string EMPLOYEE_ID = "EMPLOYEE_ID";
public const string FIRST_NAME = "FIRST_NAME";
public const string LAST_NAME = "LAST_NAME";
static public string ToColumnName(string propertyName)
{
if(ht == null)
{
ht = new Hashtable();
ht[EMPLOYEE_ID] = _EMPLOYEES.ColumnNames.EMPLOYEE_ID;
ht[FIRST_NAME] = _EMPLOYEES.ColumnNames.FIRST_NAME;
ht[LAST_NAME] = _EMPLOYEES.ColumnNames.LAST_NAME;
}
return (string)ht[propertyName];
}
static private Hashtable ht = null;
}
#endregion
#region StringPropertyNames
public class StringPropertyNames
{
public const string EMPLOYEE_ID = "s_EMPLOYEE_ID";
public const string FIRST_NAME = "s_FIRST_NAME";
public const string LAST_NAME = "s_LAST_NAME";
}
#endregion
#region Properties
public virtual decimal EMPLOYEE_ID
{
get
{
return base.Getdecimal(ColumnNames.EMPLOYEE_ID);
}
set
{
base.Setdecimal(ColumnNames.EMPLOYEE_ID, value);
}
}
public virtual string FIRST_NAME
{
get
{
return base.Getstring(ColumnNames.FIRST_NAME);
}
set
{
base.Setstring(ColumnNames.FIRST_NAME, value);
}
}
public virtual string LAST_NAME
{
get
{
return base.Getstring(ColumnNames.LAST_NAME);
}
set
{
base.Setstring(ColumnNames.LAST_NAME, value);
}
}
#endregion
#region String Properties
public virtual string s_EMPLOYEE_ID
{
get
{
return this.IsColumnNull(ColumnNames.EMPLOYEE_ID) ? string.Empty : base.GetdecimalAsString(ColumnNames.EMPLOYEE_ID);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.EMPLOYEE_ID);
else
this.EMPLOYEE_ID = base.SetdecimalAsString(ColumnNames.EMPLOYEE_ID, value);
}
}
public virtual string s_FIRST_NAME
{
get
{
return this.IsColumnNull(ColumnNames.FIRST_NAME) ? string.Empty : base.GetstringAsString(ColumnNames.FIRST_NAME);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.FIRST_NAME);
else
this.FIRST_NAME = base.SetstringAsString(ColumnNames.FIRST_NAME, value);
}
}
public virtual string s_LAST_NAME
{
get
{
return this.IsColumnNull(ColumnNames.LAST_NAME) ? string.Empty : base.GetstringAsString(ColumnNames.LAST_NAME);
}
set
{
if(string.Empty == value)
this.SetColumnNull(ColumnNames.LAST_NAME);
else
this.LAST_NAME = base.SetstringAsString(ColumnNames.LAST_NAME, value);
}
}
#endregion
#region Where Clause
public class WhereClause
{
public WhereClause(BusinessEntity entity)
{
this._entity = entity;
}
public TearOffWhereParameter TearOff
{
get
{
if(_tearOff == null)
{
_tearOff = new TearOffWhereParameter(this);
}
return _tearOff;
}
}
#region TearOff's
public class TearOffWhereParameter
{
public TearOffWhereParameter(WhereClause clause)
{
this._clause = clause;
}
public WhereParameter EMPLOYEE_ID
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.EMPLOYEE_ID, Parameters.EMPLOYEE_ID);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter FIRST_NAME
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.FIRST_NAME, Parameters.FIRST_NAME);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
public WhereParameter LAST_NAME
{
get
{
WhereParameter where = new WhereParameter(ColumnNames.LAST_NAME, Parameters.LAST_NAME);
this._clause._entity.Query.AddWhereParameter(where);
return where;
}
}
private WhereClause _clause;
}
#endregion
public WhereParameter EMPLOYEE_ID
{
get
{
if(_EMPLOYEE_ID_W == null)
{
_EMPLOYEE_ID_W = TearOff.EMPLOYEE_ID;
}
return _EMPLOYEE_ID_W;
}
}
public WhereParameter FIRST_NAME
{
get
{
if(_FIRST_NAME_W == null)
{
_FIRST_NAME_W = TearOff.FIRST_NAME;
}
return _FIRST_NAME_W;
}
}
public WhereParameter LAST_NAME
{
get
{
if(_LAST_NAME_W == null)
{
_LAST_NAME_W = TearOff.LAST_NAME;
}
return _LAST_NAME_W;
}
}
private WhereParameter _EMPLOYEE_ID_W = null;
private WhereParameter _FIRST_NAME_W = null;
private WhereParameter _LAST_NAME_W = null;
public void WhereClauseReset()
{
_EMPLOYEE_ID_W = null;
_FIRST_NAME_W = null;
_LAST_NAME_W = null;
this._entity.Query.FlushWhereParameters();
}
private BusinessEntity _entity;
private TearOffWhereParameter _tearOff;
}
public WhereClause Where
{
get
{
if(_whereClause == null)
{
_whereClause = new WhereClause(this);
}
return _whereClause;
}
}
private WhereClause _whereClause = null;
#endregion
protected override IDbCommand GetInsertCommand()
{
OracleCommand cmd = new OracleCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = this.SchemaStoredProcedure + "PI_MYEMPLOYEES";
CreateParameters(cmd);
OracleParameter p;
p = cmd.Parameters[Parameters.EMPLOYEE_ID.ParameterName];
p.Direction = ParameterDirection.Output;
return cmd;
}
protected override IDbCommand GetUpdateCommand()
{
OracleCommand cmd = new OracleCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = this.SchemaStoredProcedure + "PU_MYEMPLOYEES";
CreateParameters(cmd);
return cmd;
}
protected override IDbCommand GetDeleteCommand()
{
OracleCommand cmd = new OracleCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = this.SchemaStoredProcedure + "PD_MYEMPLOYEES";
OracleParameter p;
p = cmd.Parameters.Add(Parameters.EMPLOYEE_ID);
p.SourceColumn = ColumnNames.EMPLOYEE_ID;
p.SourceVersion = DataRowVersion.Current;
return cmd;
}
private IDbCommand CreateParameters(OracleCommand cmd)
{
OracleParameter p;
p = cmd.Parameters.Add(Parameters.EMPLOYEE_ID);
p.SourceColumn = ColumnNames.EMPLOYEE_ID;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.FIRST_NAME);
p.SourceColumn = ColumnNames.FIRST_NAME;
p.SourceVersion = DataRowVersion.Current;
p = cmd.Parameters.Add(Parameters.LAST_NAME);
p.SourceColumn = ColumnNames.LAST_NAME;
p.SourceVersion = DataRowVersion.Current;
return cmd;
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
//namespace Instinct.ApplicationUnit_.WebApplicationControl
//{
// //- GoogleMap -//
// //+ [GoogleApi]http://www.google.com/apis/maps/documentation/
// //+ [Geocoder]http://geocoder.us/help/
// public class GoogleMap : System.Web.UI.WebControls.WebControl
// {
// private static System.Type s_type = typeof(GoogleMap);
// private System.Collections.Generic.Dictionary<int, GoogleMapPoint> m_pointHash = new System.Collections.Generic.Dictionary<int, GoogleMapPoint>();
// private System.Collections.Generic.Dictionary<int, GoogleMapTextOverlay> m_textOverlayHash = new System.Collections.Generic.Dictionary<int, GoogleMapTextOverlay>();
// private string m_keyID = string.Empty;
// private int m_zoomOffset = 0;
// private GoogleMapControlType m_controlType = GoogleMapControlType.Small;
// private GoogleMapPointType m_pointType = GoogleMapPointType.Simple;
// private bool m_isAutoSelect = true;
// private string m_iconRootUri = "/";
// //- GoogleMapControlType -//
// public enum GoogleMapControlType
// {
// Large,
// LargePlus,
// Small,
// SmallPlus
// }
// //- GoogleMapPointType -//
// public enum GoogleMapPointType
// {
// Simple,
// Direction
// }
// //- Main -//
// public GoogleMap()
// {
// Width = new System.Web.UI.WebControls.Unit("560px");
// Height = new System.Web.UI.WebControls.Unit("400px");
// }
// public GoogleMap(string width, string height)
// {
// Width = new System.Web.UI.WebControls.Unit(width);
// Height = new System.Web.UI.WebControls.Unit(height);
// }
// //- AddPoint -//
// public void AddPoint(GoogleMapPoint point)
// {
// m_pointHash.Add(m_pointHash.Count, point);
// }
// //- AddTextOverlay -//
// public void AddTextOverlay(GoogleMapTextOverlay textOverlay)
// {
// m_textOverlayHash.Add(m_textOverlayHash.Count, textOverlay);
// }
// //- AppendMapToStream -//
// private void AppendMapToStream(System.Text.StringBuilder textStream)
// {
// textStream.AppendLine(" var map = new GMap2(document.getElementById(\"" + ClientID + "\"));");
// switch (m_controlType)
// {
// case GoogleMapControlType.Large:
// textStream.AppendLine(" map.addControl(new GLargeMapControl());");
// break;
// case GoogleMapControlType.LargePlus:
// textStream.AppendLine(" map.addControl(new GLargeMapControl()); map.addControl(new GMapTypeControl());");
// break;
// case GoogleMapControlType.Small:
// textStream.AppendLine(" map.addControl(new GSmallMapControl());");
// break;
// case GoogleMapControlType.SmallPlus:
// textStream.AppendLine(" map.addControl(new GSmallMapControl()); map.addControl(new GMapTypeControl());");
// break;
// }
// }
// //- ControlType -//
// public GoogleMapControlType ControlType
// {
// get
// {
// return m_controlType;
// }
// set
// {
// m_controlType = value;
// }
// }
// //- ZoomOffset -//
// public int ZoomOffset
// {
// get
// {
// return m_zoomOffset;
// }
// set
// {
// m_zoomOffset = value;
// }
// }
// //- KeyID -//
// public string KeyID
// {
// get
// {
// return m_keyID;
// }
// set
// {
// m_keyID = value;
// }
// }
// //- PointType -//
// public GoogleMapPointType PointType
// {
// get
// {
// return m_pointType;
// }
// set
// {
// m_pointType = value;
// }
// }
// //- IconRootUri -//
// public string IconRootUri
// {
// get
// {
// return m_iconRootUri;
// }
// set
// {
// m_iconRootUri = value;
// }
// }
// //- IsAutoSelect -//
// public bool IsAutoSelect
// {
// get
// {
// return m_isAutoSelect;
// }
// set
// {
// m_isAutoSelect = value;
// }
// }
// //- OnPreRender -//
// protected override void OnPreRender(System.EventArgs e)
// {
// base.OnPreRender(e);
// WebApplicationFactory.RegisterScript(Page, WebApplicationFactory.RegisterScriptFlag.Kernel);
// Page.ClientScript.RegisterClientScriptInclude(s_type, "Google", "http://maps.google.com/maps?file=api&v=2&key=" + m_keyID);
// if (m_textOverlayHash.Count > 0)
// {
// Page.ClientScript.RegisterClientScriptBlock(s_type, "GoogleMapTextOverlay", @"
//<script type=""text/javascript"">
////<![CDATA[
//function GoogleMapTextOverlay(html, point, width, height, borderStyle, moveByX, moveByY, textAlign, verticalAlign) {
// this.html_ = html;
// this.point_ = point;
// this.width_ = width;
// this.height_ = height;
// this.borderStyle_ = borderStyle;
// this.moveByX_ = moveByX;
// this.moveByY_ = moveByY;
// this.textAlign_ = textAlign;
// this.verticalAlign_ = verticalAlign;
//}
//GoogleMapTextOverlay.prototype = new GOverlay();
//
////+ creates the DIV representing this GoogleMapTextOverlay.
//GoogleMapTextOverlay.prototype.initialize = function(map) {
// // create the div representing our GoogleMapTextOverlay
// var div = document.createElement('div');
// div.style.border = this.borderStyle_;
// div.style.position = 'absolute';
// div.style.width = this.width_;
// div.style.height = this.height_;
// div.style.textAlign = this.textAlign_;
// div.style.verticalAlign = this.verticalAlign_;
// div.innerHTML = this.html_;
// //+ GoogleMapTextOverlay is flat against the map, so we add our selves to the MAP_PANE pane,
// //+ which is at the same z-index as the map itself (i.e., below the marker shadows)
// map.getPane(G_MAP_MAP_PANE).appendChild(div);
// //+
// this.map_ = map;
// this.div_ = div;
//}
//
////+ remove the main DIV from the map pane
//GoogleMapTextOverlay.prototype.remove = function() {
// this.div_.parentNode.removeChild(this.div_);
//}
//
////+ copy data to a new GoogleMapTextOverlay
//GoogleMapTextOverlay.prototype.copy = function() {
// return new GoogleMapTextOverlay(this.html_, this.point_, this.width_, this.height_, this.borderStyle_, this.moveByX_, this.moveByY_, this.textAlign_, this.verticalAlign_);
//}
//
////+ redraw the GoogleMapTextOverlay based on the current projection and zoom level
//GoogleMapTextOverlay.prototype.redraw = function(force) {
// // redraw only if the coordinate system has changed
// if (!force) return;
// //+ map point to location in div
// var c1 = this.map_.fromLatLngToDivPixel(this.point_);
// // position div
// this.div_.style.left = (c1.x + this.moveByX_) + 'px';
// this.div_.style.top = (c1.y + this.moveByY_) + 'px';
//}
////]]>
//</script>", false);
// }
// switch (m_pointType)
// {
// case GoogleMapPointType.Direction:
// if (Page.ClientScript.IsClientScriptBlockRegistered(s_type, "Direction") == false)
// {
// string clientID = ClientID;
// System.Text.StringBuilder textBuilder = new System.Text.StringBuilder();
// textBuilder.Append(@"<script type=""text/javascript"">
////<![CDATA[
//function GoogleMapTo(key) {
// var o = _gel('"); textBuilder.Append(clientID); textBuilder.Append(@"');
// if (o != null) {
// o.Marker[key].openInfoWindowHtml(o.ToText[key]);
// }
//}
//function GoogleMapFrom(key) {
// var o = _gel('"); textBuilder.Append(clientID); textBuilder.Append(@"');
// if (o != null) {
// o.Marker[key].openInfoWindowHtml(o.FromText[key]);
// }
//}
//var g_icon = new GIcon();
//g_icon.shadow = '"); textBuilder.Append(m_iconRootUri); textBuilder.Append(@"IconShadow.png';
//g_icon.iconSize = new GSize(20, 34);
//g_icon.shadowSize = new GSize(37, 34);
//g_icon.iconAnchor = new GPoint(9, 34);
//g_icon.infoWindowAnchor = new GPoint(9, 2);
//g_icon.infoShadowAnchor = new GPoint(18, 25);
//function CreatePoint(o, bound, key, icon, point, address, text) {
// bound.extend(point);
// o.ToText[key] = text
// + '<br />Directions: <b>To here</b> - <a href=""javascript:GoogleMapFrom(' + key + ')"">From here</a>'
// + '<br />Start address:<form action=""http://maps.google.com/maps"" method=""get"" target=""_blank"" style=""margin: 0;"">'
// + '<input id=""saddr"" name=""saddr"" type=""text"" size=""25"" maxlength=""60"" value="""" /><br />'
// + '<input value=""Get Directions"" type=""submit"">'
// + '<input type=""hidden"" name=""daddr"" value=""' + address + '""/></form>';
// o.FromText[key] = text
// + '<br />Directions: <a href=""javascript:GoogleMapTo(' + key + ')"">To here</a> - <b>From here</b>'
// + '<br />End address:<form action=""http://maps.google.com/maps"" method=""get"" target=""_blank"" style=""margin: 0;"">'
// + '<input id=""daddr"" name=""daddr"" type=""text"" size=""25"" maxlength=""60"" value="""" /><br />'
// + '<input value=""Get Directions"" type=""submit"">'
// + '<input type=""hidden"" name=""saddr"" value=""' + address + '""/></form>';
// text = text.replace(/\[\:Direction\:\]/, 'Directions: <a href=""javascript:GoogleMapTo(' + key + ')"">To here</a> - <a href=""javascript:GoogleMapFrom(' + key + ')"">From here</a>');
// if (icon != '') {
// var icon2 = new GIcon(g_icon);
// icon2.image = '"); textBuilder.Append(m_iconRootUri); textBuilder.Append(@"' + icon + '.png';
// var marker = new GMarker(point, icon2);
// } else {
// var marker = new GMarker(point);
// }
// GEvent.addListener(marker, 'click', function() {
// marker.openInfoWindowHtml(text);
// });
// o.Marker[key] = marker;
// o.Text[key] = text;
// return marker;
//}
////]]>
//</script>");
// Page.ClientScript.RegisterClientScriptBlock(s_type, "Direction", textBuilder.ToString(), false);
// }
// break;
// }
// }
// //- Render -//
// protected override void Render(System.Web.UI.HtmlTextWriter writer)
// {
// HtmlBuilder z = HtmlBuilder.GetBuilder(writer);
// //+
// string clientID = ClientID;
// System.Text.StringBuilder textBuilder;
// switch (m_pointType)
// {
// case GoogleMapPointType.Simple:
// if (m_pointHash.Count < 1)
// {
// return;
// }
// //+ startup script
// textBuilder = new System.Text.StringBuilder();
// textBuilder.AppendLine("if (GBrowserIsCompatible() != null) {");
// AppendMapToStream(textBuilder);
// GoogleMapPoint point = m_pointHash[0];
// //+ 37.4419, -122.1419, 13
// textBuilder.AppendFormat(" map.setCenter(new GLatLng({0}, {1}), {2});\r\n", point.Latitude, point.Longitude, point.Zoom); point = null;
// //+ text overlay
// foreach (GoogleMapTextOverlay textOverlay in m_textOverlayHash.Values)
// {
// textBuilder.AppendFormat(" map.addOverlay(new GoogleMapTextOverlay('{0}', new GLatLng({1}, {2}), '{3}', '{4}', '{5}', {6}, {7}, '{8}', '{9}'));\r\n", textOverlay.Html, textOverlay.Latitude, textOverlay.Longitude, textOverlay.Width, textOverlay.Height, textOverlay.BorderStyle, textOverlay.MoveByX, textOverlay.MoveByY, textOverlay.TextAlign, textOverlay.VerticalAlign);
// }
// textBuilder.AppendLine("}");
// Page.ClientScript.RegisterStartupScript(s_type, clientID, textBuilder.ToString(), true);
// break;
// case GoogleMapPointType.Direction:
// if (m_pointHash.Count < 1)
// {
// return;
// }
// //+ startup script
// textBuilder = new System.Text.StringBuilder();
// textBuilder.Append(@"<script type=""text/javascript"">
////<![CDATA[
//if (window.Kernel) {
// Kernel.AddEvent(window, 'load', function() {
//var o = _gel('"); textBuilder.Append(clientID); textBuilder.AppendLine(@"');
//if ((o != null) && (GBrowserIsCompatible() != null)) {
// var key = 0;
// o.Marker = [];
// o.Text = [];
// o.ToText = [];
// o.FromText = [];");
// AppendMapToStream(textBuilder);
// textBuilder.AppendLine(" var bound = new GLatLngBounds();");
// foreach (GoogleMapPoint point2 in m_pointHash.Values)
// {
// string address = KernelText.Axb(point2.Street, " ", point2.Street2) + ", " + KernelText.Axb(KernelText.Axb(point2.City, " ", point2.State), " ", point2.Zip);
// textBuilder.AppendFormat(" CreatePoint(o, bound, key++, '{0}', new GLatLng({1}, {2}), unescape('{3}'), unescape('{4}'));\r\n", point2.Icon, point2.Latitude, point2.Longitude, Http.Escape(address), Http.Escape(point2.Text));
// }
// textBuilder.Append(@"
// var centerLat = (bound.getNorthEast().lat() + bound.getSouthWest().lat()) / 2;
// var centerLng = (bound.getNorthEast().lng() + bound.getSouthWest().lng()) / 2;
// var zoomLevel = map.getBoundsZoomLevel(bound);
// map.setCenter(new GLatLng(centerLat, centerLng), zoomLevel - "); textBuilder.Append(m_zoomOffset); textBuilder.Append(@");
// while (key > 0) {
// map.addOverlay(o.Marker[--key]);
// };");
// if ((m_isAutoSelect == true) && (m_pointHash.Count == 1))
// {
// textBuilder.AppendLine(" o.Marker[0].openInfoWindowHtml(o.Text[0]);");
// }
// //+ text overlay
// foreach (GoogleMapTextOverlay textOverlay in m_textOverlayHash.Values)
// {
// textBuilder.AppendFormat(" map.addOverlay(new GoogleMapTextOverlay('{0}', new GLatLng({1}, {2}), '{3}', '{4}', '{5}', {6}, {7}, '{8}', '{9}'));\r\n", textOverlay.Html, textOverlay.Latitude, textOverlay.Longitude, textOverlay.Width, textOverlay.Height, textOverlay.BorderStyle, textOverlay.MoveByX, textOverlay.MoveByY, textOverlay.TextAlign, textOverlay.VerticalAlign);
// }
// textBuilder.Append(@"
//}
// });
//}
////]]>
//</script>");
// Page.ClientScript.RegisterStartupScript(s_type, clientID, textBuilder.ToString(), false);
// break;
// }
// //+ render
// z.AddHtmlAttrib(HtmlAttrib.Id, clientID);
// z.AddHtmlAttrib(HtmlAttrib.StyleWidth, Width.ToString());
// z.AddHtmlAttrib(HtmlAttrib.StyleHeight, Height.ToString());
// z.EmptyHtmlTag(HtmlTag.Div);
// }
// //- POINT -//
// #region POINT
// //- GoogleMapPoint -//
// public class GoogleMapPoint
// {
// private string m_icon = string.Empty;
// private string m_street = string.Empty;
// private string m_street2 = string.Empty;
// private string m_city = string.Empty;
// private string m_state = string.Empty;
// private string m_zip = string.Empty;
// private string m_text = string.Empty;
// private decimal m_latitude = -1;
// private decimal m_longitude = -1;
// private int m_zoom = -1;
// //- Main -//
// public GoogleMapPoint()
// {
// }
// public GoogleMapPoint(TableBase table, string fieldPrefix)
// {
// m_street = table.GetText(fieldPrefix + "Street");
// m_street2 = table.GetText(fieldPrefix + "Street2");
// m_city = table.GetText(fieldPrefix + "City");
// m_state = table.GetText(fieldPrefix + "State");
// m_zip = table.GetText(fieldPrefix + "Zip");
// SetCoordinate(table[fieldPrefix + "Latitude"], table[fieldPrefix + "Longitude"]);
// }
// //- Icon -//
// public string Icon
// {
// get
// {
// return m_icon;
// }
// set
// {
// m_icon = value;
// }
// }
// //- Street -//
// public string Street
// {
// get
// {
// return m_street;
// }
// set
// {
// m_street = value;
// }
// }
// //- Street2 -//
// public string Street2
// {
// get
// {
// return m_street2;
// }
// set
// {
// m_street2 = value;
// }
// }
// //- City -//
// public string City
// {
// get
// {
// return m_city;
// }
// set
// {
// m_city = value;
// }
// }
// //- State -//
// public string State
// {
// get
// {
// return m_state;
// }
// set
// {
// m_state = value;
// }
// }
// //- Zip -//
// public string Zip
// {
// get
// {
// return m_zip;
// }
// set
// {
// m_zip = value;
// }
// }
// //- Text -//
// public string Text
// {
// get
// {
// return m_text;
// }
// set
// {
// m_text = value;
// }
// }
// //- Latitude -//
// public decimal Latitude
// {
// get
// {
// return m_latitude;
// }
// set
// {
// m_latitude = value;
// }
// }
// //- Longitude -//
// public decimal Longitude
// {
// get
// {
// return m_longitude;
// }
// set
// {
// m_longitude = value;
// }
// }
// //- Zoom -//
// public int Zoom
// {
// get
// {
// return m_zoom;
// }
// set
// {
// m_zoom = value;
// }
// }
// //- SetCoordinate -//
// public void SetCoordinate(object latitude, object longitude)
// {
// string textLatitude;
// m_latitude = -1;
// if (latitude != null)
// {
// if (latitude is decimal)
// {
// m_latitude = (decimal)latitude;
// }
// else if ((textLatitude = (latitude as string)) != null)
// {
// decimal.TryParse(textLatitude, out m_latitude);
// }
// }
// string textLongitude;
// m_longitude = -1;
// if (longitude != null)
// {
// if (longitude is decimal)
// {
// m_longitude = (decimal)longitude;
// }
// else if ((textLongitude = (longitude as string)) != null)
// {
// decimal.TryParse(textLongitude, out m_longitude);
// }
// }
// }
// //- GeocodeAddress -//
// public bool GeocodeAddress(string googleMapApi)
// {
// string url = "http://maps.google.com/maps/geo?q=" + Http.UrlEncode(string.Concat(KernelText.Axb(Street, " ", Street2), ", ", KernelText.Axb(KernelText.Axb(City, " ", State), " ", Zip))) + "&output=csv&key=" + googleMapApi;
// System.Net.HttpWebRequest httpRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
// System.Net.HttpWebResponse httpResponse = null;
// try
// {
// httpResponse = (System.Net.HttpWebResponse)httpRequest.GetResponse();
// }
// catch (System.Exception)
// {
// return false;
// }
// string[] responseArray;
// try
// {
// responseArray = KernelIo.ReadTextStream(httpResponse.GetResponseStream()).Split(new string[] { "\r\n" }, System.StringSplitOptions.RemoveEmptyEntries);
// }
// catch (System.Exception e)
// {
// KernelEvent.LogEvent(LogEventType.Warning, "GoogleMap::GeocodeAddress", e);
// return false;
// }
// finally
// {
// httpResponse.Close();
// }
// responseArray = responseArray[responseArray.GetUpperBound(0)].Split(',');
// if (Kernel.ParseInt32(responseArray[0], 0) != 200)
// {
// return false;
// }
// if (responseArray.GetUpperBound(0) == 3)
// {
// SetCoordinate(responseArray[2], responseArray[3]);
// return true;
// }
// return false;
// }
// }
// #endregion POINT
// //- TEXTOVERLAY -//
// #region TEXTOVERLAY
// //- GoogleMapTextOverlay -//
// public class GoogleMapTextOverlay
// {
// private string m_borderStyle = string.Empty;
// private string m_html = string.Empty;
// private decimal m_latitude = -1;
// private decimal m_longitude = -1;
// private System.Web.UI.WebControls.Unit m_width = -1;
// private System.Web.UI.WebControls.Unit m_height = -1;
// private int m_moveByX;
// private int m_moveByY;
// private string m_textAlign = string.Empty;
// private string m_verticalAlign = string.Empty;
// //- Main -//
// public GoogleMapTextOverlay()
// {
// }
// public GoogleMapTextOverlay(string html, decimal latitude, decimal longitude, System.Web.UI.WebControls.Unit width, System.Web.UI.WebControls.Unit height)
// : this(html, latitude, longitude, width, height, 0, 0, "left", "top")
// {
// }
// public GoogleMapTextOverlay(string html, decimal latitude, decimal longitude, string width, string height)
// : this(html, latitude, longitude, new System.Web.UI.WebControls.Unit(width), new System.Web.UI.WebControls.Unit(height), 0, 0, "left", "top")
// {
// }
// public GoogleMapTextOverlay(string html, decimal latitude, decimal longitude, string width, string height, int moveByX, int moveByY, string textAlign, string verticalAlign)
// : this(html, latitude, longitude, new System.Web.UI.WebControls.Unit(width), new System.Web.UI.WebControls.Unit(height), moveByX, moveByY, textAlign, verticalAlign)
// {
// }
// public GoogleMapTextOverlay(string html, decimal latitude, decimal longitude, System.Web.UI.WebControls.Unit width, System.Web.UI.WebControls.Unit height, int moveByX, int moveByY, string textAlign, string verticalAlign)
// {
// m_html = html;
// m_latitude = latitude;
// m_longitude = longitude;
// m_width = width;
// m_height = height;
// m_moveByX = moveByX;
// m_moveByY = moveByY;
// m_textAlign = textAlign;
// m_verticalAlign = verticalAlign;
// }
// //- BorderStyle -//
// public string BorderStyle
// {
// get
// {
// return m_borderStyle;
// }
// set
// {
// m_borderStyle = value;
// }
// }
// //- Height -//
// public System.Web.UI.WebControls.Unit Height
// {
// get
// {
// return m_height;
// }
// set
// {
// m_height = value;
// }
// }
// //- Html -//
// public string Html
// {
// get
// {
// return m_html;
// }
// set
// {
// m_html = value;
// }
// }
// //- Latitude -//
// public decimal Latitude
// {
// get
// {
// return m_latitude;
// }
// set
// {
// m_latitude = value;
// }
// }
// //- Longitude -//
// public decimal Longitude
// {
// get
// {
// return m_longitude;
// }
// set
// {
// m_longitude = value;
// }
// }
// //- MoveByX -//
// public int MoveByX
// {
// get
// {
// return m_moveByX;
// }
// set
// {
// m_moveByX = value;
// }
// }
// //- MoveByY -//
// public int MoveByY
// {
// get
// {
// return m_moveByY;
// }
// set
// {
// m_moveByY = value;
// }
// }
// //- TextAlign -//
// public string TextAlign
// {
// get
// {
// return m_textAlign;
// }
// set
// {
// m_textAlign = value;
// }
// }
// //- VerticalAlign -//
// public string VerticalAlign
// {
// get
// {
// return m_verticalAlign;
// }
// set
// {
// m_verticalAlign = value;
// }
// }
// //- Width -//
// public System.Web.UI.WebControls.Unit Width
// {
// get
// {
// return m_width;
// }
// set
// {
// m_width = value;
// }
// }
// }
// #endregion TEXTOVERLAY
// }
//}
| |
//------------------------------------------------------------------------------
// <copyright file="OdbcConnectionHandle.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Runtime.ConstrainedExecution;
namespace System.Data.Odbc {
sealed internal class OdbcConnectionHandle : OdbcHandle {
private HandleState _handleState;
private enum HandleState {
Allocated = 0,
Connected = 1,
Transacted = 2,
TransactionInProgress = 3,
}
internal OdbcConnectionHandle(OdbcConnection connection, OdbcConnectionString constr, OdbcEnvironmentHandle environmentHandle) : base(ODBC32.SQL_HANDLE.DBC, environmentHandle) {
if(null == connection) {
throw ADP.ArgumentNull("connection");
}
if(null == constr) {
throw ADP.ArgumentNull("constr");
}
ODBC32.RetCode retcode;
//Set connection timeout (only before open).
//Note: We use login timeout since its odbc 1.0 option, instead of using
//connectiontimeout (which affects other things besides just login) and its
//a odbc 3.0 feature. The ConnectionTimeout on the managed providers represents
//the login timeout, nothing more.
int connectionTimeout = connection.ConnectionTimeout;
retcode = SetConnectionAttribute2(ODBC32.SQL_ATTR.LOGIN_TIMEOUT, (IntPtr)connectionTimeout, (Int32)ODBC32.SQL_IS.UINTEGER);
string connectionString = constr.UsersConnectionString(false);
// Connect to the driver. (Using the connection string supplied)
//Note: The driver doesn't filter out the password in the returned connection string
//so their is no need for us to obtain the returned connection string
// Prepare to handle a ThreadAbort Exception between SQLDriverConnectW and update of the state variables
retcode = Connect(connectionString);
connection.HandleError(this, retcode);
}
private ODBC32.RetCode AutoCommitOff() {
ODBC32.RetCode retcode;
Debug.Assert(HandleState.Connected <= _handleState, "AutoCommitOff while in wrong state?");
// Avoid runtime injected errors in the following block.
// must call SQLSetConnectAttrW and set _handleState
RuntimeHelpers.PrepareConstrainedRegions();
try {} finally {
retcode = UnsafeNativeMethods.SQLSetConnectAttrW(this, ODBC32.SQL_ATTR.AUTOCOMMIT, ODBC32.SQL_AUTOCOMMIT_OFF, (Int32)ODBC32.SQL_IS.UINTEGER);
switch(retcode) {
case ODBC32.RetCode.SUCCESS:
case ODBC32.RetCode.SUCCESS_WITH_INFO:
_handleState = HandleState.Transacted;
break;
}
}
ODBC.TraceODBC(3, "SQLSetConnectAttrW", retcode);
return retcode;
}
internal ODBC32.RetCode BeginTransaction(ref IsolationLevel isolevel) {
ODBC32.RetCode retcode = ODBC32.RetCode.SUCCESS;
ODBC32.SQL_ATTR isolationAttribute;
if(IsolationLevel.Unspecified != isolevel) {
ODBC32.SQL_TRANSACTION sql_iso;
switch(isolevel) {
case IsolationLevel.ReadUncommitted:
sql_iso = ODBC32.SQL_TRANSACTION.READ_UNCOMMITTED;
isolationAttribute = ODBC32.SQL_ATTR.TXN_ISOLATION;
break;
case IsolationLevel.ReadCommitted:
sql_iso = ODBC32.SQL_TRANSACTION.READ_COMMITTED;
isolationAttribute = ODBC32.SQL_ATTR.TXN_ISOLATION;
break;
case IsolationLevel.RepeatableRead:
sql_iso = ODBC32.SQL_TRANSACTION.REPEATABLE_READ;
isolationAttribute = ODBC32.SQL_ATTR.TXN_ISOLATION;
break;
case IsolationLevel.Serializable:
sql_iso = ODBC32.SQL_TRANSACTION.SERIALIZABLE;
isolationAttribute = ODBC32.SQL_ATTR.TXN_ISOLATION;
break;
case IsolationLevel.Snapshot:
sql_iso = ODBC32.SQL_TRANSACTION.SNAPSHOT;
// VSDD 414121: Snapshot isolation level must be set through SQL_COPT_SS_TXN_ISOLATION (http://msdn.microsoft.com/en-us/library/ms131709.aspx)
isolationAttribute = ODBC32.SQL_ATTR.SQL_COPT_SS_TXN_ISOLATION;
break;
case IsolationLevel.Chaos:
throw ODBC.NotSupportedIsolationLevel(isolevel);
default:
throw ADP.InvalidIsolationLevel(isolevel);
}
//Set the isolation level (unless its unspecified)
retcode = SetConnectionAttribute2(isolationAttribute, (IntPtr)sql_iso, (Int32)ODBC32.SQL_IS.INTEGER);
//Note: The Driver can return success_with_info to indicate it "rolled" the
//isolevel to the next higher value. If this is the case, we need to requery
//the value if th euser asks for it...
//We also still propagate the info, since it could be other info as well...
if(ODBC32.RetCode.SUCCESS_WITH_INFO == retcode) {
isolevel = IsolationLevel.Unspecified;
}
}
switch(retcode) {
case ODBC32.RetCode.SUCCESS:
case ODBC32.RetCode.SUCCESS_WITH_INFO:
//Turn off auto-commit (which basically starts the transaction)
retcode = AutoCommitOff();
_handleState = HandleState.TransactionInProgress;
break;
}
return retcode;
}
internal ODBC32.RetCode CompleteTransaction(short transactionOperation) {
bool mustRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try {
DangerousAddRef(ref mustRelease);
ODBC32.RetCode retcode = CompleteTransaction(transactionOperation, base.handle);
return retcode;
}
finally {
if (mustRelease) {
DangerousRelease();
}
}
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private ODBC32.RetCode CompleteTransaction(short transactionOperation, IntPtr handle) {
// must only call this code from ReleaseHandle or DangerousAddRef region
ODBC32.RetCode retcode = ODBC32.RetCode.SUCCESS;
// using ConstrainedRegions to make the native ODBC call and change the _handleState
RuntimeHelpers.PrepareConstrainedRegions();
try { } finally {
if (HandleState.TransactionInProgress == _handleState) {
retcode = UnsafeNativeMethods.SQLEndTran(HandleType, handle, transactionOperation);
if((ODBC32.RetCode.SUCCESS == retcode) || (ODBC32.RetCode.SUCCESS_WITH_INFO == retcode)) {
_handleState = HandleState.Transacted;
}
Bid.TraceSqlReturn("<odbc.SQLEndTran|API|ODBC|RET> %08X{SQLRETURN}\n", retcode);
}
if (HandleState.Transacted == _handleState) { // AutoCommitOn
retcode = UnsafeNativeMethods.SQLSetConnectAttrW(handle, ODBC32.SQL_ATTR.AUTOCOMMIT, ODBC32.SQL_AUTOCOMMIT_ON, (Int32)ODBC32.SQL_IS.UINTEGER);
_handleState = HandleState.Connected;
Bid.TraceSqlReturn("<odbc.SQLSetConnectAttr|API|ODBC|RET> %08X{SQLRETURN}\n", retcode);
}
}
//Overactive assert which fires if handle was allocated - but failed to connect to the server
//it can more legitmately fire if transaction failed to rollback - but there isn't much we can do in that situation
//Debug.Assert((HandleState.Connected == _handleState) || (HandleState.TransactionInProgress == _handleState), "not expected HandleState.Connected");
return retcode;
}
private ODBC32.RetCode Connect(string connectionString) {
Debug.Assert(HandleState.Allocated == _handleState, "SQLDriverConnect while in wrong state?");
ODBC32.RetCode retcode;
// Avoid runtime injected errors in the following block.
RuntimeHelpers.PrepareConstrainedRegions();
try {} finally {
short cbActualSize;
retcode = UnsafeNativeMethods.SQLDriverConnectW(this, ADP.PtrZero, connectionString, ODBC32.SQL_NTS, ADP.PtrZero, 0, out cbActualSize, (short)ODBC32.SQL_DRIVER.NOPROMPT);
switch(retcode) {
case ODBC32.RetCode.SUCCESS:
case ODBC32.RetCode.SUCCESS_WITH_INFO:
_handleState = HandleState.Connected;
break;
}
}
ODBC.TraceODBC(3, "SQLDriverConnectW", retcode);
return retcode;
}
override protected bool ReleaseHandle() {
// NOTE: The SafeHandle class guarantees this will be called exactly once and is non-interrutible.
ODBC32.RetCode retcode;
// must call complete the transaction rollback, change handle state, and disconnect the connection
retcode = CompleteTransaction(ODBC32.SQL_ROLLBACK, handle);
if ((HandleState.Connected == _handleState) || (HandleState.TransactionInProgress == _handleState)) {
retcode = UnsafeNativeMethods.SQLDisconnect(handle);
_handleState = HandleState.Allocated;
Bid.TraceSqlReturn("<odbc.SQLDisconnect|API|ODBC|RET> %08X{SQLRETURN}\n", retcode);
}
Debug.Assert(HandleState.Allocated == _handleState, "not expected HandleState.Allocated");
return base.ReleaseHandle();
}
internal ODBC32.RetCode GetConnectionAttribute(ODBC32.SQL_ATTR attribute, byte[] buffer, out int cbActual) {
ODBC32.RetCode retcode = UnsafeNativeMethods.SQLGetConnectAttrW(this, attribute, buffer, buffer.Length, out cbActual);
Bid.Trace("<odbc.SQLGetConnectAttr|ODBC> SQLRETURN=%d, Attribute=%d, BufferLength=%d, StringLength=%d\n", (int)retcode, (int)attribute, buffer.Length, (int)cbActual);
return retcode;
}
internal ODBC32.RetCode GetFunctions(ODBC32.SQL_API fFunction, out Int16 fExists) {
ODBC32.RetCode retcode = UnsafeNativeMethods.SQLGetFunctions(this, fFunction, out fExists);
ODBC.TraceODBC(3, "SQLGetFunctions", retcode);
return retcode;
}
internal ODBC32.RetCode GetInfo2(ODBC32.SQL_INFO info, byte[] buffer, out short cbActual) {
ODBC32.RetCode retcode = UnsafeNativeMethods.SQLGetInfoW(this, info, buffer, checked((short)buffer.Length), out cbActual);
Bid.Trace("<odbc.SQLGetInfo|ODBC> SQLRETURN=%d, InfoType=%d, BufferLength=%d, StringLength=%d\n", (int)retcode, (int)info, buffer.Length, (int)cbActual);
return retcode;
}
internal ODBC32.RetCode GetInfo1(ODBC32.SQL_INFO info, byte[] buffer) {
ODBC32.RetCode retcode = UnsafeNativeMethods.SQLGetInfoW(this, info, buffer, checked((short)buffer.Length), ADP.PtrZero);
Bid.Trace("<odbc.SQLGetInfo|ODBC> SQLRETURN=%d, InfoType=%d, BufferLength=%d\n", (int)retcode, (int)info, buffer.Length);
return retcode;
}
internal ODBC32.RetCode SetConnectionAttribute2(ODBC32.SQL_ATTR attribute, IntPtr value, Int32 length) {
ODBC32.RetCode retcode = UnsafeNativeMethods.SQLSetConnectAttrW(this, attribute, value, length);
ODBC.TraceODBC(3, "SQLSetConnectAttrW", retcode);
return retcode;
}
internal ODBC32.RetCode SetConnectionAttribute3(ODBC32.SQL_ATTR attribute, string buffer, Int32 length) {
ODBC32.RetCode retcode = UnsafeNativeMethods.SQLSetConnectAttrW(this, attribute, buffer, length);
Bid.Trace("<odbc.SQLSetConnectAttr|ODBC> SQLRETURN=%d, Attribute=%d, BufferLength=%d\n", (int)retcode, (int)attribute, buffer.Length);
return retcode;
}
internal ODBC32.RetCode SetConnectionAttribute4(ODBC32.SQL_ATTR attribute, System.Transactions.IDtcTransaction transaction, Int32 length) {
ODBC32.RetCode retcode = UnsafeNativeMethods.SQLSetConnectAttrW(this, attribute, transaction, length);
ODBC.TraceODBC(3, "SQLSetConnectAttrW", retcode);
return retcode;
}
}
}
| |
//
// OpenTemplate
// Copyright (c) 2006
// by OpenArrow Software ( http://www.openarrow.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.Generic;
using System.Text;
using System.Collections.ObjectModel;
using OpenArrow.Templating.Properties;
namespace OpenArrow.Templating
{
/// <summary>
/// Represents an error or warning that occurred during the execution of an activity
/// </summary>
[Serializable()]
public class Problem
{
/// <summary>
/// Error that occurs when an input file does not exist (OTC0001)
/// </summary>
/// <param name="fileName">The file that does not exist</param>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <error number="OTC0001"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
public static Problem Error_InputFileDoesNotExist(string fileName)
{ return NewError(String.Format(Resources.Error_InputFileDoesNotExist, fileName), -1, -1, "OTC0001"); }
/// <summary>
/// Error that occurs when an invalid character is found in a directive name (OTC0002)
/// </summary>
/// <param name="c">The invalid character</param>
/// <param name="lineNo">The line number of the error</param>
/// <param name="column">The column of the error</param>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <error number="OTC0002"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
public static Problem Error_InvalidCharacterInDirectiveName(char c, int lineNo, int column)
{ return NewError(String.Format(Resources.Error_InvalidCharacterInDirectiveName, c), lineNo, column, "OTC0002"); }
/// <summary>
/// Error that occurs when multiple "=" characters are found in a Directive Attribute definition (OTC0003)
/// </summary>
/// <param name="lineNo">The line number of the error</param>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <error number="OTC0003"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
public static Problem Error_MultipleEqualsCharactersInAttr(int lineNo)
{ return NewError(Resources.Error_MultipleEqualsCharactersInAttr, lineNo, -1, "OTC0003"); }
/// <summary>
/// Warning that occurs when a Directive name is not registered and could not be loaded (OTC0004)
/// </summary>
/// <param name="name">The name of the directive that is not registered</param>
/// <param name="lineNo">The line number of the warning</param>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the warning</returns>
/// <error number="OTC0004"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
public static Problem Warning_DirectiveTypeNotRegistered(string name, int lineNo)
{ return NewWarning(String.Format(Resources.Warning_DirectiveTypeNotRegistered, name), lineNo, -1, "OTC0004"); }
/// <summary>
/// Error that occurs when an attribute in a directive declaration is not recognized (OTC0005)
/// </summary>
/// <param name="name">The name of the attribute that is not recognized</param>
/// <param name="lineNo">The line number of the error</param>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <error number="OTC0005"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
public static Problem Error_UnrecognizedAttribute(string name, int lineNo)
{ return NewError(String.Format(Resources.Error_UnrecognizedAttribute, name), lineNo, -1, "OTC0005"); }
/// <summary>
/// Error that occurs when an attribute in a directive declaration is associated with a read-only property (OTC0006)
/// </summary>
/// <param name="name">The name of the attribute that is associated with a read-only property</param>
/// <param name="lineNo">The line number of the error</param>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <error number="OTC0006"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
public static Problem Error_CannotMapAttributeToReadOnlyProperty(string name, int lineNo)
{ return NewError(String.Format(Resources.Error_CannotMapAttributeToReadOnlyProperty, name), lineNo, -1, "OTC0006"); }
/// <summary>
/// Error that occurs when the value of an attribute could not be converted to the type expected by the property (OTC0007)
/// </summary>
/// <param name="name">The name of the attribute for which the value could not be converted</param>
/// <param name="lineNo">The line number of the error</param>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <error number="OTC0007"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
public static Problem Error_FailedToConvertAttributeValue(string name, int lineNo)
{ return NewError(String.Format(Resources.Error_FailedToConvertAttributeValue, name), lineNo, -1, "OTC0007"); }
/// <summary>
/// Error that occurs when parsing cannot continue due to a large number of errors (OTC0008)
/// </summary>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <error number="OTC0008"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
public static Problem Error_UnableToContinueParsing()
{ return NewError(Resources.Error_UnableToContinueParsing, -1, -1, "OTC0008"); }
/// <summary>
/// Error that occurs when a <see cref="System.CodeDom.Compiler.CodeDomProvider"/> could not be found for the language specified in a
/// Template directive (OTC0009)
/// </summary>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <error number="OTC0009"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
public static Problem Error_LanguageMismatch()
{ return NewError(Resources.Error_LanguageMismatch, -1, -1, "OTC0009"); }
/// <summary>
/// Error that occurs when a template file does not have a Template directive (OTC0010)
/// </summary>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <error number="OTC0010"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
public static Problem Error_NoTemplateDirective()
{ return NewError(Resources.Error_NoTemplateDirective, -1, -1, "OTC0010"); }
/// <summary>
/// Error that occurs when a Template directive does not specify a value for the
/// <see cref="OpenArrow.Templating.Directives.TemplateDirective.ClassName"/> property (OTC0011)
/// </summary>
/// <param name="lineNo">The line number of the error</param>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <error number="OTC0011"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
public static Problem Error_NoClassNameSpecified(int lineNo)
{ return NewError(Resources.Error_NoClassNameSpecified, lineNo, -1, "OTC0011"); }
/// <summary>
/// Warning that occurs when a Template directive does not specify a value for the
/// <see cref="OpenArrow.Templating.Directives.TemplateDirective.Namespace"/> property (OTC0012)
/// </summary>
/// <param name="defaultNamespace">The default namespace that was assumed</param>
/// <param name="lineNo">The line number of the error</param>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <error number="OTC0012"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
public static Problem Warning_NoNamespaceSpecified(string defaultNamespace, int lineNo)
{ return NewWarning(String.Format(Resources.Warning_NoNamespaceSpecified, defaultNamespace), lineNo, -1, "OTC0012"); }
/// <summary>
/// Error that occurs when a Template directive does not specify a value for the
/// <see cref="OpenArrow.Templating.Directives.TemplateDirective.Language"/> property (OTC0013)
/// </summary>
/// <param name="lineNo">The line number of the error</param>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <error number="OTC0013"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
public static Problem Error_NoLanguageSpecified(int lineNo)
{ return NewError(Resources.Error_NoLanguageSpecified, lineNo, -1, "OTC0013"); }
/// <summary>
/// Warning that occurs when there are multiple Template directives in a template file (OTC0014)
/// </summary>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <error number="OTC0014"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
public static Problem Warning_MultipleTemplateDirectives()
{ return NewWarning(Resources.Warning_MultipleTemplateDirectives, -1, -1, "OTC0014"); }
/// <summary>
/// Warning that occurs when the template file uses a feature that is not implemented yet (OTC0015)
/// </summary>
/// <param name="feature">The feature that is not implemented</param>
/// <param name="lineNo">The line number of the error</param>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <error number="OTC0015"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)")]
public static Problem Warning_FeatureNotImplemented(string feature, int lineNo)
{ return NewWarning(String.Format(Resources.Warning_MultipleTemplateDirectives, feature), lineNo, -1, "OTC0015"); }
/// <summary>
/// Error that occurs when compilation cannot continue due to a large number of errors (OTC0016)
/// </summary>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <error number="OTC0016"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
public static Problem Error_UnableToContinueCompiling()
{ return NewError(Resources.Error_UnableToContinueCompiling, -1, -1, "OTC0016"); }
/// <summary>
/// Error that occurs when a Template directive was not found in the template file (OTC0017)
/// </summary>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <error number="OTC0017"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
public static Problem Error_TemplateDirectiveNotFound()
{ return NewError(Resources.Error_UnableToContinueCompiling, -1, -1, "OTC0017"); }
/// <summary>
/// Error that occurs when a Template directive does not specify a value for the
/// <see cref="OpenArrow.Templating.Directives.TemplateDirective.Language"/> property (OTC0019)
/// </summary>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <error number="OTC0018"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
public static Problem Error_NoLanguageSpecified()
{ return NewError(Resources.Error_NoLanguageSpecified, -1, -1, "OTC0018"); }
/// <summary>
/// Error that occurs when there are no valid templates to compile (OTC0019)
/// </summary>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <error number="OTC0019"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
public static Problem Error_NoValidTemplatesToCompile()
{ return NewError(Resources.Error_NoValidTemplatesToCompile, -1, -1, "OTC0019"); }
/// <summary>
/// Error that occurs when a Property directive does not specify a value for the
/// <see cref="OpenArrow.Templating.Directives.PropertyDirective.Name"/> property (OTC0020)
/// </summary>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <error number="OTC0020"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
public static Problem Error_NoPropertyNameSpecified()
{ return NewError(Resources.Error_NoPropertyNameSpecified, -1, -1, "OTC0020"); }
/// <summary>
/// Error that occurs when a Property directive does not specify a value for the
/// <see cref="OpenArrow.Templating.Directives.PropertyDirective.Type"/> property (OTC0021)
/// </summary>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <error number="OTC0021"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
public static Problem Error_NoPropertyTypeSpecified()
{ return NewError(Resources.Error_NoPropertyTypeSpecified, -1, -1, "OTC0021"); }
/// <summary>
/// Error that occurs when the response file for the OTC Compiler could not be parsed (OTC0022)
/// </summary>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <error number="OTC0022"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
public static Problem Error_CouldNotParseResponseFile()
{ return Problem.NewError(Resources.Error_CouldNotParseResponseFile, -1, -1, "OTC0022"); }
private bool isError;
private string message;
private string errorNumber;
private int line;
private int col;
/// <summary>
/// Gets or sets a boolean determining if this problem is an error or a warning
/// </summary>
public bool IsError
{
get { return isError; }
set { isError = value; }
}
/// <summary>
/// Gets or sets a message attached to this problem
/// </summary>
public string Message
{
get { return message; }
set { message = value; }
}
/// <summary>
/// Gets or sets the error number associated with this problem
/// </summary>
public string ErrorNumber
{
get { return errorNumber; }
set { errorNumber = value; }
}
/// <summary>
/// Gets or sets the line number of this problem
/// </summary>
public int Line
{
get { return line; }
set { line = value; }
}
/// <summary>
/// Gets or sets the column of this problem
/// </summary>
public int Col
{
get { return col; }
set { col = value; }
}
/// <summary>
/// Constructs a new <see cref="Problem"/> object
/// </summary>
/// <remarks>Private constructor, use one of the overloads of <see cref="Problem.NewError"/> or <see cref="Problem.NewWarning"/></remarks>
/// <exception cref="ArgumentException"><paramref name="message"/> is <see langword="null"/> or <see cref="String.Empty"/></exception>
private Problem(bool isError, string message, int line, int col, string errorNumber)
{
if (String.IsNullOrEmpty(message))
throw new ArgumentException(String.Format(Resources.Exception_ArgIsNullOrEmpty, "message"), "message");
this.isError = isError;
this.message = message;
this.line = line;
this.col = col;
this.errorNumber = errorNumber;
}
/// <summary>
/// Converts this object to a string representation
/// </summary>
/// <returns>A string representation of this object</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object[])"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object)")]
public override string ToString()
{
string lineRef = String.Empty;
if(this.Line != -1) {
if(this.Col != -1)
lineRef = String.Format("({0}, {1}) ", this.Line, this.Col);
else
lineRef = String.Format("({0}) ", this.Line);
}
return String.Format("{0}{1} {2}: {3}", lineRef, this.IsError ? "ERROR" : "WARN", this.ErrorNumber, this.Message);
}
/// <summary>
/// Creates a new error
/// </summary>
/// <param name="message">The message associated with the error</param>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <exception cref="ArgumentException"><paramref name="message"/> is <see langword="null"/> or <see cref="String.Empty"/></exception>
public static Problem NewError(string message) { return new Problem(true, message, -1, -1, String.Empty); }
/// <summary>
/// Creates a new error
/// </summary>
/// <param name="message">The message associated with the error</param>
/// <param name="line">The line number of the error</param>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <exception cref="ArgumentException"><paramref name="message"/> is <see langword="null"/> or <see cref="String.Empty"/></exception>
public static Problem NewError(string message, int line) { return new Problem(true, message, line, -1, String.Empty); }
/// <summary>
/// Creates a new error
/// </summary>
/// <param name="message">The message associated with the error</param>
/// <param name="line">The line number of the error</param>
/// <param name="col">The column of the error</param>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <exception cref="ArgumentException"><paramref name="message"/> is <see langword="null"/> or <see cref="String.Empty"/></exception>
public static Problem NewError(string message, int line, int col) { return new Problem(true, message, line, col, String.Empty); }
/// <summary>
/// Creates a new error
/// </summary>
/// <param name="message">The message associated with the error</param>
/// <param name="line">The line number of the error</param>
/// <param name="col">The column of the error</param>
/// <param name="errorNumber">The number associated with the error</param>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the error</returns>
/// <exception cref="ArgumentException"><paramref name="message"/> is <see langword="null"/> or <see cref="String.Empty"/></exception>
public static Problem NewError(string message, int line, int col, string errorNumber) { return new Problem(true, message, line, col, errorNumber); }
/// <summary>
/// Creates a new warning
/// </summary>
/// <param name="message">The message associated with the warning</param>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the warning</returns>
/// <exception cref="ArgumentException"><paramref name="message"/> is <see langword="null"/> or <see cref="String.Empty"/></exception>
public static Problem NewWarning(string message) { return new Problem(false, message, -1, -1, String.Empty); }
/// <summary>
/// Creates a new warning
/// </summary>
/// <param name="message">The message associated with the warning</param>
/// <param name="line">The line number of the warning</param>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the warning</returns>
/// <exception cref="ArgumentException"><paramref name="message"/> is <see langword="null"/> or <see cref="String.Empty"/></exception>
public static Problem NewWarning(string message, int line) { return new Problem(false, message, line, -1, String.Empty); }
/// <summary>
/// Creates a new warning
/// </summary>
/// <param name="message">The message associated with the warning</param>
/// <param name="line">The line number of the warning</param>
/// <param name="col">The column of the warning</param>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the warning</returns>
/// <exception cref="ArgumentException"><paramref name="message"/> is <see langword="null"/> or <see cref="String.Empty"/></exception>
public static Problem NewWarning(string message, int line, int col) { return new Problem(false, message, line, col, String.Empty); }
/// <summary>
/// Creates a new warning
/// </summary>
/// <param name="message">The message associated with the warning</param>
/// <param name="line">The line number of the warning</param>
/// <param name="col">The column of the warning</param>
/// <param name="errorNumber">The number associated with the warning</param>
/// <returns>A <see cref="OpenArrow.Templating.Problem"/> object representing the warning</returns>
/// <exception cref="ArgumentException"><paramref name="message"/> is <see langword="null"/> or <see cref="String.Empty"/></exception>
public static Problem NewWarning(string message, int line, int col, string errorNumber) { return new Problem(false, message, line, col, errorNumber); }
}
}
| |
using GuruComponents.Netrix.WebEditing.Elements;
namespace GuruComponents.Netrix.WebEditing.HighLighting
{
/// <summary>
/// Interface allows access to text selection features.
/// </summary>
/// <remarks>
/// Retrieve an instance by accessing the <see cref="IHtmlEditor.TextSelector">TextSelector</see> property of base control.
/// </remarks>
/// <seealso cref="IHtmlEditor.TextSelector"/>
public interface ITextSelector
{
/// <summary>
/// Returns the current selection positions, based on markup pointers, within a given element.
/// </summary>
/// <remarks>
/// The values ignore all HTML formatting and count just characters. Returns -1 for both if there is no selection.
/// <para>
/// The method expects an element object. See other overload to retrieve within the body.
/// </para>
/// <para>
/// This method does not interfer other method in this class. It's deterministic in any way.
/// </para>
/// </remarks>
/// <param name="withinElement">Element within the selection is searched.</param>
/// <param name="posStart">Returns the start position within the body range, in characters, zero based.</param>
/// <param name="posEnd">Returns the start position within the body range, in characters, zero based.</param>
void GetSelectionPosition(IElement withinElement, out long posStart, out long posEnd);
/// <summary>
/// Returns the current selection positions, based on markup pointers.
/// </summary>
/// <remarks>
/// The values ignore all HTML formatting and count just characters. Returns -1 for both if there is no selection.
/// <para>
/// This method does not interfer other method in this class. It's deterministic in any way.
/// </para>
/// </remarks>
/// <param name="posStart">Returns the start position within the body range, in characters, zero based.</param>
/// <param name="posEnd">Returns the start position within the body range, in characters, zero based.</param>
void GetSelectionPosition(out long posStart, out long posEnd);
/// <summary>
/// Sets the gravity attribute of this pointer.
/// </summary>
/// <param name="pointer">The Pointer which gravity is to set.</param>
/// <param name="gravity">The gravity which is to set.</param>
void SetPointerGravity(PointerSelection pointer, PointerGravity gravity);
/// <overloads/>
/// <summary>
/// Returns a collection of information about both pointers.
/// </summary>
/// <remarks>
/// The number of character the information method retrieves is set to 1.
/// <seealso cref="GetPointerInformation(bool,int)"/>
/// </remarks>
/// <param name="Move">Value that specifies TRUE if the pointer is to move past the content to the left (right respectively), or FALSE otherwise. If TRUE, the pointer will move either to the other side of the tag to its left, or up to the number of characters specified by parameter tryChars, depending on the <see cref="ContextType"/> to the pointer's left (right respectively).</param>
/// <returns>Returns a structure with basic pointer informations.</returns>
PointerInformation GetPointerInformation(bool Move);
/// <summary>
/// Returns a collection of information about both pointers.
/// </summary>
/// <remarks>
/// <seealso cref="GetPointerInformation(bool)"/>
/// </remarks>
/// <param name="Move">Value that specifies TRUE if the pointer is to move past the content to the left (right respectively), or FALSE otherwise. If TRUE, the pointer will move either to the other side of the tag to its left, or up to the number of characters specified by parameter tryChars, depending on the <see cref="ContextType"/> to the pointer's left (right respectively).</param>
/// <param name="tryChars">Variable that specifies the number of characters to retrieve to XXXRetrieveChars property, if <see cref="ContextType"/> is <see cref="ContextType.Text"/>,
/// and receives the actual number of characters the method was able to retrieve. It can be set to -1,
/// indicating that the method should retrieve an arbitrary amount of text, up to the next no-scope element
/// or element scope transition.</param>
/// <returns>Returns a structure with basic pointer informations.</returns>
PointerInformation GetPointerInformation(bool Move, int tryChars);
/// <summary>
/// Retrieves the position of a markup pointer.
/// </summary>
/// <remarks>As long as the pointer's positioned, the method can be used to retrieve the carets position at line.</remarks>
/// <returns>Returns markup pointer's position</returns>
int GetMarkupPosition(PointerSelection pointer);
/// <summary>
/// Determines if the markup pointer is positioned at a word break.
/// </summary>
/// <param name="pointer">If <c>False</c> the first Pointer is checked, the second otherwise.</param>
bool IsAtWordBreak(PointerSelection pointer);
/// <summary>
/// Determines if a markup pointer is located inside of, at the beginning of, or at the end of text that is formatted as a URL.
/// </summary>
bool IsInsideURL(PointerSelection pointer);
/// <summary>
/// Moves a markup pointer to a particular element in a markup container.
/// </summary>
void MoveToElementContent(PointerSelection pointer, GuruComponents.Netrix.WebEditing.Elements.IElement element, bool atStart);
/// <summary>
/// Moves a markup pointer to a specified location in a specified direction, but not past the other markup pointer.
/// </summary>
/// <remarks>
/// This method can simplify the usage of pointers, because it avoids an frequently mistake which results
/// in some loss of functionality; the positioning of the second pointer before the first one.
/// </remarks>
void MoveUnitBounded(PointerSelection pointer, MoveUnit mu);
/// <summary>
/// Set the default highlight style.
/// </summary>
/// <remarks>
/// This methiod pre-sets the highlight style. The current selection will not be changeds.
/// </remarks>
/// <param name="HighLightStyle">The highlight style object which is used from now on.</param>
void SetHighLightStyle(IHighLightStyle HighLightStyle);
/// <summary>
/// Highlights the current range.
/// </summary>
/// <remarks>
/// This method cannot work if no text fragment was selected before call. The highlight style should be set
/// before first call.
/// </remarks>
bool HighLightRange();
/// <summary>
/// This method deletes the content of the current base range.
/// </summary>
void DeleteRangeText();
/// <summary>
/// Reset the range pointer to the beginning of the document.
/// </summary>
void ResetRangePointers();
/// <summary>
/// Returns the last added highlight segment.
/// </summary>
/// <remarks>
/// This segment contains a method which can be used to remove the segment later.
/// </remarks>
IHighLightSegment LastSegment { get; }
/// <summary>
/// Remove all highlighted fragments.
/// </summary>
void RemoveHighLighting();
/// <overloads>This method has two overloads.</overloads>
/// <summary>
/// Select the current range between two pointers.
/// </summary>
/// <remarks>
/// This method does not scroll into view if the fragment selected was outside the designer surface.
/// </remarks>
void SelectPointerRange();
/// <summary>
/// Select the current range between two pointers.
/// </summary>
/// <remarks>
/// Assure to set the text pointers before calling this method.
/// </remarks>
/// <param name="ScrollIntoView">If set to <c>true</c> the control tries to scroll the selected range into the visible area.</param>
void SelectPointerRange(bool ScrollIntoView);
/// <overloads>This method has two overloads.</overloads>
/// <summary>
/// Selects a previously selected and stored fragment.
/// </summary>
/// <remarks>
/// This method does not scroll into view if the fragment selected was outside the designer surface.
/// </remarks>
void SelectRange(string key);
/// <summary>
/// Selects a previously selected and stored fragment.
/// </summary>
/// <param name="key">The name of the stored fragment.</param>
/// <param name="ScrollIntoView">If set to <c>true</c> the control tries to scroll the selected range into the visible area.</param>
void SelectRange(string key, bool ScrollIntoView);
/// <summary>
/// Returns the text between two valid pointers.
/// </summary>
/// <returns>The text between the pointers. HTML tags are stripped out.</returns>
string GetTextBetweenPointers();
/// <summary>
/// Returns the HTML between two valid pointers.
/// </summary>
/// <returns>The text between the pointers. HTML tags are preserved.</returns>
string GetHtmlBetweenPointers();
/// <summary>
/// Set (overwrite) all text between current pointers.
/// </summary>
/// <param name="text">Text to be written.</param>
void SetTextBetweenPointers(string text);
/// <summary>
/// Set (overwrite) all text between current pointers with HTML.
/// </summary>
/// <param name="html">Html to be written.</param>
void SetHtmlBetweenPointers(string html);
/// <summary>
/// Deletes the text between the pointers.
/// </summary>
/// <remarks>If the selection is fragmented HTML a valid structure will be rebuild.</remarks>
void DeleteTextBetweenPointers();
/// <summary>
/// Searches a text between the pointers.
/// </summary>
/// <remarks>
/// This is a nice enhancement of the regular find function to narrow a search. It searches the whole document,
/// but starts searching using the current pointer position. So in case you want to restart search from the
/// beginning, just set the pointers back by calling <see cref="MovePointersToElement"/>, <see cref="MoveFirstPointer"/>,
/// or <see cref="MoveSecondPointer"/>.
/// </remarks>
/// <param name="searchString">A string to search for.</param>
/// <param name="upWards">Search upwards.</param>
/// <param name="matchCase">Must be set to <c>true</c> if match case is required.</param>
/// <param name="wholeWord">Must set to <c>true</c> if only whole words should be found.</param>
/// <returns>Returns <c>true</c> if something was found, <c>false</c> otherwise. Also returns <c>false</c> in case document ends.</returns>
bool FindTextBetweenPointers(string searchString, bool upWards, bool matchCase, bool wholeWord);
/// <summary>
/// Call this to reset the pointers to catch the whole document.
/// </summary>
void ResetFindWordPointer();
/// <summary>
/// Move the first pointer.
/// </summary>
/// <remarks>
/// The pointers can be used to create a range. The range can be moved too, using the
/// <see cref="MoveCurrentRange">MoveCurrentRange</see>
/// method.
/// </remarks>
/// <param name="Move">The first pointer will be moved to the given destination.</param>
void MoveFirstPointer(MoveTextPointer Move);
/// <summary>
/// Move the pointers to the caret to start next positioning around the caret.
/// </summary>
/// <remarks>
/// It is recommended to set the pointers actively before any caret related move operation starts.
/// </remarks>
void MovePointersToCaret();
/// <summary>
/// Move the second pointer.
/// </summary>
/// <remarks>
/// The pointers can be used to create a range. The range can be moved too, using the
/// <see cref="MoveCurrentRange">MoveCurrentRange</see>
/// method.
/// </remarks>
/// <param name="Move">The second pointer will be moved to the given destination.</param>
void MoveSecondPointer(MoveTextPointer Move);
/// <summary>
/// Move the current range completely.
/// </summary>
/// <param name="Move"></param>
/// <param name="Count"></param>
int MoveCurrentRange(MoveUnit Move, int Count);
/// <summary>
/// Moves the current range start point.
/// </summary>
/// <remarks>
/// This method may fail if the start point is beyond the end point.
/// </remarks>
/// <param name="Move"></param>
/// <param name="Count"></param>
int MoveCurrentRangeStart(MoveUnit Move, int Count);
/// <summary>
/// Moves the current range end point.
/// </summary>
/// <remarks>
/// This method may fail if the end point is before the start point.
/// </remarks>
int MoveCurrentRangeEnd(MoveUnit Move, int Count);
/// <summary>
/// Stores the current range for later access.
/// </summary>
/// <remarks>
/// This method can be used with the highlighting feature to highlight a prepared range later.
/// </remarks>
/// <param name="key"></param>
void SaveCurrentRange(string key);
/// <summary>
/// Clears all stored ranges.
/// </summary>
/// <remarks>
/// This removes highlighting and stored range pointers, but preserves the text selected with the range.
/// </remarks>
void ClearRangeStore();
/// <summary>
/// This method checks if a stored range is inside the current range.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
bool IsInCurrentRange(string key);
/// <summary>
/// This method checks if a stored range equals the current range.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
bool EqualsCurrentRange(string key);
/// <summary>
/// This method compares the endpoints.
/// </summary>
/// <param name="compare"></param>
/// <param name="key"></param>
/// <returns></returns>
int CompareEndPoints(CompareUnit compare, string key);
/// <summary>
/// Causes the object to scroll into view, aligning either to top or bottom of the window.
/// </summary>
/// <remarks>
/// Depending on the size of the given range the control may not be able to scroll exactly to the very top or
/// very bottom of the window, but will position the object as close to the requested position as possible.
/// </remarks>
/// <param name="atStart"></param>
void ScrollIntoView(bool atStart);
/// <summary>
/// Moves the caret (insertion point) to the beginning or end of the current range.
/// </summary>
/// <param name="atStart"></param>
void MoveCaretToPointer(bool atStart);
/// <summary>
/// Expand the current range to that partial units are completely contained.
/// </summary>
/// <param name="ExpandTo"></param>
/// <returns></returns>
bool ExpandRange(MoveUnit ExpandTo);
/// <summary>
/// Selects the whole text of the given element.
/// </summary>
/// <remarks>
/// This is a mixed mode command, uses internally Pointers and Ranges. The command will move both
/// pointers to the elements boundaries. Then the current base range is set to these pointers and finally
/// used to set the elements content. After all the changed content is selected and scrolled into view.
/// </remarks>
/// <param name="element">Any element object that implements <see cref="GuruComponents.Netrix.WebEditing.Elements.IElement">IElement</see> and that does contain selectable text.</param>
void SelectElementText(GuruComponents.Netrix.WebEditing.Elements.IElement element);
/// <summary>
/// Set the pointers to the inner border of the tag.
/// </summary>
/// <param name="element">The tag from which the content should be highlighted. </param>
/// <param name="withRange">Whether or not the current base range should follow the pointers immediataly.</param>
void MovePointersToElement(GuruComponents.Netrix.WebEditing.Elements.IElement element, bool withRange);
/// <summary>
/// Move the range to current pointers.
/// </summary>
void MoveRangeToPointers();
/// <summary>
/// Returns the text available in the current range.
/// </summary>
/// <returns></returns>
string GetTextInRange();
/// <summary>
/// Returns the HTML available in the current range.
/// </summary>
/// <returns></returns>
string GetHtmlInRange();
/// <summary>
/// Overwrite all text in range.
/// </summary>
/// <param name="text"></param>
void SetTextInRange(string text);
/// <summary>
/// Return text of a stored range.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
string GetTextInStoredRange(string key);
/// <summary>
/// Return HTML of the stored range.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
string GetHtmlInStoredRange(string key);
/// <summary>
/// Select the current range.
/// </summary>
void SelectRange();
/// <summary>
/// Paste the HTML text into the element.
/// </summary>
/// <remarks>
/// Element must be of type container. The HTML must be valid after pasting.
/// </remarks>
/// <seealso cref="Paste(IElement)"/>
/// <param name="element">The element in which the HTML has to be pasted.</param>
/// <param name="html">Any valid HTML text.</param>
void PasteHtml(IElement element, string html);
/// <summary>
/// Paste the Clipboard text into the element.
/// </summary>
/// <remarks>
/// Element must be of type container. The HTML must be valid after pasting.
/// </remarks>
/// <seealso cref="PasteHtml"/>
/// <exception cref="System.ArgumentException">Thrown if the clipboard has no valid data. Expected formats are HTML and Text.</exception>
/// <param name="element">The element in which the HTML has to be pasted.</param>
void Paste(IElement element);
/// <summary>
/// Paste the current content of clipboard at current caret position and let pointers and range follow the insertion point.
/// </summary>
void Paste();
/// <summary>
/// Take the current selection and set the pointer to stay in sync with that selection.
/// </summary>
/// <returns>Returns <c>true</c> if successful (selection exists).</returns>
bool SyncRangeWithSelection();
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="CloudAnchorPreprocessBuild.cs" company="Google">
//
// Copyright 2018 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCoreInternal
{
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
using System.Xml;
using UnityEditor;
using UnityEditor.Build;
using UnityEngine;
internal class CloudAnchorPreprocessBuild : PreprocessBuildBase
{
private const string k_ManifestTemplateGuid = "5e182918f0b8c4929a3d4b0af0ed6f56";
private const string k_PluginsFolderGuid = "93be2b9777c348648a2d9151b7e233fc";
private const string k_RuntimeSettingsPath = "GoogleARCore/Resources/RuntimeSettings";
public override void OnPreprocessBuild(BuildTarget target, string path)
{
if (target == BuildTarget.Android)
{
_PreprocessAndroidBuild();
}
else if (target == BuildTarget.iOS)
{
_PreprocessIosBuild();
}
}
private void _PreprocessAndroidBuild()
{
// Get the Jdk path.
var jdkPath = UnityEditor.EditorPrefs.GetString("JdkPath");
if (string.IsNullOrEmpty(jdkPath))
{
Debug.Log(
"Unity 'Preferences > External Tools > Android JDK' path is not set. " +
"Falling back to JAVA_HOME environment variable.");
jdkPath = System.Environment.GetEnvironmentVariable("JAVA_HOME");
}
if (string.IsNullOrEmpty(jdkPath))
{
throw new BuildFailedException(
"A JDK path needs to be specified for the Android build.");
}
bool cloudAnchorsEnabled =
!string.IsNullOrEmpty(ARCoreProjectSettings.Instance.CloudServicesApiKey);
var cachedCurrentDirectory = Directory.GetCurrentDirectory();
var pluginsFolderPath = Path.Combine(cachedCurrentDirectory,
AssetDatabase.GUIDToAssetPath(k_PluginsFolderGuid));
string cloudAnchorsManifestAarPath =
Path.Combine(pluginsFolderPath, "cloud_anchor_manifest.aar");
var jarPath = Path.Combine(jdkPath, "bin/jar");
if (cloudAnchorsEnabled)
{
// If the Api Key didn't change then do nothing.
if (!_IsApiKeyDirty(jarPath, cloudAnchorsManifestAarPath,
ARCoreProjectSettings.Instance.CloudServicesApiKey))
{
return;
}
// Replace the project's cloud anchor AAR with the newly generated AAR.
Debug.Log("Enabling Cloud Anchors in this build.");
var tempDirectoryPath =
Path.Combine(cachedCurrentDirectory, FileUtil.GetUniqueTempPathInProject());
try
{
// Move to a temp directory.
Directory.CreateDirectory(tempDirectoryPath);
Directory.SetCurrentDirectory(tempDirectoryPath);
var manifestTemplatePath = Path.Combine(
cachedCurrentDirectory,
AssetDatabase.GUIDToAssetPath(k_ManifestTemplateGuid));
// Extract the "template AAR" and remove it.
string output;
string errors;
ShellHelper.RunCommand(
jarPath, string.Format("xf \"{0}\"", manifestTemplatePath), out output,
out errors);
// Replace Api key template parameter in manifest file.
var manifestPath = Path.Combine(tempDirectoryPath, "AndroidManifest.xml");
var manifestText = File.ReadAllText(manifestPath);
manifestText = manifestText.Replace(
"{{CLOUD_ANCHOR_API_KEY}}",
ARCoreProjectSettings.Instance.CloudServicesApiKey);
File.WriteAllText(manifestPath, manifestText);
// Compress the new AAR.
var fileListBuilder = new StringBuilder();
foreach (var filePath in Directory.GetFiles(tempDirectoryPath))
{
fileListBuilder.AppendFormat(" {0}", Path.GetFileName(filePath));
}
string command = string.Format(
"cf cloud_anchor_manifest.aar {0}", fileListBuilder.ToString());
ShellHelper.RunCommand(
jarPath,
command,
out output,
out errors);
if (!string.IsNullOrEmpty(errors))
{
throw new BuildFailedException(
string.Format(
"Error creating jar for cloud anchor manifest: {0}", errors));
}
File.Copy(Path.Combine(tempDirectoryPath, "cloud_anchor_manifest.aar"),
cloudAnchorsManifestAarPath, true);
}
finally
{
// Cleanup.
Directory.SetCurrentDirectory(cachedCurrentDirectory);
Directory.Delete(tempDirectoryPath, true);
AssetDatabase.Refresh();
}
AssetHelper.GetPluginImporterByName("cloud_anchor_manifest.aar")
.SetCompatibleWithPlatform(BuildTarget.Android, true);
}
else
{
Debug.Log(
"Cloud Anchor API key has not been set. Cloud Anchors will be disabled in " +
"this build.");
File.Delete(cloudAnchorsManifestAarPath);
AssetDatabase.Refresh();
}
}
private bool _IsApiKeyDirty(string jarPath, string aarPath, string apiKey)
{
bool isApiKeyDirty = true;
var cachedCurrentDirectory = Directory.GetCurrentDirectory();
var tempDirectoryPath =
Path.Combine(cachedCurrentDirectory, FileUtil.GetUniqueTempPathInProject());
if (!File.Exists(aarPath))
{
return isApiKeyDirty;
}
try
{
// Move to a temp directory.
Directory.CreateDirectory(tempDirectoryPath);
Directory.SetCurrentDirectory(tempDirectoryPath);
var tempAarPath = Path.Combine(tempDirectoryPath, "cloud_anchor_manifest.aar");
File.Copy(aarPath, tempAarPath, true);
// Extract the aar.
string output;
string errors;
ShellHelper.RunCommand(jarPath, string.Format("xf \"{0}\"", tempAarPath),
out output, out errors);
// Read Api key parameter in manifest file.
var manifestPath = Path.Combine(tempDirectoryPath, "AndroidManifest.xml");
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(manifestPath);
XmlNode metaDataNode =
xmlDocument.SelectSingleNode("/manifest/application/meta-data");
string oldApiKey = metaDataNode.Attributes["android:value"].Value;
isApiKeyDirty = !apiKey.Equals(oldApiKey);
}
finally
{
// Cleanup.
Directory.SetCurrentDirectory(cachedCurrentDirectory);
Directory.Delete(tempDirectoryPath, true);
}
return isApiKeyDirty;
}
private void _PreprocessIosBuild()
{
var runtimeSettingsPath = Path.Combine(Application.dataPath, k_RuntimeSettingsPath);
Directory.CreateDirectory(runtimeSettingsPath);
string cloudServicesApiKey = ARCoreProjectSettings.Instance.IosCloudServicesApiKey;
File.WriteAllText(
Path.Combine(runtimeSettingsPath, "CloudServicesApiKey.txt"), cloudServicesApiKey);
AssetDatabase.Refresh();
}
}
}
| |
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace CSharpGL
{
/// <summary>
/// Represents a 2x2 matrix.
/// </summary>
[TypeConverter(typeof(StructTypeConverter<mat2>))]
[StructLayout(LayoutKind.Explicit)]
public struct mat2 : IEquatable<mat2>, ILoadFromString
{
//internal static mat2 Parse(string value)
//{
// string[] parts = value.Split(MatrixHelper.separator, StringSplitOptions.RemoveEmptyEntries);
// vec2 col0 = vec2.Parse(parts[1]);
// vec2 col1 = vec2.Parse(parts[3]);
// return new mat2(col0, col1);
//}
/// <summary>
/// Don't change the order of col0, col1 appears!
/// </summary>
[FieldOffset(sizeof(float) * 2 * 0)]
internal vec2 col0;
/// <summary>
/// Don't change the order of col0, col1 appears!
/// </summary>
[FieldOffset(sizeof(float) * 2 * 1)]
internal vec2 col1;
/// <summary>
/// Initializes a new instance of the <see cref="mat2"/> struct.
/// This matrix is the identity matrix scaled by <paramref name="scale"/>.
/// </summary>
/// <param name="scale">The scale.</param>
public mat2(float scale)
{
this.col0 = new vec2(scale, 0);
this.col1 = new vec2(0, scale);
}
/// <summary>
/// Initializes a new instance of the <see cref="mat2"/> struct.
/// The matrix is initialised with the <paramref name="cols"/>.
/// </summary>
/// <param name="cols">The colums of the matrix.</param>
public mat2(vec2[] cols)
{
this.col0 = cols[0];
this.col1 = cols[1];
}
/// <summary>
///
/// </summary>
/// <param name="col0"></param>
/// <param name="col1"></param>
public mat2(vec2 col0, vec2 col1)
{
this.col0 = col0;
this.col1 = col1;
}
/// <summary>
///
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
/// <param name="d"></param>
public mat2(float a, float b, float c, float d)
{
this.col0 = new vec2(a, b);
this.col1 = new vec2(c, d);
}
/// <summary>
/// Gets or sets the <see cref="vec2"/> column at the specified index.
/// </summary>
/// <value>
/// The <see cref="vec2"/> column.
/// </value>
/// <param name="column">The column index.</param>
/// <returns>The column at index <paramref name="column"/>.</returns>
public vec2 this[int column]
{
get
{
if (column == 0) { return this.col0; }
if (column == 1) { return this.col1; }
throw new ArgumentOutOfRangeException();
}
set
{
if (column == 0) { this.col0 = value; }
else if (column == 1) { this.col1 = value; }
else
{
throw new ArgumentOutOfRangeException();
}
}
}
/// <summary>
/// Gets or sets the element at <paramref name="column"/> and <paramref name="row"/>.
/// </summary>
/// <value>
/// The element at <paramref name="column"/> and <paramref name="row"/>.
/// </value>
/// <param name="column">The column index.</param>
/// <param name="row">The row index.</param>
/// <returns>
/// The element at <paramref name="column"/> and <paramref name="row"/>.
/// </returns>
public float this[int column, int row]
{
get
{
if (column == 0) { return this.col0[row]; }
if (column == 1) { return this.col1[row]; }
throw new ArgumentOutOfRangeException();
}
set
{
if (column == 0) { this.col0[row] = value; }
else if (column == 1) { this.col1[row] = value; }
else
{
throw new ArgumentOutOfRangeException();
}
}
}
/// <summary>
/// Creates an identity matrix.
/// </summary>
/// <returns>A new identity matrix.</returns>
public static mat2 identity()
{
return new mat2
{
col0 = new vec2(1, 0),
col1 = new vec2(0, 1),
};
}
/// <summary>
///
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(mat2 left, mat2 right)
{
return !(left == right);
}
/// <summary>
/// Multiplies the <paramref name="lhs"/> matrix by the <paramref name="rhs"/> vector.
/// </summary>
/// <param name="lhs">The LHS matrix.</param>
/// <param name="rhs">The RHS vector.</param>
/// <returns>The product of <paramref name="lhs"/> and <paramref name="rhs"/>.</returns>
public static vec2 operator *(mat2 lhs, vec2 rhs)
{
return new vec2(
lhs[0, 0] * rhs[0] + lhs[1, 0] * rhs[1],
lhs[0, 1] * rhs[0] + lhs[1, 1] * rhs[1]
);
}
/// <summary>
/// Multiplies the <paramref name="lhs"/> matrix by the <paramref name="rhs"/> matrix.
/// </summary>
/// <param name="lhs">The LHS matrix.</param>
/// <param name="rhs">The RHS matrix.</param>
/// <returns>The product of <paramref name="lhs"/> and <paramref name="rhs"/>.</returns>
public static mat2 operator *(mat2 lhs, mat2 rhs)
{
mat2 result = new mat2(
new vec2(
lhs[0][0] * rhs[0][0] + lhs[1][0] * rhs[0][1],
lhs[0][1] * rhs[0][0] + lhs[1][1] * rhs[0][1]
),
new vec2(
lhs[0][0] * rhs[1][0] + lhs[1][0] * rhs[1][1],
lhs[0][1] * rhs[1][0] + lhs[1][1] * rhs[1][1]
)
);
return result;
}
/// <summary>
///
/// </summary>
/// <param name="lhs"></param>
/// <param name="s"></param>
/// <returns></returns>
public static mat2 operator *(mat2 lhs, float s)
{
return new mat2(new[]
{
lhs[0]*s,
lhs[1]*s
});
}
/// <summary>
///
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(mat2 left, mat2 right)
{
//object leftObj = left, rightObj = right;
//if (leftObj == null)
//{
// if (rightObj == null) { return true; }
// else { return false; }
//}
//else
//{
// if (rightObj == null) { return false; }
//}
return left.Equals(right);
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
return (obj is mat2) && (this.Equals((mat2)obj));
}
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(mat2 other)
{
return (this.col0 == other.col0 && this.col1 == other.col1);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return this.ToString().GetHashCode();
}
void ILoadFromString.Load(string value)
{
string[] parts = value.Split(MatrixHelper.separator, StringSplitOptions.RemoveEmptyEntries);
this.col0 = vec2.Parse(parts[1]);
this.col1 = vec2.Parse(parts[3]);
}
/// <summary>
/// Returns the matrix as a flat array of elements, column major.
/// </summary>
/// <returns></returns>
public float[] ToArray()
{
var result = new float[4];
result[0 + 0] = col0.x; result[0 + 1] = col0.y;
result[2 + 0] = col1.x; result[2 + 1] = col1.y;
return result;
}
/// <summary>
///
/// </summary>
public override string ToString()
{
var builder = new System.Text.StringBuilder();
var cols = new vec2[] { col0, col1 };
for (int i = 0; i < cols.Length; i++)
{
builder.Append("col ");
builder.Append(i);
builder.Append(": [");
builder.Append(cols[i]);
builder.Append("] ");
builder.AppendLine();
}
return builder.ToString();
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Strategies.Algo
File: StrategyParam.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.Strategies
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Ecng.Common;
using Ecng.Serialization;
/// <summary>
/// The startegy parameter.
/// </summary>
public interface IStrategyParam : IPersistable
{
/// <summary>
/// Parameter name.
/// </summary>
string Name { get; }
/// <summary>
/// The parameter value.
/// </summary>
object Value { get; set; }
/// <summary>
/// The From value at optimization.
/// </summary>
object OptimizeFrom { get; set; }
/// <summary>
/// The To value at optimization.
/// </summary>
object OptimizeTo { get; set; }
/// <summary>
/// The Increment value at optimization.
/// </summary>
object OptimizeStep { get; set; }
}
/// <summary>
/// Wrapper for typified access to the strategy parameter.
/// </summary>
/// <typeparam name="T">The type of the parameter value.</typeparam>
public class StrategyParam<T> : IStrategyParam
{
private readonly Strategy _strategy;
/// <summary>
/// Initializes a new instance of the <see cref="StrategyParam{T}"/>.
/// </summary>
/// <param name="strategy">Strategy.</param>
/// <param name="name">Parameter name.</param>
public StrategyParam(Strategy strategy, string name)
: this(strategy, name, default(T))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="StrategyParam{T}"/>.
/// </summary>
/// <param name="strategy">Strategy.</param>
/// <param name="name">Parameter name.</param>
/// <param name="initialValue">The initial value.</param>
public StrategyParam(Strategy strategy, string name, T initialValue)
{
if (strategy == null)
throw new ArgumentNullException(nameof(strategy));
if (name.IsEmpty())
throw new ArgumentNullException(nameof(name));
_strategy = strategy;
Name = name;
_value = initialValue;
_strategy.Parameters.Add(this);
}
/// <summary>
/// Parameter name.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Is it possible to store in <see cref="Value"/> a value, equal to <see langword="null" />.
/// </summary>
public bool AllowNull { get; set; } = typeof(T).IsNullable();
private T _value;
/// <summary>
/// The parameter value.
/// </summary>
public T Value
{
get
{
return _value;
}
set
{
if (!AllowNull && value.IsNull())
throw new ArgumentNullException(nameof(value));
if (EqualityComparer<T>.Default.Equals(_value, value))
return;
var propChange = _value as INotifyPropertyChanged;
if (propChange != null)
propChange.PropertyChanged -= OnValueInnerStateChanged;
_value = value;
_strategy.RaiseParametersChanged(Name);
propChange = _value as INotifyPropertyChanged;
if (propChange != null)
propChange.PropertyChanged += OnValueInnerStateChanged;
}
}
/// <summary>
/// The From value at optimization.
/// </summary>
public object OptimizeFrom { get; set; }
/// <summary>
/// The To value at optimization.
/// </summary>
public object OptimizeTo { get; set; }
/// <summary>
/// The Increment value at optimization.
/// </summary>
public object OptimizeStep { get; set; }
private void OnValueInnerStateChanged(object sender, PropertyChangedEventArgs e)
{
_strategy.RaiseParametersChanged(Name);
}
object IStrategyParam.Value
{
get { return Value; }
set { Value = (T)value; }
}
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Settings storage.</param>
public void Load(SettingsStorage storage)
{
Name = storage.GetValue<string>("Name");
Value = storage.GetValue<T>("Value");
OptimizeFrom = storage.GetValue<T>("OptimizeFrom");
OptimizeTo = storage.GetValue<T>("OptimizeTo");
OptimizeStep = storage.GetValue<object>("OptimizeStep");
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="storage">Settings storage.</param>
public void Save(SettingsStorage storage)
{
storage.SetValue("Name", Name);
storage.SetValue("Value", Value);
storage.SetValue("OptimizeFrom", OptimizeFrom);
storage.SetValue("OptimizeTo", OptimizeTo);
storage.SetValue("OptimizeStep", OptimizeStep);
}
}
/// <summary>
/// The auxiliary class for <see cref="StrategyParam{T}"/>.
/// </summary>
public static class StrategyParamHelper
{
/// <summary>
/// Initializes a new instance of the <see cref="StrategyParam{T}"/>.
/// </summary>
/// <typeparam name="T">The type of the parameter value.</typeparam>
/// <param name="strategy">Strategy.</param>
/// <param name="name">Parameter name.</param>
/// <param name="initialValue">The initial value.</param>
/// <returns>The startegy parameter.</returns>
public static StrategyParam<T> Param<T>(this Strategy strategy, string name, T initialValue = default(T))
{
return new StrategyParam<T>(strategy, name, initialValue);
}
/// <summary>
/// Initializes a new instance of the <see cref="StrategyParam{T}"/>.
/// </summary>
/// <typeparam name="T">The type of the parameter value.</typeparam>
/// <param name="param">The startegy parameter.</param>
/// <param name="optimizeFrom">The From value at optimization.</param>
/// <param name="optimizeTo">The To value at optimization.</param>
/// <param name="optimizeStep">The Increment value at optimization.</param>
/// <returns>The startegy parameter.</returns>
public static StrategyParam<T> Optimize<T>(this StrategyParam<T> param, T optimizeFrom = default(T), T optimizeTo = default(T), T optimizeStep = default(T))
{
if (param == null)
throw new ArgumentNullException(nameof(param));
param.OptimizeFrom = optimizeFrom;
param.OptimizeTo = optimizeTo;
param.OptimizeStep = optimizeStep;
return param;
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Python.Runtime;
using QuantConnect.Algorithm;
using QuantConnect.Data;
using QuantConnect.Indicators;
using QuantConnect.Tests.Engine.DataFeeds;
using QuantConnect.Data.Market;
namespace QuantConnect.Tests.Indicators
{
[TestFixture]
public class PythonIndicatorTests : CommonIndicatorTests<IBaseData>
{
protected override IndicatorBase<IBaseData> CreateIndicator()
{
using (Py.GIL())
{
var module = PythonEngine.ModuleFromString(
Guid.NewGuid().ToString(),
@"
from AlgorithmImports import *
from collections import deque
class CustomSimpleMovingAverage(PythonIndicator):
def __init__(self, name, period):
self.Name = name
self.Value = 0
self.queue = deque(maxlen=period)
# Update method is mandatory
def Update(self, input):
self.queue.appendleft(input.Value)
count = len(self.queue)
self.Value = np.sum(self.queue) / count
return count == self.queue.maxlen
"
);
var indicator = module.GetAttr("CustomSimpleMovingAverage")
.Invoke("custom".ToPython(), 14.ToPython());
return new PythonIndicator(indicator);
}
}
protected override string TestFileName => "spy_with_indicators.txt";
protected override string TestColumnName => "SMA14";
protected override void RunTestIndicator(IndicatorBase<IBaseData> indicator)
{
var first = true;
var closeIndex = -1;
var targetIndex = -1;
foreach (var line in File.ReadLines(Path.Combine("TestData", TestFileName)))
{
var parts = line.Split(new[] { ',' }, StringSplitOptions.None);
if (first)
{
first = false;
for (var i = 0; i < parts.Length; i++)
{
if (parts[i].Trim() == "Close")
{
closeIndex = i;
}
if (parts[i].Trim() == TestColumnName)
{
targetIndex = i;
}
}
if (closeIndex * targetIndex < 0)
{
Assert.Fail($"Didn't find one of 'Close' or '{line}' in the header: ", TestColumnName);
}
continue;
}
var close = decimal.Parse(parts[closeIndex], CultureInfo.InvariantCulture);
var date = Time.ParseDate(parts[0]);
var data = new IndicatorDataPoint(date, close);
indicator.Update(data);
if (!indicator.IsReady || parts[targetIndex].Trim() == string.Empty)
{
continue;
}
var expected = double.Parse(parts[targetIndex], CultureInfo.InvariantCulture);
Assertion.Invoke(indicator, expected);
}
}
protected override Action<IndicatorBase<IBaseData>, double> Assertion => (indicator, expected) =>
Assert.AreEqual(expected, (double) indicator.Current.Value, 1e-2);
[Test]
public void SmaComputesCorrectly()
{
var sma = new SimpleMovingAverage(4);
var data = new[] {1m, 10m, 100m, 1000m, 10000m, 1234m, 56789m};
var seen = new List<decimal>();
for (int i = 0; i < data.Length; i++)
{
var datum = data[i];
seen.Add(datum);
sma.Update(new IndicatorDataPoint(DateTime.Now.AddSeconds(i), datum));
Assert.AreEqual(Enumerable.Reverse(seen).Take(sma.Period).Average(), sma.Current.Value);
}
}
[Test]
public void IsReadyAfterPeriodUpdates()
{
var sma = new SimpleMovingAverage(3);
sma.Update(DateTime.UtcNow, 1m);
sma.Update(DateTime.UtcNow, 1m);
Assert.IsFalse(sma.IsReady);
sma.Update(DateTime.UtcNow, 1m);
Assert.IsTrue(sma.IsReady);
}
[Test]
public override void ResetsProperly()
{
var sma = new SimpleMovingAverage(3);
foreach (var data in TestHelper.GetDataStream(4))
{
sma.Update(data);
}
Assert.IsTrue(sma.IsReady);
sma.Reset();
TestHelper.AssertIndicatorIsInDefaultState(sma);
TestHelper.AssertIndicatorIsInDefaultState(sma.RollingSum);
sma.Update(DateTime.UtcNow, 2.0m);
Assert.AreEqual(sma.Current.Value, 2.0m);
}
[Test]
public void RegisterPythonCustomIndicatorProperly()
{
var algorithm = new QCAlgorithm();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
var spy = algorithm.AddEquity("SPY").Symbol;
using (Py.GIL())
{
var module = PythonEngine.ModuleFromString(
Guid.NewGuid().ToString(),
@"
from AlgorithmImports import *
class GoodCustomIndicator(PythonIndicator):
def __init__(self):
self.Value = 0
def Update(self, input):
self.Value = input.Value
return True
class BadCustomIndicator(PythonIndicator):
def __init__(self):
self.Valeu = 0
def Update(self, input):
self.Value = input.Value
return True"
);
var goodIndicator = module.GetAttr("GoodCustomIndicator").Invoke();
Assert.DoesNotThrow(() => algorithm.RegisterIndicator(spy, goodIndicator, Resolution.Minute));
var actual = algorithm.SubscriptionManager.Subscriptions
.FirstOrDefault(config => config.TickType == TickType.Trade)
.Consolidators.Count;
Assert.AreEqual(1, actual);
var badIndicator = module.GetAttr("BadCustomIndicator").Invoke();
Assert.Throws<NotImplementedException>(() => algorithm.RegisterIndicator(spy, badIndicator, Resolution.Minute));
}
}
[Test]
public void AllPythonRegisterIndicatorCases()
{
//This test covers all three cases of registering a indicator through Python
//Setup algorithm and Equity
var algorithm = new QCAlgorithm();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
var spy = algorithm.AddEquity("SPY").Symbol;
//Setup Python Indicator and Consolidator
using (Py.GIL())
{
var module = PythonEngine.ModuleFromString(Guid.NewGuid().ToString(),
"from AlgorithmImports import *\n" +
"consolidator = QuoteBarConsolidator(timedelta(days = 5)) \n" +
"timeDelta = timedelta(days=2)\n" +
"class CustomIndicator(PythonIndicator):\n" +
" def __init__(self):\n" +
" self.Value = 0\n" +
" def Update(self, input):\n" +
" self.Value = input.Value\n" +
" return True\n" +
"class CustomConsolidator(PythonConsolidator):\n" +
" def __init__(self):\n" +
" self.InputType = QuoteBar\n" +
" self.OutputType = QuoteBar\n" +
" self.Consolidated = None\n" +
" self.WorkingData = None\n"
);
//Get our variables from Python
var PyIndicator = module.GetAttr("CustomIndicator").Invoke();
var PyConsolidator = module.GetAttr("CustomConsolidator").Invoke();
var Consolidator = module.GetAttr("consolidator");
algorithm.SubscriptionManager.AddConsolidator(spy, Consolidator);
var TimeDelta = module.GetAttr("timeDelta");
//Test 1: Using a C# Consolidator; Should convert consolidator into IDataConsolidator
Assert.DoesNotThrow(() => algorithm.RegisterIndicator(spy, PyIndicator, Consolidator));
//Test 2: Using a Python Consolidator; Should wrap consolidator
Assert.DoesNotThrow(() => algorithm.RegisterIndicator(spy, PyIndicator, PyConsolidator));
//Test 3: Using a timedelta object; Should convert timedelta to timespan
Assert.DoesNotThrow(() => algorithm.RegisterIndicator(spy, PyIndicator, TimeDelta));
}
}
[Test]
public void WarmsUpProperlyPythonIndicator()
{
using (Py.GIL())
{
var module = PythonEngine.ModuleFromString(
Guid.NewGuid().ToString(),
@"
from AlgorithmImports import *
from collections import deque
class CustomSimpleMovingAverage(PythonIndicator):
def __init__(self, name, period):
self.Name = name
self.Value = 0
self.queue = deque(maxlen=period)
self.WarmUpPeriod = period
# Update method is mandatory
def Update(self, input):
self.queue.appendleft(input.Value)
count = len(self.queue)
self.Value = np.sum(self.queue) / count
return count == self.queue.maxlen
"
);
var pythonIndicator = module.GetAttr("CustomSimpleMovingAverage")
.Invoke("custom".ToPython(), 14.ToPython());
var SMAWithWarmUpPeriod = new PythonIndicator(pythonIndicator);
var reference = new DateTime(2000, 1, 1, 0, 0, 0);
var period = ((IIndicatorWarmUpPeriodProvider)SMAWithWarmUpPeriod).WarmUpPeriod;
// Check the WarmUpPeriod parameter is the one defined in the constructor of the custom indicator
Assert.AreEqual(14, period);
for (var i = 0; i < period; i++)
{
SMAWithWarmUpPeriod.Update(new TradeBar() { Symbol = Symbols.AAPL, Low = 1, High = 2, Volume = 100, Time = reference.AddDays(1 + i) });
Assert.AreEqual(i == period - 1, SMAWithWarmUpPeriod.IsReady);
}
}
}
[Test]
public void SetDefaultWarmUpPeriodProperly()
{
using (Py.GIL())
{
var module = PythonEngine.ModuleFromString(
Guid.NewGuid().ToString(),
@"
from AlgorithmImports import *
from collections import deque
class CustomSimpleMovingAverage(PythonIndicator):
def __init__(self, name, period):
self.Name = name
self.Value = 0
self.queue = deque(maxlen=period)
# Update method is mandatory
def Update(self, input):
self.queue.appendleft(input.Value)
count = len(self.queue)
self.Value = np.sum(self.queue) / count
return count == self.queue.maxlen
"
);
var pythonIndicator = module.GetAttr("CustomSimpleMovingAverage")
.Invoke("custom".ToPython(), 14.ToPython());
var indicator = new PythonIndicator(pythonIndicator);
Assert.AreEqual(0, indicator.WarmUpPeriod);
}
}
}
}
| |
// 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.Drawing;
using System.Diagnostics;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using OpenLiveWriter.BlogClient;
using OpenLiveWriter.Interop.Com.Ribbon;
using OpenLiveWriter.Localization;
using OpenLiveWriter.PostEditor.Commands;
using OpenLiveWriter.ApplicationFramework;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.PostEditor.Configuration.Settings;
// @RIBBON TODO: Cleanly remove obsolete code.
namespace OpenLiveWriter.PostEditor
{
public class SelectBlogGalleryCommand : SelectGalleryCommand<string>
{
private readonly IBlogPostEditingManager _editingManager;
public SelectBlogGalleryCommand(IBlogPostEditingManager editingManager) : base(CommandId.SelectBlog)
{
_invalidateGalleryRepresentation = true;
_editingManager = editingManager;
}
public override void LoadItems()
{
items.Clear();
int i = 0;
string currentBlogId = _editingManager.CurrentBlog();
foreach (BlogDescriptor blogDescriptor in BlogSettings.GetBlogs(true))
{
using (Blog blog = new Blog(blogDescriptor.Id))
{
string blogName = GetShortenedBlogName(blog.Name);
if (blog.Image == null)
{
Bitmap defaultIcon = ResourceHelper.LoadAssemblyResourceBitmap("OpenPost.Images.BlogAccount.png");
items.Add(new GalleryItem(blogName, defaultIcon.Clone() as Bitmap, blog.Id));
}
else
{
items.Add(new GalleryItem(blogName, new Bitmap(blog.Image), blog.Id));
}
if (currentBlogId == blog.Id)
selectedIndex = i;
}
i++;
}
base.LoadItems();
}
public override void Invalidate()
{
if (items.Count == 0)
{
LoadItems();
UpdateInvalidationState(PropertyKeys.ItemsSource, InvalidationState.Pending);
UpdateInvalidationState(PropertyKeys.Categories, InvalidationState.Pending);
UpdateInvalidationState(PropertyKeys.SelectedItem, InvalidationState.Pending);
UpdateInvalidationState(PropertyKeys.StringValue, InvalidationState.Pending);
UpdateInvalidationState(PropertyKeys.Label, InvalidationState.Pending);
OnStateChanged(EventArgs.Empty);
}
else
{
UpdateSelectedIndex();
}
}
internal void ReloadAndInvalidate()
{
items.Clear();
Invalidate();
}
private void UpdateSelectedIndex()
{
selectedIndex = INVALID_INDEX;
SetSelectedItem(_editingManager.CurrentBlog());
}
public static string GetShortenedBlogName(string blogName)
{
return TextHelper.GetTitleFromText(blogName, 100, TextHelper.Units.Characters);
}
}
internal class WeblogCommandManager : IDynamicCommandMenuContext, IDisposable
{
public WeblogCommandManager(BlogPostEditingManager editingManager, IBlogPostEditingSite editingSite)
{
// save reference to editing context and subscribe to blog-changed event
_editingManager = editingManager;
_editingManager.BlogChanged += new EventHandler(_editingManager_BlogChanged);
_editingManager.BlogSettingsChanged += new WeblogSettingsChangedHandler(_editingManager_BlogSettingsChanged);
_editingSite = editingSite;
BlogSettings.BlogSettingsDeleted += new BlogSettings.BlogSettingsListener(BlogSettings_BlogSettingsDeleted);
// initialize commands
InitializeCommands();
// initialize UI
InitializeUI();
}
void BlogSettings_BlogSettingsDeleted(string blogId)
{
commandSelectBlog.ReloadAndInvalidate();
}
/// <summary>
/// Notification that the user has selected a weblog menu
/// </summary>
public event WeblogHandler WeblogSelected;
private void InitializeCommands()
{
CommandManager.BeginUpdate();
commandWeblogPicker = new CommandWeblogPicker();
_editingSite.CommandManager.Add(commandWeblogPicker);
commandAddWeblog = new Command(CommandId.AddWeblog);
commandAddWeblog.Execute += new EventHandler(commandAddWeblog_Execute);
CommandManager.Add(commandAddWeblog);
commandConfigureWeblog = new Command(CommandId.ConfigureWeblog);
commandConfigureWeblog.Execute += new EventHandler(commandConfigureWeblog_Execute);
CommandManager.Add(commandConfigureWeblog);
commandSelectBlog = new SelectBlogGalleryCommand(_editingManager);
commandSelectBlog.ExecuteWithArgs += new ExecuteEventHandler(commandSelectBlog_ExecuteWithArgs);
commandSelectBlog.Invalidate();
CommandManager.Add(commandSelectBlog);
CommandManager.EndUpdate();
// create the dynamic menu items that correspond to the available weblogs
_switchWeblogCommandMenu = new DynamicCommandMenu(this);
}
void commandSelectBlog_ExecuteWithArgs(object sender, ExecuteEventHandlerArgs args)
{
if (WeblogSelected != null)
WeblogSelected(BlogSettings.GetBlogs(true)[commandSelectBlog.SelectedIndex].Id);
}
private void InitializeUI()
{
// hookup menu definition to command bar button
commandWeblogPicker.CommandBarButtonContextMenuDefinition = GetWeblogContextMenuDefinition(false);
}
private CommandContextMenuDefinition GetWeblogContextMenuDefinition(bool includeAllCommands)
{
// initialize contenxt-menu definition
CommandContextMenuDefinition weblogContextMenuDefinition = new CommandContextMenuDefinition(this.components);
weblogContextMenuDefinition.CommandBar = true;
if (includeAllCommands)
{
weblogContextMenuDefinition.Entries.Add(CommandId.ViewWeblog, false, false);
weblogContextMenuDefinition.Entries.Add(CommandId.ViewWeblogAdmin, false, false);
weblogContextMenuDefinition.Entries.Add(CommandId.ConfigureWeblog, true, true);
}
// weblog switching commands
foreach (string commandIdentifier in _switchWeblogCommandMenu.CommandIdentifiers)
weblogContextMenuDefinition.Entries.Add(commandIdentifier, false, false);
weblogContextMenuDefinition.Entries.Add(CommandId.AddWeblog, true, false);
return weblogContextMenuDefinition;
}
private void _editingManager_BlogChanged(object sender, EventArgs e)
{
commandSelectBlog.Invalidate();
UpdateWeblogPicker();
}
private void _editingManager_BlogSettingsChanged(string blogId, bool templateChanged)
{
using (Blog blog = new Blog(blogId))
{
// Find the item that is changing.
var blogItem = commandSelectBlog.Items.Find(item => item.Cookie.Equals(blogId, StringComparison.Ordinal));
if (blogItem != null &&
!blogItem.Label.Equals(SelectBlogGalleryCommand.GetShortenedBlogName(blog.Name), StringComparison.Ordinal))
{
// The blog name has changed so we need to do a full reload to refresh the UI.
commandSelectBlog.ReloadAndInvalidate();
}
else
{
// WinLive 43696: The blog settings have changed, but the UI doesn't need to be refreshed. In
// order to avoid "Windows 8 Bugs" 43242, we don't want to do a full reload.
commandSelectBlog.Invalidate();
}
}
UpdateWeblogPicker();
}
private void UpdateWeblogPicker()
{
Control c = (Control)_editingSite;
CommandWeblogPicker.WeblogPicker wpbc = new CommandWeblogPicker.WeblogPicker(
Res.DefaultFont,
_editingManager.BlogImage,
_editingManager.BlogIcon,
_editingManager.BlogServiceDisplayName,
_editingManager.BlogName);
using (Graphics g = c.CreateGraphics())
{
wpbc.Layout(g);
commandWeblogPicker.WeblogPickerHelper = wpbc;
}
}
private void commandConfigureWeblog_Execute(object sender, EventArgs e)
{
_editingSite.ConfigureWeblog(_editingManager.BlogId, typeof(AccountPanel));
}
private void commandAddWeblog_Execute(object sender, EventArgs e)
{
_editingSite.AddWeblog();
}
public void Dispose()
{
if (_editingManager != null)
{
_editingManager.BlogChanged -= new EventHandler(_editingManager_BlogChanged);
_editingManager = null;
BlogSettings.BlogSettingsDeleted -= new BlogSettings.BlogSettingsListener(BlogSettings_BlogSettingsDeleted);
}
_switchWeblogCommandMenu.Dispose();
if (components != null)
components.Dispose();
}
public CommandManager CommandManager
{
get
{
return _editingSite.CommandManager;
}
}
DynamicCommandMenuOptions IDynamicCommandMenuContext.Options
{
get
{
if (_options == null)
{
_options = new DynamicCommandMenuOptions(
new Command(CommandId.ViewWeblog).MainMenuPath.Split('/')[0], 100, Res.Get(StringId.MoreWeblogs), Res.Get(StringId.SwitchWeblogs));
_options.UseNumericMnemonics = false;
_options.MaxCommandsShownOnMenu = 25;
_options.SeparatorBegin = true;
}
return _options;
}
}
private DynamicCommandMenuOptions _options;
IMenuCommandObject[] IDynamicCommandMenuContext.GetMenuCommandObjects()
{
// generate an array of command objects for the current list of weblogs
ArrayList menuCommands = new ArrayList();
foreach (BlogDescriptor blog in BlogSettings.GetBlogs(true))
menuCommands.Add(new SwitchWeblogMenuCommand(blog.Id, blog.Id == _editingManager.BlogId));
return (IMenuCommandObject[])menuCommands.ToArray(typeof(IMenuCommandObject));
}
void IDynamicCommandMenuContext.CommandExecuted(IMenuCommandObject menuCommandObject)
{
// get reference to underlying command object
SwitchWeblogMenuCommand menuCommand = menuCommandObject as SwitchWeblogMenuCommand;
// fire notification to listeners
if (WeblogSelected != null)
WeblogSelected(menuCommand.BlogId);
}
private DynamicCommandMenu _switchWeblogCommandMenu;
private BlogPostEditingManager _editingManager;
private IBlogPostEditingSite _editingSite;
private CommandWeblogPicker commandWeblogPicker;
private Command commandConfigureWeblog;
private SelectBlogGalleryCommand commandSelectBlog;
private Command commandAddWeblog;
private IContainer components = new Container();
private class SwitchWeblogMenuCommand : IMenuCommandObject
{
public SwitchWeblogMenuCommand(string blogId, bool latched)
{
_blogId = blogId;
using (BlogSettings settings = BlogSettings.ForBlogId(_blogId))
_caption = StringHelper.Ellipsis(settings.BlogName + "", 65);
_latched = latched;
}
public string BlogId { get { return _blogId; } }
private string _blogId;
Bitmap IMenuCommandObject.Image { get { return null; } }
string IMenuCommandObject.Caption { get { return _caption; } }
string IMenuCommandObject.CaptionNoMnemonic { get { return _caption; } }
private string _caption;
bool IMenuCommandObject.Latched { get { return _latched; } }
private bool _latched;
bool IMenuCommandObject.Enabled { get { return true; } }
}
}
}
| |
//
// ABPerson.cs: Implements the managed ABPerson
//
// Authors: Mono Team
//
// Copyright (C) 2009 Novell, Inc
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
using System.Runtime.InteropServices;
using MonoMac.CoreFoundation;
using MonoMac.Foundation;
using MonoMac.ObjCRuntime;
namespace MonoMac.AddressBook {
public enum ABPersonSortBy : uint {
FirstName = 0,
LastName = 1,
}
public enum ABPersonCompositeNameFormat : uint {
FirstNameFirst = 0,
LastNameFirst = 1,
}
public enum ABPersonProperty {
Address,
Birthday,
CreationDate,
Date,
Department,
Email,
FirstName,
FirstNamePhonetic,
InstantMessage,
JobTitle,
Kind,
LastName,
LastNamePhonetic,
MiddleName,
MiddleNamePhonetic,
ModificationDate,
Nickname,
Note,
Organization,
Phone,
Prefix,
RelatedNames,
Suffix,
Url,
}
[Since (4,1)]
public enum ABPersonImageFormat {
Thumbnail = 0,
OriginalSize = 2
}
static class ABPersonPropertyId {
public static int Address {get; private set;}
public static int Birthday {get; private set;}
public static int CreationDate {get; private set;}
public static int Date {get; private set;}
public static int Department {get; private set;}
public static int Email {get; private set;}
public static int FirstName {get; private set;}
public static int FirstNamePhonetic {get; private set;}
public static int InstantMessage {get; private set;}
public static int JobTitle {get; private set;}
public static int Kind {get; private set;}
public static int LastName {get; private set;}
public static int LastNamePhonetic {get; private set;}
public static int MiddleName {get; private set;}
public static int MiddleNamePhonetic {get; private set;}
public static int ModificationDate {get; private set;}
public static int Nickname {get; private set;}
public static int Note {get; private set;}
public static int Organization {get; private set;}
public static int Phone {get; private set;}
public static int Prefix {get; private set;}
public static int RelatedNames {get; private set;}
public static int Suffix {get; private set;}
public static int Url {get; private set;}
static ABPersonPropertyId ()
{
InitConstants.Init ();
}
internal static void Init ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
Address = Dlfcn.GetInt32 (handle, "kABPersonAddressProperty");
Birthday = Dlfcn.GetInt32 (handle, "kABPersonBirthdayProperty");
CreationDate = Dlfcn.GetInt32 (handle, "kABPersonCreationDateProperty");
Date = Dlfcn.GetInt32 (handle, "kABPersonDateProperty");
Department = Dlfcn.GetInt32 (handle, "kABPersonDepartmentProperty");
Email = Dlfcn.GetInt32 (handle, "kABPersonEmailProperty");
FirstName = Dlfcn.GetInt32 (handle, "kABPersonFirstNameProperty");
FirstNamePhonetic = Dlfcn.GetInt32 (handle, "kABPersonFirstNamePhoneticProperty");
InstantMessage = Dlfcn.GetInt32 (handle, "kABPersonInstantMessageProperty");
JobTitle = Dlfcn.GetInt32 (handle, "kABPersonJobTitleProperty");
Kind = Dlfcn.GetInt32 (handle, "kABPersonKindProperty");
LastName = Dlfcn.GetInt32 (handle, "kABPersonLastNameProperty");
LastNamePhonetic = Dlfcn.GetInt32 (handle, "kABPersonLastNamePhoneticProperty");
MiddleName = Dlfcn.GetInt32 (handle, "kABPersonMiddleNameProperty");
MiddleNamePhonetic = Dlfcn.GetInt32 (handle, "kABPersonMiddleNamePhoneticProperty");
ModificationDate = Dlfcn.GetInt32 (handle, "kABPersonModificationDateProperty");
Nickname = Dlfcn.GetInt32 (handle, "kABPersonNicknameProperty");
Note = Dlfcn.GetInt32 (handle, "kABPersonNoteProperty");
Organization = Dlfcn.GetInt32 (handle, "kABPersonOrganizationProperty");
Phone = Dlfcn.GetInt32 (handle, "kABPersonPhoneProperty");
Prefix = Dlfcn.GetInt32 (handle, "kABPersonPrefixProperty");
RelatedNames = Dlfcn.GetInt32 (handle, "kABPersonRelatedNamesProperty");
Suffix = Dlfcn.GetInt32 (handle, "kABPersonSuffixProperty");
Url = Dlfcn.GetInt32 (handle, "kABPersonURLProperty");
}
finally {
Dlfcn.dlclose (handle);
}
}
public static int ToId (ABPersonProperty property)
{
switch (property)
{
case ABPersonProperty.Address: return Address;
case ABPersonProperty.Birthday: return Birthday;
case ABPersonProperty.CreationDate: return CreationDate;
case ABPersonProperty.Date: return Date;
case ABPersonProperty.Department: return Department;
case ABPersonProperty.Email: return Email;
case ABPersonProperty.FirstName: return FirstName;
case ABPersonProperty.FirstNamePhonetic: return FirstNamePhonetic;
case ABPersonProperty.InstantMessage: return InstantMessage;
case ABPersonProperty.JobTitle: return JobTitle;
case ABPersonProperty.Kind: return Kind;
case ABPersonProperty.LastName: return LastName;
case ABPersonProperty.LastNamePhonetic: return LastNamePhonetic;
case ABPersonProperty.MiddleName: return MiddleName;
case ABPersonProperty.MiddleNamePhonetic: return MiddleNamePhonetic;
case ABPersonProperty.ModificationDate: return ModificationDate;
case ABPersonProperty.Nickname: return Nickname;
case ABPersonProperty.Note: return Note;
case ABPersonProperty.Organization: return Organization;
case ABPersonProperty.Phone: return Phone;
case ABPersonProperty.Prefix: return Prefix;
case ABPersonProperty.RelatedNames: return RelatedNames;
case ABPersonProperty.Suffix: return Suffix;
case ABPersonProperty.Url: return Url;
}
throw new NotSupportedException ("Invalid ABPersonProperty value: " + property);
}
public static ABPersonProperty ToPersonProperty (int id)
{
if (id == Address) return ABPersonProperty.Address;
if (id == Birthday) return ABPersonProperty.Birthday;
if (id == CreationDate) return ABPersonProperty.CreationDate;
if (id == Date) return ABPersonProperty.Date;
if (id == Department) return ABPersonProperty.Department;
if (id == Email) return ABPersonProperty.Email;
if (id == FirstName) return ABPersonProperty.FirstName;
if (id == FirstNamePhonetic) return ABPersonProperty.FirstNamePhonetic;
if (id == InstantMessage) return ABPersonProperty.InstantMessage;
if (id == JobTitle) return ABPersonProperty.JobTitle;
if (id == Kind) return ABPersonProperty.Kind;
if (id == LastName) return ABPersonProperty.LastName;
if (id == LastNamePhonetic) return ABPersonProperty.LastNamePhonetic;
if (id == MiddleName) return ABPersonProperty.MiddleName;
if (id == MiddleNamePhonetic) return ABPersonProperty.MiddleNamePhonetic;
if (id == ModificationDate) return ABPersonProperty.ModificationDate;
if (id == Nickname) return ABPersonProperty.Nickname;
if (id == Note) return ABPersonProperty.Note;
if (id == Organization) return ABPersonProperty.Organization;
if (id == Phone) return ABPersonProperty.Phone;
if (id == Prefix) return ABPersonProperty.Prefix;
if (id == RelatedNames) return ABPersonProperty.RelatedNames;
if (id == Suffix) return ABPersonProperty.Suffix;
if (id == Url) return ABPersonProperty.Url;
throw new NotSupportedException ("Invalid ABPersonPropertyId value: " + id);
}
}
public static class ABPersonAddressKey {
public static NSString City {get; private set;}
public static NSString Country {get; private set;}
public static NSString CountryCode {get; private set;}
public static NSString State {get; private set;}
public static NSString Street {get; private set;}
public static NSString Zip {get; private set;}
static ABPersonAddressKey ()
{
InitConstants.Init ();
}
internal static void Init ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
City = Dlfcn.GetStringConstant (handle, "kABPersonAddressCityKey");
Country = Dlfcn.GetStringConstant (handle, "kABPersonAddressCountryKey");
CountryCode = Dlfcn.GetStringConstant (handle, "kABPersonAddressCountryCodeKey");
State = Dlfcn.GetStringConstant (handle, "kABPersonAddressStateKey");
Street = Dlfcn.GetStringConstant (handle, "kABPersonAddressStreetKey");
Zip = Dlfcn.GetStringConstant (handle, "kABPersonAddressZIPKey");
}
finally {
Dlfcn.dlclose (handle);
}
}
}
public static class ABPersonDateLabel {
public static NSString Anniversary {get; private set;}
static ABPersonDateLabel ()
{
InitConstants.Init ();
}
internal static void Init ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
Anniversary = Dlfcn.GetStringConstant (handle, "kABPersonAnniversaryLabel");
}
finally {
Dlfcn.dlclose (handle);
}
}
}
public enum ABPersonKind {
None,
Organization,
Person,
}
static class ABPersonKindId {
public static NSNumber Organization {get; private set;}
public static NSNumber Person {get; private set;}
static ABPersonKindId ()
{
InitConstants.Init ();
}
internal static void Init ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
Organization = Dlfcn.GetNSNumber (handle, "kABPersonKindOrganization");
Person = Dlfcn.GetNSNumber (handle, "kABPersonKindPerson");
}
finally {
Dlfcn.dlclose (handle);
}
}
public static ABPersonKind ToPersonKind (NSNumber value)
{
if (object.ReferenceEquals (Organization, value))
return ABPersonKind.Organization;
if (object.ReferenceEquals (Person, value))
return ABPersonKind.Person;
return ABPersonKind.None;
}
public static NSNumber FromPersonKind (ABPersonKind value)
{
switch (value) {
case ABPersonKind.Organization: return Organization;
case ABPersonKind.Person: return Person;
}
return null;
}
}
public static class ABPersonPhoneLabel {
public static NSString HomeFax {get; private set;}
public static NSString iPhone {get; private set;}
public static NSString Main {get; private set;}
public static NSString Mobile {get; private set;}
public static NSString Pager {get; private set;}
public static NSString WorkFax {get; private set;}
static ABPersonPhoneLabel ()
{
InitConstants.Init ();
}
internal static void Init ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
HomeFax = Dlfcn.GetStringConstant (handle, "kABPersonPhoneHomeFAXLabel");
iPhone = Dlfcn.GetStringConstant (handle, "kABPersonPhoneIPhoneLabel");
Main = Dlfcn.GetStringConstant (handle, "kABPersonPhoneMainLabel");
Mobile = Dlfcn.GetStringConstant (handle, "kABPersonPhoneMobileLabel");
Pager = Dlfcn.GetStringConstant (handle, "kABPersonPhonePagerLabel");
WorkFax = Dlfcn.GetStringConstant (handle, "kABPersonPhoneWorkFAXLabel");
}
finally {
Dlfcn.dlclose (handle);
}
}
}
public static class ABPersonInstantMessageService {
public static NSString Aim {get; private set;}
public static NSString Icq {get; private set;}
public static NSString Jabber {get; private set;}
public static NSString Msn {get; private set;}
public static NSString Yahoo {get; private set;}
static ABPersonInstantMessageService ()
{
InitConstants.Init ();
}
internal static void Init ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
Aim = Dlfcn.GetStringConstant (handle, "kABPersonInstantMessageServiceAIM");
Icq = Dlfcn.GetStringConstant (handle, "kABPersonInstantMessageServiceICQ");
Jabber = Dlfcn.GetStringConstant (handle, "kABPersonInstantMessageServiceJabber");
Msn = Dlfcn.GetStringConstant (handle, "kABPersonInstantMessageServiceMSN");
Yahoo = Dlfcn.GetStringConstant (handle, "kABPersonInstantMessageServiceYahoo");
}
finally {
Dlfcn.dlclose (handle);
}
}
}
public static class ABPersonInstantMessageKey {
public static NSString Service {get; private set;}
public static NSString Username {get; private set;}
static ABPersonInstantMessageKey ()
{
InitConstants.Init ();
}
internal static void Init ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
Service = Dlfcn.GetStringConstant (handle, "kABPersonInstantMessageServiceKey");
Username = Dlfcn.GetStringConstant (handle, "kABPersonInstantMessageUsernameKey");
}
finally {
Dlfcn.dlclose (handle);
}
}
}
public static class ABPersonUrlLabel {
public static NSString HomePage {get; private set;}
static ABPersonUrlLabel ()
{
InitConstants.Init ();
}
internal static void Init ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
HomePage = Dlfcn.GetStringConstant (handle, "kABPersonHomePageLabel");
}
finally {
Dlfcn.dlclose (handle);
}
}
}
public static class ABPersonRelatedNamesLabel {
public static NSString Assistant {get; private set;}
public static NSString Brother {get; private set;}
public static NSString Child {get; private set;}
public static NSString Father {get; private set;}
public static NSString Friend {get; private set;}
public static NSString Manager {get; private set;}
public static NSString Mother {get; private set;}
public static NSString Parent {get; private set;}
public static NSString Partner {get; private set;}
public static NSString Sister {get; private set;}
public static NSString Spouse {get; private set;}
static ABPersonRelatedNamesLabel ()
{
InitConstants.Init ();
}
internal static void Init ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
Assistant = Dlfcn.GetStringConstant (handle, "kABPersonAssistantLabel");
Brother = Dlfcn.GetStringConstant (handle, "kABPersonBrotherLabel");
Child = Dlfcn.GetStringConstant (handle, "kABPersonChildLabel");
Father = Dlfcn.GetStringConstant (handle, "kABPersonFatherLabel");
Friend = Dlfcn.GetStringConstant (handle, "kABPersonFriendLabel");
Manager = Dlfcn.GetStringConstant (handle, "kABPersonMotherLabel");
Mother = Dlfcn.GetStringConstant (handle, "kABPersonManagerLabel");
Parent = Dlfcn.GetStringConstant (handle, "kABPersonParentLabel");
Partner = Dlfcn.GetStringConstant (handle, "kABPersonPartnerLabel");
Sister = Dlfcn.GetStringConstant (handle, "kABPersonSisterLabel");
Spouse = Dlfcn.GetStringConstant (handle, "kABPersonSpouseLabel");
}
finally {
Dlfcn.dlclose (handle);
}
}
}
public static class ABLabel {
public static NSString Home {get; private set;}
public static NSString Other {get; private set;}
public static NSString Work {get; private set;}
static ABLabel ()
{
InitConstants.Init ();
}
internal static void Init ()
{
var handle = Dlfcn.dlopen (Constants.AddressBookLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
Home = Dlfcn.GetStringConstant (handle, "kABHomeLabel");
Other = Dlfcn.GetStringConstant (handle, "kABOtherLabel");
Work = Dlfcn.GetStringConstant (handle, "kABWorkLabel");
}
finally {
Dlfcn.dlclose (handle);
}
}
}
public class ABPerson : ABRecord, IComparable, IComparable<ABPerson> {
[DllImport (Constants.AddressBookLibrary)]
extern static IntPtr ABPersonCreate ();
public ABPerson ()
: base (ABPersonCreate (), null)
{
InitConstants.Init ();
}
internal ABPerson (IntPtr handle, ABAddressBook addressbook)
: base (CFObject.CFRetain (handle), addressbook)
{
}
int IComparable.CompareTo (object o)
{
var other = o as ABPerson;
if (other == null)
throw new ArgumentException ("Can only compare to other ABPerson instances.", "o");
return CompareTo (other);
}
public int CompareTo (ABPerson other)
{
return CompareTo (other, ABPersonSortBy.LastName);
}
[DllImport (Constants.AddressBookLibrary)]
extern static int ABPersonComparePeopleByName (IntPtr person1, IntPtr person2, ABPersonSortBy ordering);
public int CompareTo (ABPerson other, ABPersonSortBy ordering)
{
if (other == null)
throw new ArgumentNullException ("other");
if (ordering != ABPersonSortBy.FirstName && ordering != ABPersonSortBy.LastName)
throw new ArgumentException ("Invalid ordering value: " + ordering, "ordering");
return ABPersonComparePeopleByName (Handle, other.Handle, ordering);
}
[DllImport (Constants.AddressBookLibrary)]
extern static IntPtr ABPersonCopyLocalizedPropertyName (int propertyId);
public static string LocalizedPropertyName (ABPersonProperty property)
{
return Runtime.GetNSObject (ABPersonCopyLocalizedPropertyName (ABPersonPropertyId.ToId (property))).ToString ();
}
[DllImport (Constants.AddressBookLibrary)]
extern static ABPropertyType ABPersonGetTypeOfProperty (int propertyId);
public static ABPropertyType GetPropertyType (ABPersonProperty property)
{
return ABPersonGetTypeOfProperty (ABPersonPropertyId.ToId (property));
}
[DllImport (Constants.AddressBookLibrary)]
extern static bool ABPersonSetImageData (IntPtr person, IntPtr imageData, out IntPtr error);
[DllImport (Constants.AddressBookLibrary)]
extern static IntPtr ABPersonCopyImageData (IntPtr person);
public NSData Image {
get {return (NSData) Runtime.GetNSObject (ABPersonCopyImageData (Handle));}
set {
IntPtr error;
if (!ABPersonSetImageData (Handle, value == null ? IntPtr.Zero : value.Handle, out error))
throw CFException.FromCFError (error);
}
}
[DllImport (Constants.AddressBookLibrary)]
extern static bool ABPersonHasImageData (IntPtr person);
public bool HasImage {
get {return ABPersonHasImageData (Handle);}
}
[DllImport (Constants.AddressBookLibrary)]
extern static bool ABPersonRemoveImageData (IntPtr person, out IntPtr error);
public void RemoveImage ()
{
IntPtr error;
if (!ABPersonRemoveImageData (Handle, out error))
throw CFException.FromCFError (error);
}
[DllImport (Constants.AddressBookLibrary)]
extern static ABPersonCompositeNameFormat ABPersonGetCompositeNameFormat ();
public static ABPersonCompositeNameFormat CompositeNameFormat {
get {return ABPersonGetCompositeNameFormat ();}
}
[DllImport (Constants.AddressBookLibrary)]
extern static ABPersonSortBy ABPersonGetSortOrdering ();
public static ABPersonSortBy SortOrdering {
get {return ABPersonGetSortOrdering ();}
}
public string FirstName {
get {return PropertyToString (ABPersonPropertyId.FirstName);}
set {SetValue (ABPersonPropertyId.FirstName, value);}
}
public string FirstNamePhonetic {
get {return PropertyToString (ABPersonPropertyId.FirstNamePhonetic);}
set {SetValue (ABPersonPropertyId.FirstNamePhonetic, value);}
}
public string LastName {
get {return PropertyToString (ABPersonPropertyId.LastName);}
set {SetValue (ABPersonPropertyId.LastName, value);}
}
public string LastNamePhonetic {
get {return PropertyToString (ABPersonPropertyId.LastNamePhonetic);}
set {SetValue (ABPersonPropertyId.LastNamePhonetic, value);}
}
public string MiddleName {
get {return PropertyToString (ABPersonPropertyId.MiddleName);}
set {SetValue (ABPersonPropertyId.MiddleName, value);}
}
public string MiddleNamePhonetic {
get {return PropertyToString (ABPersonPropertyId.MiddleNamePhonetic);}
set {SetValue (ABPersonPropertyId.MiddleNamePhonetic, value);}
}
public string Prefix {
get {return PropertyToString (ABPersonPropertyId.Prefix);}
set {SetValue (ABPersonPropertyId.Prefix, value);}
}
public string Suffix {
get {return PropertyToString (ABPersonPropertyId.Suffix);}
set {SetValue (ABPersonPropertyId.Suffix, value);}
}
public string Nickname {
get {return PropertyToString (ABPersonPropertyId.Nickname);}
set {SetValue (ABPersonPropertyId.Nickname, value);}
}
public string Organization {
get {return PropertyToString (ABPersonPropertyId.Organization);}
set {SetValue (ABPersonPropertyId.Organization, value);}
}
public string JobTitle {
get {return PropertyToString (ABPersonPropertyId.JobTitle);}
set {SetValue (ABPersonPropertyId.JobTitle, value);}
}
public string Department {
get {return PropertyToString (ABPersonPropertyId.Department);}
set {SetValue (ABPersonPropertyId.Department, value);}
}
internal static string ToString (IntPtr value)
{
if (value == IntPtr.Zero)
return null;
return Runtime.GetNSObject (value).ToString ();
}
internal static IntPtr ToIntPtr (string value)
{
if (value == null)
return IntPtr.Zero;
return new NSString (value).Handle;
}
public ABMultiValue<string> GetEmails ()
{
return CreateStringMultiValue (CopyValue (ABPersonPropertyId.Email));
}
static ABMultiValue<string> CreateStringMultiValue (IntPtr handle)
{
if (handle == IntPtr.Zero)
return null;
return new ABMultiValue<string> (handle, ToString, ToIntPtr);
}
public void SetEmails (ABMultiValue<string> value)
{
SetValue (ABPersonPropertyId.Email, value == null ? IntPtr.Zero : value.Handle);
}
public NSDate Birthday {
get {return PropertyTo<NSDate> (ABPersonPropertyId.Birthday);}
set {SetValue (ABPersonPropertyId.Birthday, value);}
}
public string Note {
get {return PropertyToString (ABPersonPropertyId.Note);}
set {SetValue (ABPersonPropertyId.Note, value);}
}
public NSDate CreationDate {
get {return PropertyTo<NSDate> (ABPersonPropertyId.CreationDate);}
set {SetValue (ABPersonPropertyId.CreationDate, value);}
}
public NSDate ModificationDate {
get {return PropertyTo<NSDate> (ABPersonPropertyId.ModificationDate);}
set {SetValue (ABPersonPropertyId.ModificationDate, value);}
}
public ABMultiValue<NSDictionary> GetAddresses ()
{
return CreateDictionaryMultiValue (CopyValue (ABPersonPropertyId.Address));
}
static ABMultiValue<NSDictionary> CreateDictionaryMultiValue (IntPtr handle)
{
if (handle == IntPtr.Zero)
return null;
return new ABMultiValue<NSDictionary> (handle);
}
public void SetAddresses (ABMultiValue<NSDictionary> value)
{
SetValue (ABPersonPropertyId.Address, value == null ? IntPtr.Zero : value.Handle);
}
public ABMultiValue<NSDate> GetDates ()
{
return CreateDateMultiValue (CopyValue (ABPersonPropertyId.Date));
}
static ABMultiValue<NSDate> CreateDateMultiValue (IntPtr handle)
{
if (handle == IntPtr.Zero)
return null;
return new ABMultiValue<NSDate> (handle);
}
public void SetDates (ABMultiValue<NSDate> value)
{
SetValue (ABPersonPropertyId.Date, value == null ? IntPtr.Zero : value.Handle);
}
public ABPersonKind PersonKind {
get {return ABPersonKindId.ToPersonKind (PropertyTo<NSNumber> (ABPersonPropertyId.Kind));}
set {SetValue (ABPersonPropertyId.Kind, ABPersonKindId.FromPersonKind (value));}
}
public ABMultiValue<string> GetPhones ()
{
return CreateStringMultiValue (CopyValue (ABPersonPropertyId.Phone));
}
public void SetPhones (ABMultiValue<string> value)
{
SetValue (ABPersonPropertyId.Phone, value == null ? IntPtr.Zero : value.Handle);
}
public ABMultiValue<NSDictionary> GetInstantMessages ()
{
return CreateDictionaryMultiValue (CopyValue (ABPersonPropertyId.InstantMessage));
}
public void SetInstantMessages (ABMultiValue<NSDictionary> value)
{
SetValue (ABPersonPropertyId.InstantMessage, value == null ? IntPtr.Zero : value.Handle);
}
public ABMultiValue<string> GetUrls ()
{
return CreateStringMultiValue (CopyValue (ABPersonPropertyId.Url));
}
public void SetUrls (ABMultiValue<string> value)
{
SetValue (ABPersonPropertyId.Url, value == null ? IntPtr.Zero : value.Handle);
}
public ABMultiValue<string> GetRelatedNames ()
{
return CreateStringMultiValue (CopyValue (ABPersonPropertyId.RelatedNames));
}
public void SetRelatedNames (ABMultiValue<string> value)
{
SetValue (ABPersonPropertyId.RelatedNames, value == null ? IntPtr.Zero : value.Handle);
}
// TODO: Is there a better way to do this?
public object GetProperty (ABPersonProperty property)
{
switch (property) {
case ABPersonProperty.Address: return GetAddresses ();
case ABPersonProperty.Birthday: return Birthday;
case ABPersonProperty.CreationDate: return CreationDate;
case ABPersonProperty.Date: return GetDates ();
case ABPersonProperty.Department: return Department;
case ABPersonProperty.Email: return GetEmails ();
case ABPersonProperty.FirstName: return FirstName;
case ABPersonProperty.FirstNamePhonetic: return FirstNamePhonetic;
case ABPersonProperty.InstantMessage: return GetInstantMessages ();
case ABPersonProperty.JobTitle: return JobTitle;
case ABPersonProperty.Kind: return PersonKind;
case ABPersonProperty.LastName: return LastName;
case ABPersonProperty.LastNamePhonetic: return LastNamePhonetic;
case ABPersonProperty.MiddleName: return MiddleName;
case ABPersonProperty.MiddleNamePhonetic: return MiddleNamePhonetic;
case ABPersonProperty.ModificationDate: return ModificationDate;
case ABPersonProperty.Nickname: return Nickname;
case ABPersonProperty.Note: return Note;
case ABPersonProperty.Organization: return Organization;
case ABPersonProperty.Phone: return GetPhones ();
case ABPersonProperty.Prefix: return Prefix;
case ABPersonProperty.RelatedNames: return GetRelatedNames ();
case ABPersonProperty.Suffix: return Suffix;
case ABPersonProperty.Url: return GetUrls ();
}
throw new ArgumentException ("Invalid property value: " + property);
}
[DllImport (Constants.AddressBookLibrary)]
extern static IntPtr ABPersonCopyImageDataWithFormat (IntPtr handle, ABPersonImageFormat format);
[Since (4,1)]
NSData CopyImage (ABPersonImageFormat format)
{
return new NSData (ABPersonCopyImageDataWithFormat (Handle, format));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Text;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Threading;
namespace System.IO
{
public static class Directory
{
public static DirectoryInfo GetParent(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_PathEmpty, "path");
Contract.EndContractBlock();
String fullPath = Path.GetFullPath(path);
String s = Path.GetDirectoryName(fullPath);
if (s == null)
return null;
return new DirectoryInfo(s);
}
[System.Security.SecuritySafeCritical]
public static DirectoryInfo CreateDirectory(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_PathEmpty, "path");
Contract.EndContractBlock();
String fullPath = Path.GetFullPath(path);
FileSystem.Current.CreateDirectory(fullPath);
return new DirectoryInfo(fullPath, null);
}
// Input to this method should already be fullpath. This method will ensure that we append
// the trailing slash only when appropriate.
internal static String EnsureTrailingDirectorySeparator(string fullPath)
{
String fullPathWithTrailingDirectorySeparator;
if (!PathHelpers.EndsInDirectorySeparator(fullPath))
fullPathWithTrailingDirectorySeparator = fullPath + PathHelpers.DirectorySeparatorCharAsString;
else
fullPathWithTrailingDirectorySeparator = fullPath;
return fullPathWithTrailingDirectorySeparator;
}
// Tests if the given path refers to an existing DirectoryInfo on disk.
//
// Your application must have Read permission to the directory's
// contents.
//
[System.Security.SecuritySafeCritical] // auto-generated
public static bool Exists(String path)
{
try
{
if (path == null)
return false;
if (path.Length == 0)
return false;
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.DirectoryExists(fullPath);
}
catch (ArgumentException) { }
catch (NotSupportedException) { } // Security can throw this on ":"
catch (SecurityException) { }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
return false;
}
public static void SetCreationTime(String path, DateTime creationTime)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetCreationTime(fullPath, creationTime, asDirectory: true);
}
public static void SetCreationTimeUtc(String path, DateTime creationTimeUtc)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetCreationTime(fullPath, File.GetUtcDateTimeOffset(creationTimeUtc), asDirectory: true);
}
public static DateTime GetCreationTime(String path)
{
return File.GetCreationTime(path);
}
public static DateTime GetCreationTimeUtc(String path)
{
return File.GetCreationTimeUtc(path);
}
public static void SetLastWriteTime(String path, DateTime lastWriteTime)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetLastWriteTime(fullPath, lastWriteTime, asDirectory: true);
}
public static void SetLastWriteTimeUtc(String path, DateTime lastWriteTimeUtc)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetLastWriteTime(fullPath, File.GetUtcDateTimeOffset(lastWriteTimeUtc), asDirectory: true);
}
public static DateTime GetLastWriteTime(String path)
{
return File.GetLastWriteTime(path);
}
public static DateTime GetLastWriteTimeUtc(String path)
{
return File.GetLastWriteTimeUtc(path);
}
public static void SetLastAccessTime(String path, DateTime lastAccessTime)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetLastAccessTime(fullPath, lastAccessTime, asDirectory: true);
}
public static void SetLastAccessTimeUtc(String path, DateTime lastAccessTimeUtc)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetLastAccessTime(fullPath, File.GetUtcDateTimeOffset(lastAccessTimeUtc), asDirectory: true);
}
public static DateTime GetLastAccessTime(String path)
{
return File.GetLastAccessTime(path);
}
public static DateTime GetLastAccessTimeUtc(String path)
{
return File.GetLastAccessTimeUtc(path);
}
// Returns an array of filenames in the DirectoryInfo specified by path
public static String[] GetFiles(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFiles(path, "*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search pattern (ie, "*.txt").
public static String[] GetFiles(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFiles(path, searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search pattern (ie, "*.txt") and search option
public static String[] GetFiles(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFiles(path, searchPattern, searchOption);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search pattern (ie, "*.txt") and search option
private static String[] InternalGetFiles(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return InternalGetFileDirectoryNames(path, path, searchPattern, true, false, searchOption);
}
// Returns an array of Directories in the current directory.
public static String[] GetDirectories(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetDirectories(path, "*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
public static String[] GetDirectories(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
public static String[] GetDirectories(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetDirectories(path, searchPattern, searchOption);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
private static String[] InternalGetDirectories(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<String[]>() != null);
return InternalGetFileDirectoryNames(path, path, searchPattern, false, true, searchOption);
}
// Returns an array of strongly typed FileSystemInfo entries in the path
public static String[] GetFileSystemEntries(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (ie, "*.txt"). We disallow .. as a part of the search criteria
public static String[] GetFileSystemEntries(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFileSystemEntries(path, searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (ie, "*.txt"). We disallow .. as a part of the search criteria
public static String[] GetFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFileSystemEntries(path, searchPattern, searchOption);
}
private static String[] InternalGetFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return InternalGetFileDirectoryNames(path, path, searchPattern, true, true, searchOption);
}
// Returns fully qualified user path of dirs/files that matches the search parameters.
// For recursive search this method will search through all the sub dirs and execute
// the given search criteria against every dir.
// For all the dirs/files returned, it will then demand path discovery permission for
// their parent folders (it will avoid duplicate permission checks)
internal static String[] InternalGetFileDirectoryNames(String path, String userPathOriginal, String searchPattern, bool includeFiles, bool includeDirs, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(userPathOriginal != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<String> enumerable = FileSystem.Current.EnumeratePaths(path, searchPattern, searchOption,
(includeFiles ? SearchTarget.Files : 0) | (includeDirs ? SearchTarget.Directories : 0));
return EnumerableHelpers.ToArray(enumerable);
}
public static IEnumerable<String> EnumerateDirectories(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
return InternalEnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.EndContractBlock();
return InternalEnumerateDirectories(path, searchPattern, SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalEnumerateDirectories(path, searchPattern, searchOption);
}
private static IEnumerable<String> InternalEnumerateDirectories(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return EnumerateFileSystemNames(path, searchPattern, searchOption, false, true);
}
public static IEnumerable<String> EnumerateFiles(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFiles(path, "*", SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateFiles(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFiles(path, searchPattern, SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateFiles(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFiles(path, searchPattern, searchOption);
}
private static IEnumerable<String> InternalEnumerateFiles(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
return EnumerateFileSystemNames(path, searchPattern, searchOption, true, false);
}
public static IEnumerable<String> EnumerateFileSystemEntries(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFileSystemEntries(path, searchPattern, SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFileSystemEntries(path, searchPattern, searchOption);
}
private static IEnumerable<String> InternalEnumerateFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
return EnumerateFileSystemNames(path, searchPattern, searchOption, true, true);
}
private static IEnumerable<String> EnumerateFileSystemNames(String path, String searchPattern, SearchOption searchOption,
bool includeFiles, bool includeDirs)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
return FileSystem.Current.EnumeratePaths(path, searchPattern, searchOption,
(includeFiles ? SearchTarget.Files : 0) | (includeDirs ? SearchTarget.Directories : 0));
}
[System.Security.SecuritySafeCritical]
public static String GetDirectoryRoot(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
String fullPath = Path.GetFullPath(path);
String root = fullPath.Substring(0, PathInternal.GetRootLength(fullPath));
return root;
}
internal static String InternalGetDirectoryRoot(String path)
{
if (path == null) return null;
return path.Substring(0, PathInternal.GetRootLength(path));
}
/*===============================CurrentDirectory===============================
**Action: Provides a getter and setter for the current directory. The original
** current DirectoryInfo is the one from which the process was started.
**Returns: The current DirectoryInfo (from the getter). Void from the setter.
**Arguments: The current DirectoryInfo to which to switch to the setter.
**Exceptions:
==============================================================================*/
[System.Security.SecuritySafeCritical]
public static String GetCurrentDirectory()
{
return FileSystem.Current.GetCurrentDirectory();
}
[System.Security.SecurityCritical] // auto-generated
public static void SetCurrentDirectory(String path)
{
if (path == null)
throw new ArgumentNullException("value");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_PathEmpty, "path");
Contract.EndContractBlock();
if (PathInternal.IsPathTooLong(path))
throw new PathTooLongException(SR.IO_PathTooLong);
String fulldestDirName = Path.GetFullPath(path);
FileSystem.Current.SetCurrentDirectory(fulldestDirName);
}
[System.Security.SecuritySafeCritical]
public static void Move(String sourceDirName, String destDirName)
{
if (sourceDirName == null)
throw new ArgumentNullException("sourceDirName");
if (sourceDirName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, "sourceDirName");
if (destDirName == null)
throw new ArgumentNullException("destDirName");
if (destDirName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, "destDirName");
Contract.EndContractBlock();
String fullsourceDirName = Path.GetFullPath(sourceDirName);
String sourcePath = EnsureTrailingDirectorySeparator(fullsourceDirName);
if (PathInternal.IsDirectoryTooLong(sourcePath))
throw new PathTooLongException(SR.IO_PathTooLong);
String fulldestDirName = Path.GetFullPath(destDirName);
String destPath = EnsureTrailingDirectorySeparator(fulldestDirName);
if (PathInternal.IsDirectoryTooLong(destPath))
throw new PathTooLongException(SR.IO_PathTooLong);
StringComparison pathComparison = PathInternal.StringComparison;
if (String.Equals(sourcePath, destPath, pathComparison))
throw new IOException(SR.IO_SourceDestMustBeDifferent);
String sourceRoot = Path.GetPathRoot(sourcePath);
String destinationRoot = Path.GetPathRoot(destPath);
if (!String.Equals(sourceRoot, destinationRoot, pathComparison))
throw new IOException(SR.IO_SourceDestMustHaveSameRoot);
FileSystem.Current.MoveDirectory(fullsourceDirName, fulldestDirName);
}
[System.Security.SecuritySafeCritical]
public static void Delete(String path)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.RemoveDirectory(fullPath, false);
}
[System.Security.SecuritySafeCritical]
public static void Delete(String path, bool recursive)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.RemoveDirectory(fullPath, recursive);
}
}
}
| |
// 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 Microsoft.CSharp.RuntimeBinder.Errors;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal sealed class SymbolLoader
{
private readonly NameManager _nameManager;
public PredefinedMembers PredefinedMembers { get; }
private GlobalSymbolContext GlobalSymbolContext { get; }
public ErrorHandling ErrorContext { get; }
public SymbolTable RuntimeBinderSymbolTable { get; private set; }
public SymbolLoader(
GlobalSymbolContext globalSymbols,
UserStringBuilder userStringBuilder,
ErrorHandling errorContext
)
{
_nameManager = globalSymbols.GetNameManager();
PredefinedMembers = new PredefinedMembers(this);
ErrorContext = errorContext;
GlobalSymbolContext = globalSymbols;
Debug.Assert(GlobalSymbolContext != null);
}
public ErrorHandling GetErrorContext()
{
return ErrorContext;
}
public GlobalSymbolContext GetGlobalSymbolContext()
{
return GlobalSymbolContext;
}
public MethodSymbol LookupInvokeMeth(AggregateSymbol pAggDel)
{
Debug.Assert(pAggDel.AggKind() == AggKindEnum.Delegate);
for (Symbol pSym = LookupAggMember(GetNameManager().GetPredefName(PredefinedName.PN_INVOKE), pAggDel, symbmask_t.MASK_ALL);
pSym != null;
pSym = LookupNextSym(pSym, pAggDel, symbmask_t.MASK_ALL))
{
if (pSym.IsMethodSymbol() && pSym.AsMethodSymbol().isInvoke())
{
return pSym.AsMethodSymbol();
}
}
return null;
}
public NameManager GetNameManager()
{
return _nameManager;
}
public PredefinedTypes getPredefTypes()
{
return GlobalSymbolContext.GetPredefTypes();
}
public TypeManager GetTypeManager()
{
return TypeManager;
}
public TypeManager TypeManager
{
get { return GlobalSymbolContext.TypeManager; }
}
public PredefinedMembers getPredefinedMembers()
{
return PredefinedMembers;
}
public BSYMMGR getBSymmgr()
{
return GlobalSymbolContext.GetGlobalSymbols();
}
public SymFactory GetGlobalSymbolFactory()
{
return GlobalSymbolContext.GetGlobalSymbolFactory();
}
public MiscSymFactory GetGlobalMiscSymFactory()
{
return GlobalSymbolContext.GetGlobalMiscSymFactory();
}
public AggregateType GetReqPredefType(PredefinedType pt)
{
return GetReqPredefType(pt, true);
}
public AggregateType GetReqPredefType(PredefinedType pt, bool fEnsureState)
{
AggregateSymbol agg = GetTypeManager().GetReqPredefAgg(pt);
if (agg == null)
{
Debug.Assert(false, "Required predef type missing");
return null;
}
AggregateType ats = agg.getThisType();
return ats;
}
public AggregateSymbol GetOptPredefAgg(PredefinedType pt)
{
return GetOptPredefAgg(pt, true);
}
private AggregateSymbol GetOptPredefAgg(PredefinedType pt, bool fEnsureState)
{
AggregateSymbol agg = GetTypeManager().GetOptPredefAgg(pt);
return agg;
}
public AggregateType GetOptPredefType(PredefinedType pt)
{
return GetOptPredefType(pt, true);
}
public AggregateType GetOptPredefType(PredefinedType pt, bool fEnsureState)
{
AggregateSymbol agg = GetTypeManager().GetOptPredefAgg(pt);
if (agg == null)
return null;
AggregateType ats = agg.getThisType();
return ats;
}
public AggregateType GetOptPredefTypeErr(PredefinedType pt, bool fEnsureState)
{
AggregateSymbol agg = GetTypeManager().GetOptPredefAgg(pt);
if (agg == null)
{
getPredefTypes().ReportMissingPredefTypeError(ErrorContext, pt);
return null;
}
AggregateType ats = agg.getThisType();
return ats;
}
public Symbol LookupAggMember(Name name, AggregateSymbol agg, symbmask_t mask)
{
return getBSymmgr().LookupAggMember(name, agg, mask);
}
public Symbol LookupNextSym(Symbol sym, ParentSymbol parent, symbmask_t kindmask)
{
return BSYMMGR.LookupNextSym(sym, parent, kindmask);
}
public bool isManagedType(CType type)
{
return type.computeManagedType(this);
}
// It would be nice to make this a virtual method on typeSym.
public AggregateType GetAggTypeSym(CType typeSym)
{
Debug.Assert(typeSym != null);
Debug.Assert(typeSym.IsAggregateType() ||
typeSym.IsTypeParameterType() ||
typeSym.IsArrayType() ||
typeSym.IsNullableType());
switch (typeSym.GetTypeKind())
{
case TypeKind.TK_AggregateType:
return typeSym.AsAggregateType();
case TypeKind.TK_ArrayType:
return GetReqPredefType(PredefinedType.PT_ARRAY);
case TypeKind.TK_TypeParameterType:
return typeSym.AsTypeParameterType().GetEffectiveBaseClass();
case TypeKind.TK_NullableType:
return typeSym.AsNullableType().GetAts(ErrorContext);
}
Debug.Assert(false, "Bad typeSym!");
return null;
}
private bool IsBaseInterface(CType pDerived, CType pBase)
{
Debug.Assert(pDerived != null);
Debug.Assert(pBase != null);
if (!pBase.isInterfaceType())
{
return false;
}
if (!pDerived.IsAggregateType())
{
return false;
}
AggregateType atsDer = pDerived.AsAggregateType();
while (atsDer != null)
{
TypeArray ifacesAll = atsDer.GetIfacesAll();
for (int i = 0; i < ifacesAll.Count; i++)
{
if (AreTypesEqualForConversion(ifacesAll[i], pBase))
{
return true;
}
}
atsDer = atsDer.GetBaseClass();
}
return false;
}
public bool IsBaseClassOfClass(CType pDerived, CType pBase)
{
Debug.Assert(pDerived != null);
Debug.Assert(pBase != null);
// This checks to see whether derived is a class, and if so,
// if base is a base class of derived.
if (!pDerived.isClassType())
{
return false;
}
return IsBaseClass(pDerived, pBase);
}
private bool IsBaseClass(CType pDerived, CType pBase)
{
Debug.Assert(pDerived != null);
Debug.Assert(pBase != null);
// A base class has got to be a class. The derived type might be a struct.
if (!pBase.isClassType())
{
return false;
}
if (pDerived.IsNullableType())
{
pDerived = pDerived.AsNullableType().GetAts(ErrorContext);
if (pDerived == null)
{
return false;
}
}
if (!pDerived.IsAggregateType())
{
return false;
}
AggregateType atsDer = pDerived.AsAggregateType();
AggregateType atsBase = pBase.AsAggregateType();
AggregateType atsCur = atsDer.GetBaseClass();
while (atsCur != null)
{
if (atsCur == atsBase)
{
return true;
}
atsCur = atsCur.GetBaseClass();
}
return false;
}
private bool HasCovariantArrayConversion(ArrayType pSource, ArrayType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
// * S and T differ only in element type. In other words, S and T have the same number of dimensions.
// * Both SE and TE are reference types.
// * An implicit reference conversion exists from SE to TE.
return (pSource.rank == pDest.rank) &&
HasImplicitReferenceConversion(pSource.GetElementType(), pDest.GetElementType());
}
public bool HasIdentityOrImplicitReferenceConversion(CType pSource, CType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
if (AreTypesEqualForConversion(pSource, pDest))
{
return true;
}
return HasImplicitReferenceConversion(pSource, pDest);
}
private bool AreTypesEqualForConversion(CType pType1, CType pType2)
{
return pType1.Equals(pType2);
}
private bool HasArrayConversionToInterface(ArrayType pSource, CType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
if (pSource.rank != 1)
{
return false;
}
if (!pDest.isInterfaceType())
{
return false;
}
// * From a single-dimensional array type S[] to IList<T> or IReadOnlyList<T> and their base
// interfaces, provided that there is an implicit identity or reference
// conversion from S to T.
// We only have six interfaces to check. IList<T>, IReadOnlyList<T> and their bases:
// * The base interface of IList<T> is ICollection<T>.
// * The base interface of ICollection<T> is IEnumerable<T>.
// * The base interface of IEnumerable<T> is IEnumerable.
// * The base interface of IReadOnlyList<T> is IReadOnlyCollection<T>.
// * The base interface of IReadOnlyCollection<T> is IEnumerable<T>.
if (pDest.isPredefType(PredefinedType.PT_IENUMERABLE))
{
return true;
}
AggregateType atsDest = pDest.AsAggregateType();
AggregateSymbol aggDest = pDest.getAggregate();
if (!aggDest.isPredefAgg(PredefinedType.PT_G_ILIST) &&
!aggDest.isPredefAgg(PredefinedType.PT_G_ICOLLECTION) &&
!aggDest.isPredefAgg(PredefinedType.PT_G_IENUMERABLE) &&
!aggDest.isPredefAgg(PredefinedType.PT_G_IREADONLYCOLLECTION) &&
!aggDest.isPredefAgg(PredefinedType.PT_G_IREADONLYLIST))
{
return false;
}
Debug.Assert(atsDest.GetTypeArgsAll().Count == 1);
CType pSourceElement = pSource.GetElementType();
CType pDestTypeArgument = atsDest.GetTypeArgsAll()[0];
return HasIdentityOrImplicitReferenceConversion(pSourceElement, pDestTypeArgument);
}
private bool HasImplicitReferenceConversion(CType pSource, CType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
// The implicit reference conversions are:
// * From any reference type to Object.
if (pSource.IsRefType() && pDest.isPredefType(PredefinedType.PT_OBJECT))
{
return true;
}
// * From any class type S to any class type T provided S is derived from T.
if (pSource.isClassType() && pDest.isClassType() && IsBaseClass(pSource, pDest))
{
return true;
}
// ORIGINAL RULES:
// // * From any class type S to any interface type T provided S implements T.
// if (pSource.isClassType() && pDest.isInterfaceType() && IsBaseInterface(pSource, pDest))
// {
// return true;
// }
// // * from any interface type S to any interface type T, provided S is derived from T.
// if (pSource.isInterfaceType() && pDest.isInterfaceType() && IsBaseInterface(pSource, pDest))
// {
// return true;
// }
// VARIANCE EXTENSIONS:
// * From any class type S to any interface type T provided S implements an interface
// convertible to T.
// * From any interface type S to any interface type T provided S implements an interface
// convertible to T.
// * From any interface type S to any interface type T provided S is not T and S is
// an interface convertible to T.
if (pSource.isClassType() && pDest.isInterfaceType() && HasAnyBaseInterfaceConversion(pSource, pDest))
{
return true;
}
if (pSource.isInterfaceType() && pDest.isInterfaceType() && HasAnyBaseInterfaceConversion(pSource, pDest))
{
return true;
}
if (pSource.isInterfaceType() && pDest.isInterfaceType() && pSource != pDest &&
HasInterfaceConversion(pSource.AsAggregateType(), pDest.AsAggregateType()))
{
return true;
}
// * From an array type S with an element type SE to an array type T with element type TE
// provided that all of the following are true:
// * S and T differ only in element type. In other words, S and T have the same number of dimensions.
// * Both SE and TE are reference types.
// * An implicit reference conversion exists from SE to TE.
if (pSource.IsArrayType() && pDest.IsArrayType() &&
HasCovariantArrayConversion(pSource.AsArrayType(), pDest.AsArrayType()))
{
return true;
}
// * From any array type to System.Array or any interface implemented by System.Array.
if (pSource.IsArrayType() && (pDest.isPredefType(PredefinedType.PT_ARRAY) ||
IsBaseInterface(GetReqPredefType(PredefinedType.PT_ARRAY, false), pDest)))
{
return true;
}
// * From a single-dimensional array type S[] to IList<T> and its base
// interfaces, provided that there is an implicit identity or reference
// conversion from S to T.
if (pSource.IsArrayType() && HasArrayConversionToInterface(pSource.AsArrayType(), pDest))
{
return true;
}
// * From any delegate type to System.Delegate
//
// SPEC OMISSION:
//
// The spec should actually say
//
// * From any delegate type to System.Delegate
// * From any delegate type to System.MulticastDelegate
// * From any delegate type to any interface implemented by System.MulticastDelegate
if (pSource.isDelegateType() &&
(pDest.isPredefType(PredefinedType.PT_MULTIDEL) ||
pDest.isPredefType(PredefinedType.PT_DELEGATE) ||
IsBaseInterface(GetReqPredefType(PredefinedType.PT_MULTIDEL, false), pDest)))
{
return true;
}
// VARIANCE EXTENSION:
// * From any delegate type S to a delegate type T provided S is not T and
// S is a delegate convertible to T
if (pSource.isDelegateType() && pDest.isDelegateType() &&
HasDelegateConversion(pSource.AsAggregateType(), pDest.AsAggregateType()))
{
return true;
}
// * From the null literal to any reference type
// NOTE: We extend the specification here. The C# 3.0 spec does not describe
// a "null type". Rather, it says that the null literal is typeless, and is
// convertible to any reference or nullable type. However, the C# 2.0 and 3.0
// implementations have a "null type" which some expressions other than the
// null literal may have. (For example, (null??null), which is also an
// extension to the specification.)
if (pSource.IsNullType() && pDest.IsRefType())
{
return true;
}
if (pSource.IsNullType() && pDest.IsNullableType())
{
return true;
}
// * Implicit conversions involving type parameters that are known to be reference types.
if (pSource.IsTypeParameterType() &&
HasImplicitReferenceTypeParameterConversion(pSource.AsTypeParameterType(), pDest))
{
return true;
}
return false;
}
private bool HasImplicitReferenceTypeParameterConversion(
TypeParameterType pSource, CType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
if (!pSource.IsRefType())
{
// Not a reference conversion.
return false;
}
// The following implicit conversions exist for a given type parameter T:
//
// * From T to its effective base class C.
AggregateType pEBC = pSource.GetEffectiveBaseClass();
if (pDest == pEBC)
{
return true;
}
// * From T to any base class of C.
if (IsBaseClass(pEBC, pDest))
{
return true;
}
// * From T to any interface implemented by C.
if (IsBaseInterface(pEBC, pDest))
{
return true;
}
// * From T to any interface type I in T's effective interface set, and
// from T to any base interface of I.
TypeArray pInterfaces = pSource.GetInterfaceBounds();
for (int i = 0; i < pInterfaces.Count; ++i)
{
if (pInterfaces[i] == pDest)
{
return true;
}
}
// * From T to a type parameter U, provided T depends on U.
if (pDest.IsTypeParameterType() && pSource.DependsOn(pDest.AsTypeParameterType()))
{
return true;
}
return false;
}
private bool HasAnyBaseInterfaceConversion(CType pDerived, CType pBase)
{
if (!pBase.isInterfaceType())
{
return false;
}
if (!pDerived.IsAggregateType())
{
return false;
}
AggregateType atsDer = pDerived.AsAggregateType();
while (atsDer != null)
{
TypeArray ifacesAll = atsDer.GetIfacesAll();
for (int i = 0; i < ifacesAll.Count; i++)
{
if (HasInterfaceConversion(ifacesAll[i].AsAggregateType(), pBase.AsAggregateType()))
{
return true;
}
}
atsDer = atsDer.GetBaseClass();
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// The rules for variant interface and delegate conversions are the same:
//
// An interface/delegate type S is convertible to an interface/delegate type T
// if and only if T is U<S1, ... Sn> and T is U<T1, ... Tn> such that for all
// parameters of U:
//
// * if the ith parameter of U is invariant then Si is exactly equal to Ti.
// * if the ith parameter of U is covariant then either Si is exactly equal
// to Ti, or there is an implicit reference conversion from Si to Ti.
// * if the ith parameter of U is contravariant then either Si is exactly
// equal to Ti, or there is an implicit reference conversion from Ti to Si.
private bool HasInterfaceConversion(AggregateType pSource, AggregateType pDest)
{
Debug.Assert(pSource != null && pSource.isInterfaceType());
Debug.Assert(pDest != null && pDest.isInterfaceType());
return HasVariantConversion(pSource, pDest);
}
//////////////////////////////////////////////////////////////////////////////
private bool HasDelegateConversion(AggregateType pSource, AggregateType pDest)
{
Debug.Assert(pSource != null && pSource.isDelegateType());
Debug.Assert(pDest != null && pDest.isDelegateType());
return HasVariantConversion(pSource, pDest);
}
//////////////////////////////////////////////////////////////////////////////
private bool HasVariantConversion(AggregateType pSource, AggregateType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
if (pSource == pDest)
{
return true;
}
AggregateSymbol pAggSym = pSource.getAggregate();
if (pAggSym != pDest.getAggregate())
{
return false;
}
TypeArray pTypeParams = pAggSym.GetTypeVarsAll();
TypeArray pSourceArgs = pSource.GetTypeArgsAll();
TypeArray pDestArgs = pDest.GetTypeArgsAll();
Debug.Assert(pTypeParams.Count == pSourceArgs.Count);
Debug.Assert(pTypeParams.Count == pDestArgs.Count);
for (int iParam = 0; iParam < pTypeParams.Count; ++iParam)
{
CType pSourceArg = pSourceArgs[iParam];
CType pDestArg = pDestArgs[iParam];
// If they're identical then this one is automatically good, so skip it.
if (pSourceArg == pDestArg)
{
continue;
}
TypeParameterType pParam = pTypeParams[iParam].AsTypeParameterType();
if (pParam.Invariant)
{
return false;
}
if (pParam.Covariant)
{
if (!HasImplicitReferenceConversion(pSourceArg, pDestArg))
{
return false;
}
}
if (pParam.Contravariant)
{
if (!HasImplicitReferenceConversion(pDestArg, pSourceArg))
{
return false;
}
}
}
return true;
}
private bool HasImplicitBoxingTypeParameterConversion(
TypeParameterType pSource, CType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
if (pSource.IsRefType())
{
// Not a boxing conversion; both source and destination are references.
return false;
}
// The following implicit conversions exist for a given type parameter T:
//
// * From T to its effective base class C.
AggregateType pEBC = pSource.GetEffectiveBaseClass();
if (pDest == pEBC)
{
return true;
}
// * From T to any base class of C.
if (IsBaseClass(pEBC, pDest))
{
return true;
}
// * From T to any interface implemented by C.
if (IsBaseInterface(pEBC, pDest))
{
return true;
}
// * From T to any interface type I in T's effective interface set, and
// from T to any base interface of I.
TypeArray pInterfaces = pSource.GetInterfaceBounds();
for (int i = 0; i < pInterfaces.Count; ++i)
{
if (pInterfaces[i] == pDest)
{
return true;
}
}
// * The conversion from T to a type parameter U, provided T depends on U, is not
// classified as a boxing conversion because it is not guaranteed to box.
// (If both T and U are value types then it is an identity conversion.)
return false;
}
private bool HasImplicitTypeParameterBaseConversion(
TypeParameterType pSource, CType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
if (HasImplicitReferenceTypeParameterConversion(pSource, pDest))
{
return true;
}
if (HasImplicitBoxingTypeParameterConversion(pSource, pDest))
{
return true;
}
if (pDest.IsTypeParameterType() && pSource.DependsOn(pDest.AsTypeParameterType()))
{
return true;
}
return false;
}
public bool HasImplicitBoxingConversion(CType pSource, CType pDest)
{
Debug.Assert(pSource != null);
Debug.Assert(pDest != null);
// Certain type parameter conversions are classified as boxing conversions.
if (pSource.IsTypeParameterType() &&
HasImplicitBoxingTypeParameterConversion(pSource.AsTypeParameterType(), pDest))
{
return true;
}
// The rest of the boxing conversions only operate when going from a value type
// to a reference type.
if (!pSource.IsValType() || !pDest.IsRefType())
{
return false;
}
// A boxing conversion exists from a nullable type to a reference type
// if and only if a boxing conversion exists from the underlying type.
if (pSource.IsNullableType())
{
return HasImplicitBoxingConversion(pSource.AsNullableType().GetUnderlyingType(), pDest);
}
// A boxing conversion exists from any non-nullable value type to object,
// to System.ValueType, and to any interface type implemented by the
// non-nullable value type. Furthermore, an enum type can be converted
// to the type System.Enum.
// We set the base class of the structs to System.ValueType, System.Enum, etc,
// so we can just check here.
if (IsBaseClass(pSource, pDest))
{
return true;
}
if (HasAnyBaseInterfaceConversion(pSource, pDest))
{
return true;
}
return false;
}
public bool HasBaseConversion(CType pSource, CType pDest)
{
// By a "base conversion" we mean:
//
// * an identity conversion
// * an implicit reference conversion
// * an implicit boxing conversion
// * an implicit type parameter conversion
//
// In other words, these are conversions that can be made to a base
// class, base interface or co/contravariant type without any change in
// representation other than boxing. A conversion from, say, int to double,
// is NOT a "base conversion", because representation is changed. A conversion
// from, say, lambda to expression tree is not a "base conversion" because
// do not have a type.
//
// The existence of a base conversion depends solely upon the source and
// destination types, not the source expression.
//
// This notion is not found in the spec but it is useful in the implementation.
if (pSource.IsAggregateType() && pDest.isPredefType(PredefinedType.PT_OBJECT))
{
// If we are going from any aggregate type (class, struct, interface, enum or delegate)
// to object, we immediately return true. This may seem like a mere optimization --
// after all, if we have an aggregate then we have some kind of implicit conversion
// to object.
//
// However, it is not a mere optimization; this introduces a control flow change
// in error reporting scenarios for unresolved type forwarders. If a type forwarder
// cannot be resolved then the resulting type symbol will be an aggregate, but
// we will not be able to classify it into class, struct, etc.
//
// We know that we will have an error in this case; we do not wish to compound
// that error by giving a spurious "you cannot convert this thing to object"
// error, which, after all, will go away when the type forwarding problem is
// fixed.
return true;
}
if (HasIdentityOrImplicitReferenceConversion(pSource, pDest))
{
return true;
}
if (HasImplicitBoxingConversion(pSource, pDest))
{
return true;
}
if (pSource.IsTypeParameterType() &&
HasImplicitTypeParameterBaseConversion(pSource.AsTypeParameterType(), pDest))
{
return true;
}
return false;
}
public bool FCanLift()
{
return null != GetOptPredefAgg(PredefinedType.PT_G_OPTIONAL, false);
}
public bool IsBaseAggregate(AggregateSymbol derived, AggregateSymbol @base)
{
Debug.Assert(!derived.IsEnum() && !@base.IsEnum());
if (derived == @base)
return true; // identity.
// refactoring error tolerance: structs and delegates can be base classes in error scenarios so
// we cannot filter on whether or not the base is marked as sealed.
if (@base.IsInterface())
{
// Search the direct and indirect interfaces via ifacesAll, going up the base chain...
while (derived != null)
{
for (int i = 0; i < derived.GetIfacesAll().Count; i++)
{
AggregateType iface = derived.GetIfacesAll()[i].AsAggregateType();
if (iface.getAggregate() == @base)
return true;
}
derived = derived.GetBaseAgg();
}
return false;
}
// base is a class. Just go up the base class chain to look for it.
while (derived.GetBaseClass() != null)
{
derived = derived.GetBaseClass().getAggregate();
if (derived == @base)
return true;
}
return false;
}
internal void SetSymbolTable(SymbolTable symbolTable)
{
RuntimeBinderSymbolTable = symbolTable;
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Threading.Tasks;
using Orchard.Caching;
using Orchard.Environment.Configuration;
using Orchard.Environment.Extensions;
using Orchard.Environment.ShellBuilders;
using Orchard.Environment.State;
using Orchard.Environment.Descriptor;
using Orchard.Environment.Descriptor.Models;
using Orchard.Localization;
using Orchard.Logging;
using Orchard.Utility.Extensions;
namespace Orchard.Environment {
// All the event handlers that DefaultOrchardHost implements have to be declared in OrchardStarter.
public class DefaultOrchardHost : IOrchardHost, IShellSettingsManagerEventHandler, IShellDescriptorManagerEventHandler {
private readonly IHostLocalRestart _hostLocalRestart;
private readonly IShellSettingsManager _shellSettingsManager;
private readonly IShellContextFactory _shellContextFactory;
private readonly IRunningShellTable _runningShellTable;
private readonly IProcessingEngine _processingEngine;
private readonly IExtensionLoaderCoordinator _extensionLoaderCoordinator;
private readonly IExtensionMonitoringCoordinator _extensionMonitoringCoordinator;
private readonly ICacheManager _cacheManager;
private readonly static object _syncLock = new object();
private readonly static object _shellContextsWriteLock = new object();
private IEnumerable<ShellContext> _shellContexts;
private readonly ContextState<IList<ShellSettings>> _tenantsToRestart;
public DefaultOrchardHost(
IShellSettingsManager shellSettingsManager,
IShellContextFactory shellContextFactory,
IRunningShellTable runningShellTable,
IProcessingEngine processingEngine,
IExtensionLoaderCoordinator extensionLoaderCoordinator,
IExtensionMonitoringCoordinator extensionMonitoringCoordinator,
ICacheManager cacheManager,
IHostLocalRestart hostLocalRestart) {
_shellSettingsManager = shellSettingsManager;
_shellContextFactory = shellContextFactory;
_runningShellTable = runningShellTable;
_processingEngine = processingEngine;
_extensionLoaderCoordinator = extensionLoaderCoordinator;
_extensionMonitoringCoordinator = extensionMonitoringCoordinator;
_cacheManager = cacheManager;
_hostLocalRestart = hostLocalRestart;
_tenantsToRestart = new ContextState<IList<ShellSettings>>("DefaultOrchardHost.TenantsToRestart", () => new List<ShellSettings>());
T = NullLocalizer.Instance;
Logger = NullLogger.Instance;
}
public Localizer T { get; set; }
public ILogger Logger { get; set; }
public IList<ShellContext> Current {
get { return BuildCurrent().ToReadOnlyCollection(); }
}
public ShellContext GetShellContext(ShellSettings shellSettings) {
return BuildCurrent().SingleOrDefault(shellContext => shellContext.Settings.Name.Equals(shellSettings.Name));
}
void IOrchardHost.Initialize() {
Logger.Information("Initializing");
BuildCurrent();
Logger.Information("Initialized");
}
void IOrchardHost.ReloadExtensions() {
DisposeShellContext();
}
void IOrchardHost.BeginRequest() {
Logger.Debug("BeginRequest");
BeginRequest();
}
void IOrchardHost.EndRequest() {
Logger.Debug("EndRequest");
EndRequest();
}
IWorkContextScope IOrchardHost.CreateStandaloneEnvironment(ShellSettings shellSettings) {
Logger.Debug("Creating standalone environment for tenant {0}", shellSettings.Name);
MonitorExtensions();
BuildCurrent();
var shellContext = CreateShellContext(shellSettings);
var workContext = shellContext.LifetimeScope.CreateWorkContextScope();
return new StandaloneEnvironmentWorkContextScopeWrapper(workContext, shellContext);
}
/// <summary>
/// Ensures shells are activated, or re-activated if extensions have changed
/// </summary>
IEnumerable<ShellContext> BuildCurrent() {
if (_shellContexts == null) {
lock (_syncLock) {
if (_shellContexts == null) {
SetupExtensions();
MonitorExtensions();
CreateAndActivateShells();
}
}
}
return _shellContexts;
}
void StartUpdatedShells() {
while (_tenantsToRestart.GetState().Any()) {
var settings = _tenantsToRestart.GetState().First();
_tenantsToRestart.GetState().Remove(settings);
Logger.Debug("Updating shell: " + settings.Name);
lock (_syncLock) {
ActivateShell(settings);
}
}
}
void CreateAndActivateShells() {
Logger.Information("Start creation of shells");
// Is there any tenant right now?
var allSettings = _shellSettingsManager.LoadSettings()
.Where(settings => settings.State == TenantState.Running || settings.State == TenantState.Uninitialized || settings.State == TenantState.Initializing)
.ToArray();
// Load all tenants, and activate their shell.
if (allSettings.Any()) {
Parallel.ForEach(allSettings, settings => {
try {
var context = CreateShellContext(settings);
ActivateShell(context);
}
catch (Exception e) {
Logger.Error(e, "A tenant could not be started: " + settings.Name);
}
while (_processingEngine.AreTasksPending()) {
Logger.Debug("Processing pending task after activate Shell");
_processingEngine.ExecuteNextTask();
}
});
}
// No settings, run the Setup.
else {
var setupContext = CreateSetupContext();
ActivateShell(setupContext);
}
Logger.Information("Done creating shells");
}
/// <summary>
/// Starts a Shell and registers its settings in RunningShellTable
/// </summary>
private void ActivateShell(ShellContext context) {
Logger.Debug("Activating context for tenant {0}", context.Settings.Name);
context.Shell.Activate();
lock (_shellContextsWriteLock) {
_shellContexts = (_shellContexts ?? Enumerable.Empty<ShellContext>())
.Where(c => c.Settings.Name != context.Settings.Name)
.Concat(new[] { context })
.ToArray();
}
_runningShellTable.Add(context.Settings);
}
/// <summary>
/// Creates a transient shell for the default tenant's setup.
/// </summary>
private ShellContext CreateSetupContext() {
Logger.Debug("Creating shell context for root setup.");
return _shellContextFactory.CreateSetupContext(new ShellSettings { Name = ShellSettings.DefaultName });
}
/// <summary>
/// Creates a shell context based on shell settings.
/// </summary>
private ShellContext CreateShellContext(ShellSettings settings) {
switch (settings.State) {
case TenantState.Uninitialized:
case TenantState.Initializing:
Logger.Debug("Creating shell context for tenant {0} setup.", settings.Name);
return _shellContextFactory.CreateSetupContext(settings);
default:
Logger.Debug("Creating shell context for tenant {0}.", settings.Name);
return _shellContextFactory.CreateShellContext(settings);
}
}
private void SetupExtensions() {
_extensionLoaderCoordinator.SetupExtensions();
}
private void MonitorExtensions() {
// This is a "fake" cache entry to allow the extension loader coordinator
// notify us (by resetting _current to "null") when an extension has changed
// on disk, and we need to reload new/updated extensions.
_cacheManager.Get("OrchardHost_Extensions",
ctx => {
_extensionMonitoringCoordinator.MonitorExtensions(ctx.Monitor);
_hostLocalRestart.Monitor(ctx.Monitor);
DisposeShellContext();
return "";
});
}
/// <summary>
/// Terminates all active shell contexts, and dispose their scope, forcing
/// them to be reloaded if necessary.
/// </summary>
private void DisposeShellContext() {
Logger.Information("Disposing active shell contexts");
if (_shellContexts != null) {
lock (_syncLock) {
if (_shellContexts != null) {
foreach (var shellContext in _shellContexts) {
shellContext.Shell.Terminate();
shellContext.Dispose();
}
}
}
_shellContexts = null;
}
}
protected virtual void BeginRequest() {
// Ensure all shell contexts are loaded, or need to be reloaded if
// extensions have changed
MonitorExtensions();
BuildCurrent();
StartUpdatedShells();
}
protected virtual void EndRequest() {
// Synchronously process all pending tasks. It's safe to do this at this point
// of the pipeline, as the request transaction has been closed, so creating a new
// environment and transaction for these tasks will behave as expected.)
while (_processingEngine.AreTasksPending()) {
Logger.Debug("Processing pending task");
_processingEngine.ExecuteNextTask();
}
StartUpdatedShells();
}
void IShellSettingsManagerEventHandler.Saved(ShellSettings settings) {
Logger.Debug("Shell saved: " + settings.Name);
// if a tenant has been created
if (settings.State != TenantState.Invalid) {
if (!_tenantsToRestart.GetState().Any(t => t.Name.Equals(settings.Name))) {
Logger.Debug("Adding tenant to restart: " + settings.Name + " " + settings.State);
_tenantsToRestart.GetState().Add(settings);
}
}
}
public void ActivateShell(ShellSettings settings) {
Logger.Debug("Activating shell: " + settings.Name);
// look for the associated shell context
var shellContext = _shellContexts.FirstOrDefault(c => c.Settings.Name == settings.Name);
if (shellContext == null && settings.State == TenantState.Disabled) {
return;
}
// is this is a new tenant ? or is it a tenant waiting for setup ?
if (shellContext == null || settings.State == TenantState.Uninitialized) {
// create the Shell
var context = CreateShellContext(settings);
// activate the Shell
ActivateShell(context);
}
// terminate the shell if the tenant was disabled
else if (settings.State == TenantState.Disabled) {
shellContext.Shell.Terminate();
_runningShellTable.Remove(settings);
// Forcing enumeration with ToArray() so a lazy execution isn't causing issues by accessing the disposed context.
_shellContexts = _shellContexts.Where(shell => shell.Settings.Name != settings.Name).ToArray();
shellContext.Dispose();
}
// reload the shell as its settings have changed
else {
// dispose previous context
shellContext.Shell.Terminate();
var context = _shellContextFactory.CreateShellContext(settings);
// Activate and register modified context.
// Forcing enumeration with ToArray() so a lazy execution isn't causing issues by accessing the disposed shell context.
_shellContexts = _shellContexts.Where(shell => shell.Settings.Name != settings.Name).Union(new[] { context }).ToArray();
shellContext.Dispose();
context.Shell.Activate();
_runningShellTable.Update(settings);
}
}
/// <summary>
/// A feature is enabled/disabled, the tenant needs to be restarted
/// </summary>
void IShellDescriptorManagerEventHandler.Changed(ShellDescriptor descriptor, string tenant) {
if (_shellContexts == null) {
return;
}
Logger.Debug("Shell changed: " + tenant);
var context = _shellContexts.FirstOrDefault(x => x.Settings.Name == tenant);
if (context == null) {
return;
}
// don't restart when tenant is in setup
if (context.Settings.State != TenantState.Running) {
return;
}
// don't flag the tenant if already listed
if (_tenantsToRestart.GetState().Any(x => x.Name == tenant)) {
return;
}
Logger.Debug("Adding tenant to restart: " + tenant);
_tenantsToRestart.GetState().Add(context.Settings);
}
// To be used from CreateStandaloneEnvironment(), also disposes the ShellContext LifetimeScope.
private class StandaloneEnvironmentWorkContextScopeWrapper : IWorkContextScope {
private readonly ShellContext _shellContext;
private readonly IWorkContextScope _workContextScope;
public WorkContext WorkContext {
get { return _workContextScope.WorkContext; }
}
public StandaloneEnvironmentWorkContextScopeWrapper(IWorkContextScope workContextScope, ShellContext shellContext) {
_workContextScope = workContextScope;
_shellContext = shellContext;
}
public TService Resolve<TService>() {
return _workContextScope.Resolve<TService>();
}
public bool TryResolve<TService>(out TService service) {
return _workContextScope.TryResolve<TService>(out service);
}
public void Dispose() {
_workContextScope.Dispose();
_shellContext.Dispose();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace System.Data.SqlClient.SNI
{
/// <summary>
/// SNI Packet
/// </summary>
internal partial class SNIPacket : IDisposable, IEquatable<SNIPacket>
{
private byte[] _data;
private int _length;
private int _capacity;
private int _offset;
private string _description;
private SNIAsyncCallback _completionCallback;
private bool _isBufferFromArrayPool;
public SNIPacket() { }
public SNIPacket(int capacity)
{
Allocate(capacity);
}
/// <summary>
/// Packet description (used for debugging)
/// </summary>
public string Description
{
get
{
return _description;
}
set
{
_description = value;
}
}
/// <summary>
/// Length of data left to process
/// </summary>
public int DataLeft => (_length - _offset);
/// <summary>
/// Length of data
/// </summary>
public int Length => _length;
/// <summary>
/// Packet validity
/// </summary>
public bool IsInvalid => (_data == null);
/// <summary>
/// Packet data
/// </summary>
public void Dispose()
{
Release();
}
/// <summary>
/// Set async completion callback
/// </summary>
/// <param name="completionCallback">Completion callback</param>
public void SetCompletionCallback(SNIAsyncCallback completionCallback)
{
_completionCallback = completionCallback;
}
/// <summary>
/// Invoke the completion callback
/// </summary>
/// <param name="sniErrorCode">SNI error</param>
public void InvokeCompletionCallback(uint sniErrorCode)
{
_completionCallback(this, sniErrorCode);
}
/// <summary>
/// Allocate space for data
/// </summary>
/// <param name="capacity">Length of byte array to be allocated</param>
public void Allocate(int capacity)
{
if (_data != null && _data.Length < capacity)
{
if (_isBufferFromArrayPool)
{
ArrayPool<byte>.Shared.Return(_data);
}
_data = null;
}
if (_data == null)
{
_data = ArrayPool<byte>.Shared.Rent(capacity);
_isBufferFromArrayPool = true;
}
_capacity = capacity;
_length = 0;
_offset = 0;
}
/// <summary>
/// Clone packet
/// </summary>
/// <returns>Cloned packet</returns>
public SNIPacket Clone()
{
SNIPacket packet = new SNIPacket(_capacity);
Buffer.BlockCopy(_data, 0, packet._data, 0, _capacity);
packet._length = _length;
packet._description = _description;
packet._completionCallback = _completionCallback;
return packet;
}
/// <summary>
/// Get packet data
/// </summary>
/// <param name="buffer">Buffer</param>
/// <param name="dataSize">Data in packet</param>
public void GetData(byte[] buffer, ref int dataSize)
{
Buffer.BlockCopy(_data, 0, buffer, 0, _length);
dataSize = _length;
}
/// <summary>
/// Set packet data
/// </summary>
/// <param name="data">Data</param>
/// <param name="length">Length</param>
public void SetData(byte[] data, int length)
{
_data = data;
_length = length;
_capacity = data.Length;
_offset = 0;
_isBufferFromArrayPool = false;
}
/// <summary>
/// Take data from another packet
/// </summary>
/// <param name="packet">Packet</param>
/// <param name="size">Data to take</param>
/// <returns>Amount of data taken</returns>
public int TakeData(SNIPacket packet, int size)
{
int dataSize = TakeData(packet._data, packet._length, size);
packet._length += dataSize;
return dataSize;
}
/// <summary>
/// Append data
/// </summary>
/// <param name="data">Data</param>
/// <param name="size">Size</param>
public void AppendData(byte[] data, int size)
{
Buffer.BlockCopy(data, 0, _data, _length, size);
_length += size;
}
public void AppendData(ReadOnlySpan<byte> data)
{
data.CopyTo(_data.AsSpan(_length));
_length += data.Length;
}
/// <summary>
/// Append another packet
/// </summary>
/// <param name="packet">Packet</param>
public void AppendPacket(SNIPacket packet)
{
Buffer.BlockCopy(packet._data, 0, _data, _length, packet._length);
_length += packet._length;
}
/// <summary>
/// Take data from packet and advance offset
/// </summary>
/// <param name="buffer">Buffer</param>
/// <param name="dataOffset">Data offset</param>
/// <param name="size">Size</param>
/// <returns></returns>
public int TakeData(byte[] buffer, int dataOffset, int size)
{
if (_offset >= _length)
{
return 0;
}
if (_offset + size > _length)
{
size = _length - _offset;
}
Buffer.BlockCopy(_data, _offset, buffer, dataOffset, size);
_offset += size;
return size;
}
/// <summary>
/// Release packet
/// </summary>
public void Release()
{
if (_data != null)
{
if(_isBufferFromArrayPool)
{
ArrayPool<byte>.Shared.Return(_data);
}
_data = null;
_capacity = 0;
}
Reset();
}
/// <summary>
/// Reset packet
/// </summary>
public void Reset()
{
_length = 0;
_offset = 0;
_description = null;
_completionCallback = null;
}
/// <summary>
/// Read data from a stream synchronously
/// </summary>
/// <param name="stream">Stream to read from</param>
public void ReadFromStream(Stream stream)
{
_length = stream.Read(_data, 0, _capacity);
}
/// <summary>
/// Write data to a stream synchronously
/// </summary>
/// <param name="stream">Stream to write to</param>
public void WriteToStream(Stream stream)
{
stream.Write(_data, 0, _length);
}
/// <summary>
/// Get hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Check packet equality
/// </summary>
/// <param name="obj"></param>
/// <returns>true if equal</returns>
public override bool Equals(object obj)
{
SNIPacket packet = obj as SNIPacket;
if (packet != null)
{
return Equals(packet);
}
return false;
}
/// <summary>
/// Check packet equality
/// </summary>
/// <param name="packet"></param>
/// <returns>true if equal</returns>
public bool Equals(SNIPacket packet)
{
if (packet != null)
{
return ReferenceEquals(packet, this);
}
return false;
}
}
}
| |
//
// https://github.com/ServiceStack/ServiceStack.Text
// ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers.
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2012 Service Stack LLC. All Rights Reserved.
//
// Licensed under the same terms of ServiceStack.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Linq;
using ServiceStack.Text.Common;
namespace ServiceStack.Text
{
public static class TranslateListWithElements
{
private static Dictionary<Type, ConvertInstanceDelegate> TranslateICollectionCache
= new Dictionary<Type, ConvertInstanceDelegate>();
public static object TranslateToGenericICollectionCache(object from, Type toInstanceOfType, Type elementType)
{
ConvertInstanceDelegate translateToFn;
if (TranslateICollectionCache.TryGetValue(toInstanceOfType, out translateToFn))
return translateToFn(from, toInstanceOfType);
var genericType = typeof(TranslateListWithElements<>).MakeGenericType(elementType);
var mi = genericType.GetStaticMethod("LateBoundTranslateToGenericICollection");
translateToFn = (ConvertInstanceDelegate)mi.MakeDelegate(typeof(ConvertInstanceDelegate));
Dictionary<Type, ConvertInstanceDelegate> snapshot, newCache;
do
{
snapshot = TranslateICollectionCache;
newCache = new Dictionary<Type, ConvertInstanceDelegate>(TranslateICollectionCache);
newCache[elementType] = translateToFn;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref TranslateICollectionCache, newCache, snapshot), snapshot));
return translateToFn(from, toInstanceOfType);
}
private static Dictionary<ConvertibleTypeKey, ConvertInstanceDelegate> TranslateConvertibleICollectionCache
= new Dictionary<ConvertibleTypeKey, ConvertInstanceDelegate>();
public static object TranslateToConvertibleGenericICollectionCache(
object from, Type toInstanceOfType, Type fromElementType)
{
var typeKey = new ConvertibleTypeKey(toInstanceOfType, fromElementType);
ConvertInstanceDelegate translateToFn;
if (TranslateConvertibleICollectionCache.TryGetValue(typeKey, out translateToFn)) return translateToFn(from, toInstanceOfType);
var toElementType = toInstanceOfType.FirstGenericType().GenericTypeArguments()[0];
var genericType = typeof(TranslateListWithConvertibleElements<,>).MakeGenericType(fromElementType, toElementType);
var mi = genericType.GetStaticMethod("LateBoundTranslateToGenericICollection");
translateToFn = (ConvertInstanceDelegate)mi.MakeDelegate(typeof(ConvertInstanceDelegate));
Dictionary<ConvertibleTypeKey, ConvertInstanceDelegate> snapshot, newCache;
do
{
snapshot = TranslateConvertibleICollectionCache;
newCache = new Dictionary<ConvertibleTypeKey, ConvertInstanceDelegate>(TranslateConvertibleICollectionCache);
newCache[typeKey] = translateToFn;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref TranslateConvertibleICollectionCache, newCache, snapshot), snapshot));
return translateToFn(from, toInstanceOfType);
}
public static object TryTranslateCollections(Type fromPropertyType, Type toPropertyType, object fromValue)
{
var args = typeof(IEnumerable<>).GetGenericArgumentsIfBothHaveSameGenericDefinitionTypeAndArguments(
fromPropertyType, toPropertyType);
if (args != null)
{
return TranslateToGenericICollectionCache(
fromValue, toPropertyType, args[0]);
}
var varArgs = typeof(IEnumerable<>).GetGenericArgumentsIfBothHaveConvertibleGenericDefinitionTypeAndArguments(
fromPropertyType, toPropertyType);
if (varArgs != null)
{
return TranslateToConvertibleGenericICollectionCache(
fromValue, toPropertyType, varArgs.Args1[0]);
}
return null;
}
}
public class ConvertibleTypeKey
{
public Type ToInstanceType { get; set; }
public Type FromElemenetType { get; set; }
public ConvertibleTypeKey()
{
}
public ConvertibleTypeKey(Type toInstanceType, Type fromElemenetType)
{
ToInstanceType = toInstanceType;
FromElemenetType = fromElemenetType;
}
public bool Equals(ConvertibleTypeKey other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.ToInstanceType, ToInstanceType) && Equals(other.FromElemenetType, FromElemenetType);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(ConvertibleTypeKey)) return false;
return Equals((ConvertibleTypeKey)obj);
}
public override int GetHashCode()
{
unchecked
{
return ((ToInstanceType != null ? ToInstanceType.GetHashCode() : 0) * 397)
^ (FromElemenetType != null ? FromElemenetType.GetHashCode() : 0);
}
}
}
public class TranslateListWithElements<T>
{
public static object CreateInstance(Type toInstanceOfType)
{
if (toInstanceOfType.IsGeneric())
{
if (toInstanceOfType.HasAnyTypeDefinitionsOf(
typeof(ICollection<>), typeof(IList<>)))
{
return typeof(List<T>).CreateInstance();
}
}
return toInstanceOfType.CreateInstance();
}
public static IList TranslateToIList(IList fromList, Type toInstanceOfType)
{
var to = (IList)toInstanceOfType.CreateInstance();
foreach (var item in fromList)
{
to.Add(item);
}
return to;
}
public static object LateBoundTranslateToGenericICollection(
object fromList, Type toInstanceOfType)
{
if (fromList == null)
return null; //AOT
if (toInstanceOfType.IsArray)
{
var result = TranslateToGenericICollection(
(ICollection<T>)fromList, typeof(List<T>));
return result.ToArray();
}
return TranslateToGenericICollection(
(ICollection<T>)fromList, toInstanceOfType);
}
public static ICollection<T> TranslateToGenericICollection(
ICollection<T> fromList, Type toInstanceOfType)
{
var to = (ICollection<T>)CreateInstance(toInstanceOfType);
foreach (var item in fromList)
{
to.Add(item);
}
return to;
}
}
public class TranslateListWithConvertibleElements<TFrom, TTo>
{
private static readonly Func<TFrom, TTo> ConvertFn;
static TranslateListWithConvertibleElements()
{
ConvertFn = GetConvertFn();
}
public static object LateBoundTranslateToGenericICollection(
object fromList, Type toInstanceOfType)
{
return TranslateToGenericICollection(
(ICollection<TFrom>)fromList, toInstanceOfType);
}
public static ICollection<TTo> TranslateToGenericICollection(
ICollection<TFrom> fromList, Type toInstanceOfType)
{
if (fromList == null) return null; //AOT
var to = (ICollection<TTo>)TranslateListWithElements<TTo>.CreateInstance(toInstanceOfType);
foreach (var item in fromList)
{
var toItem = ConvertFn(item);
to.Add(toItem);
}
return to;
}
private static Func<TFrom, TTo> GetConvertFn()
{
if (typeof(TTo) == typeof(string))
{
return x => (TTo)(object)TypeSerializer.SerializeToString(x);
}
if (typeof(TFrom) == typeof(string))
{
return x => TypeSerializer.DeserializeFromString<TTo>((string)(object)x);
}
return x => TypeSerializer.DeserializeFromString<TTo>(TypeSerializer.SerializeToString(x));
}
}
}
| |
// 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 OLEDB.Test.ModuleCore;
using Xunit;
namespace System.Xml.Tests
{
public partial class FactoryReaderTest : CGenericTestModule
{
private static void RunTestCaseAsync(Func<CTestBase> testCaseGenerator)
{
CModInfo.CommandLine = "/async";
RunTestCase(testCaseGenerator);
}
private static void RunTestCase(Func<CTestBase> testCaseGenerator)
{
var module = new FactoryReaderTest();
module.Init(null);
module.AddChild(testCaseGenerator());
module.Execute();
Assert.Equal(0, module.FailCount);
}
private static void RunTest(Func<CTestBase> testCaseGenerator)
{
RunTestCase(testCaseGenerator);
RunTestCaseAsync(testCaseGenerator);
}
[Fact]
[OuterLoop]
public static void ErrorConditionReader()
{
RunTest(() => new TCErrorConditionReader() { Attribute = new TestCase() { Name = "ErrorCondition", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void XMLExceptionReader()
{
RunTest(() => new TCXMLExceptionReader() { Attribute = new TestCase() { Name = "XMLException", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void LinePosReader()
{
RunTest(() => new TCLinePosReader() { Attribute = new TestCase() { Name = "LinePos", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void DepthReader()
{
RunTest(() => new TCDepthReader() { Attribute = new TestCase() { Name = "Depth", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void NamespaceReader()
{
RunTest(() => new TCNamespaceReader() { Attribute = new TestCase() { Name = "Namespace", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void LookupNamespaceReader()
{
RunTest(() => new TCLookupNamespaceReader() { Attribute = new TestCase() { Name = "LookupNamespace", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void HasValueReader()
{
RunTest(() => new TCHasValueReader() { Attribute = new TestCase() { Name = "HasValue", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void IsEmptyElementReader()
{
RunTest(() => new TCIsEmptyElementReader() { Attribute = new TestCase() { Name = "IsEmptyElement", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void XmlSpaceReader()
{
RunTest(() => new TCXmlSpaceReader() { Attribute = new TestCase() { Name = "XmlSpace", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void XmlLangReader()
{
RunTest(() => new TCXmlLangReader() { Attribute = new TestCase() { Name = "XmlLang", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void SkipReader()
{
RunTest(() => new TCSkipReader() { Attribute = new TestCase() { Name = "Skip", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void BaseURIReader()
{
RunTest(() => new TCBaseURIReader() { Attribute = new TestCase() { Name = "BaseURI", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void InvalidXMLReader()
{
RunTest(() => new TCInvalidXMLReader() { Attribute = new TestCase() { Name = "InvalidXML", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadOuterXmlReader()
{
RunTest(() => new TCReadOuterXmlReader() { Attribute = new TestCase() { Name = "ReadOuterXml", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void AttributeAccessReader()
{
RunTest(() => new TCAttributeAccessReader() { Attribute = new TestCase() { Name = "AttributeAccess", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ThisNameReader()
{
RunTest(() => new TCThisNameReader() { Attribute = new TestCase() { Name = "This(Name) and This(Name, Namespace)", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToAttributeReader()
{
RunTest(() => new TCMoveToAttributeReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void GetAttributeOrdinalReader()
{
RunTest(() => new TCGetAttributeOrdinalReader() { Attribute = new TestCase() { Name = "GetAttribute (Ordinal)", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void GetAttributeNameReader()
{
RunTest(() => new TCGetAttributeNameReader() { Attribute = new TestCase() { Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ThisOrdinalReader()
{
RunTest(() => new TCThisOrdinalReader() { Attribute = new TestCase() { Name = "This [Ordinal]", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToAttributeOrdinalReader()
{
RunTest(() => new TCMoveToAttributeOrdinalReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Ordinal)", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToFirstAttributeReader()
{
RunTest(() => new TCMoveToFirstAttributeReader() { Attribute = new TestCase() { Name = "MoveToFirstAttribute()", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToNextAttributeReader()
{
RunTest(() => new TCMoveToNextAttributeReader() { Attribute = new TestCase() { Name = "MoveToNextAttribute()", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void AttributeTestReader()
{
RunTest(() => new TCAttributeTestReader() { Attribute = new TestCase() { Name = "Attribute Test when NodeType != Attributes", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void AttributeXmlDeclarationReader()
{
RunTest(() => new TCAttributeXmlDeclarationReader() { Attribute = new TestCase() { Name = "Attributes test on XmlDeclaration", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void XmlnsReader()
{
RunTest(() => new TCXmlnsReader() { Attribute = new TestCase() { Name = "xmlns as local name", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void XmlnsPrefixReader()
{
RunTest(() => new TCXmlnsPrefixReader() { Attribute = new TestCase() { Name = "bounded namespace to xmlns prefix", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadStateReader()
{
RunTest(() => new TCReadStateReader() { Attribute = new TestCase() { Name = "ReadState", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadInnerXmlReader()
{
RunTest(() => new TCReadInnerXmlReader() { Attribute = new TestCase() { Name = "ReadInnerXml", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToContentReader()
{
RunTest(() => new TCMoveToContentReader() { Attribute = new TestCase() { Name = "MoveToContent", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void IsStartElementReader()
{
RunTest(() => new TCIsStartElementReader() { Attribute = new TestCase() { Name = "IsStartElement", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadStartElementReader()
{
RunTest(() => new TCReadStartElementReader() { Attribute = new TestCase() { Name = "ReadStartElement", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadEndElementReader()
{
RunTest(() => new TCReadEndElementReader() { Attribute = new TestCase() { Name = "ReadEndElement", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ResolveEntityReader()
{
RunTest(() => new TCResolveEntityReader() { Attribute = new TestCase() { Name = "ResolveEntity and ReadAttributeValue", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadAttributeValueReader()
{
RunTest(() => new TCReadAttributeValueReader() { Attribute = new TestCase() { Name = "ReadAttributeValue", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadReader()
{
RunTest(() => new TCReadReader() { Attribute = new TestCase() { Name = "Read", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToElementReader()
{
RunTest(() => new TCMoveToElementReader() { Attribute = new TestCase() { Name = "MoveToElement", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void DisposeReader()
{
RunTest(() => new TCDisposeReader() { Attribute = new TestCase() { Name = "Dispose", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void BufferBoundariesReader()
{
RunTest(() => new TCBufferBoundariesReader() { Attribute = new TestCase() { Name = "Buffer Boundaries", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileBeforeRead()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "BeforeRead", Desc = "BeforeRead" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileAfterCloseInMiddle()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileAfterClose()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterClose", Desc = "AfterClose" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileAfterReadIsFalse()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse" } });
}
[Fact]
[OuterLoop]
public static void ReadSubtreeReader()
{
RunTest(() => new TCReadSubtreeReader() { Attribute = new TestCase() { Name = "Read Subtree", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadToDescendantReader()
{
RunTest(() => new TCReadToDescendantReader() { Attribute = new TestCase() { Name = "ReadToDescendant", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadToNextSiblingReader()
{
RunTest(() => new TCReadToNextSiblingReader() { Attribute = new TestCase() { Name = "ReadToNextSibling", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadValueReader()
{
RunTest(() => new TCReadValueReader() { Attribute = new TestCase() { Name = "ReadValue", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadContentAsBase64Reader()
{
RunTest(() => new TCReadContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadContentAsBase64", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadElementContentAsBase64Reader()
{
RunTest(() => new TCReadElementContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadElementContentAsBase64", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadContentAsBinHexReader()
{
RunTest(() => new TCReadContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadContentAsBinHex", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadElementContentAsBinHexReader()
{
RunTest(() => new TCReadElementContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadElementContentAsBinHex", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void ReadToFollowingReader()
{
RunTest(() => new TCReadToFollowingReader() { Attribute = new TestCase() { Name = "ReadToFollowing", Desc = "FactoryReader" } });
}
[Fact]
[OuterLoop]
public static void Normalization()
{
RunTest(() => new TCNormalization() { Attribute = new TestCase() { Name = "FactoryReader Normalization", Desc = "FactoryReader" } });
}
}
}
| |
//-----------------------------------------------------------------------------
//
// <copyright file="ContainerUtilities.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description:
// Common container-related operations that can be shared among internal
// components.
//
// History:
// ??/??/2002: ? : Initial implementation
// 03/10/2003: RogerCh: Added the path array <-> path string conversion.
// 05/29/2003: RogerCh: Ported to WCP tree.
// 11/21/2003: Sarjanas: Added a method to apply predefined fragments to a
// stream.
//
//-----------------------------------------------------------------------------
using System;
using System.Collections; // for IList
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Text; // for StringBuilder
using System.Diagnostics; // for Debug.Assert
using System.Security;
#if PBTCOMPILER
using MS.Utility; // For SR.cs
using MS.Internal.PresentationBuildTasks;
#else
using System.Windows;
using MS.Internal.WindowsBase;
#endif
namespace MS.Internal.IO.Packaging.CompoundFile
{
/// <summary>
/// ContainerUtilities
/// </summary>
static internal class ContainerUtilities
{
static private readonly Int32 _int16Size = SizeOfInt16();
static private readonly Int32 _int32Size = SizeOfInt32();
static private readonly byte[] _paddingBuf = new byte[4]; // for writing DWORD padding
#if !PBTCOMPILER
static private readonly Int32 _int64Size = SizeOfInt64();
/// Used by ConvertBackSlashPathToStringArrayPath and
/// ConvertStringArrayPathToBackSlashPath to separate path elements.
static readonly internal char PathSeparator = '\\';
static private readonly char[] _PathSeparatorArray = new char[] { PathSeparator };
static readonly internal string PathSeparatorAsString = new string(ContainerUtilities.PathSeparator, 1);
static private readonly CaseInsensitiveOrdinalStringComparer _stringCaseInsensitiveComparer = new CaseInsensitiveOrdinalStringComparer();
#endif
/// <summary>
/// Byte size of Int16 Type
/// </summary>
static internal Int32 Int16Size
{
get
{
return _int16Size;
}
}
#if !PBTCOMPILER
/// <summary>
/// Byte size of Int32 Type
/// </summary>
static internal Int32 Int32Size
{
get
{
return _int32Size;
}
}
/// <summary>
/// Byte size of Int64 Type
/// </summary>
static internal Int32 Int64Size
{
get
{
return _int64Size;
}
}
static internal CaseInsensitiveOrdinalStringComparer StringCaseInsensitiveComparer
{
get
{
return _stringCaseInsensitiveComparer;
}
}
#endif
//The length should be verified by the caller to be non-negative
internal static int CalculateDWordPadBytesLength(int length)
{
Debug.Assert(length >= 0, "The length cannot be negative. Caller must verify this");
int padLen = length & 3;
if (padLen > 0)
{
padLen = 4 - padLen;
}
return (padLen);
}
/// <summary>
/// Write out a string via a BinaryWriter. Prefixed with int32 length in
/// bytes and padded at the end to the next 32-bit (DWORD) boundary
/// </summary>
/// <param name="writer">BinaryWriter configured for Unicode characters</param>
/// <param name="outputString">String to write out to BinaryWriter</param>
/// <returns>Number of bytes written including Prefixed int32 length, Unicode string,
/// and padding</returns>
/// <remarks>If writer==null, it will return the number of bytes it will take
/// to write it out; If outputString==null, it will write out 0 as length and
/// an empty string; After this operation, the current position of BinaryWriter
/// will be changed</remarks>
internal static int WriteByteLengthPrefixedDWordPaddedUnicodeString(BinaryWriter writer, String outputString)
{
checked
{
Int32 strByteLen = 0;
if (outputString != null)
{
strByteLen = outputString.Length * 2;
}
if (writer != null)
{
// Write length, in bytes, of the unicode string
writer.Write(strByteLen);
if (strByteLen != 0)
{
// Write the Unicode characters
writer.Write(outputString.ToCharArray());
}
}
if (strByteLen != 0)
{
int padLength = CalculateDWordPadBytesLength(strByteLen);
if (padLength != 0)
{
strByteLen += padLength;
if (writer != null)
{
writer.Write(_paddingBuf, 0, padLength);
}
}
}
strByteLen += _int32Size; // Size of the string length written at the beginning of this method
return strByteLen;
}
}
#if !PBTCOMPILER
/// <summary>
/// Read a string whose length is specified by the first four bytes as a
/// int32 and whose end is padded to the next 32-bit (DWORD) boundary.
/// </summary>
/// <param name="reader">A BinaryReader initialized for Unicode characters</param>
/// <returns>Unicode string without padding; After this operation, the current
/// position of BinaryWriter will be changed</returns>
internal static String ReadByteLengthPrefixedDWordPaddedUnicodeString(BinaryReader reader)
{
int bytesRead;
return ReadByteLengthPrefixedDWordPaddedUnicodeString(reader, out bytesRead);
}
/// <summary>
/// Read a string whose length is specified by the first four bytes as a
/// int32 and whose end is padded to the next 32-bit (DWORD) boundary.
/// </summary>
/// <param name="reader">A BinaryReader initialized for Unicode characters</param>
/// <param name="bytesRead">Total bytes read including prefixed length and padding</param>
/// <returns>Unicode string without padding</returns>
/// <remarks>If the string length is 0, it returns an empty string; After this operation,
/// the current position of BinaryWriter will be changed</remarks>
internal static String ReadByteLengthPrefixedDWordPaddedUnicodeString(BinaryReader reader, out int bytesRead)
{
checked
{
bytesRead = 0;
CheckAgainstNull(reader, "reader");
bytesRead = reader.ReadInt32(); // Length of the string in bytes
String inString = null;
if (bytesRead > 0)
{
try
{
if (reader.BaseStream.Length < bytesRead / 2)
{
#if !PBTCOMPILER
throw new FileFormatException(SR.Get(SRID.InvalidStringFormat));
#else
throw new SerializationException(SR.Get(SRID.InvalidStringFormat));
#endif
}
}
catch (NotSupportedException)
{
// if the stream does not support the Length operator, it will throw a NotSupportedException.
}
inString = new String(reader.ReadChars(bytesRead / 2));
// Make sure the length of string read matches the length specified
if (inString.Length != (bytesRead / 2))
{
#if !PBTCOMPILER
throw new FileFormatException(SR.Get(SRID.InvalidStringFormat));
#else
throw new SerializationException(SR.Get(SRID.InvalidStringFormat));
#endif
}
}
else if (bytesRead == 0)
{
inString = String.Empty;
}
else
{
#if !PBTCOMPILER
throw new FileFormatException(SR.Get(SRID.InvalidStringFormat));
#else
throw new SerializationException(SR.Get(SRID.InvalidStringFormat));
#endif
}
// skip the padding
int padLength = CalculateDWordPadBytesLength(bytesRead);
if (padLength > 0)
{
byte[] padding;
padding = reader.ReadBytes(padLength);
// Make sure the string is padded with the correct number of bytes
if (padding.Length != padLength)
{
#if !PBTCOMPILER
throw new FileFormatException(SR.Get(SRID.InvalidStringFormat));
#else
throw new SerializationException(SR.Get(SRID.InvalidStringFormat));
#endif
}
bytesRead += padLength;
}
bytesRead += _int32Size; //// Size of the string length read at the beginning of this method
return inString;
}
}
#endif
/// <summary>
/// Subset of CheckStringAgainstNullAndEmpty - and just checks against null reference.
/// </summary>
static internal void CheckAgainstNull(object paramRef,
string testStringIdentifier)
{
if (paramRef == null)
throw new ArgumentNullException(testStringIdentifier);
}
#if !PBTCOMPILER
/// <SecurityNote>
/// Critical : Calls critical Marshal.SizeOf
/// Safe : Calls method with trusted input (well known safe type)
/// </SecurityNote>
[SecuritySafeCritical]
#endif
private static int SizeOfInt16()
{
return Marshal.SizeOf(typeof(Int16));
}
#if !PBTCOMPILER
/// <SecurityNote>
/// Critical : Calls critical Marshal.SizeOf
/// Safe : Calls method with trusted input (well known safe type)
/// </SecurityNote>
[SecuritySafeCritical]
#endif
private static int SizeOfInt32()
{
return Marshal.SizeOf(typeof(Int32));
}
#if !PBTCOMPILER
/// <SecurityNote>
/// Critical : Calls critical Marshal.SizeOf
/// Safe : Calls method with trusted input (well known safe type)
/// </SecurityNote>
[SecuritySafeCritical]
private static int SizeOfInt64()
{
return Marshal.SizeOf(typeof(Int64));
}
#endif
#if !PBTCOMPILER
/// <summary>
/// Interprets a single string by treating it as a set of names
/// delimited by a special character. The character is the backslash,
/// serving the same role it has served since the original MS-DOS.
/// The individual names are extracted from this string and
/// returned as an array of string names.
///
/// string "images\button.jpg" -> string [] { "images", "button.jpg" }
///
/// </summary>
/// <param name="backSlashPath">
/// String path to be converted
/// </param>
/// <returns>
/// The elements of the path as a string array
/// </returns>
/// <remarks>
/// Mirror counterpart of ConvertStringArrayPathToBackSlashPath
/// </remarks>
// In theory, parsing strings should be done with regular expressions.
// In practice, the RegEx class is too heavyweight for this application.
// IMPORTANT: When updating this, make sure the counterpart is similarly
// updated.
static internal string[] ConvertBackSlashPathToStringArrayPath(string backSlashPath)
{
// A null string will get a null array
if ((null == backSlashPath) || (0 == backSlashPath.Length))
return new string[0];
// Reject leading/trailing whitespace
if (Char.IsWhiteSpace(backSlashPath[0]) ||
Char.IsWhiteSpace(backSlashPath[backSlashPath.Length - 1]))
{
throw new ArgumentException(SR.Get(SRID.MalformedCompoundFilePath));
}
// Build the array
string[] splitArray =
backSlashPath.Split(_PathSeparatorArray);
// Look for empty strings in the array
foreach (string arrayElement in splitArray)
{
if (0 == arrayElement.Length)
throw new ArgumentException(
SR.Get(SRID.PathHasEmptyElement), "backSlashPath");
}
// No empty strings, this array should be fine.
return splitArray;
}
/// <summary>
/// Concatenates the names in an array of strings into a backslash-
/// delimited string.
///
/// string[] { "images", "button.jpg" } -> string "images\button.jpg"
///
/// </summary>
/// <param name="arrayPath">
/// String array of names
/// </param>
/// <returns>
/// Concatenated path with all the names in the given array
///</returns>
/// <remarks>
/// Mirror counterpart to ConvertBackSlashPathToStringArrayPath
///</remarks>
// IMPORTANT: When updating this, make sure the counterpart is similarly
// updated.
static internal string ConvertStringArrayPathToBackSlashPath(IList arrayPath)
{
// Null array gets a null string
if ((null == arrayPath) || (1 > arrayPath.Count))
return String.Empty;
// Length of one gets that element returned
if (1 == arrayPath.Count)
return (string)arrayPath[0];
// More than one - OK it's time to build something.
CheckStringForEmbeddedPathSeparator((string)arrayPath[0], "Path array element");
StringBuilder pathBuilder =
new StringBuilder((string)arrayPath[0]);
for (int counter = 1; counter < arrayPath.Count; counter++)
{
CheckStringForEmbeddedPathSeparator((String)arrayPath[counter], "Path array element");
pathBuilder.Append(PathSeparator);
pathBuilder.Append((String)arrayPath[counter]);
}
return pathBuilder.ToString();
}
/// <summary>
/// Convert to path when storage array and stream name are separate
/// </summary>
/// <param name="storages">storage collection (strings)</param>
/// <param name="streamName">stream name</param>
static internal string ConvertStringArrayPathToBackSlashPath(IList storages, string streamName)
{
string result = ConvertStringArrayPathToBackSlashPath(storages);
if (result.Length > 0)
return result + PathSeparator + streamName;
else
return streamName;
}
/// <summary>
/// Utility function to check a string (presumably an input to the
/// caller function) against null, then against empty. Throwing an
/// exception if either is true.
/// </summary>
/// <param name="testString">
/// The string to be tested
/// </param>
/// <param name="testStringIdentifier">
/// A label for the test string to be used in the exception message.
/// </param>
/// <returns>
/// No return value
///</returns>
/// <remarks>
///
/// CheckStringAgainstNullAndEmpty( fooName, "The name parameter ");
///
/// may get:
///
/// ArgumentNullException "The name parameter cannot be a null string"
/// or
/// ArgumentException "The name parameter cannot be an empty string"
///
///</remarks>
static internal void CheckStringAgainstNullAndEmpty(string testString,
string testStringIdentifier)
{
if (testString == null)
throw new ArgumentNullException(testStringIdentifier);
if (testString.Length == 0)
throw new ArgumentException(SR.Get(SRID.StringEmpty), testStringIdentifier);
}
/// <summary>
/// Checks if the given string fits within the range of reserved
/// names and throws an ArgumentException if it does.
/// The 0x01 through 0x1F characters, serving as the first character of the stream/storage name,
/// are reserved for use by OLE. This is a compound file restriction.
/// </summary>
static internal void CheckStringAgainstReservedName(string nameString,
string nameStringIdentifier)
{
if (IsReservedName(nameString))
throw new ArgumentException(
SR.Get(SRID.StringCanNotBeReservedName, nameStringIdentifier));
}
/// <summary>
/// A certain subset of compound file storage and stream names are
/// reserved for use be OLE. These are names that start with a character in the
/// range 0x01 to 0x1F. (1-31)
/// This is a compound file restriction
/// </summary>
static internal bool IsReservedName(string nameString)
{
CheckStringAgainstNullAndEmpty(nameString, "nameString");
return (nameString[0] >= '\x0001'
&&
nameString[0] <= '\x001F');
}
/// <summary>
/// Checks for embedded delimiter in the string (as well as Null and Empty)
/// </summary>
/// <param name="testString">string to test</param>
/// <param name="testStringIdentifier">message for exception</param>
static internal void CheckStringForEmbeddedPathSeparator(string testString,
string testStringIdentifier)
{
CheckStringAgainstNullAndEmpty(testString, testStringIdentifier);
if (testString.IndexOf(PathSeparator) != -1)
throw new ArgumentException(
SR.Get(SRID.NameCanNotHaveDelimiter,
testStringIdentifier,
PathSeparator), "testString");
}
#endif
}
}
| |
// Discoverer classes.
// Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors.
//
// 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.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using GSF.Net.Snmp.Security;
namespace GSF.Net.Snmp.Messaging
{
/// <summary>
/// Discoverer class to discover SNMP agents in the same network.
/// </summary>
public sealed class Discoverer
{
private int _active;
private int _bufferSize;
private int _requestId;
private static readonly UserRegistry Empty = new UserRegistry();
private readonly IList<Variable> _defaultVariables = new List<Variable> { new Variable(new ObjectIdentifier(new uint[] { 1, 3, 6, 1, 2, 1, 1, 1, 0 })) };
private const int Active = 1;
private const int Inactive = 0;
/// <summary>
/// Occurs when an SNMP agent is found.
/// </summary>
public event EventHandler<AgentFoundEventArgs> AgentFound;
/// <summary>
/// Occurs when an exception is raised.
/// </summary>
/// <remarks>The exception is typical <see cref="SocketException"/> here.</remarks>
public event EventHandler<ExceptionRaisedEventArgs> ExceptionRaised;
/// <summary>
/// Discovers agents of the specified version in a specific time interval.
/// </summary>
/// <param name="version">The version.</param>
/// <param name="broadcastAddress">The broadcast address.</param>
/// <param name="community">The community.</param>
/// <param name="interval">The discovering time interval, in milliseconds.</param>
/// <remarks><paramref name="broadcastAddress"/> must be an IPv4 address. IPv6 is not yet supported here.</remarks>
public void Discover(VersionCode version, IPEndPoint broadcastAddress, OctetString community, int interval)
{
if (broadcastAddress == null)
{
throw new ArgumentNullException(nameof(broadcastAddress));
}
if (version != VersionCode.V3 && community == null)
{
throw new ArgumentNullException(nameof(community));
}
AddressFamily addressFamily = broadcastAddress.AddressFamily;
if (addressFamily == AddressFamily.InterNetworkV6)
{
throw new ArgumentException("IP v6 is not yet supported.", nameof(broadcastAddress));
}
byte[] bytes;
_requestId = Messenger.NextRequestId;
if (version == VersionCode.V3)
{
// throw new NotSupportedException("SNMP v3 is not supported");
Discovery discovery = new Discovery(Messenger.NextMessageId, _requestId, Messenger.MaxMessageSize);
bytes = discovery.ToBytes();
}
else
{
GetRequestMessage message = new GetRequestMessage(_requestId, version, community, _defaultVariables);
bytes = message.ToBytes();
}
using (UdpClient udp = new UdpClient(addressFamily))
{
#if (!CF)
udp.EnableBroadcast = true;
#endif
#if NET471
udp.Send(bytes, bytes.Length, broadcastAddress);
#else
AsyncHelper.RunSync(() => udp.SendAsync(bytes, bytes.Length, broadcastAddress));
#endif
int activeBefore = Interlocked.CompareExchange(ref _active, Active, Inactive);
if (activeBefore == Active)
{
// If already started, we've nothing to do.
return;
}
_bufferSize = udp.Client.ReceiveBufferSize = Messenger.MaxMessageSize;
#if ASYNC
Task.Factory.StartNew(() => AsyncBeginReceive(udp.Client));
#else
Task.Factory.StartNew(() => AsyncReceive(udp.Client));
#endif
Thread.Sleep(interval);
Interlocked.CompareExchange(ref _active, Inactive, Active);
#if NET471
udp.Close();
#endif
}
}
#if ASYNC
private void AsyncBeginReceive(Socket socket)
{
while (true)
{
// If no more active, then stop.
if (Interlocked.Exchange(ref _active, _active) == Inactive)
{
return;
}
byte[] buffer = new byte[_bufferSize];
EndPoint remote = new IPEndPoint(IPAddress.Any, 0);
IAsyncResult iar = null;
try
{
iar = socket.BeginReceiveFrom(buffer, 0, _bufferSize, SocketFlags.None, ref remote, AsyncEndReceive, new Tuple<Socket, byte[]>(socket, buffer));
}
catch (SocketException ex)
{
// ignore WSAECONNRESET, http://bytes.com/topic/c-sharp/answers/237558-strange-udp-socket-problem
if (ex.SocketErrorCode != SocketError.ConnectionReset)
{
// If the SnmpTrapListener was active, marks it as stopped and call HandleException.
// If it was inactive, the exception is likely to result from this, and we raise nothing.
long activeBefore = Interlocked.CompareExchange(ref _active, Inactive, Active);
if (activeBefore == Active)
{
HandleException(ex);
}
}
}
if (iar != null)
{
iar.AsyncWaitHandle.WaitOne();
}
}
}
private void AsyncEndReceive(IAsyncResult iar)
{
// If no more active, then stop. This discards the received packet, if any (indeed, we may be there either
// because we've received a packet, or because the socket has been closed).
if (Interlocked.Exchange(ref _active, _active) == Inactive)
{
return;
}
//// We start another receive operation.
//AsyncBeginReceive();
Tuple<Socket, byte[]> data = (Tuple<Socket, byte[]>)iar.AsyncState;
byte[] buffer = data.Item2;
try
{
EndPoint remote = data.Item1.AddressFamily == AddressFamily.InterNetwork ? new IPEndPoint(IPAddress.Any, 0) : new IPEndPoint(IPAddress.IPv6Any, 0);
int count = data.Item1.EndReceiveFrom(iar, ref remote);
HandleMessage(buffer, count, (IPEndPoint)remote);
}
catch (SocketException ex)
{
// ignore WSAECONNRESET, http://bytes.com/topic/c-sharp/answers/237558-strange-udp-socket-problem
if (ex.SocketErrorCode != SocketError.ConnectionReset)
{
// If the SnmpTrapListener was active, marks it as stopped and call HandleException.
// If it was inactive, the exception is likely to result from this, and we raise nothing.
long activeBefore = Interlocked.CompareExchange(ref _active, Inactive, Active);
if (activeBefore == Active)
{
HandleException(ex);
}
}
}
}
#else
private void AsyncReceive(Socket socket)
{
while (true)
{
// If no more active, then stop.
if (Interlocked.Exchange(ref _active, _active) == Inactive)
{
return;
}
try
{
var buffer = new byte[_bufferSize];
EndPoint remote = new IPEndPoint(IPAddress.Any, 0);
var count = socket.ReceiveFrom(buffer, ref remote);
Task.Factory.StartNew(()=> HandleMessage(buffer, count, (IPEndPoint)remote));
}
catch (SocketException ex)
{
if (ex.SocketErrorCode != SocketError.ConnectionReset)
{
// If the SnmpTrapListener was active, marks it as stopped and call HandleException.
// If it was inactive, the exception is likely to result from this, and we raise nothing.
var activeBefore = Interlocked.CompareExchange(ref _active, Inactive, Active);
if (activeBefore == Active)
{
HandleException(ex);
}
}
}
}
}
#endif
private void HandleException(Exception exception)
{
ExceptionRaised?.Invoke(this, new ExceptionRaisedEventArgs(exception));
}
private void HandleMessage(byte[] buffer, int count, IPEndPoint remote)
{
foreach (ISnmpMessage message in MessageFactory.ParseMessages(buffer, 0, count, Empty))
{
SnmpType code = message.TypeCode();
if (code == SnmpType.ReportPdu)
{
ReportMessage report = (ReportMessage)message;
if (report.RequestId() != _requestId)
{
continue;
}
if (report.Pdu().ErrorStatus.ToErrorCode() != ErrorCode.NoError)
{
continue;
}
AgentFound?.Invoke(this, new AgentFoundEventArgs(remote, null));
}
if (code != SnmpType.ResponsePdu)
{
continue;
}
ResponseMessage response = (ResponseMessage)message;
if (response.RequestId() != _requestId)
{
continue;
}
if (response.ErrorStatus != ErrorCode.NoError)
{
continue;
}
AgentFound?.Invoke(this, new AgentFoundEventArgs(remote, response.Variables()[0]));
}
}
/// <summary>
/// Discovers agents of the specified version in a specific time interval.
/// </summary>
/// <param name="version">The version.</param>
/// <param name="broadcastAddress">The broadcast address.</param>
/// <param name="community">The community.</param>
/// <param name="interval">The discovering time interval, in milliseconds.</param>
/// <remarks><paramref name="broadcastAddress"/> must be an IPv4 address. IPv6 is not yet supported here.</remarks>
public async Task DiscoverAsync(VersionCode version, IPEndPoint broadcastAddress, OctetString community, int interval)
{
if (broadcastAddress == null)
{
throw new ArgumentNullException(nameof(broadcastAddress));
}
if (version != VersionCode.V3 && community == null)
{
throw new ArgumentNullException(nameof(community));
}
AddressFamily addressFamily = broadcastAddress.AddressFamily;
if (addressFamily == AddressFamily.InterNetworkV6)
{
throw new ArgumentException("IP v6 is not yet supported.", nameof(broadcastAddress));
}
byte[] bytes;
_requestId = Messenger.NextRequestId;
if (version == VersionCode.V3)
{
// throw new NotSupportedException("SNMP v3 is not supported");
Discovery discovery = new Discovery(Messenger.NextMessageId, _requestId, Messenger.MaxMessageSize);
bytes = discovery.ToBytes();
}
else
{
GetRequestMessage message = new GetRequestMessage(_requestId, version, community, _defaultVariables);
bytes = message.ToBytes();
}
using (Socket udp = new Socket(addressFamily, SocketType.Dgram, ProtocolType.Udp))
{
udp.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
SocketAsyncEventArgs info = SocketExtension.EventArgsFactory.Create();
info.RemoteEndPoint = broadcastAddress;
info.SetBuffer(bytes, 0, bytes.Length);
using (SocketAwaitable awaitable1 = new SocketAwaitable(info))
{
await udp.SendToAsync(awaitable1);
}
int activeBefore = Interlocked.CompareExchange(ref _active, Active, Inactive);
if (activeBefore == Active)
{
// If already started, we've nothing to do.
return;
}
_bufferSize = udp.ReceiveBufferSize;
await Task.WhenAny(
ReceiveAsync(udp),
Task.Delay(interval));
Interlocked.CompareExchange(ref _active, Inactive, Active);
try
{
udp.Shutdown(SocketShutdown.Both);
}
catch (SocketException ex)
{
// This exception is thrown in .NET Core <=2.1.4 on non-Windows systems.
// However, the shutdown call is necessary to release the socket binding.
if (!SnmpMessageExtension.IsRunningOnWindows && ex.SocketErrorCode == SocketError.NotConnected)
{
}
}
}
}
private async Task ReceiveAsync(Socket socket)
{
while (true)
{
// If no more active, then stop.
if (Interlocked.Exchange(ref _active, _active) == Inactive)
{
return;
}
int count;
byte[] reply = new byte[_bufferSize];
SocketAsyncEventArgs args = SocketExtension.EventArgsFactory.Create();
try
{
EndPoint remote = new IPEndPoint(IPAddress.Any, 0);
args.RemoteEndPoint = remote;
args.SetBuffer(reply, 0, _bufferSize);
using (SocketAwaitable awaitable = new SocketAwaitable(args))
{
count = await socket.ReceiveMessageFromAsync(awaitable);
}
await Task.Factory.StartNew(() => HandleMessage(reply, count, (IPEndPoint) args.RemoteEndPoint))
.ConfigureAwait(false);
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.ConnectionReset)
{
continue;
}
// If the SnmpTrapListener was active, marks it as stopped and call HandleException.
// If it was inactive, the exception is likely to result from this, and we raise nothing.
int activeBefore = Interlocked.CompareExchange(ref _active, Inactive, Active);
if (activeBefore == Active)
{
HandleException(ex);
}
}
catch (NullReferenceException)
{
args.UserToken = SocketAsyncEventArgsFactory.DisposedMessage;
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using Res = System.SR;
namespace System
{
internal static partial class SR
{
internal static string GetString(string value)
{
return value;
}
internal static string GetString(string format, params object[] args)
{
return SR.Format(format, args);
}
}
}
namespace System.Data.Common
{
internal static class ADP
{
// The class ADP defines the exceptions that are specific to the Adapters.
// The class contains functions that take the proper informational variables and then construct
// the appropriate exception with an error string obtained from the resource framework.
// The exception is then returned to the caller, so that the caller may then throw from its
// location so that the catcher of the exception will have the appropriate call stack.
// This class is used so that there will be compile time checking of error messages.
static internal Task<T> CreatedTaskWithException<T>(Exception ex)
{
return Task.FromException<T>(ex);
}
static internal Task<T> CreatedTaskWithCancellation<T>()
{
TaskCompletionSource<T> completion = new TaskCompletionSource<T>();
completion.SetCanceled();
return completion.Task;
}
static internal Exception ExceptionWithStackTrace(Exception e)
{
try
{
throw e;
}
catch (Exception caught)
{
return caught;
}
}
// NOTE: Initializing a Task in SQL CLR requires the "UNSAFE" permission set (http://msdn.microsoft.com/en-us/library/ms172338.aspx)
// Therefore we are lazily initializing these Tasks to avoid forcing customers to use the "UNSAFE" set when they are actually using no Async features
static private Task<bool> s_trueTask = null;
static internal Task<bool> TrueTask
{
get
{
if (s_trueTask == null)
{
s_trueTask = Task.FromResult<bool>(true);
}
return s_trueTask;
}
}
static private Task<bool> s_falseTask = null;
static internal Task<bool> FalseTask
{
get
{
if (s_falseTask == null)
{
s_falseTask = Task.FromResult<bool>(false);
}
return s_falseTask;
}
}
//
// COM+ exceptions
//
static internal ArgumentException Argument(string error)
{
ArgumentException e = new ArgumentException(error);
return e;
}
static internal ArgumentException Argument(string error, Exception inner)
{
ArgumentException e = new ArgumentException(error, inner);
return e;
}
static internal ArgumentException Argument(string error, string parameter)
{
ArgumentException e = new ArgumentException(error, parameter);
return e;
}
static internal ArgumentNullException ArgumentNull(string parameter)
{
ArgumentNullException e = new ArgumentNullException(parameter);
return e;
}
static internal ArgumentNullException ArgumentNull(string parameter, string error)
{
ArgumentNullException e = new ArgumentNullException(parameter, error);
return e;
}
static internal ArgumentOutOfRangeException ArgumentOutOfRange(string parameterName)
{
ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName);
return e;
}
static internal ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName)
{
ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, message);
return e;
}
static internal IndexOutOfRangeException IndexOutOfRange(int value)
{
IndexOutOfRangeException e = new IndexOutOfRangeException(value.ToString(CultureInfo.InvariantCulture));
return e;
}
static internal IndexOutOfRangeException IndexOutOfRange(string error)
{
IndexOutOfRangeException e = new IndexOutOfRangeException(error);
return e;
}
static internal IndexOutOfRangeException IndexOutOfRange()
{
IndexOutOfRangeException e = new IndexOutOfRangeException();
return e;
}
static internal InvalidCastException InvalidCast(string error)
{
return InvalidCast(error, null);
}
static internal InvalidCastException InvalidCast(string error, Exception inner)
{
InvalidCastException e = new InvalidCastException(error, inner);
return e;
}
static internal InvalidOperationException InvalidOperation(string error)
{
InvalidOperationException e = new InvalidOperationException(error);
return e;
}
static internal TimeoutException TimeoutException(string error)
{
TimeoutException e = new TimeoutException(error);
return e;
}
static internal InvalidOperationException InvalidOperation(string error, Exception inner)
{
InvalidOperationException e = new InvalidOperationException(error, inner);
return e;
}
static internal NotSupportedException NotSupported()
{
NotSupportedException e = new NotSupportedException();
return e;
}
static internal NotSupportedException NotSupported(string error)
{
NotSupportedException e = new NotSupportedException(error);
return e;
}
static internal OverflowException Overflow(string error)
{
return Overflow(error, null);
}
static internal OverflowException Overflow(string error, Exception inner)
{
OverflowException e = new OverflowException(error, inner);
return e;
}
static internal PlatformNotSupportedException DbTypeNotSupported(string dbType)
{
PlatformNotSupportedException e = new PlatformNotSupportedException(Res.GetString(Res.SQL_DbTypeNotSupportedOnThisPlatform, dbType));
return e;
}
static internal InvalidCastException InvalidCast()
{
InvalidCastException e = new InvalidCastException();
return e;
}
static internal IOException IO(string error)
{
IOException e = new IOException(error);
return e;
}
static internal IOException IO(string error, Exception inner)
{
IOException e = new IOException(error, inner);
return e;
}
static internal InvalidOperationException DataAdapter(string error)
{
return InvalidOperation(error);
}
static private InvalidOperationException Provider(string error)
{
return InvalidOperation(error);
}
static internal ObjectDisposedException ObjectDisposed(object instance)
{
ObjectDisposedException e = new ObjectDisposedException(instance.GetType().Name);
return e;
}
static internal InvalidOperationException MethodCalledTwice(string method)
{
InvalidOperationException e = new InvalidOperationException(Res.GetString(Res.ADP_CalledTwice, method));
return e;
}
static internal ArgumentException InvalidMultipartName(string property, string value)
{
ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_InvalidMultipartName, Res.GetString(property), value));
return e;
}
static internal ArgumentException InvalidMultipartNameIncorrectUsageOfQuotes(string property, string value)
{
ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_InvalidMultipartNameQuoteUsage, Res.GetString(property), value));
return e;
}
static internal ArgumentException InvalidMultipartNameToManyParts(string property, string value, int limit)
{
ArgumentException e = new ArgumentException(Res.GetString(Res.ADP_InvalidMultipartNameToManyParts, Res.GetString(property), value, limit));
return e;
}
static internal void CheckArgumentNull(object value, string parameterName)
{
if (null == value)
{
throw ArgumentNull(parameterName);
}
}
static internal bool IsCatchableExceptionType(Exception e)
{
return !((e is NullReferenceException) ||
(e is SecurityException));
}
static internal bool IsCatchableOrSecurityExceptionType(Exception e)
{
// a 'catchable' exception is defined by what it is not.
// since IsCatchableExceptionType defined SecurityException as not 'catchable'
// this method will return true for SecurityException has being catchable.
// the other way to write this method is, but then SecurityException is checked twice
// return ((e is SecurityException) || IsCatchableExceptionType(e));
Debug.Assert(e != null, "Unexpected null exception!");
// Most of the exception types above will cause the process to fail fast
// So they are no longer needed in this check
return !(e is NullReferenceException);
}
// Invalid Enumeration
static internal ArgumentOutOfRangeException InvalidEnumerationValue(Type type, int value)
{
return ADP.ArgumentOutOfRange(Res.GetString(Res.ADP_InvalidEnumerationValue, type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name);
}
// IDbCommand.CommandType
static internal ArgumentOutOfRangeException InvalidCommandType(CommandType value)
{
#if DEBUG
switch (value)
{
case CommandType.Text:
case CommandType.StoredProcedure:
case CommandType.TableDirect:
Debug.Assert(false, "valid CommandType " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(CommandType), (int)value);
}
// IDbConnection.BeginTransaction, OleDbTransaction.Begin
static internal ArgumentOutOfRangeException InvalidIsolationLevel(IsolationLevel value)
{
#if DEBUG
switch (value)
{
case IsolationLevel.Unspecified:
case IsolationLevel.Chaos:
case IsolationLevel.ReadUncommitted:
case IsolationLevel.ReadCommitted:
case IsolationLevel.RepeatableRead:
case IsolationLevel.Serializable:
case IsolationLevel.Snapshot:
Debug.Fail("valid IsolationLevel " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(IsolationLevel), (int)value);
}
// IDataParameter.Direction
static internal ArgumentOutOfRangeException InvalidParameterDirection(ParameterDirection value)
{
#if DEBUG
switch (value)
{
case ParameterDirection.Input:
case ParameterDirection.Output:
case ParameterDirection.InputOutput:
case ParameterDirection.ReturnValue:
Debug.Assert(false, "valid ParameterDirection " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(ParameterDirection), (int)value);
}
// IDbCommand.UpdateRowSource
static internal ArgumentOutOfRangeException InvalidUpdateRowSource(UpdateRowSource value)
{
#if DEBUG
switch (value)
{
case UpdateRowSource.None:
case UpdateRowSource.OutputParameters:
case UpdateRowSource.FirstReturnedRecord:
case UpdateRowSource.Both:
Debug.Assert(false, "valid UpdateRowSource " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(UpdateRowSource), (int)value);
}
//
// DbConnectionOptions, DataAccess
//
static internal ArgumentException ConnectionStringSyntax(int index)
{
return Argument(Res.GetString(Res.ADP_ConnectionStringSyntax, index));
}
static internal ArgumentException KeywordNotSupported(string keyword)
{
return Argument(Res.GetString(Res.ADP_KeywordNotSupported, keyword));
}
static internal ArgumentException InvalidMinMaxPoolSizeValues()
{
return ADP.Argument(Res.GetString(Res.ADP_InvalidMinMaxPoolSizeValues));
}
static internal ArgumentException ConvertFailed(Type fromType, Type toType, Exception innerException)
{
return ADP.Argument(Res.GetString(Res.SqlConvert_ConvertFailed, fromType.FullName, toType.FullName), innerException);
}
//
// DbConnection
//
static internal InvalidOperationException NoConnectionString()
{
return InvalidOperation(Res.GetString(Res.ADP_NoConnectionString));
}
static internal Exception MethodNotImplemented(string methodName)
{
return NotImplemented.ByDesignWithMessage(methodName);
}
static private string ConnectionStateMsg(ConnectionState state)
{
switch (state)
{
case (ConnectionState.Closed):
case (ConnectionState.Connecting | ConnectionState.Broken):
return Res.GetString(Res.ADP_ConnectionStateMsg_Closed);
case (ConnectionState.Connecting):
return Res.GetString(Res.ADP_ConnectionStateMsg_Connecting);
case (ConnectionState.Open):
return Res.GetString(Res.ADP_ConnectionStateMsg_Open);
case (ConnectionState.Open | ConnectionState.Executing):
return Res.GetString(Res.ADP_ConnectionStateMsg_OpenExecuting);
case (ConnectionState.Open | ConnectionState.Fetching):
return Res.GetString(Res.ADP_ConnectionStateMsg_OpenFetching);
default:
return Res.GetString(Res.ADP_ConnectionStateMsg, state.ToString());
}
}
//
// : DbConnectionOptions, DataAccess, SqlClient
//
static internal Exception InvalidConnectionOptionValue(string key)
{
return InvalidConnectionOptionValue(key, null);
}
static internal Exception InvalidConnectionOptionValueLength(string key, int limit)
{
return Argument(Res.GetString(Res.ADP_InvalidConnectionOptionValueLength, key, limit));
}
static internal Exception InvalidConnectionOptionValue(string key, Exception inner)
{
return Argument(Res.GetString(Res.ADP_InvalidConnectionOptionValue, key), inner);
}
static internal Exception MissingConnectionOptionValue(string key, string requiredAdditionalKey)
{
return Argument(Res.GetString(Res.ADP_MissingConnectionOptionValue, key, requiredAdditionalKey));
}
static internal Exception WrongType(Type got, Type expected)
{
return Argument(Res.GetString(Res.SQL_WrongType, got.ToString(), expected.ToString()));
}
//
// DbConnectionPool and related
//
static internal Exception PooledOpenTimeout()
{
return ADP.InvalidOperation(Res.GetString(Res.ADP_PooledOpenTimeout));
}
static internal Exception NonPooledOpenTimeout()
{
return ADP.TimeoutException(Res.GetString(Res.ADP_NonPooledOpenTimeout));
}
//
// Generic Data Provider Collection
//
static internal ArgumentException CollectionRemoveInvalidObject(Type itemType, ICollection collection)
{
return Argument(Res.GetString(Res.ADP_CollectionRemoveInvalidObject, itemType.Name, collection.GetType().Name));
}
static internal ArgumentNullException CollectionNullValue(string parameter, Type collection, Type itemType)
{
return ArgumentNull(parameter, Res.GetString(Res.ADP_CollectionNullValue, collection.Name, itemType.Name));
}
static internal IndexOutOfRangeException CollectionIndexInt32(int index, Type collection, int count)
{
return IndexOutOfRange(Res.GetString(Res.ADP_CollectionIndexInt32, index.ToString(CultureInfo.InvariantCulture), collection.Name, count.ToString(CultureInfo.InvariantCulture)));
}
static internal IndexOutOfRangeException CollectionIndexString(Type itemType, string propertyName, string propertyValue, Type collection)
{
return IndexOutOfRange(Res.GetString(Res.ADP_CollectionIndexString, itemType.Name, propertyName, propertyValue, collection.Name));
}
static internal InvalidCastException CollectionInvalidType(Type collection, Type itemType, object invalidValue)
{
return InvalidCast(Res.GetString(Res.ADP_CollectionInvalidType, collection.Name, itemType.Name, invalidValue.GetType().Name));
}
static internal ArgumentException ParametersIsNotParent(Type parameterType, ICollection collection)
{
return Argument(Res.GetString(Res.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name));
}
static internal ArgumentException ParametersIsParent(Type parameterType, ICollection collection)
{
return Argument(Res.GetString(Res.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name));
}
//
// DbProviderException
//
static internal InvalidOperationException TransactionConnectionMismatch()
{
return Provider(Res.GetString(Res.ADP_TransactionConnectionMismatch));
}
static internal InvalidOperationException TransactionRequired(string method)
{
return Provider(Res.GetString(Res.ADP_TransactionRequired, method));
}
static internal Exception CommandTextRequired(string method)
{
return InvalidOperation(Res.GetString(Res.ADP_CommandTextRequired, method));
}
static internal InvalidOperationException ConnectionRequired(string method)
{
return InvalidOperation(Res.GetString(Res.ADP_ConnectionRequired, method));
}
static internal InvalidOperationException OpenConnectionRequired(string method, ConnectionState state)
{
return InvalidOperation(Res.GetString(Res.ADP_OpenConnectionRequired, method, ADP.ConnectionStateMsg(state)));
}
static internal Exception OpenReaderExists()
{
return OpenReaderExists(null);
}
static internal Exception OpenReaderExists(Exception e)
{
return InvalidOperation(Res.GetString(Res.ADP_OpenReaderExists), e);
}
//
// DbDataReader
//
static internal Exception NonSeqByteAccess(long badIndex, long currIndex, string method)
{
return InvalidOperation(Res.GetString(Res.ADP_NonSeqByteAccess, badIndex.ToString(CultureInfo.InvariantCulture), currIndex.ToString(CultureInfo.InvariantCulture), method));
}
static internal Exception NegativeParameter(string parameterName)
{
return InvalidOperation(Res.GetString(Res.ADP_NegativeParameter, parameterName));
}
static internal Exception InvalidSeekOrigin(string parameterName)
{
return ArgumentOutOfRange(Res.GetString(Res.ADP_InvalidSeekOrigin), parameterName);
}
//
// SqlMetaData, SqlTypes, SqlClient
//
static internal Exception InvalidMetaDataValue()
{
return ADP.Argument(Res.GetString(Res.ADP_InvalidMetaDataValue));
}
static internal InvalidOperationException NonSequentialColumnAccess(int badCol, int currCol)
{
return InvalidOperation(Res.GetString(Res.ADP_NonSequentialColumnAccess, badCol.ToString(CultureInfo.InvariantCulture), currCol.ToString(CultureInfo.InvariantCulture)));
}
//
// : IDbCommand
//
static internal Exception InvalidCommandTimeout(int value)
{
return Argument(Res.GetString(Res.ADP_InvalidCommandTimeout, value.ToString(CultureInfo.InvariantCulture)), ADP.CommandTimeout);
}
static internal Exception UninitializedParameterSize(int index, Type dataType)
{
return InvalidOperation(Res.GetString(Res.ADP_UninitializedParameterSize, index.ToString(CultureInfo.InvariantCulture), dataType.Name));
}
static internal Exception PrepareParameterType(DbCommand cmd)
{
return InvalidOperation(Res.GetString(Res.ADP_PrepareParameterType, cmd.GetType().Name));
}
static internal Exception PrepareParameterSize(DbCommand cmd)
{
return InvalidOperation(Res.GetString(Res.ADP_PrepareParameterSize, cmd.GetType().Name));
}
static internal Exception PrepareParameterScale(DbCommand cmd, string type)
{
return InvalidOperation(Res.GetString(Res.ADP_PrepareParameterScale, cmd.GetType().Name, type));
}
static internal Exception MismatchedAsyncResult(string expectedMethod, string gotMethod)
{
return InvalidOperation(Res.GetString(Res.ADP_MismatchedAsyncResult, expectedMethod, gotMethod));
}
//
// : ConnectionUtil
//
static internal Exception ConnectionIsDisabled(Exception InnerException)
{
return InvalidOperation(Res.GetString(Res.ADP_ConnectionIsDisabled), InnerException);
}
static internal Exception ClosedConnectionError()
{
return InvalidOperation(Res.GetString(Res.ADP_ClosedConnectionError));
}
static internal Exception ConnectionAlreadyOpen(ConnectionState state)
{
return InvalidOperation(Res.GetString(Res.ADP_ConnectionAlreadyOpen, ADP.ConnectionStateMsg(state)));
}
static internal Exception OpenConnectionPropertySet(string property, ConnectionState state)
{
return InvalidOperation(Res.GetString(Res.ADP_OpenConnectionPropertySet, property, ADP.ConnectionStateMsg(state)));
}
static internal Exception EmptyDatabaseName()
{
return Argument(Res.GetString(Res.ADP_EmptyDatabaseName));
}
internal enum ConnectionError
{
BeginGetConnectionReturnsNull,
GetConnectionReturnsNull,
ConnectionOptionsMissing,
CouldNotSwitchToClosedPreviouslyOpenedState,
}
static internal Exception InternalConnectionError(ConnectionError internalError)
{
return InvalidOperation(Res.GetString(Res.ADP_InternalConnectionError, (int)internalError));
}
internal enum InternalErrorCode
{
UnpooledObjectHasOwner = 0,
UnpooledObjectHasWrongOwner = 1,
PushingObjectSecondTime = 2,
PooledObjectHasOwner = 3,
PooledObjectInPoolMoreThanOnce = 4,
CreateObjectReturnedNull = 5,
NewObjectCannotBePooled = 6,
NonPooledObjectUsedMoreThanOnce = 7,
AttemptingToPoolOnRestrictedToken = 8,
// ConnectionOptionsInUse = 9,
ConvertSidToStringSidWReturnedNull = 10,
// UnexpectedTransactedObject = 11,
AttemptingToConstructReferenceCollectionOnStaticObject = 12,
AttemptingToEnlistTwice = 13,
CreateReferenceCollectionReturnedNull = 14,
PooledObjectWithoutPool = 15,
UnexpectedWaitAnyResult = 16,
SynchronousConnectReturnedPending = 17,
CompletedConnectReturnedPending = 18,
NameValuePairNext = 20,
InvalidParserState1 = 21,
InvalidParserState2 = 22,
InvalidParserState3 = 23,
InvalidBuffer = 30,
UnimplementedSMIMethod = 40,
InvalidSmiCall = 41,
SqlDependencyObtainProcessDispatcherFailureObjectHandle = 50,
SqlDependencyProcessDispatcherFailureCreateInstance = 51,
SqlDependencyProcessDispatcherFailureAppDomain = 52,
SqlDependencyCommandHashIsNotAssociatedWithNotification = 53,
UnknownTransactionFailure = 60,
}
static internal Exception InternalError(InternalErrorCode internalError)
{
return InvalidOperation(Res.GetString(Res.ADP_InternalProviderError, (int)internalError));
}
static internal Exception InvalidConnectRetryCountValue()
{
return Argument(Res.GetString(Res.SQLCR_InvalidConnectRetryCountValue));
}
static internal Exception InvalidConnectRetryIntervalValue()
{
return Argument(Res.GetString(Res.SQLCR_InvalidConnectRetryIntervalValue));
}
//
// : DbDataReader
//
static internal Exception DataReaderClosed(string method)
{
return InvalidOperation(Res.GetString(Res.ADP_DataReaderClosed, method));
}
static internal ArgumentOutOfRangeException InvalidSourceBufferIndex(int maxLen, long srcOffset, string parameterName)
{
return ArgumentOutOfRange(Res.GetString(Res.ADP_InvalidSourceBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), srcOffset.ToString(CultureInfo.InvariantCulture)), parameterName);
}
static internal ArgumentOutOfRangeException InvalidDestinationBufferIndex(int maxLen, int dstOffset, string parameterName)
{
return ArgumentOutOfRange(Res.GetString(Res.ADP_InvalidDestinationBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), dstOffset.ToString(CultureInfo.InvariantCulture)), parameterName);
}
static internal IndexOutOfRangeException InvalidBufferSizeOrIndex(int numBytes, int bufferIndex)
{
return IndexOutOfRange(Res.GetString(Res.SQL_InvalidBufferSizeOrIndex, numBytes.ToString(CultureInfo.InvariantCulture), bufferIndex.ToString(CultureInfo.InvariantCulture)));
}
static internal Exception InvalidDataLength(long length)
{
return IndexOutOfRange(Res.GetString(Res.SQL_InvalidDataLength, length.ToString(CultureInfo.InvariantCulture)));
}
static internal InvalidOperationException AsyncOperationPending()
{
return InvalidOperation(Res.GetString(Res.ADP_PendingAsyncOperation));
}
//
// : Stream
//
static internal Exception StreamClosed(string method)
{
return InvalidOperation(Res.GetString(Res.ADP_StreamClosed, method));
}
static internal IOException ErrorReadingFromStream(Exception internalException)
{
return IO(Res.GetString(Res.SqlMisc_StreamErrorMessage), internalException);
}
static internal ArgumentException InvalidDataType(string typeName)
{
return Argument(Res.GetString(Res.ADP_InvalidDataType, typeName));
}
static internal ArgumentException UnknownDataType(Type dataType)
{
return Argument(Res.GetString(Res.ADP_UnknownDataType, dataType.FullName));
}
static internal ArgumentException DbTypeNotSupported(System.Data.DbType type, Type enumtype)
{
return Argument(Res.GetString(Res.ADP_DbTypeNotSupported, type.ToString(), enumtype.Name));
}
static internal ArgumentException InvalidOffsetValue(int value)
{
return Argument(Res.GetString(Res.ADP_InvalidOffsetValue, value.ToString(CultureInfo.InvariantCulture)));
}
static internal ArgumentException InvalidSizeValue(int value)
{
return Argument(Res.GetString(Res.ADP_InvalidSizeValue, value.ToString(CultureInfo.InvariantCulture)));
}
static internal ArgumentException ParameterValueOutOfRange(Decimal value)
{
return ADP.Argument(Res.GetString(Res.ADP_ParameterValueOutOfRange, value.ToString((IFormatProvider)null)));
}
static internal ArgumentException ParameterValueOutOfRange(SqlDecimal value)
{
return ADP.Argument(Res.GetString(Res.ADP_ParameterValueOutOfRange, value.ToString()));
}
static internal ArgumentException VersionDoesNotSupportDataType(string typeName)
{
return Argument(Res.GetString(Res.ADP_VersionDoesNotSupportDataType, typeName));
}
static internal Exception ParameterConversionFailed(object value, Type destType, Exception inner)
{
Debug.Assert(null != value, "null value on conversion failure");
Debug.Assert(null != inner, "null inner on conversion failure");
Exception e;
string message = Res.GetString(Res.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name);
if (inner is ArgumentException)
{
e = new ArgumentException(message, inner);
}
else if (inner is FormatException)
{
e = new FormatException(message, inner);
}
else if (inner is InvalidCastException)
{
e = new InvalidCastException(message, inner);
}
else if (inner is OverflowException)
{
e = new OverflowException(message, inner);
}
else
{
e = inner;
}
return e;
}
//
// : IDataParameterCollection
//
static internal Exception ParametersMappingIndex(int index, DbParameterCollection collection)
{
return CollectionIndexInt32(index, collection.GetType(), collection.Count);
}
static internal Exception ParametersSourceIndex(string parameterName, DbParameterCollection collection, Type parameterType)
{
return CollectionIndexString(parameterType, ADP.ParameterName, parameterName, collection.GetType());
}
static internal Exception ParameterNull(string parameter, DbParameterCollection collection, Type parameterType)
{
return CollectionNullValue(parameter, collection.GetType(), parameterType);
}
static internal Exception InvalidParameterType(DbParameterCollection collection, Type parameterType, object invalidValue)
{
return CollectionInvalidType(collection.GetType(), parameterType, invalidValue);
}
//
// : IDbTransaction
//
static internal Exception ParallelTransactionsNotSupported(DbConnection obj)
{
return InvalidOperation(Res.GetString(Res.ADP_ParallelTransactionsNotSupported, obj.GetType().Name));
}
static internal Exception TransactionZombied(DbTransaction obj)
{
return InvalidOperation(Res.GetString(Res.ADP_TransactionZombied, obj.GetType().Name));
}
// global constant strings
internal const string Append = "Append";
internal const string BeginExecuteNonQuery = "BeginExecuteNonQuery";
internal const string BeginExecuteReader = "BeginExecuteReader";
internal const string BeginTransaction = "BeginTransaction";
internal const string BeginExecuteXmlReader = "BeginExecuteXmlReader";
internal const string ChangeDatabase = "ChangeDatabase";
internal const string Cancel = "Cancel";
internal const string Clone = "Clone";
internal const string CommitTransaction = "CommitTransaction";
internal const string CommandTimeout = "CommandTimeout";
internal const string ConnectionString = "ConnectionString";
internal const string DataSetColumn = "DataSetColumn";
internal const string DataSetTable = "DataSetTable";
internal const string Delete = "Delete";
internal const string DeleteCommand = "DeleteCommand";
internal const string DeriveParameters = "DeriveParameters";
internal const string EndExecuteNonQuery = "EndExecuteNonQuery";
internal const string EndExecuteReader = "EndExecuteReader";
internal const string EndExecuteXmlReader = "EndExecuteXmlReader";
internal const string ExecuteReader = "ExecuteReader";
internal const string ExecuteRow = "ExecuteRow";
internal const string ExecuteNonQuery = "ExecuteNonQuery";
internal const string ExecuteScalar = "ExecuteScalar";
internal const string ExecuteSqlScalar = "ExecuteSqlScalar";
internal const string ExecuteXmlReader = "ExecuteXmlReader";
internal const string Fill = "Fill";
internal const string FillPage = "FillPage";
internal const string FillSchema = "FillSchema";
internal const string GetBytes = "GetBytes";
internal const string GetChars = "GetChars";
internal const string GetOleDbSchemaTable = "GetOleDbSchemaTable";
internal const string GetProperties = "GetProperties";
internal const string GetSchema = "GetSchema";
internal const string GetSchemaTable = "GetSchemaTable";
internal const string GetServerTransactionLevel = "GetServerTransactionLevel";
internal const string Insert = "Insert";
internal const string Open = "Open";
internal const string Parameter = "Parameter";
internal const string ParameterBuffer = "buffer";
internal const string ParameterCount = "count";
internal const string ParameterDestinationType = "destinationType";
internal const string ParameterIndex = "index";
internal const string ParameterName = "ParameterName";
internal const string ParameterOffset = "offset";
internal const string ParameterSetPosition = "set_Position";
internal const string ParameterService = "Service";
internal const string ParameterTimeout = "Timeout";
internal const string ParameterUserData = "UserData";
internal const string Prepare = "Prepare";
internal const string QuoteIdentifier = "QuoteIdentifier";
internal const string Read = "Read";
internal const string ReadAsync = "ReadAsync";
internal const string Remove = "Remove";
internal const string RollbackTransaction = "RollbackTransaction";
internal const string SaveTransaction = "SaveTransaction";
internal const string SetProperties = "SetProperties";
internal const string SourceColumn = "SourceColumn";
internal const string SourceVersion = "SourceVersion";
internal const string SourceTable = "SourceTable";
internal const string UnquoteIdentifier = "UnquoteIdentifier";
internal const string Update = "Update";
internal const string UpdateCommand = "UpdateCommand";
internal const string UpdateRows = "UpdateRows";
internal const CompareOptions compareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase;
internal const int DecimalMaxPrecision = 29;
internal const int DecimalMaxPrecision28 = 28; // there are some cases in Odbc where we need that ...
internal const int DefaultCommandTimeout = 30;
internal const int DefaultConnectionTimeout = DbConnectionStringDefaults.ConnectTimeout;
internal const float FailoverTimeoutStep = 0.08F; // fraction of timeout to use for fast failover connections
// security issue, don't rely upon static public readonly values - AS/URT 109635
static internal readonly String StrEmpty = ""; // String.Empty
internal const int CharSize = sizeof(char);
static internal void TimerCurrent(out long ticks)
{
ticks = DateTime.UtcNow.ToFileTimeUtc();
}
static internal long TimerCurrent()
{
return DateTime.UtcNow.ToFileTimeUtc();
}
static internal long TimerFromSeconds(int seconds)
{
long result = checked((long)seconds * TimeSpan.TicksPerSecond);
return result;
}
static internal long TimerFromMilliseconds(long milliseconds)
{
long result = checked(milliseconds * TimeSpan.TicksPerMillisecond);
return result;
}
static internal bool TimerHasExpired(long timerExpire)
{
bool result = TimerCurrent() > timerExpire;
return result;
}
static internal long TimerRemaining(long timerExpire)
{
long timerNow = TimerCurrent();
long result = checked(timerExpire - timerNow);
return result;
}
static internal long TimerRemainingMilliseconds(long timerExpire)
{
long result = TimerToMilliseconds(TimerRemaining(timerExpire));
return result;
}
static internal long TimerRemainingSeconds(long timerExpire)
{
long result = TimerToSeconds(TimerRemaining(timerExpire));
return result;
}
static internal long TimerToMilliseconds(long timerValue)
{
long result = timerValue / TimeSpan.TicksPerMillisecond;
return result;
}
static private long TimerToSeconds(long timerValue)
{
long result = timerValue / TimeSpan.TicksPerSecond;
return result;
}
static internal string BuildQuotedString(string quotePrefix, string quoteSuffix, string unQuotedString)
{
StringBuilder resultString = new StringBuilder();
if (ADP.IsEmpty(quotePrefix) == false)
{
resultString.Append(quotePrefix);
}
// Assuming that the suffix is escaped by doubling it. i.e. foo"bar becomes "foo""bar".
if (ADP.IsEmpty(quoteSuffix) == false)
{
resultString.Append(unQuotedString.Replace(quoteSuffix, quoteSuffix + quoteSuffix));
resultString.Append(quoteSuffix);
}
else
{
resultString.Append(unQuotedString);
}
return resultString.ToString();
}
// { "a", "a", "a" } -> { "a", "a1", "a2" }
// { "a", "a", "a1" } -> { "a", "a2", "a1" }
// { "a", "A", "a" } -> { "a", "A1", "a2" }
// { "a", "A", "a1" } -> { "a", "A2", "a1" }
static internal void BuildSchemaTableInfoTableNames(string[] columnNameArray)
{
Dictionary<string, int> hash = new Dictionary<string, int>(columnNameArray.Length);
int startIndex = columnNameArray.Length; // lowest non-unique index
for (int i = columnNameArray.Length - 1; 0 <= i; --i)
{
string columnName = columnNameArray[i];
if ((null != columnName) && (0 < columnName.Length))
{
columnName = columnName.ToLowerInvariant();
int index;
if (hash.TryGetValue(columnName, out index))
{
startIndex = Math.Min(startIndex, index);
}
hash[columnName] = i;
}
else
{
columnNameArray[i] = ADP.StrEmpty;
startIndex = i;
}
}
int uniqueIndex = 1;
for (int i = startIndex; i < columnNameArray.Length; ++i)
{
string columnName = columnNameArray[i];
if (0 == columnName.Length)
{ // generate a unique name
columnNameArray[i] = "Column";
uniqueIndex = GenerateUniqueName(hash, ref columnNameArray[i], i, uniqueIndex);
}
else
{
columnName = columnName.ToLowerInvariant();
if (i != hash[columnName])
{
GenerateUniqueName(hash, ref columnNameArray[i], i, 1);
}
}
}
}
static private int GenerateUniqueName(Dictionary<string, int> hash, ref string columnName, int index, int uniqueIndex)
{
for (; ; ++uniqueIndex)
{
string uniqueName = columnName + uniqueIndex.ToString(CultureInfo.InvariantCulture);
string lowerName = uniqueName.ToLowerInvariant();
if (!hash.ContainsKey(lowerName))
{
columnName = uniqueName;
hash.Add(lowerName, index);
break;
}
}
return uniqueIndex;
}
static internal int DstCompare(string strA, string strB)
{ // this is null safe
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, ADP.compareOptions);
}
static internal bool IsDirection(DbParameter value, ParameterDirection condition)
{
#if DEBUG
IsDirectionValid(condition);
#endif
return (condition == (condition & value.Direction));
}
#if DEBUG
static private void IsDirectionValid(ParameterDirection value)
{
switch (value)
{ // @perfnote: Enum.IsDefined
case ParameterDirection.Input:
case ParameterDirection.Output:
case ParameterDirection.InputOutput:
case ParameterDirection.ReturnValue:
break;
default:
throw ADP.InvalidParameterDirection(value);
}
}
#endif
static internal bool IsEmpty(string str)
{
return ((null == str) || (0 == str.Length));
}
static internal bool IsNull(object value)
{
if ((null == value) || (DBNull.Value == value))
{
return true;
}
INullable nullable = (value as INullable);
return ((null != nullable) && nullable.IsNull);
}
static internal void IsNullOrSqlType(object value, out bool isNull, out bool isSqlType)
{
if ((value == null) || (value == DBNull.Value))
{
isNull = true;
isSqlType = false;
}
else
{
INullable nullable = (value as INullable);
if (nullable != null)
{
isNull = nullable.IsNull;
// Duplicated from DataStorage.cs
// For back-compat, SqlXml is not in this list
isSqlType = ((value is SqlBinary) ||
(value is SqlBoolean) ||
(value is SqlByte) ||
(value is SqlBytes) ||
(value is SqlChars) ||
(value is SqlDateTime) ||
(value is SqlDecimal) ||
(value is SqlDouble) ||
(value is SqlGuid) ||
(value is SqlInt16) ||
(value is SqlInt32) ||
(value is SqlInt64) ||
(value is SqlMoney) ||
(value is SqlSingle) ||
(value is SqlString));
}
else
{
isNull = false;
isSqlType = false;
}
}
}
private static Version s_systemDataVersion;
static internal Version GetAssemblyVersion()
{
// NOTE: Using lazy thread-safety since we don't care if two threads both happen to update the value at the same time
if (s_systemDataVersion == null)
{
s_systemDataVersion = new Version(ThisAssembly.InformationalVersion);
}
return s_systemDataVersion;
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.dll Alpha
// Description: A library module for the DotSpatial geospatial framework for .Net.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 1/16/2009 4:22:19 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System.Drawing;
using System.IO;
using System.Xml;
namespace DotSpatial.Data.Forms
{
public class TryXmlDocument
{
#region Private Variables
private XmlElement _currentElement;
private XmlDocument _doc;
private string _fileName;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of TryXmlDocument
/// </summary>
public TryXmlDocument()
{
_doc = new XmlDocument();
}
#endregion
#region Methods
/// <summary>
/// This changes CurrentNode to the child node with the specified name.
/// If there are no child nodes, or the child node is not found, this returns false.
/// If the navigation is successful, this returns true.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public bool NavigateToChild(string name)
{
if (_currentElement.HasChildNodes == false) return false;
foreach (XmlElement node in _currentElement.ChildNodes)
{
if (node.Name == name)
{
_currentElement = node;
return true;
}
}
// node was not found
return false;
}
/// <summary>
/// Attempts to navigate to the parent.
/// </summary>
/// <returns></returns>
public bool NavigateToParent()
{
if (_currentElement.ParentNode != null)
{
_currentElement = _currentElement.ParentNode as XmlElement;
if (_currentElement != null) return true;
}
// this node may be a root node with no parent
return false;
}
/// <summary>
/// Opens the specified
/// </summary>
public void Open(string fileName)
{
if (File.Exists(fileName) == false)
{
throw new FileNotFoundException(fileName);
}
_doc.Load(fileName);
_currentElement = _doc.DocumentElement;
}
/// <summary>
/// Attempts to read the string for the specified value. This will first test to see if the
/// attribute exists and encloses the test in a try block. If it fails or the node does not
/// exist, the default value is returned.
/// </summary>
/// <param name="attribute">The string name for the attribute to read from the CurrentElement.</param>
/// <returns>A string specifying the value</returns>
/// <exception cref="TryXmlDocumentException">CurrentElement Not Specified</exception>
public string ReadText(string attribute)
{
if (_currentElement == null)
{
throw new TryXmlDocumentException(DataFormsMessageStrings.CurrentElementNotSpecified);
}
string result = string.Empty;
try
{
if (_currentElement.HasAttribute(attribute))
{
result = _currentElement.GetAttribute(attribute);
}
}
catch { }
return result;
}
/// <summary>
/// Attempts to read the color from a text representation of an argb integer value.
/// </summary>
/// <param name="attribute">The name of the attribute to read from the CurrentElement</param>
/// <returns>A Color structure</returns>
/// <exception cref="TryXmlDocumentException">CurrentElement Not Specified</exception>
public Color ReadColor(string attribute)
{
if (_currentElement == null)
{
throw new TryXmlDocumentException(DataFormsMessageStrings.CurrentElementNotSpecified);
}
Color result = Color.Empty;
try
{
if (_currentElement.HasAttribute(attribute))
{
string txtCol = _currentElement.GetAttribute(attribute);
result = Color.FromArgb(int.Parse(txtCol));
}
}
catch { }
return result;
}
/// <summary>
/// Attempts to read the boolean value from the specified attribute, translating it from
/// a text equivalent.
/// </summary>
/// <param name="attribute">The string name of the attribute to read from the CurrentElement</param>
/// <returns>A boolean value based on parsing the text.</returns>
/// <exception cref="TryXmlDocumentException">CurrentElement Not Specified</exception>
public bool ReadBool(string attribute)
{
if (_currentElement == null)
{
throw new TryXmlDocumentException(DataFormsMessageStrings.CurrentElementNotSpecified);
}
bool result = false;
try
{
if (_currentElement.HasAttribute(attribute))
{
result = bool.Parse(_currentElement.GetAttribute(attribute));
}
}
catch { }
return result;
}
/// <summary>
/// Attempts to read the integer value from the specified attribute, translating it from
/// a text equivalent via parsing.
/// </summary>
/// <param name="attribute">The string name of the attribute to read from the CurrentElement</param>
/// <returns>An integer parsed from the inner text of the specified attribute on the CurrentElement</returns>
/// <exception cref="TryXmlDocumentException">CurrentElement Not Specified</exception>
public int ReadInteger(string attribute)
{
if (_currentElement == null)
{
throw new TryXmlDocumentException(DataFormsMessageStrings.CurrentElementNotSpecified);
}
int result = 0;
try
{
if (_currentElement.HasAttribute(attribute))
{
result = int.Parse(_currentElement.GetAttribute(attribute));
}
}
catch { }
return result;
}
/// <summary>
/// Attempts to read the double value from the specified attribute, translating it from
/// a text equivalent via parsing.
/// </summary>
/// <param name="attribute">The string name of the attribute to read from the CurrentElement</param>
/// <returns>A double value parsed from the inner text of the specified attribute on the CurrentElement</returns>
/// <exception cref="TryXmlDocumentException">CurrentElement Not Specified</exception>
public double ReadDouble(string attribute)
{
if (_currentElement == null)
{
throw new TryXmlDocumentException(DataFormsMessageStrings.CurrentElementNotSpecified);
}
double result = 0.0;
try
{
if (_currentElement.HasAttribute(attribute))
{
result = double.Parse(_currentElement.GetAttribute(attribute));
}
}
catch { }
return result;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the fileName for this document.
/// </summary>
public string Filename
{
get { return _fileName; }
set { _fileName = value; }
}
/// <summary>
/// Gets or sets the XmlDocument that this class uses for data access.
/// </summary>
public XmlDocument Document
{
get { return _doc; }
set { _doc = value; }
}
/// <summary>
/// Gets or sets the current node that should be referenced for reading attributes.
/// </summary>
public XmlElement CurrentElement
{
get { return _currentElement; }
set { _currentElement = value; }
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.Contracts;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Test
{
public class ImmutableListTest : ImmutableListTestBase
{
private enum Operation
{
Add,
AddRange,
Insert,
InsertRange,
RemoveAt,
RemoveRange,
Last,
}
[Fact]
public void RandomOperationsTest()
{
int operationCount = this.RandomOperationsCount;
var expected = new List<int>();
var actual = ImmutableList<int>.Empty;
int seed = (int)DateTime.Now.Ticks;
Console.WriteLine("Using random seed {0}", seed);
var random = new Random(seed);
for (int iOp = 0; iOp < operationCount; iOp++)
{
switch ((Operation)random.Next((int)Operation.Last))
{
case Operation.Add:
int value = random.Next();
Console.WriteLine("Adding \"{0}\" to the list.", value);
expected.Add(value);
actual = actual.Add(value);
break;
case Operation.AddRange:
int inputLength = random.Next(100);
int[] values = Enumerable.Range(0, inputLength).Select(i => random.Next()).ToArray();
Console.WriteLine("Adding {0} elements to the list.", inputLength);
expected.AddRange(values);
actual = actual.AddRange(values);
break;
case Operation.Insert:
int position = random.Next(expected.Count + 1);
value = random.Next();
Console.WriteLine("Adding \"{0}\" to position {1} in the list.", value, position);
expected.Insert(position, value);
actual = actual.Insert(position, value);
break;
case Operation.InsertRange:
inputLength = random.Next(100);
values = Enumerable.Range(0, inputLength).Select(i => random.Next()).ToArray();
position = random.Next(expected.Count + 1);
Console.WriteLine("Adding {0} elements to position {1} in the list.", inputLength, position);
expected.InsertRange(position, values);
actual = actual.InsertRange(position, values);
break;
case Operation.RemoveAt:
if (expected.Count > 0)
{
position = random.Next(expected.Count);
Console.WriteLine("Removing element at position {0} from the list.", position);
expected.RemoveAt(position);
actual = actual.RemoveAt(position);
}
break;
case Operation.RemoveRange:
position = random.Next(expected.Count);
inputLength = random.Next(expected.Count - position);
Console.WriteLine("Removing {0} elements starting at position {1} from the list.", inputLength, position);
expected.RemoveRange(position, inputLength);
actual = actual.RemoveRange(position, inputLength);
break;
}
Assert.Equal<int>(expected, actual);
}
}
[Fact]
public void EmptyTest()
{
var empty = ImmutableList<GenericParameterHelper>.Empty;
Assert.Same(empty, ImmutableList<GenericParameterHelper>.Empty);
Assert.Same(empty, empty.Clear());
Assert.Same(empty, ((IImmutableList<GenericParameterHelper>)empty).Clear());
Assert.True(empty.IsEmpty);
Assert.Equal(0, empty.Count);
Assert.Equal(-1, empty.IndexOf(new GenericParameterHelper()));
Assert.Equal(-1, empty.IndexOf(null));
}
[Fact]
public void GetHashCodeVariesByInstance()
{
Assert.NotEqual(ImmutableList.Create<int>().GetHashCode(), ImmutableList.Create(5).GetHashCode());
}
[Fact]
public void AddAndIndexerTest()
{
var list = ImmutableList<int>.Empty;
for (int i = 1; i <= 10; i++)
{
list = list.Add(i * 10);
Assert.False(list.IsEmpty);
Assert.Equal(i, list.Count);
}
for (int i = 1; i <= 10; i++)
{
Assert.Equal(i * 10, list[i - 1]);
}
var bulkList = ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 10).Select(i => i * 10));
Assert.Equal<int>(list.ToArray(), bulkList.ToArray());
}
[Fact]
public void AddRangeOptimizationsTest()
{
// All these optimizations are tested based on filling an empty list.
var emptyList = ImmutableList.Create<string>();
// Adding an empty list to an empty list should yield the original list.
Assert.Same(emptyList, emptyList.AddRange(new string[0]));
// Adding a non-empty immutable list to an empty one should return the added list.
var nonEmptyListDefaultComparer = ImmutableList.Create("5");
Assert.Same(nonEmptyListDefaultComparer, emptyList.AddRange(nonEmptyListDefaultComparer));
// Adding a Builder instance to an empty list should be seen through.
var builderOfNonEmptyListDefaultComparer = nonEmptyListDefaultComparer.ToBuilder();
Assert.Same(nonEmptyListDefaultComparer, emptyList.AddRange(builderOfNonEmptyListDefaultComparer));
}
[Fact]
public void InsertTest()
{
var list = ImmutableList<int>.Empty;
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(1, 5));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, 5));
list = list.Insert(0, 10);
list = list.Insert(1, 20);
list = list.Insert(2, 30);
list = list.Insert(2, 25);
list = list.Insert(1, 15);
list = list.Insert(0, 5);
Assert.Equal(6, list.Count);
var expectedList = new[] { 5, 10, 15, 20, 25, 30 };
var actualList = list.ToArray();
Assert.Equal<int>(expectedList, actualList);
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(7, 5));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, 5));
}
[Fact]
public void InsertRangeTest()
{
var list = ImmutableList<int>.Empty;
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(1, new[] { 1 }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { 1 }));
list = list.InsertRange(0, new[] { 1, 4, 5 });
list = list.InsertRange(1, new[] { 2, 3 });
list = list.InsertRange(2, new int[0]);
Assert.Equal(Enumerable.Range(1, 5), list);
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(6, new[] { 1 }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { 1 }));
}
[Fact]
public void NullHandlingTest()
{
var list = ImmutableList<GenericParameterHelper>.Empty;
Assert.False(list.Contains(null));
Assert.Equal(-1, list.IndexOf(null));
list = list.Add((GenericParameterHelper)null);
Assert.Equal(1, list.Count);
Assert.Null(list[0]);
Assert.True(list.Contains(null));
Assert.Equal(0, list.IndexOf(null));
list = list.Remove((GenericParameterHelper)null);
Assert.Equal(0, list.Count);
Assert.True(list.IsEmpty);
Assert.False(list.Contains(null));
Assert.Equal(-1, list.IndexOf(null));
}
[Fact]
public void RemoveTest()
{
ImmutableList<int> list = ImmutableList<int>.Empty;
for (int i = 1; i <= 10; i++)
{
list = list.Add(i * 10);
}
list = list.Remove(30);
Assert.Equal(9, list.Count);
Assert.False(list.Contains(30));
list = list.Remove(100);
Assert.Equal(8, list.Count);
Assert.False(list.Contains(100));
list = list.Remove(10);
Assert.Equal(7, list.Count);
Assert.False(list.Contains(10));
var removeList = new int[] { 20, 70 };
list = list.RemoveAll(removeList.Contains);
Assert.Equal(5, list.Count);
Assert.False(list.Contains(20));
Assert.False(list.Contains(70));
IImmutableList<int> list2 = ImmutableList<int>.Empty;
for (int i = 1; i <= 10; i++)
{
list2 = list2.Add(i * 10);
}
list2 = list2.Remove(30);
Assert.Equal(9, list2.Count);
Assert.False(list2.Contains(30));
list2 = list2.Remove(100);
Assert.Equal(8, list2.Count);
Assert.False(list2.Contains(100));
list2 = list2.Remove(10);
Assert.Equal(7, list2.Count);
Assert.False(list2.Contains(10));
list2 = list2.RemoveAll(removeList.Contains);
Assert.Equal(5, list2.Count);
Assert.False(list2.Contains(20));
Assert.False(list2.Contains(70));
}
[Fact]
public void RemoveNonExistentKeepsReference()
{
var list = ImmutableList<int>.Empty;
Assert.Same(list, list.Remove(3));
}
[Fact]
public void RemoveAtTest()
{
var list = ImmutableList<int>.Empty;
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(0));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(1));
for (int i = 1; i <= 10; i++)
{
list = list.Add(i * 10);
}
list = list.RemoveAt(2);
Assert.Equal(9, list.Count);
Assert.False(list.Contains(30));
list = list.RemoveAt(8);
Assert.Equal(8, list.Count);
Assert.False(list.Contains(100));
list = list.RemoveAt(0);
Assert.Equal(7, list.Count);
Assert.False(list.Contains(10));
}
[Fact]
public void IndexOfAndContainsTest()
{
var expectedList = new List<string>(new[] { "Microsoft", "Windows", "Bing", "Visual Studio", "Comics", "Computers", "Laptops" });
var list = ImmutableList<string>.Empty;
foreach (string newElement in expectedList)
{
Assert.False(list.Contains(newElement));
list = list.Add(newElement);
Assert.True(list.Contains(newElement));
Assert.Equal(expectedList.IndexOf(newElement), list.IndexOf(newElement));
Assert.Equal(expectedList.IndexOf(newElement), list.IndexOf(newElement.ToUpperInvariant(), StringComparer.OrdinalIgnoreCase));
Assert.Equal(-1, list.IndexOf(newElement.ToUpperInvariant()));
foreach (string existingElement in expectedList.TakeWhile(v => v != newElement))
{
Assert.True(list.Contains(existingElement));
Assert.Equal(expectedList.IndexOf(existingElement), list.IndexOf(existingElement));
Assert.Equal(expectedList.IndexOf(existingElement), list.IndexOf(existingElement.ToUpperInvariant(), StringComparer.OrdinalIgnoreCase));
Assert.Equal(-1, list.IndexOf(existingElement.ToUpperInvariant()));
}
}
}
[Fact]
public void Indexer()
{
var list = ImmutableList.CreateRange(Enumerable.Range(1, 3));
Assert.Equal(1, list[0]);
Assert.Equal(2, list[1]);
Assert.Equal(3, list[2]);
Assert.Throws<ArgumentOutOfRangeException>(() => list[3]);
Assert.Throws<ArgumentOutOfRangeException>(() => list[-1]);
Assert.Equal(3, ((IList)list)[2]);
Assert.Equal(3, ((IList<int>)list)[2]);
}
[Fact]
public void IndexOf()
{
IndexOfTests.IndexOfTest(
seq => ImmutableList.CreateRange(seq),
(b, v) => b.IndexOf(v),
(b, v, i) => b.IndexOf(v, i),
(b, v, i, c) => b.IndexOf(v, i, c),
(b, v, i, c, eq) => b.IndexOf(v, i, c, eq));
IndexOfTests.IndexOfTest(
seq => (IImmutableList<int>)ImmutableList.CreateRange(seq),
(b, v) => b.IndexOf(v),
(b, v, i) => b.IndexOf(v, i),
(b, v, i, c) => b.IndexOf(v, i, c),
(b, v, i, c, eq) => b.IndexOf(v, i, c, eq));
}
[Fact]
public void LastIndexOf()
{
IndexOfTests.LastIndexOfTest(
seq => ImmutableList.CreateRange(seq),
(b, v) => b.LastIndexOf(v),
(b, v, eq) => b.LastIndexOf(v, eq),
(b, v, i) => b.LastIndexOf(v, i),
(b, v, i, c) => b.LastIndexOf(v, i, c),
(b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq));
IndexOfTests.LastIndexOfTest(
seq => (IImmutableList<int>)ImmutableList.CreateRange(seq),
(b, v) => b.LastIndexOf(v),
(b, v, eq) => b.LastIndexOf(v, eq),
(b, v, i) => b.LastIndexOf(v, i),
(b, v, i, c) => b.LastIndexOf(v, i, c),
(b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq));
}
[Fact]
public void ReplaceTest()
{
// Verify replace at beginning, middle, and end.
var list = ImmutableList<int>.Empty.Add(3).Add(5).Add(8);
Assert.Equal<int>(new[] { 4, 5, 8 }, list.Replace(3, 4));
Assert.Equal<int>(new[] { 3, 6, 8 }, list.Replace(5, 6));
Assert.Equal<int>(new[] { 3, 5, 9 }, list.Replace(8, 9));
Assert.Equal<int>(new[] { 4, 5, 8 }, ((IImmutableList<int>)list).Replace(3, 4));
Assert.Equal<int>(new[] { 3, 6, 8 }, ((IImmutableList<int>)list).Replace(5, 6));
Assert.Equal<int>(new[] { 3, 5, 9 }, ((IImmutableList<int>)list).Replace(8, 9));
// Verify replacement of first element when there are duplicates.
list = ImmutableList<int>.Empty.Add(3).Add(3).Add(5);
Assert.Equal<int>(new[] { 4, 3, 5 }, list.Replace(3, 4));
Assert.Equal<int>(new[] { 4, 4, 5 }, list.Replace(3, 4).Replace(3, 4));
Assert.Equal<int>(new[] { 4, 3, 5 }, ((IImmutableList<int>)list).Replace(3, 4));
Assert.Equal<int>(new[] { 4, 4, 5 }, ((IImmutableList<int>)list).Replace(3, 4).Replace(3, 4));
}
[Fact]
public void ReplaceWithEqualityComparerTest()
{
var list = ImmutableList.Create(new Person { Name = "Andrew", Age = 20 });
var newAge = new Person { Name = "Andrew", Age = 21 };
var updatedList = list.Replace(newAge, newAge, new NameOnlyEqualityComparer());
Assert.Equal(newAge.Age, updatedList[0].Age);
}
[Fact]
public void ReplaceMissingThrowsTest()
{
Assert.Throws<ArgumentException>(() => ImmutableList<int>.Empty.Replace(5, 3));
}
[Fact]
public void EqualsTest()
{
Assert.False(ImmutableList<int>.Empty.Equals(null));
Assert.False(ImmutableList<int>.Empty.Equals("hi"));
Assert.True(ImmutableList<int>.Empty.Equals(ImmutableList<int>.Empty));
Assert.False(ImmutableList<int>.Empty.Add(3).Equals(ImmutableList<int>.Empty.Add(3)));
}
[Fact]
public void Create()
{
var comparer = StringComparer.OrdinalIgnoreCase;
ImmutableList<string> list = ImmutableList.Create<string>();
Assert.Equal(0, list.Count);
list = ImmutableList.Create("a");
Assert.Equal(1, list.Count);
list = ImmutableList.Create("a", "b");
Assert.Equal(2, list.Count);
list = ImmutableList.CreateRange((IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, list.Count);
}
[Fact]
public void ToImmutableList()
{
ImmutableList<string> list = new[] { "a", "b" }.ToImmutableList();
Assert.Equal(2, list.Count);
list = new[] { "a", "b" }.ToImmutableList();
Assert.Equal(2, list.Count);
}
[Fact]
public void ToImmutableListOfSameType()
{
var list = ImmutableList.Create("a");
Assert.Same(list, list.ToImmutableList());
}
[Fact]
public void RemoveAllNullTest()
{
Assert.Throws<ArgumentNullException>(() => ImmutableList<int>.Empty.RemoveAll(null));
}
[Fact]
public void RemoveRangeArrayTest()
{
var list = ImmutableList.Create(1, 2, 3);
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveRange(-1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveRange(0, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveRange(4, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveRange(0, 4));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveRange(2, 2));
list.RemoveRange(3, 0);
Assert.Equal(3, list.Count);
}
[Fact]
public void RemoveRangeEnumerableTest()
{
var list = ImmutableList.Create(1, 2, 3);
Assert.Throws<ArgumentNullException>(() => list.RemoveRange(null));
ImmutableList<int> removed2 = list.RemoveRange(new[] { 2 });
Assert.Equal(2, removed2.Count);
Assert.Equal(new[] { 1, 3 }, removed2);
ImmutableList<int> removed13 = list.RemoveRange(new[] { 1, 3, 5 });
Assert.Equal(1, removed13.Count);
Assert.Equal(new[] { 2 }, removed13);
Assert.Equal(new[] { 2 }, ((IImmutableList<int>)list).RemoveRange(new[] { 1, 3, 5 }));
Assert.Same(list, list.RemoveRange(new[] { 5 }));
Assert.Same(ImmutableList.Create<int>(), ImmutableList.Create<int>().RemoveRange(new[] { 1 }));
var listWithDuplicates = ImmutableList.Create(1, 2, 2, 3);
Assert.Equal(new[] { 1, 2, 3 }, listWithDuplicates.RemoveRange(new[] { 2 }));
Assert.Equal(new[] { 1, 3 }, listWithDuplicates.RemoveRange(new[] { 2, 2 }));
Assert.Throws<ArgumentNullException>(() => ((IImmutableList<int>)ImmutableList.Create(1, 2, 3)).RemoveRange(null));
Assert.Equal(new[] { 1, 3 }, ((IImmutableList<int>)ImmutableList.Create(1, 2, 3)).RemoveRange(new[] { 2 }));
}
[Fact]
public void EnumeratorTest()
{
var list = ImmutableList.Create("a");
var enumerator = list.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal("a", enumerator.Current);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal("a", enumerator.Current);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var collection = ImmutableList.Create(1);
var enumerator = collection.GetEnumerator();
var enumeratorCopy = enumerator;
Assert.True(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = collection.GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.Equal(collection[0], enumerator.Current);
enumerator.Dispose();
}
[Fact]
public void ReverseTest2()
{
var emptyList = ImmutableList.Create<int>();
Assert.Same(emptyList, emptyList.Reverse());
var populatedList = ImmutableList.Create(3, 2, 1);
Assert.Equal(Enumerable.Range(1, 3), populatedList.Reverse());
}
[Fact]
public void SetItem()
{
var emptyList = ImmutableList.Create<int>();
Assert.Throws<ArgumentOutOfRangeException>(() => emptyList[-1]);
Assert.Throws<ArgumentOutOfRangeException>(() => emptyList[0]);
Assert.Throws<ArgumentOutOfRangeException>(() => emptyList[1]);
var listOfOne = emptyList.Add(5);
Assert.Throws<ArgumentOutOfRangeException>(() => listOfOne[-1]);
Assert.Equal(5, listOfOne[0]);
Assert.Throws<ArgumentOutOfRangeException>(() => listOfOne[1]);
}
[Fact]
public void IsSynchronized()
{
ICollection collection = ImmutableList.Create<int>();
Assert.True(collection.IsSynchronized);
}
[Fact]
public void IListIsReadOnly()
{
IList list = ImmutableList.Create<int>();
Assert.True(list.IsReadOnly);
Assert.True(list.IsFixedSize);
Assert.Throws<NotSupportedException>(() => list.Add(1));
Assert.Throws<NotSupportedException>(() => list.Clear());
Assert.Throws<NotSupportedException>(() => list.Insert(0, 1));
Assert.Throws<NotSupportedException>(() => list.Remove(1));
Assert.Throws<NotSupportedException>(() => list.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => list[0] = 1);
}
[Fact]
public void IListOfTIsReadOnly()
{
IList<int> list = ImmutableList.Create<int>();
Assert.True(list.IsReadOnly);
Assert.Throws<NotSupportedException>(() => list.Add(1));
Assert.Throws<NotSupportedException>(() => list.Clear());
Assert.Throws<NotSupportedException>(() => list.Insert(0, 1));
Assert.Throws<NotSupportedException>(() => list.Remove(1));
Assert.Throws<NotSupportedException>(() => list.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => list[0] = 1);
}
protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents)
{
return ImmutableList<T>.Empty.AddRange(contents);
}
protected override void RemoveAllTestHelper<T>(ImmutableList<T> list, Predicate<T> test)
{
var expected = list.ToList();
expected.RemoveAll(test);
var actual = list.RemoveAll(test);
Assert.Equal<T>(expected, actual.ToList());
}
protected override void ReverseTestHelper<T>(ImmutableList<T> list, int index, int count)
{
var expected = list.ToList();
expected.Reverse(index, count);
var actual = list.Reverse(index, count);
Assert.Equal<T>(expected, actual.ToList());
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list)
{
return list.Sort().ToList();
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list, Comparison<T> comparison)
{
return list.Sort(comparison).ToList();
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list, IComparer<T> comparer)
{
return list.Sort(comparer).ToList();
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list, int index, int count, IComparer<T> comparer)
{
return list.Sort(index, count, comparer).ToList();
}
internal override IImmutableListQueries<T> GetListQuery<T>(ImmutableList<T> list)
{
return list;
}
private struct Person
{
public string Name { get; set; }
public int Age { get; set; }
}
private class NameOnlyEqualityComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
return x.Name == y.Name;
}
public int GetHashCode(Person obj)
{
return obj.Name.GetHashCode();
}
}
}
}
| |
// 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;
namespace System.Collections.Generic
{
/// <summary>
/// Represents a reserved region within a <see cref="SparseArrayBuilder{T}"/>.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
internal readonly struct Marker
{
/// <summary>
/// Constructs a new marker.
/// </summary>
/// <param name="count">The number of items to reserve.</param>
/// <param name="index">The index in the builder where this marker starts.</param>
public Marker(int count, int index)
{
Debug.Assert(count >= 0);
Debug.Assert(index >= 0);
Count = count;
Index = index;
}
/// <summary>
/// The number of items to reserve.
/// </summary>
public int Count { get; }
/// <summary>
/// The index in the builder where this marker starts.
/// </summary>
public int Index { get; }
/// <summary>
/// Gets a string suitable for display in the debugger.
/// </summary>
private string DebuggerDisplay => $"{nameof(Index)}: {Index}, {nameof(Count)}: {Count}";
}
/// <summary>
/// Helper type for building arrays where sizes of certain segments are known in advance.
/// </summary>
/// <typeparam name="T">The element type.</typeparam>
internal struct SparseArrayBuilder<T>
{
/// <summary>
/// The underlying builder that stores items from non-reserved regions.
/// </summary>
/// <remarks>
/// This field is a mutable struct; do not mark it readonly.
/// </remarks>
private LargeArrayBuilder<T> _builder;
/// <summary>
/// The list of reserved regions within this builder.
/// </summary>
/// <remarks>
/// This field is a mutable struct; do not mark it readonly.
/// </remarks>
private ArrayBuilder<Marker> _markers;
/// <summary>
/// The total number of reserved slots within this builder.
/// </summary>
private int _reservedCount;
/// <summary>
/// Constructs a new builder.
/// </summary>
/// <param name="initialize">Pass <c>true</c>.</param>
public SparseArrayBuilder(bool initialize)
: this()
{
// Once C# gains parameterless struct constructors, please
// remove this workaround.
Debug.Assert(initialize);
_builder = new LargeArrayBuilder<T>(initialize: true);
}
/// <summary>
/// The total number of items in this builder, including reserved regions.
/// </summary>
public int Count => checked(_builder.Count + _reservedCount);
/// <summary>
/// The list of reserved regions in this builder.
/// </summary>
public ArrayBuilder<Marker> Markers => _markers;
/// <summary>
/// Adds an item to this builder.
/// </summary>
/// <param name="item">The item to add.</param>
public void Add(T item) => _builder.Add(item);
/// <summary>
/// Adds a range of items to this builder.
/// </summary>
/// <param name="items">The sequence to add.</param>
public void AddRange(IEnumerable<T> items) => _builder.AddRange(items);
/// <summary>
/// Copies the contents of this builder to the specified array.
/// </summary>
/// <param name="array">The destination array.</param>
/// <param name="arrayIndex">The index in <see cref="array"/> to start copying to.</param>
/// <param name="count">The number of items to copy.</param>
public void CopyTo(T[] array, int arrayIndex, int count)
{
Debug.Assert(array != null);
Debug.Assert(arrayIndex >= 0);
Debug.Assert(count >= 0 && count <= Count);
Debug.Assert(array.Length - arrayIndex >= count);
int copied = 0;
var position = CopyPosition.Start;
for (int i = 0; i < _markers.Count; i++)
{
Marker marker = _markers[i];
// During this iteration, copy until we satisfy `count` or reach the marker.
int toCopy = Math.Min(marker.Index - copied, count);
if (toCopy > 0)
{
position = _builder.CopyTo(position, array, arrayIndex, toCopy);
arrayIndex += toCopy;
copied += toCopy;
count -= toCopy;
}
if (count == 0)
{
return;
}
// We hit our marker. Advance until we satisfy `count` or fulfill `marker.Count`.
int reservedCount = Math.Min(marker.Count, count);
arrayIndex += reservedCount;
copied += reservedCount;
count -= reservedCount;
}
if (count > 0)
{
// Finish copying after the final marker.
_builder.CopyTo(position, array, arrayIndex, count);
}
}
/// <summary>
/// Reserves a region starting from the current index.
/// </summary>
/// <param name="count">The number of items to reserve.</param>
/// <remarks>
/// This method will not make optimizations if <paramref name="count"/>
/// is zero; the caller is responsible for doing so. The reason for this
/// is that the number of markers needs to match up exactly with the number
/// of times <see cref="Reserve"/> was called.
/// </remarks>
public void Reserve(int count)
{
Debug.Assert(count >= 0);
_markers.Add(new Marker(count: count, index: Count));
checked
{
_reservedCount += count;
}
}
/// <summary>
/// Reserves a region if the items' count can be predetermined; otherwise, adds the items to this builder.
/// </summary>
/// <param name="items">The items to reserve or add.</param>
/// <returns><c>true</c> if the items were reserved; otherwise, <c>false</c>.</returns>
/// <remarks>
/// If the items' count is predetermined to be 0, no reservation is made and the return value is <c>false</c>.
/// The effect is the same as if the items were added, since adding an empty collection does nothing.
/// </remarks>
public bool ReserveOrAdd(IEnumerable<T> items)
{
int itemCount;
if (EnumerableHelpers.TryGetCount(items, out itemCount))
{
if (itemCount > 0)
{
Reserve(itemCount);
return true;
}
}
else
{
AddRange(items);
}
return false;
}
/// <summary>
/// Creates an array from the contents of this builder.
/// </summary>
/// <remarks>
/// Regions created with <see cref="Reserve"/> will be default-initialized.
/// </remarks>
public T[] ToArray()
{
// If no regions were reserved, there are no 'gaps' we need to add to the array.
// In that case, we can just call ToArray on the underlying builder.
if (_markers.Count == 0)
{
Debug.Assert(_reservedCount == 0);
return _builder.ToArray();
}
var array = new T[Count];
CopyTo(array, 0, array.Length);
return array;
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace BuildIt.CognitiveServices
{
/// <summary>
/// Use this API to create and manage your custom lists of Images and
/// Text. The lists that you create can be used in the Image/Match and
/// Text/Screen APIs.
///
/// When using the API, images need to have a minimum of 128 pixels and a
/// maximum file size of 4MB. Text can be at most 1024 characters long.
/// If the content passed to the text API or the image API exceeds the
/// size limits, the API will return an error code that informs about the
/// issue.
///
/// </summary>
public partial interface IContentModeratorListManagement : System.IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; }
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> ImageListsCreateWithHttpMessagesAsync(string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> ImageListsGetAllWithHttpMessagesAsync(string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <param name='listId'>
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> ImageListsDeleteWithHttpMessagesAsync(string listId, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <param name='listId'>
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> ImageListsGetDetailsWithHttpMessagesAsync(string listId, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <param name='listId'>
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> ImageListsUpdateDetailsWithHttpMessagesAsync(string listId, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Add an Image to your image list. The image list can be used to do
/// fuzzy matching against other images when using Image/Match API.
///
/// Note: Remember to call <a
/// href="https://wabashcognitiveservices.portal.azure-api.net/docs/services/57cf755e3f9b070c105bd2c2/operations/57cf755e3f9b070868a1f677">Refresh
/// Search Index</a> for this list before you want to use it on
/// the Image/Match API
/// </summary>
/// <param name='listId'>
/// </param>
/// <param name='tag'>
/// <ul>
/// <li>101: Nudity</li>
/// <li>102: Sexual Content</li>
/// <li>201: Alcohol</li>
/// <li>202: Tobacco</li>
/// <li>203: Drugs</li>
/// <li>301: Child Exploitation</li>
/// <li>401: Violence</li>
/// <li>402: Weapons</li>
/// <li>403: Gore</li>
/// <li>501: Profanity</li>
/// <li>502: Vulgarity</li>
/// </ul>
/// </param>
/// <param name='label'>
/// Any additional information about the reference image.
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> ImageAddImageWithHttpMessagesAsync(string listId, double? tag = default(double?), string label = default(string), string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <param name='listId'>
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> ImageGetallImageIdsWithHttpMessagesAsync(string listId, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Delete all images from your list. The image list can be used to do
/// fuzzy matching against other images when using Image/Match API.
///
/// Note: Remember to call <a
/// href="https://wabashcognitiveservices.portal.azure-api.net/docs/services/57cf755e3f9b070c105bd2c2/operations/57cf755e3f9b070868a1f677">Refresh
/// Search Index</a> for this list before you want to use it on
/// the Image/Match API
/// </summary>
/// <param name='listId'>
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> ImageDeleteallImagesWithHttpMessagesAsync(string listId, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <param name='listId'>
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> ImageListsRefreshSearchIndexWithHttpMessagesAsync(string listId, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Delete an Image from your image list. The image list can be used
/// to do fuzzy matching against other images when using Image/Match
/// API.
///
/// Note: Remember to call <a
/// href="https://wabashcognitiveservices.portal.azure-api.net/docs/services/57cf755e3f9b070c105bd2c2/operations/57cf755e3f9b070868a1f677">Refresh
/// Search Index</a> for this list before you want to use it on
/// the Image/Match API
/// </summary>
/// <param name='listId'>
/// </param>
/// <param name='imageId'>
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> ImageDeleteWithHttpMessagesAsync(string listId, string imageId, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <param name='listId'>
/// </param>
/// <param name='term'>
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> TermAddTermWithHttpMessagesAsync(string listId, string term, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <param name='listId'>
/// </param>
/// <param name='term'>
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> TermDeleteWithHttpMessagesAsync(string listId, string term, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <param name='listId'>
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> TermDeleteAllTermsWithHttpMessagesAsync(string listId, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <param name='listId'>
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> TermGetAllTermsWithHttpMessagesAsync(string listId, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> TermListsCreateWithHttpMessagesAsync(string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> TermListsGetAllWithHttpMessagesAsync(string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <param name='listId'>
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> TermListsDeleteWithHttpMessagesAsync(string listId, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <param name='listId'>
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> TermListsGetDetailsWithHttpMessagesAsync(string listId, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <param name='listId'>
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> TermListsUpdateDetailsWithHttpMessagesAsync(string listId, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <param name='listId'>
/// </param>
/// <param name='subscriptionKey'>
/// subscription key in url
/// </param>
/// <param name='ocpApimSubscriptionKey'>
/// subscription key in header
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> TermListsRefreshSearchIndexWithHttpMessagesAsync(string listId, string subscriptionKey = default(string), string ocpApimSubscriptionKey = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Testing.Algo
File: MarketEmulatorSettings.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.Testing
{
using System;
using System.ComponentModel.DataAnnotations;
using Ecng.ComponentModel;
using Ecng.Serialization;
using StockSharp.Localization;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
/// <summary>
/// Settings of exchange emulator.
/// </summary>
public class MarketEmulatorSettings : NotifiableObject, IPersistable
{
/// <summary>
/// Initializes a new instance of the <see cref="MarketEmulatorSettings"/>.
/// </summary>
public MarketEmulatorSettings()
{
}
private bool _matchOnTouch = true;
/// <summary>
/// At emulation of clearing by trades, to perform clearing of orders, when trade price touches the order price (is equal to order price), rather than only when the trade price is better than order price. Is On by default (optimistic scenario).
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str1176Key,
Description = LocalizedStrings.Str1177Key,
GroupName = LocalizedStrings.Str1175Key,
Order = 200)]
public bool MatchOnTouch
{
get => _matchOnTouch;
set
{
if (_matchOnTouch == value)
return;
_matchOnTouch = value;
NotifyChanged();
}
}
private TimeSpan _depthExpirationTime = TimeSpan.FromDays(1);
/// <summary>
/// The maximal time, during which the order book is in the emulator, if no renewal during this time, the order book is deleted, This feature may be used to remove old order books if the are holes in data. By default is equal to 1 day.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str1178Key,
Description = LocalizedStrings.Str1179Key,
GroupName = LocalizedStrings.Str1175Key,
Order = 201)]
public TimeSpan DepthExpirationTime
{
get => _depthExpirationTime;
set
{
if (_depthExpirationTime == value)
return;
_depthExpirationTime = value;
NotifyChanged();
}
}
private double _failing;
/// <summary>
/// The percentage value of new orders registration error. The value may be from 0 (not a single error) to 100. By default is Off.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str1180Key,
Description = LocalizedStrings.Str1181Key,
GroupName = LocalizedStrings.Str1175Key,
Order = 202)]
public double Failing
{
get => _failing;
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.Str1182);
if (value > 100)
throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.Str1183);
_failing = value;
NotifyChanged();
}
}
private TimeSpan _latency;
/// <summary>
/// The minimal value of the registered orders delay. By default, it is <see cref="TimeSpan.Zero"/>, which means instant adoption of registered orders by exchange.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str161Key,
Description = LocalizedStrings.Str1184Key,
GroupName = LocalizedStrings.Str1175Key,
Order = 203)]
public TimeSpan Latency
{
get => _latency;
set
{
if (value < TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.Str1185);
_latency = value;
NotifyChanged();
}
}
private bool _isSupportAtomicReRegister = true;
/// <summary>
/// Gets a value indicating whether the re-registration orders as a single transaction. By default is enabled.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.ReregisteringKey,
Description = LocalizedStrings.Str60Key,
GroupName = LocalizedStrings.Str1175Key,
Order = 204)]
public bool IsSupportAtomicReRegister
{
get => _isSupportAtomicReRegister;
set
{
_isSupportAtomicReRegister = value;
NotifyChanged();
}
}
private TimeSpan _bufferTime;
/// <summary>
/// Responses shall be sent in intervals by whole package. The network delay and buffered operation of exchange are emulated. The default is 0 ms.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str1186Key,
Description = LocalizedStrings.Str1187Key,
GroupName = LocalizedStrings.Str1175Key,
Order = 205)]
public TimeSpan BufferTime
{
get => _bufferTime;
set
{
if (value < TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.Str940);
_bufferTime = value;
NotifyChanged();
}
}
private long _initialOrderId;
/// <summary>
/// The number, starting at which the emulator will generate identifiers for orders <see cref="Order.Id"/>.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str1190Key,
Description = LocalizedStrings.Str1191Key,
GroupName = LocalizedStrings.Str1175Key,
Order = 206)]
public long InitialOrderId
{
get => _initialOrderId;
set
{
_initialOrderId = value;
NotifyChanged();
}
}
private long _initialTradeId;
/// <summary>
/// The number, starting at which the emulator will generate identifiers fir trades <see cref="Trade.Id"/>.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str1192Key,
Description = LocalizedStrings.Str1193Key,
GroupName = LocalizedStrings.Str1175Key,
Order = 207)]
public long InitialTradeId
{
get => _initialTradeId;
set
{
_initialTradeId = value;
NotifyChanged();
}
}
private long _initialTransactionId;
/// <summary>
/// The number, starting at which the emulator will generate numbers for order trades <see cref="Order.TransactionId"/>.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.TransactionKey,
Description = LocalizedStrings.Str1194Key,
GroupName = LocalizedStrings.Str1175Key,
Order = 208)]
public long InitialTransactionId
{
get => _initialTransactionId;
set
{
_initialTransactionId = value;
NotifyChanged();
}
}
private int _spreadSize = 2;
/// <summary>
/// The size of spread in price increments. It used at determination of spread for generation of order book from tick trades. By default equals to 2.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str1195Key,
Description = LocalizedStrings.Str1196Key,
GroupName = LocalizedStrings.Str1175Key,
Order = 209)]
public int SpreadSize
{
get => _spreadSize;
set
{
if (value < 1)
throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.Str1219);
_spreadSize = value;
NotifyChanged();
}
}
private int _maxDepth = 5;
/// <summary>
/// The maximal depth of order book, which will be generated from ticks. It used, if there is no order book history. By default equals to 5.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str1197Key,
Description = LocalizedStrings.Str1198Key,
GroupName = LocalizedStrings.Str1175Key,
Order = 210)]
public int MaxDepth
{
get => _maxDepth;
set
{
if (value < 1)
throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.Str1219);
_maxDepth = value;
NotifyChanged();
}
}
private int _volumeMultiplier = 2;
/// <summary>
/// The number of volume increments, at which the order exceeds the tick trade. It used at testing on tick trades. By default equals to 2.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str1199Key,
Description = LocalizedStrings.Str1200Key,
GroupName = LocalizedStrings.Str1175Key,
Order = 211)]
public int VolumeMultiplier
{
get => _volumeMultiplier;
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.Str1219);
_volumeMultiplier = value;
NotifyChanged();
}
}
private TimeSpan _portfolioRecalcInterval = TimeSpan.Zero;
/// <summary>
/// The interval for recalculation of data on portfolios. If interval equals <see cref="TimeSpan.Zero"/>, recalculation is not performed.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str1201Key,
Description = LocalizedStrings.Str1202Key,
GroupName = LocalizedStrings.Str1175Key,
Order = 212)]
public TimeSpan PortfolioRecalcInterval
{
get => _portfolioRecalcInterval;
set
{
if (value < TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.Str940);
_portfolioRecalcInterval = value;
NotifyChanged();
}
}
private bool _convertTime;
/// <summary>
/// To convert time for orders and trades into exchange time. By default, it is disabled.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str1203Key,
Description = LocalizedStrings.Str1204Key,
GroupName = LocalizedStrings.Str1175Key,
Order = 213)]
public bool ConvertTime
{
get => _convertTime;
set
{
_convertTime = value;
NotifyChanged();
}
}
private TimeZoneInfo _timeZone;
/// <summary>
/// Information about the time zone where the exchange is located.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.TimeZoneKey,
Description = LocalizedStrings.Str68Key,
GroupName = LocalizedStrings.Str1175Key,
Order = 214)]
public TimeZoneInfo TimeZone
{
get => _timeZone;
set
{
_timeZone = value;
NotifyChanged();
}
}
private Unit _priceLimitOffset = new(40, UnitTypes.Percent);
/// <summary>
/// The price shift from the previous trade, determining boundaries of maximal and minimal prices for the next session. Used only if there is no saved information <see cref="Level1ChangeMessage"/>. By default, it equals to 40%.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str1205Key,
Description = LocalizedStrings.Str1206Key,
GroupName = LocalizedStrings.Str1175Key,
Order = 215)]
public Unit PriceLimitOffset
{
get => _priceLimitOffset;
set
{
_priceLimitOffset = value ?? throw new ArgumentNullException(nameof(value));
NotifyChanged();
}
}
private bool _increaseDepthVolume = true;
/// <summary>
/// To add the additional volume into order book at registering orders with greater volume. By default, it is enabled.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str1207Key,
Description = LocalizedStrings.Str1208Key,
GroupName = LocalizedStrings.Str1175Key,
Order = 216)]
public bool IncreaseDepthVolume
{
get => _increaseDepthVolume;
set
{
_increaseDepthVolume = value;
NotifyChanged();
}
}
private bool _checkTradingState;
/// <summary>
/// Check trading state.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.SessionStateKey,
Description = LocalizedStrings.CheckTradingStateKey,
GroupName = LocalizedStrings.Str1175Key,
Order = 217)]
public bool CheckTradingState
{
get => _checkTradingState;
set
{
_checkTradingState = value;
NotifyChanged();
}
}
private bool _checkMoney;
/// <summary>
/// Check money balance.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str1543Key,
Description = LocalizedStrings.CheckMoneyKey,
GroupName = LocalizedStrings.Str1175Key,
Order = 218)]
public bool CheckMoney
{
get => _checkMoney;
set
{
_checkMoney = value;
NotifyChanged();
}
}
/// <summary>
/// Can have short positions.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.ShortableKey,
Description = LocalizedStrings.ShortableDescKey,
GroupName = LocalizedStrings.Str1175Key,
Order = 218)]
public bool CheckShortable { get; set; }
/// <summary>
/// Allow store generated by <see cref="IMarketEmulator"/> messages.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str1405Key,
//Description = ,
GroupName = LocalizedStrings.Str1175Key,
Order = 219)]
public bool AllowStoreGenerateMessages { get; set; }
/// <summary>
/// To save the state of paper trading parameters.
/// </summary>
/// <param name="storage">Storage.</param>
public virtual void Save(SettingsStorage storage)
{
storage.SetValue(nameof(DepthExpirationTime), DepthExpirationTime);
storage.SetValue(nameof(MatchOnTouch), MatchOnTouch);
storage.SetValue(nameof(Failing), Failing);
storage.SetValue(nameof(Latency), Latency);
storage.SetValue(nameof(IsSupportAtomicReRegister), IsSupportAtomicReRegister);
storage.SetValue(nameof(BufferTime), BufferTime);
//storage.SetValue(nameof(UseCandlesTimeFrame), UseCandlesTimeFrame);
storage.SetValue(nameof(InitialOrderId), InitialOrderId);
storage.SetValue(nameof(InitialTradeId), InitialTradeId);
storage.SetValue(nameof(InitialTransactionId), InitialTransactionId);
storage.SetValue(nameof(SpreadSize), SpreadSize);
storage.SetValue(nameof(MaxDepth), MaxDepth);
storage.SetValue(nameof(VolumeMultiplier), VolumeMultiplier);
storage.SetValue(nameof(PortfolioRecalcInterval), PortfolioRecalcInterval);
storage.SetValue(nameof(ConvertTime), ConvertTime);
storage.SetValue(nameof(PriceLimitOffset), PriceLimitOffset);
storage.SetValue(nameof(IncreaseDepthVolume), IncreaseDepthVolume);
storage.SetValue(nameof(CheckTradingState), CheckTradingState);
storage.SetValue(nameof(CheckMoney), CheckMoney);
storage.SetValue(nameof(CheckShortable), CheckShortable);
storage.SetValue(nameof(AllowStoreGenerateMessages), AllowStoreGenerateMessages);
if (TimeZone != null)
storage.SetValue(nameof(TimeZone), TimeZone);
}
/// <summary>
/// To load the state of paper trading parameters.
/// </summary>
/// <param name="storage">Storage.</param>
public virtual void Load(SettingsStorage storage)
{
DepthExpirationTime = storage.GetValue(nameof(DepthExpirationTime), DepthExpirationTime);
MatchOnTouch = storage.GetValue(nameof(MatchOnTouch), MatchOnTouch);
Failing = storage.GetValue(nameof(Failing), Failing);
Latency = storage.GetValue(nameof(Latency), Latency);
IsSupportAtomicReRegister = storage.GetValue(nameof(IsSupportAtomicReRegister), IsSupportAtomicReRegister);
BufferTime = storage.GetValue(nameof(BufferTime), BufferTime);
//UseCandlesTimeFrame = storage.GetValue(nameof(UseCandlesTimeFrame), UseCandlesTimeFrame);
InitialOrderId = storage.GetValue(nameof(InitialOrderId), InitialOrderId);
InitialTradeId = storage.GetValue(nameof(InitialTradeId), InitialTradeId);
InitialTransactionId = storage.GetValue(nameof(InitialTransactionId), InitialTransactionId);
SpreadSize = storage.GetValue(nameof(SpreadSize), SpreadSize);
MaxDepth = storage.GetValue(nameof(MaxDepth), MaxDepth);
VolumeMultiplier = storage.GetValue(nameof(VolumeMultiplier), VolumeMultiplier);
PortfolioRecalcInterval = storage.GetValue(nameof(PortfolioRecalcInterval), PortfolioRecalcInterval);
ConvertTime = storage.GetValue(nameof(ConvertTime), ConvertTime);
PriceLimitOffset = storage.GetValue(nameof(PriceLimitOffset), PriceLimitOffset);
IncreaseDepthVolume = storage.GetValue(nameof(IncreaseDepthVolume), IncreaseDepthVolume);
CheckTradingState = storage.GetValue(nameof(CheckTradingState), CheckTradingState);
CheckMoney = storage.GetValue(nameof(CheckMoney), CheckMoney);
CheckShortable = storage.GetValue(nameof(CheckShortable), CheckShortable);
AllowStoreGenerateMessages = storage.GetValue(nameof(AllowStoreGenerateMessages), AllowStoreGenerateMessages);
if (storage.Contains(nameof(TimeZone)))
TimeZone = storage.GetValue<TimeZoneInfo>(nameof(TimeZone));
}
}
}
| |
//
// mcs/class/System.Data/System.Xml/XmlDataDocument.cs
//
// Purpose: Provides a W3C XML DOM Document to interact with
// relational data in a DataSet
//
// class: XmlDataDocument
// assembly: System.Data.dll
// namespace: System.Xml
//
// Author:
// Daniel Morgan <danmorg@sc.rr.com>
// Ville Palo <vi64pa@koti.soon.fi>
// Atsushi Enomoto <atsushi@ximian.com>
//
// (c)copyright 2002 Daniel Morgan
// (c)copyright 2003 Ville Palo
// (c)2004 Novell Inc.
//
// XmlDataDocument is included within the Mono Class Library.
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Data;
using System.IO;
using System.Text;
using System.Xml.XPath;
using System.Collections;
using System.Globalization;
using System.ComponentModel;
namespace System.Xml
{
public class XmlDataDocument : XmlDocument
{
// Should we consider overriding CloneNode() ? By default
// base CloneNode() will be invoked and thus no DataRow conflict
// would happen, that sounds the best (that means, no mapped
// DataRow will be provided).
internal class XmlDataElement : XmlElement
{
DataRow row;
internal XmlDataElement (DataRow row, string prefix, string localName, string ns, XmlDataDocument doc)
: base (prefix, localName, ns, doc)
{
this.row = row;
// Embed row ID only when the element is mapped to
// certain DataRow.
if (row != null) {
row.DataElement = this;
row.XmlRowID = doc.dataRowID;
doc.dataRowIDList.Add (row.XmlRowID);
// It should not be done here. The node is detached
// dt.Rows.Add (tempRow);
doc.dataRowID++;
}
}
internal DataRow DataRow {
get { return row; }
}
}
#region Fields
private DataSet dataSet;
private int dataRowID = 1;
private ArrayList dataRowIDList = new ArrayList ();
// this keeps whether table change events should be handles
private bool raiseDataSetEvents = true;
private bool raiseDocumentEvents = true;
// this is needed for inserting new row to datatable via xml
private Hashtable TempTable = new Hashtable ();
DataColumnChangeEventHandler columnChanged;
DataRowChangeEventHandler rowDeleted;
DataRowChangeEventHandler rowChanged;
CollectionChangeEventHandler tablesChanged;
#endregion // Fields
#region Constructors
public XmlDataDocument ()
{
InitDelegateFields ();
dataSet = new DataSet();
dataSet._xmlDataDocument = this;
dataSet.Tables.CollectionChanged += tablesChanged;
AddXmlDocumentListeners ();
DataSet.EnforceConstraints = false;
}
public XmlDataDocument (DataSet dataset)
{
if (dataset == null)
throw new ArgumentException ("Parameter dataset cannot be null.");
if (dataset._xmlDataDocument != null)
throw new ArgumentException ("DataSet cannot be associated with two or more XmlDataDocument.");
InitDelegateFields ();
this.dataSet = dataset;
this.dataSet._xmlDataDocument = this;
XmlElement docElem = CreateElement (dataSet.Prefix, dataSet.DataSetName, dataSet.Namespace);
foreach (DataTable dt in dataSet.Tables) {
if (dt.ParentRelations.Count > 0)
continue; // don't add them here
FillNodeRows (docElem, dt, dt.Rows);
}
// This seems required to avoid Load() error when for
// example empty DataSet will be filled on Load().
if (docElem.ChildNodes.Count > 0)
AppendChild (docElem);
foreach (DataTable dt in dataSet.Tables) {
dt.ColumnChanged += columnChanged;
dt.RowDeleted += rowDeleted;
dt.RowChanged += rowChanged;
}
AddXmlDocumentListeners ();
}
// bool clone. If we are cloning XmlDataDocument then clone should be true.
// FIXME: shouldn't DataSet be mapped to at most one document??
private XmlDataDocument (DataSet dataset, bool clone)
{
InitDelegateFields ();
this.dataSet = dataset;
this.dataSet._xmlDataDocument = this;
foreach (DataTable Table in DataSet.Tables) {
foreach (DataRow Row in Table.Rows) {
Row.XmlRowID = dataRowID;
dataRowIDList.Add (dataRowID);
dataRowID++;
}
}
AddXmlDocumentListeners ();
foreach (DataTable Table in dataSet.Tables) {
Table.ColumnChanged += columnChanged;
Table.RowDeleted += rowDeleted;
Table.RowChanged += rowChanged;
}
}
#endregion // Constructors
#region Public Properties
public DataSet DataSet {
get {
return dataSet;
}
}
#endregion // Public Properties
#region Public Methods
private void FillNodeRows (XmlElement parent, DataTable dt, ICollection rows)
{
foreach (DataRow dr in dt.Rows) {
XmlDataElement el = new XmlDataElement (dr, dt.Prefix, dt.TableName, dt.Namespace, this);
for (int i = 0; i < dt.Columns.Count; i++) {
DataColumn col = dt.Columns [i];
string value = dr.IsNull (col) ? String.Empty : dr [col].ToString ();
switch (col.ColumnMapping) {
case MappingType.Element:
XmlElement cel = CreateElement (col.Prefix, col.ColumnName, col.Namespace);
cel.InnerText = value;
el.AppendChild (cel);
break;
case MappingType.Attribute:
XmlAttribute a = CreateAttribute (col.Prefix, col.ColumnName, col.Namespace);
a.Value = value;
el.SetAttributeNode (a);
break;
case MappingType.SimpleContent:
XmlText t = CreateTextNode (value);
el.AppendChild (t);
break;
}
}
foreach (DataRelation rel in dt.ChildRelations)
FillNodeRows (el, rel.ChildTable, dr.GetChildRows (rel));
parent.AppendChild (el);
}
}
public override XmlNode CloneNode (bool deep)
{
XmlDataDocument Document;
if (deep)
Document = new XmlDataDocument (DataSet.Copy (), true);
else
Document = new XmlDataDocument (DataSet.Clone (), true);
Document.RemoveXmlDocumentListeners ();
Document.PreserveWhitespace = PreserveWhitespace;
if (deep) {
foreach(XmlNode n in ChildNodes)
Document.AppendChild (Document.ImportNode (n, deep));
}
Document.AddXmlDocumentListeners ();
return Document;
}
#region overloaded CreateElement methods
public override XmlElement CreateElement(
string prefix, string localName, string namespaceURI)
{
DataTable dt = DataSet.Tables [localName];
DataRow row = dt != null ? dt.NewRow () : null;
if (row != null)
return GetElementFromRow (row);
else
return base.CreateElement (prefix, localName, namespaceURI);
}
#endregion // overloaded CreateElement Methods
// It is not supported in XmlDataDocument
public override XmlEntityReference CreateEntityReference(string name)
{
throw new NotSupportedException ();
}
// It is not supported in XmlDataDocument
public override XmlElement GetElementById (string elemId)
{
throw new NotSupportedException ();
}
// get the XmlElement associated with the DataRow
public XmlElement GetElementFromRow (DataRow r)
{
return r.DataElement;
}
// get the DataRow associated with the XmlElement
public DataRow GetRowFromElement (XmlElement e)
{
XmlDataElement el = e as XmlDataElement;
if (el == null)
return null;
return el.DataRow;
}
#region overload Load methods
public override void Load(Stream inStream) {
Load (new XmlTextReader (inStream));
}
public override void Load(string filename) {
Load (new XmlTextReader (filename));
}
public override void Load(TextReader txtReader) {
Load (new XmlTextReader (txtReader));
}
public override void Load (XmlReader reader)
{
if (DocumentElement != null)
throw new InvalidOperationException ("XmlDataDocument does not support multi-time loading. New XmlDadaDocument is always required.");
bool OldEC = DataSet.EnforceConstraints;
DataSet.EnforceConstraints = false;
dataSet.Tables.CollectionChanged -= tablesChanged;
base.Load (reader);
DataSet.EnforceConstraints = OldEC;
dataSet.Tables.CollectionChanged += tablesChanged;
}
#endregion // overloaded Load methods
#endregion // Public Methods
#region Protected Methods
[MonoTODO ("Create optimized XPathNavigator")]
protected override XPathNavigator CreateNavigator(XmlNode node) {
return base.CreateNavigator (node);
}
#endregion // Protected Methods
#region XmlDocument event handlers
private void OnNodeChanging (object sender, XmlNodeChangedEventArgs args)
{
if (!this.raiseDocumentEvents)
return;
if (DataSet.EnforceConstraints)
throw new InvalidOperationException (Locale.GetText ("Please set DataSet.EnforceConstraints == false before trying to edit XmlDataDocument using XML operations."));
}
// Invoked when XmlNode is changed colum is changed
private void OnNodeChanged (object sender, XmlNodeChangedEventArgs args)
{
if (!raiseDocumentEvents)
return;
bool escapedRaiseDataSetEvents = raiseDataSetEvents;
raiseDataSetEvents = false;
try {
if (args.Node == null)
return;
DataRow row = GetRowFromElement ((XmlElement)args.Node.ParentNode.ParentNode);
if (row == null)
return;
if (!row.Table.Columns.Contains (args.Node.ParentNode.Name))
return;
if (row [args.Node.ParentNode.Name].ToString () != args.Node.InnerText) {
DataColumn col = row.Table.Columns [args.Node.ParentNode.Name];
row [col] = StringToObject (col.DataType, args.Node.InnerText);
}
} finally {
raiseDataSetEvents = escapedRaiseDataSetEvents;
}
}
private void OnNodeRemoving (object sender, XmlNodeChangedEventArgs args)
{
if (!this.raiseDocumentEvents)
return;
if (DataSet.EnforceConstraints)
throw new InvalidOperationException (Locale.GetText ("Please set DataSet.EnforceConstraints == false before trying to edit XmlDataDocument using XML operations."));
}
// Invoked when XmlNode is removed
private void OnNodeRemoved (object sender, XmlNodeChangedEventArgs args)
{
if (!raiseDocumentEvents)
return;
bool escapedRaiseDataSetEvents = raiseDataSetEvents;
raiseDataSetEvents = false;
try {
if (args.OldParent == null)
return;
XmlElement oldParentElem = args.OldParent as XmlElement;
if (oldParentElem == null)
return;
// detach child row (if exists)
XmlElement childElem = args.Node as XmlElement;
if (childElem != null) {
DataRow childRow = GetRowFromElement (childElem);
if (childRow != null)
childRow.Table.Rows.Remove (childRow);
}
DataRow row = GetRowFromElement (oldParentElem);
if (row == null)
return ;
row [args.Node.Name] = null;
} finally {
raiseDataSetEvents = escapedRaiseDataSetEvents;
}
}
private void OnNodeInserting (object sender, XmlNodeChangedEventArgs args)
{
if (!this.raiseDocumentEvents)
return;
if (DataSet.EnforceConstraints)
throw new InvalidOperationException (Locale.GetText ("Please set DataSet.EnforceConstraints == false before trying to edit XmlDataDocument using XML operations."));
}
private void OnNodeInserted (object sender, XmlNodeChangedEventArgs args)
{
if (!raiseDocumentEvents)
return;
bool escapedRaiseDataSetEvents = raiseDataSetEvents;
raiseDataSetEvents = false;
// If the parent node is mapped to a DataTable, then
// add a DataRow and map the parent element to it.
//
// AND If the child node is mapped to a DataTable, then
// 1. if it is mapped to a DataTable and relation, add
// a new DataRow and map the child element to it.
// 2. if it is mapped to a DataColumn, set the column
// value of the parent DataRow as the child
try {
if (! (args.NewParent is XmlElement)) {
// i.e. adding document element
foreach (XmlNode table in args.Node.ChildNodes)
CheckDescendantRelationship (table);
return;
}
DataRow row = GetRowFromElement (args.NewParent as XmlElement);
if (row == null) {
// That happens only when adding table to existing DocumentElement (aka DataSet element)
if (args.NewParent == DocumentElement)
CheckDescendantRelationship (args.Node);
return;
}
XmlAttribute attr = args.Node as XmlAttribute;
if (attr != null) { // fill attribute value
DataColumn col = row.Table.Columns [attr.LocalName];
if (col != null)
row [col] = StringToObject (col.DataType, args.Node.Value);
} else {
DataRow childRow = GetRowFromElement (args.Node as XmlElement);
if (childRow != null) {
// child might be a table row.
// I might be impossible to set parent
// since either of them might be detached
if (childRow.RowState != DataRowState.Detached && row.RowState != DataRowState.Detached) {
FillRelationship (row, childRow, args.NewParent, args.Node);
}
} else if (args.Node.NodeType == XmlNodeType.Element) {
// child element might be a column
DataColumn col = row.Table.Columns [args.Node.LocalName];
if (col != null)
row [col] = StringToObject (col.DataType, args.Node.InnerText);
} else if (args.Node is XmlCharacterData) {
if (args.Node.NodeType != XmlNodeType.Comment) {
for (int i = 0; i < row.Table.Columns.Count; i++) {
DataColumn col = row.Table.Columns [i];
if (col.ColumnMapping == MappingType.SimpleContent)
row [col] = StringToObject (col.DataType, args.Node.Value);
}
}
}
}
} finally {
raiseDataSetEvents = escapedRaiseDataSetEvents;
}
}
private void CheckDescendantRelationship (XmlNode n)
{
XmlElement el = n as XmlElement;
DataRow row = GetRowFromElement (el);
if (row == null)
return;
row.Table.Rows.Add (row); // attach
CheckDescendantRelationship (n, row);
}
private void CheckDescendantRelationship (XmlNode p, DataRow row)
{
foreach (XmlNode n in p.ChildNodes) {
XmlElement el = n as XmlElement;
if (el == null)
continue;
DataRow childRow = GetRowFromElement (el);
if (childRow == null)
continue;
childRow.Table.Rows.Add (childRow);
FillRelationship (row, childRow, p, el);
}
}
private void FillRelationship (DataRow row, DataRow childRow, XmlNode parentNode, XmlNode childNode)
{
for (int i = 0; i < childRow.Table.ParentRelations.Count; i++) {
DataRelation rel = childRow.Table.ParentRelations [i];
if (rel.ParentTable == row.Table) {
childRow.SetParentRow (row);
break;
}
}
CheckDescendantRelationship (childNode, childRow);
}
#endregion // DataSet event handlers
#region DataSet event handlers
// If DataTable is added or removed from DataSet
private void OnDataTableChanged (object sender, CollectionChangeEventArgs eventArgs)
{
if (!raiseDataSetEvents)
return;
bool escapedRaiseDocumentEvents = raiseDocumentEvents;
raiseDocumentEvents = false;
try {
DataTable Table = (DataTable)eventArgs.Element;
switch (eventArgs.Action) {
case CollectionChangeAction.Add:
Table.ColumnChanged += columnChanged;
Table.RowDeleted += rowDeleted;
Table.RowChanged += rowChanged;
break;
case CollectionChangeAction.Remove:
Table.ColumnChanged -= columnChanged;
Table.RowDeleted -= rowDeleted;
Table.RowChanged -= rowChanged;
break;
}
} finally {
raiseDocumentEvents = escapedRaiseDocumentEvents;
}
}
// If column has changed
private void OnDataTableColumnChanged (object sender,
DataColumnChangeEventArgs eventArgs)
{
if (!raiseDataSetEvents)
return;
bool escapedRaiseDocumentEvents = raiseDocumentEvents;
raiseDocumentEvents = false;
try {
DataRow row = eventArgs.Row;
XmlElement el = GetElementFromRow (row);
if (el == null)
return;
DataColumn col = eventArgs.Column;
string value = row.IsNull (col) ? String.Empty : row [col].ToString ();
switch (col.ColumnMapping) {
case MappingType.Attribute:
el.SetAttribute (col.ColumnName, col.Namespace, value);
break;
case MappingType.SimpleContent:
el.InnerText = value;
break;
case MappingType.Element:
bool exists = false;
for (int i = 0; i < el.ChildNodes.Count; i++) {
XmlElement c = el.ChildNodes [i] as XmlElement;
if (c != null && c.LocalName == col.ColumnName && c.NamespaceURI == col.Namespace) {
exists = true;
c.InnerText = value;
break;
}
}
if (!exists) {
XmlElement cel = CreateElement (col.Prefix, col.ColumnName, col.Namespace);
cel.InnerText = value;
el.AppendChild (cel);
}
break;
// FIXME: how to handle hidden?
}
} finally {
raiseDocumentEvents = escapedRaiseDocumentEvents;
}
}
private void OnDataTableRowDeleted (object sender,
DataRowChangeEventArgs eventArgs)
{
if (!raiseDataSetEvents)
return;
bool escapedRaiseDocumentEvents = raiseDocumentEvents;
raiseDocumentEvents = false;
try {
// This code is obsolete XmlDataDocument one
DataRow deletedRow = null;
deletedRow = eventArgs.Row;
XmlElement el = GetElementFromRow (eventArgs.Row);
if (el == null)
return;
el.ParentNode.RemoveChild (el);
} finally {
raiseDocumentEvents = escapedRaiseDocumentEvents;
}
}
[MonoTODO ("Need to handle hidden columns? - see comments on each private method")]
private void OnDataTableRowChanged (object sender, DataRowChangeEventArgs eventArgs)
{
if (!raiseDataSetEvents)
return;
bool escapedRaiseDocumentEvents = raiseDocumentEvents;
raiseDocumentEvents = false;
try {
switch (eventArgs.Action) {
case DataRowAction.Delete:
OnDataTableRowDeleted (sender, eventArgs);
break;
case DataRowAction.Add:
OnDataTableRowAdded (eventArgs);
break;
case DataRowAction.Rollback:
OnDataTableRowRollback (eventArgs);
break;
default:
break;
}
} finally {
raiseDocumentEvents = escapedRaiseDocumentEvents;
}
}
// Added - see FillNodeChildrenFromRow comment
private void OnDataTableRowAdded (DataRowChangeEventArgs args)
{
if (!raiseDataSetEvents)
return;
bool escapedRaiseDocumentEvents = raiseDocumentEvents;
raiseDocumentEvents = false;
try {
// Create row element. Row's name same as TableName
DataRow row = args.Row;
// create document element if it does not exist
if (DocumentElement == null)
this.AppendChild (CreateElement (DataSet.DataSetName));
DataTable table= args.Row.Table;
XmlElement element = GetElementFromRow (row);
if (element == null)
element = CreateElement (table.Prefix, table.TableName, table.Namespace);
if (element.ParentNode == null) {
// parent is not always DocumentElement.
XmlElement parent = null;
if (table.ParentRelations.Count > 0) {
for (int i = 0; i < table.ParentRelations.Count; i++) {
DataRelation rel = table.ParentRelations [i];
DataRow parentRow = row.GetParentRow (rel);
if (parentRow == null)
continue;
parent = GetElementFromRow (parentRow);
}
}
// The row might be orphan. In such case, the
// element is appended to DocumentElement.
if (parent == null)
parent = DocumentElement;
parent.AppendChild (element);
}
} finally {
raiseDocumentEvents = escapedRaiseDocumentEvents;
}
}
private void FillNodeChildrenFromRow (DataRow row, XmlElement element)
{
DataTable table = row.Table;
// fill columns for the row
for (int i = 0; i < table.Columns.Count; i++) {
DataColumn col = table.Columns [i];
string value = row.IsNull (col) ? String.Empty : row [col].ToString ();
switch (col.ColumnMapping) {
case MappingType.Element:
XmlElement el = CreateElement (col.Prefix, col.ColumnName, col.Namespace);
el.InnerText = value;
element.AppendChild (el);
break;
case MappingType.Attribute:
XmlAttribute attr = CreateAttribute (col.Prefix, col.ColumnName, col.Namespace);
attr.Value = value;
element.SetAttributeNode (attr);
break;
case MappingType.SimpleContent:
XmlText text = CreateTextNode (value);
element.AppendChild (text);
break;
// FIXME: how to handle hidden?
}
}
}
// Rollback
[MonoTODO ("It does not look complete.")]
private void OnDataTableRowRollback (DataRowChangeEventArgs args)
{
if (!raiseDataSetEvents)
return;
bool escapedRaiseDocumentEvents = raiseDocumentEvents;
raiseDocumentEvents = false;
try {
DataRow r = args.Row;
XmlElement el = GetElementFromRow (r);
if (el == null)
return;
DataTable tab = r.Table;
ArrayList al = new ArrayList ();
foreach (XmlAttribute attr in el.Attributes) {
DataColumn col = tab.Columns [attr.LocalName];
if (col != null) {
if (r.IsNull (col))
// should be removed
al.Add (attr);
else
attr.Value = r [col].ToString ();
}
}
foreach (XmlAttribute attr in al)
el.RemoveAttributeNode (attr);
al.Clear ();
foreach (XmlNode child in el.ChildNodes) {
if (child.NodeType == XmlNodeType.Element) {
DataColumn col = tab.Columns [child.LocalName];
if (col != null) {
if (r.IsNull (col))
al.Add (child);
else
child.InnerText = r [col].ToString ();
}
}
}
foreach (XmlNode n in al)
el.RemoveChild (n);
} finally {
raiseDocumentEvents = escapedRaiseDocumentEvents;
}
}
#endregion // DataSet event handlers
#region Private methods
private void InitDelegateFields ()
{
columnChanged = new DataColumnChangeEventHandler (OnDataTableColumnChanged);
rowDeleted = new DataRowChangeEventHandler (OnDataTableRowDeleted);
rowChanged = new DataRowChangeEventHandler (OnDataTableRowChanged);
tablesChanged = new CollectionChangeEventHandler (OnDataTableChanged);
}
private void RemoveXmlDocumentListeners ()
{
this.NodeInserting -= new XmlNodeChangedEventHandler (OnNodeInserting);
this.NodeInserted -= new XmlNodeChangedEventHandler (OnNodeInserted);
this.NodeChanging -= new XmlNodeChangedEventHandler (OnNodeChanging);
this.NodeChanged -= new XmlNodeChangedEventHandler (OnNodeChanged);
this.NodeRemoving -= new XmlNodeChangedEventHandler (OnNodeRemoving);
this.NodeRemoved -= new XmlNodeChangedEventHandler (OnNodeRemoved);
}
private void AddXmlDocumentListeners ()
{
this.NodeInserting += new XmlNodeChangedEventHandler (OnNodeInserting);
this.NodeInserted += new XmlNodeChangedEventHandler (OnNodeInserted);
this.NodeChanging += new XmlNodeChangedEventHandler (OnNodeChanging);
this.NodeChanged += new XmlNodeChangedEventHandler (OnNodeChanged);
this.NodeRemoving += new XmlNodeChangedEventHandler (OnNodeRemoving);
this.NodeRemoved += new XmlNodeChangedEventHandler (OnNodeRemoved);
}
internal static object StringToObject (Type type, string value)
{
if (type == null) return value;
switch (Type.GetTypeCode (type)) {
case TypeCode.Boolean: return XmlConvert.ToBoolean (value);
case TypeCode.Byte: return XmlConvert.ToByte (value);
case TypeCode.Char: return (char)XmlConvert.ToInt32 (value);
case TypeCode.DateTime: return XmlConvert.ToDateTime (value);
case TypeCode.Decimal: return XmlConvert.ToDecimal (value);
case TypeCode.Double: return XmlConvert.ToDouble (value);
case TypeCode.Int16: return XmlConvert.ToInt16 (value);
case TypeCode.Int32: return XmlConvert.ToInt32 (value);
case TypeCode.Int64: return XmlConvert.ToInt64 (value);
case TypeCode.SByte: return XmlConvert.ToSByte (value);
case TypeCode.Single: return XmlConvert.ToSingle (value);
case TypeCode.UInt16: return XmlConvert.ToUInt16 (value);
case TypeCode.UInt32: return XmlConvert.ToUInt32 (value);
case TypeCode.UInt64: return XmlConvert.ToUInt64 (value);
}
if (type == typeof (TimeSpan)) return XmlConvert.ToTimeSpan (value);
if (type == typeof (Guid)) return XmlConvert.ToGuid (value);
if (type == typeof (byte[])) return Convert.FromBase64String (value);
return Convert.ChangeType (value, type);
}
#endregion // Private methods
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.ComponentModel;
using Newtonsoft.Json.Serialization;
using System.Reflection;
#if !(SILVERLIGHT || MONODROID || MONOTOUCH)
using System.Data.SqlTypes;
#endif
namespace Newtonsoft.Json.Utilities
{
internal static class ConvertUtils
{
internal struct TypeConvertKey : IEquatable<TypeConvertKey>
{
private readonly Type _initialType;
private readonly Type _targetType;
public Type InitialType
{
get { return _initialType; }
}
public Type TargetType
{
get { return _targetType; }
}
public TypeConvertKey(Type initialType, Type targetType)
{
_initialType = initialType;
_targetType = targetType;
}
public override int GetHashCode()
{
return _initialType.GetHashCode() ^ _targetType.GetHashCode();
}
public override bool Equals(object obj)
{
if (!(obj is TypeConvertKey))
return false;
return Equals((TypeConvertKey)obj);
}
public bool Equals(TypeConvertKey other)
{
return (_initialType == other._initialType && _targetType == other._targetType);
}
}
private static readonly ThreadSafeStore<TypeConvertKey, Func<object, object>> CastConverters =
new ThreadSafeStore<TypeConvertKey, Func<object, object>>(CreateCastConverter);
private static Func<object, object> CreateCastConverter(TypeConvertKey t)
{
MethodInfo castMethodInfo = t.TargetType.GetMethod("op_Implicit", new[] { t.InitialType });
if (castMethodInfo == null)
castMethodInfo = t.TargetType.GetMethod("op_Explicit", new[] { t.InitialType });
if (castMethodInfo == null)
return null;
MethodCall<object, object> call = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(castMethodInfo);
return o => call(null, o);
}
public static bool CanConvertType(Type initialType, Type targetType, bool allowTypeNameToString)
{
ValidationUtils.ArgumentNotNull(initialType, "initialType");
ValidationUtils.ArgumentNotNull(targetType, "targetType");
if (ReflectionUtils.IsNullableType(targetType))
targetType = Nullable.GetUnderlyingType(targetType);
if (targetType == initialType)
return true;
if (typeof(IConvertible).IsAssignableFrom(initialType) && typeof(IConvertible).IsAssignableFrom(targetType))
{
return true;
}
#if !PocketPC && !NET20
if (initialType == typeof(DateTime) && targetType == typeof(DateTimeOffset))
return true;
#endif
if (initialType == typeof(Guid) && (targetType == typeof(Guid) || targetType == typeof(string)))
return true;
if (initialType == typeof(Type) && targetType == typeof(string))
return true;
#if !PocketPC
// see if source or target types have a TypeConverter that converts between the two
TypeConverter toConverter = GetConverter(initialType);
if (toConverter != null && !IsComponentConverter(toConverter) && toConverter.CanConvertTo(targetType))
{
if (allowTypeNameToString || toConverter.GetType() != typeof(TypeConverter))
return true;
}
TypeConverter fromConverter = GetConverter(targetType);
if (fromConverter != null && !IsComponentConverter(fromConverter) && fromConverter.CanConvertFrom(initialType))
return true;
#endif
// handle DBNull and INullable
if (initialType == typeof(DBNull))
{
if (ReflectionUtils.IsNullable(targetType))
return true;
}
return false;
}
private static bool IsComponentConverter(TypeConverter converter)
{
#if !SILVERLIGHT && !PocketPC
return (converter is ComponentConverter);
#else
return false;
#endif
}
#region Convert
/// <summary>
/// Converts the value to the specified type.
/// </summary>
/// <typeparam name="T">The type to convert the value to.</typeparam>
/// <param name="initialValue">The value to convert.</param>
/// <returns>The converted type.</returns>
public static T Convert<T>(object initialValue)
{
return Convert<T>(initialValue, CultureInfo.CurrentCulture);
}
/// <summary>
/// Converts the value to the specified type.
/// </summary>
/// <typeparam name="T">The type to convert the value to.</typeparam>
/// <param name="initialValue">The value to convert.</param>
/// <param name="culture">The culture to use when converting.</param>
/// <returns>The converted type.</returns>
public static T Convert<T>(object initialValue, CultureInfo culture)
{
return (T)Convert(initialValue, culture, typeof(T));
}
/// <summary>
/// Converts the value to the specified type.
/// </summary>
/// <param name="initialValue">The value to convert.</param>
/// <param name="culture">The culture to use when converting.</param>
/// <param name="targetType">The type to convert the value to.</param>
/// <returns>The converted type.</returns>
public static object Convert(object initialValue, CultureInfo culture, Type targetType)
{
if (initialValue == null)
throw new ArgumentNullException("initialValue");
if (ReflectionUtils.IsNullableType(targetType))
targetType = Nullable.GetUnderlyingType(targetType);
Type initialType = initialValue.GetType();
if (targetType == initialType)
return initialValue;
if (initialValue is string && typeof(Type).IsAssignableFrom(targetType))
return Type.GetType((string) initialValue, true);
if (targetType.IsInterface || targetType.IsGenericTypeDefinition || targetType.IsAbstract)
throw new ArgumentException("Target type {0} is not a value type or a non-abstract class.".FormatWith(CultureInfo.InvariantCulture, targetType), "targetType");
// use Convert.ChangeType if both types are IConvertible
if (initialValue is IConvertible && typeof(IConvertible).IsAssignableFrom(targetType))
{
if (targetType.IsEnum)
{
if (initialValue is string)
return Enum.Parse(targetType, initialValue.ToString(), true);
else if (IsInteger(initialValue))
return Enum.ToObject(targetType, initialValue);
}
return System.Convert.ChangeType(initialValue, targetType, culture);
}
#if !PocketPC && !NET20
if (initialValue is DateTime && targetType == typeof(DateTimeOffset))
return new DateTimeOffset((DateTime)initialValue);
#endif
if (initialValue is string)
{
if (targetType == typeof (Guid))
return new Guid((string) initialValue);
if (targetType == typeof (Uri))
return new Uri((string) initialValue);
if (targetType == typeof (TimeSpan))
#if !(NET35 || NET20 || SILVERLIGHT)
return TimeSpan.Parse((string) initialValue, CultureInfo.InvariantCulture);
#else
return TimeSpan.Parse((string)initialValue);
#endif
}
#if !PocketPC
// see if source or target types have a TypeConverter that converts between the two
TypeConverter toConverter = GetConverter(initialType);
if (toConverter != null && toConverter.CanConvertTo(targetType))
{
#if !SILVERLIGHT
return toConverter.ConvertTo(null, culture, initialValue, targetType);
#else
return toConverter.ConvertTo(initialValue, targetType);
#endif
}
TypeConverter fromConverter = GetConverter(targetType);
if (fromConverter != null && fromConverter.CanConvertFrom(initialType))
{
#if !SILVERLIGHT
return fromConverter.ConvertFrom(null, culture, initialValue);
#else
return fromConverter.ConvertFrom(initialValue);
#endif
}
#endif
// handle DBNull and INullable
if (initialValue == DBNull.Value)
{
if (ReflectionUtils.IsNullable(targetType))
return EnsureTypeAssignable(null, initialType, targetType);
throw new Exception("Can not convert null {0} into non-nullable {1}.".FormatWith(CultureInfo.InvariantCulture, initialType, targetType));
}
#if !(SILVERLIGHT || MONODROID || MONOTOUCH)
if (initialValue is INullable)
return EnsureTypeAssignable(ToValue((INullable)initialValue), initialType, targetType);
#endif
throw new Exception("Can not convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, initialType, targetType));
}
#endregion
#region TryConvert
/// <summary>
/// Converts the value to the specified type.
/// </summary>
/// <typeparam name="T">The type to convert the value to.</typeparam>
/// <param name="initialValue">The value to convert.</param>
/// <param name="convertedValue">The converted value if the conversion was successful or the default value of <c>T</c> if it failed.</param>
/// <returns>
/// <c>true</c> if <c>initialValue</c> was converted successfully; otherwise, <c>false</c>.
/// </returns>
public static bool TryConvert<T>(object initialValue, out T convertedValue)
{
return TryConvert(initialValue, CultureInfo.CurrentCulture, out convertedValue);
}
/// <summary>
/// Converts the value to the specified type.
/// </summary>
/// <typeparam name="T">The type to convert the value to.</typeparam>
/// <param name="initialValue">The value to convert.</param>
/// <param name="culture">The culture to use when converting.</param>
/// <param name="convertedValue">The converted value if the conversion was successful or the default value of <c>T</c> if it failed.</param>
/// <returns>
/// <c>true</c> if <c>initialValue</c> was converted successfully; otherwise, <c>false</c>.
/// </returns>
public static bool TryConvert<T>(object initialValue, CultureInfo culture, out T convertedValue)
{
return MiscellaneousUtils.TryAction<T>(delegate
{
object tempConvertedValue;
TryConvert(initialValue, CultureInfo.CurrentCulture, typeof(T), out tempConvertedValue);
return (T)tempConvertedValue;
}, out convertedValue);
}
/// <summary>
/// Converts the value to the specified type.
/// </summary>
/// <param name="initialValue">The value to convert.</param>
/// <param name="culture">The culture to use when converting.</param>
/// <param name="targetType">The type to convert the value to.</param>
/// <param name="convertedValue">The converted value if the conversion was successful or the default value of <c>T</c> if it failed.</param>
/// <returns>
/// <c>true</c> if <c>initialValue</c> was converted successfully; otherwise, <c>false</c>.
/// </returns>
public static bool TryConvert(object initialValue, CultureInfo culture, Type targetType, out object convertedValue)
{
return MiscellaneousUtils.TryAction<object>(delegate { return Convert(initialValue, culture, targetType); }, out convertedValue);
}
#endregion
#region ConvertOrCast
/// <summary>
/// Converts the value to the specified type. If the value is unable to be converted, the
/// value is checked whether it assignable to the specified type.
/// </summary>
/// <typeparam name="T">The type to convert or cast the value to.</typeparam>
/// <param name="initialValue">The value to convert.</param>
/// <returns>The converted type. If conversion was unsuccessful, the initial value is returned if assignable to the target type</returns>
public static T ConvertOrCast<T>(object initialValue)
{
return ConvertOrCast<T>(initialValue, CultureInfo.CurrentCulture);
}
/// <summary>
/// Converts the value to the specified type. If the value is unable to be converted, the
/// value is checked whether it assignable to the specified type.
/// </summary>
/// <typeparam name="T">The type to convert or cast the value to.</typeparam>
/// <param name="initialValue">The value to convert.</param>
/// <param name="culture">The culture to use when converting.</param>
/// <returns>The converted type. If conversion was unsuccessful, the initial value is returned if assignable to the target type</returns>
public static T ConvertOrCast<T>(object initialValue, CultureInfo culture)
{
return (T)ConvertOrCast(initialValue, culture, typeof(T));
}
/// <summary>
/// Converts the value to the specified type. If the value is unable to be converted, the
/// value is checked whether it assignable to the specified type.
/// </summary>
/// <param name="initialValue">The value to convert.</param>
/// <param name="culture">The culture to use when converting.</param>
/// <param name="targetType">The type to convert or cast the value to.</param>
/// <returns>
/// The converted type. If conversion was unsuccessful, the initial value
/// is returned if assignable to the target type.
/// </returns>
public static object ConvertOrCast(object initialValue, CultureInfo culture, Type targetType)
{
object convertedValue;
if (targetType == typeof(object))
return initialValue;
if (initialValue == null && ReflectionUtils.IsNullable(targetType))
return null;
if (TryConvert(initialValue, culture, targetType, out convertedValue))
return convertedValue;
return EnsureTypeAssignable(initialValue, ReflectionUtils.GetObjectType(initialValue), targetType);
}
#endregion
#region TryConvertOrCast
/// <summary>
/// Converts the value to the specified type. If the value is unable to be converted, the
/// value is checked whether it assignable to the specified type.
/// </summary>
/// <typeparam name="T">The type to convert the value to.</typeparam>
/// <param name="initialValue">The value to convert.</param>
/// <param name="convertedValue">The converted value if the conversion was successful or the default value of <c>T</c> if it failed.</param>
/// <returns>
/// <c>true</c> if <c>initialValue</c> was converted successfully or is assignable; otherwise, <c>false</c>.
/// </returns>
public static bool TryConvertOrCast<T>(object initialValue, out T convertedValue)
{
return TryConvertOrCast<T>(initialValue, CultureInfo.CurrentCulture, out convertedValue);
}
/// <summary>
/// Converts the value to the specified type. If the value is unable to be converted, the
/// value is checked whether it assignable to the specified type.
/// </summary>
/// <typeparam name="T">The type to convert the value to.</typeparam>
/// <param name="initialValue">The value to convert.</param>
/// <param name="culture">The culture to use when converting.</param>
/// <param name="convertedValue">The converted value if the conversion was successful or the default value of <c>T</c> if it failed.</param>
/// <returns>
/// <c>true</c> if <c>initialValue</c> was converted successfully or is assignable; otherwise, <c>false</c>.
/// </returns>
public static bool TryConvertOrCast<T>(object initialValue, CultureInfo culture, out T convertedValue)
{
return MiscellaneousUtils.TryAction<T>(delegate
{
object tempConvertedValue;
TryConvertOrCast(initialValue, CultureInfo.CurrentCulture, typeof(T), out tempConvertedValue);
return (T)tempConvertedValue;
}, out convertedValue);
}
/// <summary>
/// Converts the value to the specified type. If the value is unable to be converted, the
/// value is checked whether it assignable to the specified type.
/// </summary>
/// <param name="initialValue">The value to convert.</param>
/// <param name="culture">The culture to use when converting.</param>
/// <param name="targetType">The type to convert the value to.</param>
/// <param name="convertedValue">The converted value if the conversion was successful or the default value of <c>T</c> if it failed.</param>
/// <returns>
/// <c>true</c> if <c>initialValue</c> was converted successfully or is assignable; otherwise, <c>false</c>.
/// </returns>
public static bool TryConvertOrCast(object initialValue, CultureInfo culture, Type targetType, out object convertedValue)
{
return MiscellaneousUtils.TryAction<object>(delegate { return ConvertOrCast(initialValue, culture, targetType); }, out convertedValue);
}
#endregion
private static object EnsureTypeAssignable(object value, Type initialType, Type targetType)
{
Type valueType = (value != null) ? value.GetType() : null;
if (value != null)
{
if (targetType.IsAssignableFrom(valueType))
return value;
Func<object, object> castConverter = CastConverters.Get(new TypeConvertKey(valueType, targetType));
if (castConverter != null)
return castConverter(value);
}
else
{
if (ReflectionUtils.IsNullable(targetType))
return null;
}
throw new Exception("Could not cast or convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, (initialType != null) ? initialType.ToString() : "{null}", targetType));
}
#if !(SILVERLIGHT || MONODROID || MONOTOUCH)
public static object ToValue(INullable nullableValue)
{
if (nullableValue == null)
return null;
else if (nullableValue is SqlInt32)
return ToValue((SqlInt32)nullableValue);
else if (nullableValue is SqlInt64)
return ToValue((SqlInt64)nullableValue);
else if (nullableValue is SqlBoolean)
return ToValue((SqlBoolean)nullableValue);
else if (nullableValue is SqlString)
return ToValue((SqlString)nullableValue);
else if (nullableValue is SqlDateTime)
return ToValue((SqlDateTime)nullableValue);
throw new Exception("Unsupported INullable type: {0}".FormatWith(CultureInfo.InvariantCulture, nullableValue.GetType()));
}
#endif
#if !PocketPC
internal static TypeConverter GetConverter(Type t)
{
return JsonTypeReflector.GetTypeConverter(t);
}
#endif
public static bool IsInteger(object value)
{
switch (System.Convert.GetTypeCode(value))
{
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
return true;
default:
return false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using Test.IO.Streams;
using Xunit;
namespace System.Security.Cryptography.Rsa.Tests
{
public class SignVerify
{
[Fact]
public static void ExpectedSignature_SHA1_2048()
{
byte[] expectedSignature = new byte[]
{
0xA1, 0xFC, 0x74, 0x67, 0x49, 0x91, 0xF4, 0x28,
0xB0, 0xF6, 0x2B, 0xB8, 0x5E, 0x5F, 0x2E, 0x0F,
0xD8, 0xBC, 0xB4, 0x6E, 0x0A, 0xF7, 0x11, 0xC2,
0x65, 0x35, 0x5C, 0x1B, 0x1B, 0xC1, 0x20, 0xC0,
0x7D, 0x5B, 0x98, 0xAF, 0xB4, 0xC1, 0x6A, 0x25,
0x17, 0x47, 0x2C, 0x7F, 0x20, 0x2A, 0xDD, 0xF0,
0x5F, 0xDF, 0x6F, 0x5B, 0x7D, 0xEE, 0xAA, 0x4B,
0x9E, 0x8B, 0xA6, 0x0D, 0x81, 0x54, 0x93, 0x6E,
0xB2, 0x86, 0xC8, 0x14, 0x4F, 0xE7, 0x4A, 0xCC,
0xBE, 0x51, 0x2D, 0x0B, 0x9B, 0x46, 0xF1, 0x39,
0x80, 0x1D, 0xD0, 0x07, 0xBA, 0x46, 0x48, 0xFC,
0x7A, 0x50, 0x17, 0xC9, 0x7F, 0xEF, 0xDD, 0x42,
0xC5, 0x8B, 0x69, 0x38, 0x67, 0xAB, 0xBD, 0x39,
0xA6, 0xF4, 0x02, 0x34, 0x88, 0x56, 0x50, 0x05,
0xEA, 0x95, 0x24, 0x7D, 0x34, 0xD9, 0x9F, 0xB1,
0x05, 0x39, 0x6A, 0x42, 0x9E, 0x5E, 0xEB, 0xC9,
0x90, 0xC1, 0x93, 0x63, 0x29, 0x0C, 0xC5, 0xBC,
0xC8, 0x65, 0xB0, 0xFA, 0x63, 0x61, 0x77, 0xD9,
0x16, 0x59, 0xF0, 0xAD, 0x28, 0xC7, 0x98, 0x3C,
0x53, 0xF1, 0x6C, 0x91, 0x7E, 0x36, 0xC3, 0x3A,
0x23, 0x87, 0xA7, 0x3A, 0x18, 0x18, 0xBF, 0xD2,
0x3E, 0x51, 0x9E, 0xAB, 0x9E, 0x4C, 0x65, 0xBA,
0x43, 0xC0, 0x7E, 0xA2, 0x6B, 0xCF, 0x69, 0x7C,
0x8F, 0xAB, 0x22, 0x28, 0xD6, 0xF1, 0x65, 0x0B,
0x4A, 0x5B, 0x9B, 0x1F, 0xD4, 0xAA, 0xEF, 0x35,
0xA2, 0x42, 0x32, 0x00, 0x9F, 0x42, 0xBB, 0x19,
0x99, 0x49, 0x6D, 0xB8, 0x03, 0x3D, 0x35, 0x96,
0x0C, 0x57, 0xBB, 0x6B, 0x07, 0xA4, 0xB9, 0x7F,
0x9B, 0xEC, 0x78, 0x90, 0xB7, 0xC8, 0x5E, 0x7F,
0x3B, 0xAB, 0xC1, 0xB6, 0x0C, 0x84, 0x3C, 0xBC,
0x7F, 0x04, 0x79, 0xB7, 0x9C, 0xC0, 0xFE, 0xB0,
0xAE, 0xBD, 0xA5, 0x57, 0x2C, 0xEC, 0x3D, 0x0D,
};
ExpectSignature(expectedSignature, TestData.HelloBytes, "SHA1", TestData.RSA2048Params);
}
[Fact]
public static void ExpectedSignature_SHA256_1024()
{
byte[] expectedSignature = new byte[]
{
0x5C, 0x2F, 0x00, 0xA9, 0xE4, 0x63, 0xD7, 0xB7,
0x94, 0x93, 0xCE, 0xA8, 0x7E, 0x71, 0xAE, 0x97,
0xC2, 0x6B, 0x37, 0x31, 0x5B, 0xB8, 0xE3, 0x30,
0xDF, 0x77, 0xF8, 0xBB, 0xB5, 0xBF, 0x41, 0x9F,
0x14, 0x6A, 0x61, 0x26, 0x2E, 0x80, 0xE5, 0xE6,
0x8A, 0xEA, 0xC7, 0x60, 0x0B, 0xAE, 0x2B, 0xB2,
0x18, 0xD8, 0x5D, 0xC8, 0x58, 0x86, 0x5E, 0x23,
0x62, 0x44, 0x72, 0xEA, 0x3B, 0xF7, 0x70, 0xC6,
0x4C, 0x2B, 0x54, 0x5B, 0xF4, 0x24, 0xA1, 0xE5,
0x63, 0xDD, 0x50, 0x3A, 0x29, 0x26, 0x84, 0x06,
0xEF, 0x13, 0xD0, 0xCE, 0xCC, 0xA1, 0x05, 0xB4,
0x72, 0x81, 0x0A, 0x2E, 0x33, 0xF6, 0x2F, 0xD1,
0xEA, 0x41, 0xB0, 0xB3, 0x93, 0x4C, 0xF3, 0x0F,
0x6F, 0x21, 0x3E, 0xD7, 0x5F, 0x57, 0x2E, 0xC7,
0x5F, 0xF5, 0x28, 0x89, 0xB8, 0x07, 0xDB, 0xAC,
0x70, 0x95, 0x25, 0x49, 0x8A, 0x1A, 0xD7, 0xFC,
};
ExpectSignature(expectedSignature, TestData.HelloBytes, "SHA256", TestData.RSA1024Params);
}
[Fact]
public static void ExpectedSignature_SHA256_2048()
{
byte[] expectedSignature = new byte[]
{
0x2C, 0x74, 0x98, 0x23, 0xF4, 0x38, 0x7F, 0x49,
0x82, 0xB6, 0x55, 0xCF, 0xC3, 0x25, 0x4F, 0xE3,
0x4B, 0x17, 0xE7, 0xED, 0xEA, 0x58, 0x1E, 0x63,
0x57, 0x58, 0xCD, 0xB5, 0x06, 0xD6, 0xCA, 0x13,
0x28, 0x81, 0xE6, 0xE0, 0x8B, 0xDC, 0xC6, 0x05,
0x35, 0x35, 0x40, 0x73, 0x76, 0x61, 0x67, 0x42,
0x94, 0xF7, 0x54, 0x0E, 0xB6, 0x30, 0x9A, 0x70,
0xC3, 0x06, 0xC1, 0x59, 0xA7, 0x89, 0x66, 0x38,
0x02, 0x5C, 0x52, 0x02, 0x17, 0x4E, 0xEC, 0x21,
0xE9, 0x24, 0x85, 0xCB, 0x56, 0x42, 0xAB, 0x21,
0x3A, 0x19, 0xC3, 0x95, 0x06, 0xBA, 0xDB, 0xD9,
0x89, 0x7C, 0xB9, 0xEC, 0x1D, 0x8B, 0x5A, 0x64,
0x87, 0xAF, 0x36, 0x71, 0xAC, 0x0A, 0x2B, 0xC7,
0x7D, 0x2F, 0x44, 0xAA, 0xB4, 0x1C, 0xBE, 0x0B,
0x0A, 0x4E, 0xEA, 0xF8, 0x75, 0x40, 0xD9, 0x4A,
0x82, 0x1C, 0x82, 0x81, 0x97, 0xC2, 0xF1, 0xC8,
0xA7, 0x4B, 0x45, 0x9A, 0x66, 0x8E, 0x35, 0x2E,
0xE5, 0x1A, 0x2B, 0x0B, 0xF9, 0xAB, 0xC4, 0x2A,
0xE0, 0x47, 0x72, 0x2A, 0xC2, 0xD8, 0xC6, 0xFD,
0x91, 0x30, 0xD2, 0x45, 0xA4, 0x7F, 0x0F, 0x39,
0x80, 0xBC, 0xA9, 0xBD, 0xEC, 0xA5, 0x03, 0x6F,
0x01, 0xF6, 0x19, 0xD5, 0x2B, 0xD9, 0x40, 0xCD,
0x7F, 0xEF, 0x0F, 0x9D, 0x93, 0x02, 0xCD, 0x89,
0xB8, 0x2C, 0xC7, 0xD6, 0xFD, 0xAA, 0x12, 0x6E,
0x4C, 0x06, 0x35, 0x08, 0x61, 0x79, 0x27, 0xE1,
0xEA, 0x46, 0x75, 0x08, 0x5B, 0x51, 0xA1, 0x80,
0x78, 0x02, 0xEA, 0x3E, 0xEC, 0x29, 0xD2, 0x8B,
0xC5, 0x9E, 0x7D, 0xA4, 0x85, 0x8D, 0xAD, 0x73,
0x39, 0x17, 0x64, 0x82, 0x46, 0x4A, 0xA4, 0x34,
0xF0, 0xCC, 0x2F, 0x9F, 0x55, 0xA4, 0xEA, 0xEC,
0xC9, 0xA7, 0xAB, 0xBA, 0xA8, 0x84, 0x14, 0x62,
0x6B, 0x9B, 0x97, 0x2D, 0x8C, 0xB2, 0x1C, 0x16,
};
ExpectSignature(expectedSignature, TestData.HelloBytes, "SHA256", TestData.RSA2048Params);
}
[Fact]
public static void ExpectSignature_SHA256_1024_Stream()
{
byte[] expectedSignature = new byte[]
{
0x78, 0x6F, 0x42, 0x00, 0xF4, 0x5A, 0xDB, 0x09,
0x72, 0xB9, 0xCD, 0xBE, 0xB8, 0x46, 0x54, 0xE0,
0xCF, 0x02, 0xB5, 0xA1, 0xF1, 0x7C, 0xA7, 0x5A,
0xCF, 0x09, 0x60, 0xB6, 0xFF, 0x6B, 0x8A, 0x92,
0x8E, 0xB4, 0xD5, 0x2C, 0x64, 0x90, 0x3E, 0x38,
0x8B, 0x1D, 0x7D, 0x0E, 0xE8, 0x3C, 0xF0, 0xB9,
0xBB, 0xEF, 0x90, 0x49, 0x7E, 0x6A, 0x1C, 0xEC,
0x51, 0xB9, 0x13, 0x9B, 0x02, 0x02, 0x66, 0x59,
0xC6, 0xB1, 0x51, 0xBD, 0x17, 0x2E, 0x03, 0xEC,
0x93, 0x2B, 0xE9, 0x41, 0x28, 0x57, 0x8C, 0xB2,
0x42, 0x60, 0xDE, 0xB4, 0x18, 0x85, 0x81, 0x55,
0xAE, 0x09, 0xD9, 0xC4, 0x87, 0x57, 0xD1, 0x90,
0xB3, 0x18, 0xD2, 0x96, 0x18, 0x91, 0x2D, 0x38,
0x98, 0x0E, 0x68, 0x3C, 0xA6, 0x2E, 0xFE, 0x0D,
0xD0, 0x50, 0x18, 0x55, 0x75, 0xA9, 0x85, 0x40,
0xAB, 0x72, 0xE6, 0x7F, 0x9F, 0xDC, 0x30, 0xB9,
};
byte[] signature;
using (Stream stream = new PositionValueStream(10))
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA1024Params);
signature = rsa.SignData(stream, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}
Assert.Equal(expectedSignature, signature);
}
[Fact]
public static void VerifySignature_SHA1_2048()
{
byte[] signature = new byte[]
{
0xA1, 0xFC, 0x74, 0x67, 0x49, 0x91, 0xF4, 0x28,
0xB0, 0xF6, 0x2B, 0xB8, 0x5E, 0x5F, 0x2E, 0x0F,
0xD8, 0xBC, 0xB4, 0x6E, 0x0A, 0xF7, 0x11, 0xC2,
0x65, 0x35, 0x5C, 0x1B, 0x1B, 0xC1, 0x20, 0xC0,
0x7D, 0x5B, 0x98, 0xAF, 0xB4, 0xC1, 0x6A, 0x25,
0x17, 0x47, 0x2C, 0x7F, 0x20, 0x2A, 0xDD, 0xF0,
0x5F, 0xDF, 0x6F, 0x5B, 0x7D, 0xEE, 0xAA, 0x4B,
0x9E, 0x8B, 0xA6, 0x0D, 0x81, 0x54, 0x93, 0x6E,
0xB2, 0x86, 0xC8, 0x14, 0x4F, 0xE7, 0x4A, 0xCC,
0xBE, 0x51, 0x2D, 0x0B, 0x9B, 0x46, 0xF1, 0x39,
0x80, 0x1D, 0xD0, 0x07, 0xBA, 0x46, 0x48, 0xFC,
0x7A, 0x50, 0x17, 0xC9, 0x7F, 0xEF, 0xDD, 0x42,
0xC5, 0x8B, 0x69, 0x38, 0x67, 0xAB, 0xBD, 0x39,
0xA6, 0xF4, 0x02, 0x34, 0x88, 0x56, 0x50, 0x05,
0xEA, 0x95, 0x24, 0x7D, 0x34, 0xD9, 0x9F, 0xB1,
0x05, 0x39, 0x6A, 0x42, 0x9E, 0x5E, 0xEB, 0xC9,
0x90, 0xC1, 0x93, 0x63, 0x29, 0x0C, 0xC5, 0xBC,
0xC8, 0x65, 0xB0, 0xFA, 0x63, 0x61, 0x77, 0xD9,
0x16, 0x59, 0xF0, 0xAD, 0x28, 0xC7, 0x98, 0x3C,
0x53, 0xF1, 0x6C, 0x91, 0x7E, 0x36, 0xC3, 0x3A,
0x23, 0x87, 0xA7, 0x3A, 0x18, 0x18, 0xBF, 0xD2,
0x3E, 0x51, 0x9E, 0xAB, 0x9E, 0x4C, 0x65, 0xBA,
0x43, 0xC0, 0x7E, 0xA2, 0x6B, 0xCF, 0x69, 0x7C,
0x8F, 0xAB, 0x22, 0x28, 0xD6, 0xF1, 0x65, 0x0B,
0x4A, 0x5B, 0x9B, 0x1F, 0xD4, 0xAA, 0xEF, 0x35,
0xA2, 0x42, 0x32, 0x00, 0x9F, 0x42, 0xBB, 0x19,
0x99, 0x49, 0x6D, 0xB8, 0x03, 0x3D, 0x35, 0x96,
0x0C, 0x57, 0xBB, 0x6B, 0x07, 0xA4, 0xB9, 0x7F,
0x9B, 0xEC, 0x78, 0x90, 0xB7, 0xC8, 0x5E, 0x7F,
0x3B, 0xAB, 0xC1, 0xB6, 0x0C, 0x84, 0x3C, 0xBC,
0x7F, 0x04, 0x79, 0xB7, 0x9C, 0xC0, 0xFE, 0xB0,
0xAE, 0xBD, 0xA5, 0x57, 0x2C, 0xEC, 0x3D, 0x0D,
};
VerifySignature(signature, TestData.HelloBytes, "SHA1", TestData.RSA2048Params);
}
[Fact]
public static void VerifySignature_SHA256_1024()
{
byte[] signature = new byte[]
{
0x5C, 0x2F, 0x00, 0xA9, 0xE4, 0x63, 0xD7, 0xB7,
0x94, 0x93, 0xCE, 0xA8, 0x7E, 0x71, 0xAE, 0x97,
0xC2, 0x6B, 0x37, 0x31, 0x5B, 0xB8, 0xE3, 0x30,
0xDF, 0x77, 0xF8, 0xBB, 0xB5, 0xBF, 0x41, 0x9F,
0x14, 0x6A, 0x61, 0x26, 0x2E, 0x80, 0xE5, 0xE6,
0x8A, 0xEA, 0xC7, 0x60, 0x0B, 0xAE, 0x2B, 0xB2,
0x18, 0xD8, 0x5D, 0xC8, 0x58, 0x86, 0x5E, 0x23,
0x62, 0x44, 0x72, 0xEA, 0x3B, 0xF7, 0x70, 0xC6,
0x4C, 0x2B, 0x54, 0x5B, 0xF4, 0x24, 0xA1, 0xE5,
0x63, 0xDD, 0x50, 0x3A, 0x29, 0x26, 0x84, 0x06,
0xEF, 0x13, 0xD0, 0xCE, 0xCC, 0xA1, 0x05, 0xB4,
0x72, 0x81, 0x0A, 0x2E, 0x33, 0xF6, 0x2F, 0xD1,
0xEA, 0x41, 0xB0, 0xB3, 0x93, 0x4C, 0xF3, 0x0F,
0x6F, 0x21, 0x3E, 0xD7, 0x5F, 0x57, 0x2E, 0xC7,
0x5F, 0xF5, 0x28, 0x89, 0xB8, 0x07, 0xDB, 0xAC,
0x70, 0x95, 0x25, 0x49, 0x8A, 0x1A, 0xD7, 0xFC,
};
VerifySignature(signature, TestData.HelloBytes, "SHA256", TestData.RSA1024Params);
}
[Fact]
public static void VerifySignature_SHA256_2048()
{
byte[] signature = new byte[]
{
0x2C, 0x74, 0x98, 0x23, 0xF4, 0x38, 0x7F, 0x49,
0x82, 0xB6, 0x55, 0xCF, 0xC3, 0x25, 0x4F, 0xE3,
0x4B, 0x17, 0xE7, 0xED, 0xEA, 0x58, 0x1E, 0x63,
0x57, 0x58, 0xCD, 0xB5, 0x06, 0xD6, 0xCA, 0x13,
0x28, 0x81, 0xE6, 0xE0, 0x8B, 0xDC, 0xC6, 0x05,
0x35, 0x35, 0x40, 0x73, 0x76, 0x61, 0x67, 0x42,
0x94, 0xF7, 0x54, 0x0E, 0xB6, 0x30, 0x9A, 0x70,
0xC3, 0x06, 0xC1, 0x59, 0xA7, 0x89, 0x66, 0x38,
0x02, 0x5C, 0x52, 0x02, 0x17, 0x4E, 0xEC, 0x21,
0xE9, 0x24, 0x85, 0xCB, 0x56, 0x42, 0xAB, 0x21,
0x3A, 0x19, 0xC3, 0x95, 0x06, 0xBA, 0xDB, 0xD9,
0x89, 0x7C, 0xB9, 0xEC, 0x1D, 0x8B, 0x5A, 0x64,
0x87, 0xAF, 0x36, 0x71, 0xAC, 0x0A, 0x2B, 0xC7,
0x7D, 0x2F, 0x44, 0xAA, 0xB4, 0x1C, 0xBE, 0x0B,
0x0A, 0x4E, 0xEA, 0xF8, 0x75, 0x40, 0xD9, 0x4A,
0x82, 0x1C, 0x82, 0x81, 0x97, 0xC2, 0xF1, 0xC8,
0xA7, 0x4B, 0x45, 0x9A, 0x66, 0x8E, 0x35, 0x2E,
0xE5, 0x1A, 0x2B, 0x0B, 0xF9, 0xAB, 0xC4, 0x2A,
0xE0, 0x47, 0x72, 0x2A, 0xC2, 0xD8, 0xC6, 0xFD,
0x91, 0x30, 0xD2, 0x45, 0xA4, 0x7F, 0x0F, 0x39,
0x80, 0xBC, 0xA9, 0xBD, 0xEC, 0xA5, 0x03, 0x6F,
0x01, 0xF6, 0x19, 0xD5, 0x2B, 0xD9, 0x40, 0xCD,
0x7F, 0xEF, 0x0F, 0x9D, 0x93, 0x02, 0xCD, 0x89,
0xB8, 0x2C, 0xC7, 0xD6, 0xFD, 0xAA, 0x12, 0x6E,
0x4C, 0x06, 0x35, 0x08, 0x61, 0x79, 0x27, 0xE1,
0xEA, 0x46, 0x75, 0x08, 0x5B, 0x51, 0xA1, 0x80,
0x78, 0x02, 0xEA, 0x3E, 0xEC, 0x29, 0xD2, 0x8B,
0xC5, 0x9E, 0x7D, 0xA4, 0x85, 0x8D, 0xAD, 0x73,
0x39, 0x17, 0x64, 0x82, 0x46, 0x4A, 0xA4, 0x34,
0xF0, 0xCC, 0x2F, 0x9F, 0x55, 0xA4, 0xEA, 0xEC,
0xC9, 0xA7, 0xAB, 0xBA, 0xA8, 0x84, 0x14, 0x62,
0x6B, 0x9B, 0x97, 0x2D, 0x8C, 0xB2, 0x1C, 0x16,
};
VerifySignature(signature, TestData.HelloBytes, "SHA256", TestData.RSA2048Params);
}
[Fact]
public static void SignAndVerify_SHA1_1024()
{
SignAndVerify(TestData.HelloBytes, "SHA1", TestData.RSA1024Params);
}
[Fact]
public static void SignAndVerify_SHA1_2048()
{
SignAndVerify(TestData.HelloBytes, "SHA1", TestData.RSA2048Params);
}
[Fact]
public static void SignAndVerify_SHA256_1024()
{
SignAndVerify(TestData.HelloBytes, "SHA256", TestData.RSA1024Params);
}
[Fact]
public static void NegativeVerify_WrongAlgorithm()
{
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA2048Params);
byte[] signature = rsa.SignData(TestData.HelloBytes, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
bool signatureMatched = rsa.VerifyData(TestData.HelloBytes, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
Assert.False(signatureMatched);
}
}
[Fact]
public static void NegativeVerify_WrongSignature()
{
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA2048Params);
byte[] signature = rsa.SignData(TestData.HelloBytes, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
// Invalidate the signature.
signature[0] = (byte)~signature[0];
bool signatureMatched = rsa.VerifyData(TestData.HelloBytes, signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.False(signatureMatched);
}
}
[Fact]
public static void NegativeVerify_TamperedData()
{
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA2048Params);
byte[] signature = rsa.SignData(TestData.HelloBytes, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
bool signatureMatched = rsa.VerifyData(Array.Empty<byte>(), signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.False(signatureMatched);
}
}
[Fact]
public static void NegativeVerify_BadKeysize()
{
byte[] signature;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA2048Params);
signature = rsa.SignData(TestData.HelloBytes, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
}
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(TestData.RSA1024Params);
bool signatureMatched = rsa.VerifyData(TestData.HelloBytes, signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.False(signatureMatched);
}
}
[Fact]
public static void ExpectedHashSignature_SHA1_2048()
{
byte[] expectedHashSignature = new byte[]
{
0xA1, 0xFC, 0x74, 0x67, 0x49, 0x91, 0xF4, 0x28,
0xB0, 0xF6, 0x2B, 0xB8, 0x5E, 0x5F, 0x2E, 0x0F,
0xD8, 0xBC, 0xB4, 0x6E, 0x0A, 0xF7, 0x11, 0xC2,
0x65, 0x35, 0x5C, 0x1B, 0x1B, 0xC1, 0x20, 0xC0,
0x7D, 0x5B, 0x98, 0xAF, 0xB4, 0xC1, 0x6A, 0x25,
0x17, 0x47, 0x2C, 0x7F, 0x20, 0x2A, 0xDD, 0xF0,
0x5F, 0xDF, 0x6F, 0x5B, 0x7D, 0xEE, 0xAA, 0x4B,
0x9E, 0x8B, 0xA6, 0x0D, 0x81, 0x54, 0x93, 0x6E,
0xB2, 0x86, 0xC8, 0x14, 0x4F, 0xE7, 0x4A, 0xCC,
0xBE, 0x51, 0x2D, 0x0B, 0x9B, 0x46, 0xF1, 0x39,
0x80, 0x1D, 0xD0, 0x07, 0xBA, 0x46, 0x48, 0xFC,
0x7A, 0x50, 0x17, 0xC9, 0x7F, 0xEF, 0xDD, 0x42,
0xC5, 0x8B, 0x69, 0x38, 0x67, 0xAB, 0xBD, 0x39,
0xA6, 0xF4, 0x02, 0x34, 0x88, 0x56, 0x50, 0x05,
0xEA, 0x95, 0x24, 0x7D, 0x34, 0xD9, 0x9F, 0xB1,
0x05, 0x39, 0x6A, 0x42, 0x9E, 0x5E, 0xEB, 0xC9,
0x90, 0xC1, 0x93, 0x63, 0x29, 0x0C, 0xC5, 0xBC,
0xC8, 0x65, 0xB0, 0xFA, 0x63, 0x61, 0x77, 0xD9,
0x16, 0x59, 0xF0, 0xAD, 0x28, 0xC7, 0x98, 0x3C,
0x53, 0xF1, 0x6C, 0x91, 0x7E, 0x36, 0xC3, 0x3A,
0x23, 0x87, 0xA7, 0x3A, 0x18, 0x18, 0xBF, 0xD2,
0x3E, 0x51, 0x9E, 0xAB, 0x9E, 0x4C, 0x65, 0xBA,
0x43, 0xC0, 0x7E, 0xA2, 0x6B, 0xCF, 0x69, 0x7C,
0x8F, 0xAB, 0x22, 0x28, 0xD6, 0xF1, 0x65, 0x0B,
0x4A, 0x5B, 0x9B, 0x1F, 0xD4, 0xAA, 0xEF, 0x35,
0xA2, 0x42, 0x32, 0x00, 0x9F, 0x42, 0xBB, 0x19,
0x99, 0x49, 0x6D, 0xB8, 0x03, 0x3D, 0x35, 0x96,
0x0C, 0x57, 0xBB, 0x6B, 0x07, 0xA4, 0xB9, 0x7F,
0x9B, 0xEC, 0x78, 0x90, 0xB7, 0xC8, 0x5E, 0x7F,
0x3B, 0xAB, 0xC1, 0xB6, 0x0C, 0x84, 0x3C, 0xBC,
0x7F, 0x04, 0x79, 0xB7, 0x9C, 0xC0, 0xFE, 0xB0,
0xAE, 0xBD, 0xA5, 0x57, 0x2C, 0xEC, 0x3D, 0x0D,
};
byte[] dataHash;
using (HashAlgorithm hash = SHA1.Create())
{
dataHash = hash.ComputeHash(TestData.HelloBytes);
}
ExpectHashSignature(expectedHashSignature, dataHash, "SHA1", TestData.RSA2048Params);
}
[Fact]
public static void ExpectedHashSignature_SHA256_1024()
{
byte[] expectedHashSignature = new byte[]
{
0x5C, 0x2F, 0x00, 0xA9, 0xE4, 0x63, 0xD7, 0xB7,
0x94, 0x93, 0xCE, 0xA8, 0x7E, 0x71, 0xAE, 0x97,
0xC2, 0x6B, 0x37, 0x31, 0x5B, 0xB8, 0xE3, 0x30,
0xDF, 0x77, 0xF8, 0xBB, 0xB5, 0xBF, 0x41, 0x9F,
0x14, 0x6A, 0x61, 0x26, 0x2E, 0x80, 0xE5, 0xE6,
0x8A, 0xEA, 0xC7, 0x60, 0x0B, 0xAE, 0x2B, 0xB2,
0x18, 0xD8, 0x5D, 0xC8, 0x58, 0x86, 0x5E, 0x23,
0x62, 0x44, 0x72, 0xEA, 0x3B, 0xF7, 0x70, 0xC6,
0x4C, 0x2B, 0x54, 0x5B, 0xF4, 0x24, 0xA1, 0xE5,
0x63, 0xDD, 0x50, 0x3A, 0x29, 0x26, 0x84, 0x06,
0xEF, 0x13, 0xD0, 0xCE, 0xCC, 0xA1, 0x05, 0xB4,
0x72, 0x81, 0x0A, 0x2E, 0x33, 0xF6, 0x2F, 0xD1,
0xEA, 0x41, 0xB0, 0xB3, 0x93, 0x4C, 0xF3, 0x0F,
0x6F, 0x21, 0x3E, 0xD7, 0x5F, 0x57, 0x2E, 0xC7,
0x5F, 0xF5, 0x28, 0x89, 0xB8, 0x07, 0xDB, 0xAC,
0x70, 0x95, 0x25, 0x49, 0x8A, 0x1A, 0xD7, 0xFC,
};
byte[] dataHash;
using (HashAlgorithm hash = SHA256.Create())
{
dataHash = hash.ComputeHash(TestData.HelloBytes);
}
ExpectHashSignature(expectedHashSignature, dataHash, "SHA256", TestData.RSA1024Params);
}
[Fact]
public static void ExpectedHashSignature_SHA256_2048()
{
byte[] expectedHashSignature = new byte[]
{
0x2C, 0x74, 0x98, 0x23, 0xF4, 0x38, 0x7F, 0x49,
0x82, 0xB6, 0x55, 0xCF, 0xC3, 0x25, 0x4F, 0xE3,
0x4B, 0x17, 0xE7, 0xED, 0xEA, 0x58, 0x1E, 0x63,
0x57, 0x58, 0xCD, 0xB5, 0x06, 0xD6, 0xCA, 0x13,
0x28, 0x81, 0xE6, 0xE0, 0x8B, 0xDC, 0xC6, 0x05,
0x35, 0x35, 0x40, 0x73, 0x76, 0x61, 0x67, 0x42,
0x94, 0xF7, 0x54, 0x0E, 0xB6, 0x30, 0x9A, 0x70,
0xC3, 0x06, 0xC1, 0x59, 0xA7, 0x89, 0x66, 0x38,
0x02, 0x5C, 0x52, 0x02, 0x17, 0x4E, 0xEC, 0x21,
0xE9, 0x24, 0x85, 0xCB, 0x56, 0x42, 0xAB, 0x21,
0x3A, 0x19, 0xC3, 0x95, 0x06, 0xBA, 0xDB, 0xD9,
0x89, 0x7C, 0xB9, 0xEC, 0x1D, 0x8B, 0x5A, 0x64,
0x87, 0xAF, 0x36, 0x71, 0xAC, 0x0A, 0x2B, 0xC7,
0x7D, 0x2F, 0x44, 0xAA, 0xB4, 0x1C, 0xBE, 0x0B,
0x0A, 0x4E, 0xEA, 0xF8, 0x75, 0x40, 0xD9, 0x4A,
0x82, 0x1C, 0x82, 0x81, 0x97, 0xC2, 0xF1, 0xC8,
0xA7, 0x4B, 0x45, 0x9A, 0x66, 0x8E, 0x35, 0x2E,
0xE5, 0x1A, 0x2B, 0x0B, 0xF9, 0xAB, 0xC4, 0x2A,
0xE0, 0x47, 0x72, 0x2A, 0xC2, 0xD8, 0xC6, 0xFD,
0x91, 0x30, 0xD2, 0x45, 0xA4, 0x7F, 0x0F, 0x39,
0x80, 0xBC, 0xA9, 0xBD, 0xEC, 0xA5, 0x03, 0x6F,
0x01, 0xF6, 0x19, 0xD5, 0x2B, 0xD9, 0x40, 0xCD,
0x7F, 0xEF, 0x0F, 0x9D, 0x93, 0x02, 0xCD, 0x89,
0xB8, 0x2C, 0xC7, 0xD6, 0xFD, 0xAA, 0x12, 0x6E,
0x4C, 0x06, 0x35, 0x08, 0x61, 0x79, 0x27, 0xE1,
0xEA, 0x46, 0x75, 0x08, 0x5B, 0x51, 0xA1, 0x80,
0x78, 0x02, 0xEA, 0x3E, 0xEC, 0x29, 0xD2, 0x8B,
0xC5, 0x9E, 0x7D, 0xA4, 0x85, 0x8D, 0xAD, 0x73,
0x39, 0x17, 0x64, 0x82, 0x46, 0x4A, 0xA4, 0x34,
0xF0, 0xCC, 0x2F, 0x9F, 0x55, 0xA4, 0xEA, 0xEC,
0xC9, 0xA7, 0xAB, 0xBA, 0xA8, 0x84, 0x14, 0x62,
0x6B, 0x9B, 0x97, 0x2D, 0x8C, 0xB2, 0x1C, 0x16,
};
byte[] dataHash;
using (HashAlgorithm hash = SHA256.Create())
{
dataHash = hash.ComputeHash(TestData.HelloBytes);
}
ExpectHashSignature(expectedHashSignature, dataHash, "SHA256", TestData.RSA2048Params);
}
[Fact]
public static void VerifyHashSignature_SHA1_2048()
{
byte[] hashSignature = new byte[]
{
0xA1, 0xFC, 0x74, 0x67, 0x49, 0x91, 0xF4, 0x28,
0xB0, 0xF6, 0x2B, 0xB8, 0x5E, 0x5F, 0x2E, 0x0F,
0xD8, 0xBC, 0xB4, 0x6E, 0x0A, 0xF7, 0x11, 0xC2,
0x65, 0x35, 0x5C, 0x1B, 0x1B, 0xC1, 0x20, 0xC0,
0x7D, 0x5B, 0x98, 0xAF, 0xB4, 0xC1, 0x6A, 0x25,
0x17, 0x47, 0x2C, 0x7F, 0x20, 0x2A, 0xDD, 0xF0,
0x5F, 0xDF, 0x6F, 0x5B, 0x7D, 0xEE, 0xAA, 0x4B,
0x9E, 0x8B, 0xA6, 0x0D, 0x81, 0x54, 0x93, 0x6E,
0xB2, 0x86, 0xC8, 0x14, 0x4F, 0xE7, 0x4A, 0xCC,
0xBE, 0x51, 0x2D, 0x0B, 0x9B, 0x46, 0xF1, 0x39,
0x80, 0x1D, 0xD0, 0x07, 0xBA, 0x46, 0x48, 0xFC,
0x7A, 0x50, 0x17, 0xC9, 0x7F, 0xEF, 0xDD, 0x42,
0xC5, 0x8B, 0x69, 0x38, 0x67, 0xAB, 0xBD, 0x39,
0xA6, 0xF4, 0x02, 0x34, 0x88, 0x56, 0x50, 0x05,
0xEA, 0x95, 0x24, 0x7D, 0x34, 0xD9, 0x9F, 0xB1,
0x05, 0x39, 0x6A, 0x42, 0x9E, 0x5E, 0xEB, 0xC9,
0x90, 0xC1, 0x93, 0x63, 0x29, 0x0C, 0xC5, 0xBC,
0xC8, 0x65, 0xB0, 0xFA, 0x63, 0x61, 0x77, 0xD9,
0x16, 0x59, 0xF0, 0xAD, 0x28, 0xC7, 0x98, 0x3C,
0x53, 0xF1, 0x6C, 0x91, 0x7E, 0x36, 0xC3, 0x3A,
0x23, 0x87, 0xA7, 0x3A, 0x18, 0x18, 0xBF, 0xD2,
0x3E, 0x51, 0x9E, 0xAB, 0x9E, 0x4C, 0x65, 0xBA,
0x43, 0xC0, 0x7E, 0xA2, 0x6B, 0xCF, 0x69, 0x7C,
0x8F, 0xAB, 0x22, 0x28, 0xD6, 0xF1, 0x65, 0x0B,
0x4A, 0x5B, 0x9B, 0x1F, 0xD4, 0xAA, 0xEF, 0x35,
0xA2, 0x42, 0x32, 0x00, 0x9F, 0x42, 0xBB, 0x19,
0x99, 0x49, 0x6D, 0xB8, 0x03, 0x3D, 0x35, 0x96,
0x0C, 0x57, 0xBB, 0x6B, 0x07, 0xA4, 0xB9, 0x7F,
0x9B, 0xEC, 0x78, 0x90, 0xB7, 0xC8, 0x5E, 0x7F,
0x3B, 0xAB, 0xC1, 0xB6, 0x0C, 0x84, 0x3C, 0xBC,
0x7F, 0x04, 0x79, 0xB7, 0x9C, 0xC0, 0xFE, 0xB0,
0xAE, 0xBD, 0xA5, 0x57, 0x2C, 0xEC, 0x3D, 0x0D,
};
byte[] dataHash;
using (HashAlgorithm hash = SHA1.Create())
{
dataHash = hash.ComputeHash(TestData.HelloBytes);
}
VerifyHashSignature(hashSignature, dataHash, "SHA1", TestData.RSA2048Params);
}
[Fact]
public static void VerifyHashSignature_SHA256_1024()
{
byte[] hashSignature = new byte[]
{
0x5C, 0x2F, 0x00, 0xA9, 0xE4, 0x63, 0xD7, 0xB7,
0x94, 0x93, 0xCE, 0xA8, 0x7E, 0x71, 0xAE, 0x97,
0xC2, 0x6B, 0x37, 0x31, 0x5B, 0xB8, 0xE3, 0x30,
0xDF, 0x77, 0xF8, 0xBB, 0xB5, 0xBF, 0x41, 0x9F,
0x14, 0x6A, 0x61, 0x26, 0x2E, 0x80, 0xE5, 0xE6,
0x8A, 0xEA, 0xC7, 0x60, 0x0B, 0xAE, 0x2B, 0xB2,
0x18, 0xD8, 0x5D, 0xC8, 0x58, 0x86, 0x5E, 0x23,
0x62, 0x44, 0x72, 0xEA, 0x3B, 0xF7, 0x70, 0xC6,
0x4C, 0x2B, 0x54, 0x5B, 0xF4, 0x24, 0xA1, 0xE5,
0x63, 0xDD, 0x50, 0x3A, 0x29, 0x26, 0x84, 0x06,
0xEF, 0x13, 0xD0, 0xCE, 0xCC, 0xA1, 0x05, 0xB4,
0x72, 0x81, 0x0A, 0x2E, 0x33, 0xF6, 0x2F, 0xD1,
0xEA, 0x41, 0xB0, 0xB3, 0x93, 0x4C, 0xF3, 0x0F,
0x6F, 0x21, 0x3E, 0xD7, 0x5F, 0x57, 0x2E, 0xC7,
0x5F, 0xF5, 0x28, 0x89, 0xB8, 0x07, 0xDB, 0xAC,
0x70, 0x95, 0x25, 0x49, 0x8A, 0x1A, 0xD7, 0xFC,
};
byte[] dataHash;
using (HashAlgorithm hash = SHA256.Create())
{
dataHash = hash.ComputeHash(TestData.HelloBytes);
}
VerifyHashSignature(hashSignature, dataHash, "SHA256", TestData.RSA1024Params);
}
[Fact]
public static void VerifyHashSignature_SHA256_2048()
{
byte[] hashSignature = new byte[]
{
0x2C, 0x74, 0x98, 0x23, 0xF4, 0x38, 0x7F, 0x49,
0x82, 0xB6, 0x55, 0xCF, 0xC3, 0x25, 0x4F, 0xE3,
0x4B, 0x17, 0xE7, 0xED, 0xEA, 0x58, 0x1E, 0x63,
0x57, 0x58, 0xCD, 0xB5, 0x06, 0xD6, 0xCA, 0x13,
0x28, 0x81, 0xE6, 0xE0, 0x8B, 0xDC, 0xC6, 0x05,
0x35, 0x35, 0x40, 0x73, 0x76, 0x61, 0x67, 0x42,
0x94, 0xF7, 0x54, 0x0E, 0xB6, 0x30, 0x9A, 0x70,
0xC3, 0x06, 0xC1, 0x59, 0xA7, 0x89, 0x66, 0x38,
0x02, 0x5C, 0x52, 0x02, 0x17, 0x4E, 0xEC, 0x21,
0xE9, 0x24, 0x85, 0xCB, 0x56, 0x42, 0xAB, 0x21,
0x3A, 0x19, 0xC3, 0x95, 0x06, 0xBA, 0xDB, 0xD9,
0x89, 0x7C, 0xB9, 0xEC, 0x1D, 0x8B, 0x5A, 0x64,
0x87, 0xAF, 0x36, 0x71, 0xAC, 0x0A, 0x2B, 0xC7,
0x7D, 0x2F, 0x44, 0xAA, 0xB4, 0x1C, 0xBE, 0x0B,
0x0A, 0x4E, 0xEA, 0xF8, 0x75, 0x40, 0xD9, 0x4A,
0x82, 0x1C, 0x82, 0x81, 0x97, 0xC2, 0xF1, 0xC8,
0xA7, 0x4B, 0x45, 0x9A, 0x66, 0x8E, 0x35, 0x2E,
0xE5, 0x1A, 0x2B, 0x0B, 0xF9, 0xAB, 0xC4, 0x2A,
0xE0, 0x47, 0x72, 0x2A, 0xC2, 0xD8, 0xC6, 0xFD,
0x91, 0x30, 0xD2, 0x45, 0xA4, 0x7F, 0x0F, 0x39,
0x80, 0xBC, 0xA9, 0xBD, 0xEC, 0xA5, 0x03, 0x6F,
0x01, 0xF6, 0x19, 0xD5, 0x2B, 0xD9, 0x40, 0xCD,
0x7F, 0xEF, 0x0F, 0x9D, 0x93, 0x02, 0xCD, 0x89,
0xB8, 0x2C, 0xC7, 0xD6, 0xFD, 0xAA, 0x12, 0x6E,
0x4C, 0x06, 0x35, 0x08, 0x61, 0x79, 0x27, 0xE1,
0xEA, 0x46, 0x75, 0x08, 0x5B, 0x51, 0xA1, 0x80,
0x78, 0x02, 0xEA, 0x3E, 0xEC, 0x29, 0xD2, 0x8B,
0xC5, 0x9E, 0x7D, 0xA4, 0x85, 0x8D, 0xAD, 0x73,
0x39, 0x17, 0x64, 0x82, 0x46, 0x4A, 0xA4, 0x34,
0xF0, 0xCC, 0x2F, 0x9F, 0x55, 0xA4, 0xEA, 0xEC,
0xC9, 0xA7, 0xAB, 0xBA, 0xA8, 0x84, 0x14, 0x62,
0x6B, 0x9B, 0x97, 0x2D, 0x8C, 0xB2, 0x1C, 0x16,
};
byte[] dataHash;
using (HashAlgorithm hash = SHA256.Create())
{
dataHash = hash.ComputeHash(TestData.HelloBytes);
}
VerifyHashSignature(hashSignature, dataHash, "SHA256", TestData.RSA2048Params);
}
private static void ExpectSignature(
byte[] expectedSignature,
byte[] data,
string hashAlgorithmName,
RSAParameters rsaParameters)
{
// RSA signatures use PKCS 1.5 EMSA encoding (encoding method, signature algorithm).
// EMSA specifies a fixed filler type of { 0x01, 0xFF, 0xFF ... 0xFF, 0x00 } whose length
// is as long as it needs to be to match the block size. Since the filler is deterministic,
// the signature is deterministic, so we can safely verify it here.
byte[] signature;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(rsaParameters);
signature = rsa.SignData(data, new HashAlgorithmName(hashAlgorithmName), RSASignaturePadding.Pkcs1);
}
Assert.Equal(expectedSignature, signature);
}
private static void ExpectHashSignature(
byte[] expectedSignature,
byte[] dataHash,
string hashAlgorithmName,
RSAParameters rsaParameters)
{
// RSA signatures use PKCS 1.5 EMSA encoding (encoding method, signature algorithm).
// EMSA specifies a fixed filler type of { 0x01, 0xFF, 0xFF ... 0xFF, 0x00 } whose length
// is as long as it needs to be to match the block size. Since the filler is deterministic,
// the signature is deterministic, so we can safely verify it here.
byte[] signature;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(rsaParameters);
signature = rsa.SignHash(dataHash, new HashAlgorithmName(hashAlgorithmName), RSASignaturePadding.Pkcs1);
}
Assert.Equal(expectedSignature, signature);
}
private static void VerifySignature(
byte[] signature,
byte[] data,
string hashAlgorithmName,
RSAParameters rsaParameters)
{
RSAParameters publicOnly = new RSAParameters
{
Modulus = rsaParameters.Modulus,
Exponent = rsaParameters.Exponent,
};
bool signatureMatched;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(publicOnly);
signatureMatched = rsa.VerifyData(data, signature, new HashAlgorithmName(hashAlgorithmName), RSASignaturePadding.Pkcs1);
}
Assert.True(signatureMatched);
}
private static void VerifyHashSignature(
byte[] signature,
byte[] dataHash,
string hashAlgorithmName,
RSAParameters rsaParameters)
{
RSAParameters publicOnly = new RSAParameters
{
Modulus = rsaParameters.Modulus,
Exponent = rsaParameters.Exponent,
};
bool signatureMatched;
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(publicOnly);
signatureMatched = rsa.VerifyHash(dataHash, signature, new HashAlgorithmName(hashAlgorithmName), RSASignaturePadding.Pkcs1);
}
Assert.True(signatureMatched);
}
private static void SignAndVerify(byte[] data, string hashAlgorithmName, RSAParameters rsaParameters)
{
using (RSA rsa = RSAFactory.Create())
{
rsa.ImportParameters(rsaParameters);
byte[] signature = rsa.SignData(data, new HashAlgorithmName(hashAlgorithmName), RSASignaturePadding.Pkcs1);
bool signatureMatched = rsa.VerifyData(data, signature, new HashAlgorithmName(hashAlgorithmName), RSASignaturePadding.Pkcs1);
Assert.True(signatureMatched);
}
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using SDKTemplate;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.Globalization;
using Windows.Media.SpeechRecognition;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Documents;
using Windows.UI.Xaml.Navigation;
using Windows.Foundation;
using Windows.ApplicationModel.Resources.Core;
namespace SpeechAndTTS
{
public sealed partial class PredefinedWebSearchGrammarScenario : Page
{
/// <summary>
/// This HResult represents the scenario where a user is prompted to allow in-app speech, but
/// declines. This should only happen on a Phone device, where speech is enabled for the entire device,
/// not per-app.
/// </summary>
private static uint HResultPrivacyStatementDeclined = 0x80045509;
private SpeechRecognizer speechRecognizer;
private CoreDispatcher dispatcher;
private IAsyncOperation<SpeechRecognitionResult> recognitionOperation;
private ResourceContext speechContext;
private ResourceMap speechResourceMap;
public PredefinedWebSearchGrammarScenario()
{
InitializeComponent();
}
/// <summary>
/// When activating the scenario, ensure we have permission from the user to access their microphone, and
/// provide an appropriate path for the user to enable access to the microphone if they haven't
/// given explicit permission for it.
/// </summary>
/// <param name="e">The navigation event details</param>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
// Save the UI thread dispatcher to allow speech status messages to be shown on the UI.
dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission();
if (permissionGained)
{
// Enable the recognition buttons.
btnRecognizeWithUI.IsEnabled = true;
btnRecognizeWithoutUI.IsEnabled = true;
}
else
{
resultTextBlock.Visibility = Visibility.Visible;
resultTextBlock.Text = "Permission to access capture resources was not given by the user; please set the application setting in Settings->Privacy->Microphone.";
}
Language speechLanguage = SpeechRecognizer.SystemSpeechLanguage;
speechContext = ResourceContext.GetForCurrentView();
speechContext.Languages = new string[] { speechLanguage.LanguageTag};
speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources");
PopulateLanguageDropDown();
await InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage);
}
/// <summary>
/// Look up the supported languages for this speech recognition scenario,
/// that are installed on this machine, and populate a dropdown with a list.
/// </summary>
private void PopulateLanguageDropDown()
{
Language defaultLanguage = SpeechRecognizer.SystemSpeechLanguage;
IEnumerable<Language> supportedLanguages = SpeechRecognizer.SupportedTopicLanguages;
foreach (Language lang in supportedLanguages)
{
ComboBoxItem item = new ComboBoxItem();
item.Tag = lang;
item.Content = lang.DisplayName;
cbLanguageSelection.Items.Add(item);
if (lang.LanguageTag == defaultLanguage.LanguageTag)
{
item.IsSelected = true;
cbLanguageSelection.SelectedItem = item;
}
}
}
/// <summary>
/// Ensure that we clean up any state tracking event handlers created in OnNavigatedTo to prevent leaks.
/// </summary>
/// <param name="e">Details about the navigation event</param>
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
if (speechRecognizer != null)
{
if (speechRecognizer.State != SpeechRecognizerState.Idle)
{
if (recognitionOperation != null)
{
recognitionOperation.Cancel();
recognitionOperation = null;
}
}
speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
this.speechRecognizer.Dispose();
this.speechRecognizer = null;
}
}
/// <summary>
/// Initialize Speech Recognizer and compile constraints.
/// </summary>
/// <param name="recognizerLanguage">Language to use for the speech recognizer</param>
/// <returns>Awaitable task.</returns>
private async Task InitializeRecognizer(Language recognizerLanguage)
{
if (speechRecognizer != null)
{
// cleanup prior to re-initializing this scenario.
speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
this.speechRecognizer.Dispose();
this.speechRecognizer = null;
}
// Create an instance of SpeechRecognizer.
speechRecognizer = new SpeechRecognizer(recognizerLanguage);
// Provide feedback to the user about the state of the recognizer.
speechRecognizer.StateChanged += SpeechRecognizer_StateChanged;
// Add a web search topic constraint to the recognizer.
var webSearchGrammar = new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario.WebSearch, "webSearch");
speechRecognizer.Constraints.Add(webSearchGrammar);
// RecognizeWithUIAsync allows developers to customize the prompts.
speechRecognizer.UIOptions.AudiblePrompt = "Say what you want to search for...";
speechRecognizer.UIOptions.ExampleText = speechResourceMap.GetValue("WebSearchUIOptionsExampleText", speechContext).ValueAsString;
// Compile the constraint.
SpeechRecognitionCompilationResult compilationResult = await speechRecognizer.CompileConstraintsAsync();
// Check to make sure that the constraints were in a proper format and the recognizer was able to compile it.
if (compilationResult.Status != SpeechRecognitionResultStatus.Success)
{
// Disable the recognition buttons.
btnRecognizeWithUI.IsEnabled = false;
btnRecognizeWithoutUI.IsEnabled = false;
// Let the user know that the grammar didn't compile properly.
resultTextBlock.Visibility = Visibility.Visible;
resultTextBlock.Text = "Unable to compile grammar.";
}
}
/// <summary>
/// Handle SpeechRecognizer state changed events by updating a UI component.
/// </summary>
/// <param name="sender">Speech recognizer that generated this status event</param>
/// <param name="args">The recognizer's status</param>
private async void SpeechRecognizer_StateChanged(SpeechRecognizer sender, SpeechRecognizerStateChangedEventArgs args)
{
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
MainPage.Current.NotifyUser("Speech recognizer state: " + args.State.ToString(), NotifyType.StatusMessage);
});
}
/// <summary>
/// Uses the recognizer constructed earlier to listen for speech from the user before displaying
/// it back on the screen. Uses the built-in speech recognition UI.
/// </summary>
/// <param name="sender">Button that triggered this event</param>
/// <param name="e">State information about the routed event</param>
private async void RecognizeWithUIWebSearchGrammar_Click(object sender, RoutedEventArgs e)
{
heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Collapsed;
hlOpenPrivacySettings.Visibility = Visibility.Collapsed;
// Start recognition.
try
{
recognitionOperation = speechRecognizer.RecognizeWithUIAsync();
SpeechRecognitionResult speechRecognitionResult = await recognitionOperation;
// If successful, display the recognition result.
if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success)
{
heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Visible;
resultTextBlock.Text = speechRecognitionResult.Text;
}
}
catch (TaskCanceledException exception)
{
// TaskCanceledException will be thrown if you exit the scenario while the recognizer is actively
// processing speech. Since this happens here when we navigate out of the scenario, don't try to
// show a message dialog for this exception.
System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):");
System.Diagnostics.Debug.WriteLine(exception.ToString());
}
catch (Exception exception)
{
// Handle the speech privacy policy error.
if ((uint)exception.HResult == HResultPrivacyStatementDeclined)
{
hlOpenPrivacySettings.Visibility = Visibility.Visible;
}
else
{
var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
await messageDialog.ShowAsync();
}
}
}
/// <summary>
/// Uses the recognizer constructed earlier to listen for speech from the user before displaying
/// it back on the screen. Uses developer-provided UI for user feedback.
/// </summary>
/// <param name="sender">Button that triggered this event</param>
/// <param name="e">State information about the routed event</param>
private async void RecognizeWithoutUIWebSearchGrammar_Click(object sender, RoutedEventArgs e)
{
heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Collapsed;
// Disable the UI while recognition is occurring, and provide feedback to the user about current state.
btnRecognizeWithUI.IsEnabled = false;
btnRecognizeWithoutUI.IsEnabled = false;
cbLanguageSelection.IsEnabled = false;
hlOpenPrivacySettings.Visibility = Visibility.Collapsed;
listenWithoutUIButtonText.Text = " listening for speech...";
// Start recognition.
try
{
recognitionOperation = speechRecognizer.RecognizeAsync();
SpeechRecognitionResult speechRecognitionResult = await recognitionOperation;
// If successful, display the recognition result.
if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success)
{
heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Visible;
resultTextBlock.Text = speechRecognitionResult.Text;
}
}
catch (TaskCanceledException exception)
{
// TaskCanceledException will be thrown if you exit the scenario while the recognizer is actively
// processing speech. Since this happens here when we navigate out of the scenario, don't try to
// show a message dialog for this exception.
System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):");
System.Diagnostics.Debug.WriteLine(exception.ToString());
}
catch (Exception exception)
{
// Handle the speech privacy policy error.
if ((uint)exception.HResult == HResultPrivacyStatementDeclined)
{
hlOpenPrivacySettings.Visibility = Visibility.Visible;
}
else
{
var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
await messageDialog.ShowAsync();
}
}
// Reset UI state.
listenWithoutUIButtonText.Text = " without UI";
btnRecognizeWithUI.IsEnabled = true;
cbLanguageSelection.IsEnabled = true;
btnRecognizeWithoutUI.IsEnabled = true;
}
/// <summary>
/// When a user changes the speech recognition language, trigger re-initialization of the
/// speech engine with that language, and change any speech-specific UI assets.
/// </summary>
/// <param name="sender">Ignored</param>
/// <param name="e">Ignored</param>
private async void cbLanguageSelection_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (speechRecognizer != null)
{
ComboBoxItem item = (ComboBoxItem)(cbLanguageSelection.SelectedItem);
Language newLanguage = (Language)item.Tag;
if (speechRecognizer.CurrentLanguage != newLanguage)
{
// trigger cleanup and re-initialization of speech.
try
{
speechContext.Languages = new string[] { newLanguage.LanguageTag };
await InitializeRecognizer(newLanguage);
}
catch (Exception exception)
{
var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
await messageDialog.ShowAsync();
}
}
}
}
/// <summary>
/// Open the Speech, Inking and Typing page under Settings -> Privacy, enabling a user to accept the
/// Microsoft Privacy Policy, and enable personalization.
/// </summary>
/// <param name="sender">Ignored</param>
/// <param name="args">Ignored</param>
private async void openPrivacySettings_Click(Hyperlink sender, HyperlinkClickEventArgs args)
{
await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-speechtyping"));
}
}
}
| |
//
// cominterop.cs:
//
// Tests for COM Interop related features
//
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public class Tests
{
[DllImport("libtest")]
public static extern int mono_test_marshal_bstr_in([MarshalAs(UnmanagedType.BStr)]string str);
[DllImport("libtest")]
public static extern int mono_test_marshal_bstr_out([MarshalAs(UnmanagedType.BStr)] out string str);
[DllImport("libtest")]
public static extern int mono_test_marshal_bstr_in_null([MarshalAs(UnmanagedType.BStr)]string str);
[DllImport("libtest")]
public static extern int mono_test_marshal_bstr_out_null([MarshalAs(UnmanagedType.BStr)] out string str);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_in_sbyte([MarshalAs(UnmanagedType.Struct)]object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_in_byte([MarshalAs(UnmanagedType.Struct)]object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_in_short([MarshalAs(UnmanagedType.Struct)]object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_in_ushort([MarshalAs(UnmanagedType.Struct)]object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_in_int([MarshalAs(UnmanagedType.Struct)]object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_in_uint([MarshalAs(UnmanagedType.Struct)]object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_in_long([MarshalAs(UnmanagedType.Struct)]object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_in_ulong([MarshalAs(UnmanagedType.Struct)]object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_in_float([MarshalAs(UnmanagedType.Struct)]object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_in_double([MarshalAs(UnmanagedType.Struct)]object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_in_bstr ([MarshalAs (UnmanagedType.Struct)]object obj);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_in_bool_true ([MarshalAs (UnmanagedType.Struct)]object obj);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_in_bool_false ([MarshalAs (UnmanagedType.Struct)]object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_sbyte([MarshalAs(UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_sbyte_byref([MarshalAs(UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_byte([MarshalAs(UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_byte_byref([MarshalAs(UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_short([MarshalAs(UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_short_byref([MarshalAs(UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_ushort([MarshalAs(UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_ushort_byref([MarshalAs(UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_int([MarshalAs(UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_int_byref([MarshalAs(UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_uint([MarshalAs(UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_uint_byref([MarshalAs(UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_long([MarshalAs(UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_long_byref([MarshalAs(UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_ulong([MarshalAs(UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_ulong_byref([MarshalAs(UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_float([MarshalAs(UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_float_byref([MarshalAs(UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_double([MarshalAs(UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_double_byref([MarshalAs(UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_bstr ([MarshalAs (UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_bstr_byref ([MarshalAs (UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_bool_true ([MarshalAs (UnmanagedType.Struct)]out object obj);
[DllImport("libtest")]
public static extern int mono_test_marshal_variant_out_bool_true_byref ([MarshalAs (UnmanagedType.Struct)]out object obj);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_out_bool_false ([MarshalAs (UnmanagedType.Struct)]out object obj);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_out_bool_false_byref ([MarshalAs (UnmanagedType.Struct)]out object obj);
public delegate int VarFunc (VarEnum vt, [MarshalAs (UnmanagedType.Struct)] object obj);
public delegate int VarRefFunc (VarEnum vt, [MarshalAs (UnmanagedType.Struct)] ref object obj);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_in_sbyte_unmanaged (VarFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_in_byte_unmanaged (VarFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_in_short_unmanaged (VarFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_in_ushort_unmanaged (VarFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_in_int_unmanaged (VarFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_in_uint_unmanaged (VarFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_in_long_unmanaged (VarFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_in_ulong_unmanaged (VarFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_in_float_unmanaged (VarFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_in_double_unmanaged (VarFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_in_bstr_unmanaged (VarFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_in_bool_true_unmanaged (VarFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_in_bool_false_unmanaged (VarFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_out_sbyte_unmanaged (VarRefFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_out_byte_unmanaged (VarRefFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_out_short_unmanaged (VarRefFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_out_ushort_unmanaged (VarRefFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_out_int_unmanaged (VarRefFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_out_uint_unmanaged (VarRefFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_out_long_unmanaged (VarRefFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_out_ulong_unmanaged (VarRefFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_out_float_unmanaged (VarRefFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_out_double_unmanaged (VarRefFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_out_bstr_unmanaged (VarRefFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_out_bool_true_unmanaged (VarRefFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_variant_out_bool_false_unmanaged (VarRefFunc func);
[DllImport ("libtest")]
public static extern int mono_test_marshal_com_object_create (out IntPtr pUnk);
[DllImport ("libtest")]
public static extern int mono_test_marshal_com_object_same (out IntPtr pUnk);
[DllImport ("libtest")]
public static extern int mono_test_marshal_com_object_destroy (IntPtr pUnk);
[DllImport ("libtest")]
public static extern int mono_test_marshal_com_object_ref_count (IntPtr pUnk);
[DllImport ("libtest")]
public static extern int mono_test_marshal_ccw_identity ([MarshalAs (UnmanagedType.Interface)]ITest itest);
[DllImport ("libtest")]
public static extern int mono_test_marshal_ccw_reflexive ([MarshalAs (UnmanagedType.Interface)]ITest itest);
[DllImport ("libtest")]
public static extern int mono_test_marshal_ccw_transitive ([MarshalAs (UnmanagedType.Interface)]ITest itest);
[DllImport ("libtest")]
public static extern int mono_test_marshal_ccw_itest ([MarshalAs (UnmanagedType.Interface)]ITest itest);
[DllImport ("libtest")]
public static extern int mono_test_marshal_ccw_itest ([MarshalAs (UnmanagedType.Interface)]ITestPresSig itest);
[DllImport("libtest")]
public static extern int mono_test_marshal_safearray_out_1dim_vt_bstr_empty ([MarshalAs (UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)]out Array array);
[DllImport("libtest")]
public static extern int mono_test_marshal_safearray_out_1dim_vt_bstr ([MarshalAs (UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)]out Array array);
[DllImport("libtest")]
public static extern int mono_test_marshal_safearray_out_2dim_vt_i4 ([MarshalAs (UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)]out Array array);
[DllImport("libtest")]
public static extern int mono_test_marshal_safearray_out_4dim_vt_i4 ([MarshalAs (UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)]out Array array);
[DllImport("libtest")]
public static extern int mono_test_marshal_safearray_in_byval_1dim_empty ([In, MarshalAs (UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] Array array);
[DllImport("libtest")]
public static extern int mono_test_marshal_safearray_in_byval_1dim_vt_i4 ([In, MarshalAs (UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] Array array);
[DllImport("libtest")]
public static extern int mono_test_marshal_safearray_in_byval_1dim_vt_mixed ([In, MarshalAs (UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] Array array);
[DllImport("libtest")]
public static extern int mono_test_marshal_safearray_in_byval_2dim_vt_i4 ([In, MarshalAs (UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] Array array);
[DllImport("libtest")]
public static extern int mono_test_marshal_safearray_in_byval_3dim_vt_bstr ([In, MarshalAs (UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] Array array);
[DllImport("libtest")]
public static extern int mono_test_marshal_safearray_in_byref_3dim_vt_bstr ([In, MarshalAs (UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] ref Array array);
[DllImport("libtest")]
public static extern int mono_test_marshal_safearray_in_out_byref_1dim_empty ([In, Out, MarshalAs (UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] ref Array array);
[DllImport("libtest")]
public static extern int mono_test_marshal_safearray_in_out_byref_3dim_vt_bstr ([In, Out, MarshalAs (UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] ref Array array);
[DllImport("libtest")]
public static extern int mono_test_marshal_safearray_in_out_byref_1dim_vt_i4 ([In, Out, MarshalAs (UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] ref Array array);
[DllImport("libtest")]
public static extern int mono_test_marshal_safearray_in_out_byval_1dim_vt_i4 ([In, Out, MarshalAs (UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] Array array);
[DllImport("libtest")]
public static extern int mono_test_marshal_safearray_in_out_byval_3dim_vt_bstr ([In, Out, MarshalAs (UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] Array array);
[DllImport("libtest")]
public static extern int mono_test_marshal_safearray_mixed (
[In, Out, MarshalAs (UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] Array array1,
[MarshalAs (UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] out Array array2,
[In, MarshalAs (UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] Array array3,
[In, Out, MarshalAs (UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_VARIANT)] ref Array array4);
[DllImport("libtest")]
public static extern bool mono_cominterop_is_supported ();
public static int Main ()
{
bool isWindows = !(((int)Environment.OSVersion.Platform == 4) ||
((int)Environment.OSVersion.Platform == 128));
if (mono_cominterop_is_supported () || isWindows)
{
#region BSTR Tests
string str;
if (mono_test_marshal_bstr_in ("mono_test_marshal_bstr_in") != 0)
return 1;
if (mono_test_marshal_bstr_out (out str) != 0 || str != "mono_test_marshal_bstr_out")
return 2;
if (mono_test_marshal_bstr_in_null (null) != 0)
return 1;
if (mono_test_marshal_bstr_out_null (out str) != 0 || str != null)
return 2;
#endregion // BSTR Tests
#region VARIANT Tests
object obj;
if (mono_test_marshal_variant_in_sbyte ((sbyte)100) != 0)
return 13;
if (mono_test_marshal_variant_in_byte ((byte)100) != 0)
return 14;
if (mono_test_marshal_variant_in_short ((short)314) != 0)
return 15;
if (mono_test_marshal_variant_in_ushort ((ushort)314) != 0)
return 16;
if (mono_test_marshal_variant_in_int ((int)314) != 0)
return 17;
if (mono_test_marshal_variant_in_uint ((uint)314) != 0)
return 18;
if (mono_test_marshal_variant_in_long ((long)314) != 0)
return 19;
if (mono_test_marshal_variant_in_ulong ((ulong)314) != 0)
return 20;
if (mono_test_marshal_variant_in_float ((float)3.14) != 0)
return 21;
if (mono_test_marshal_variant_in_double ((double)3.14) != 0)
return 22;
if (mono_test_marshal_variant_in_bstr ("PI") != 0)
return 23;
if (mono_test_marshal_variant_out_sbyte (out obj) != 0 || (sbyte)obj != 100)
return 24;
if (mono_test_marshal_variant_out_byte (out obj) != 0 || (byte)obj != 100)
return 25;
if (mono_test_marshal_variant_out_short (out obj) != 0 || (short)obj != 314)
return 26;
if (mono_test_marshal_variant_out_ushort (out obj) != 0 || (ushort)obj != 314)
return 27;
if (mono_test_marshal_variant_out_int (out obj) != 0 || (int)obj != 314)
return 28;
if (mono_test_marshal_variant_out_uint (out obj) != 0 || (uint)obj != 314)
return 29;
if (mono_test_marshal_variant_out_long (out obj) != 0 || (long)obj != 314)
return 30;
if (mono_test_marshal_variant_out_ulong (out obj) != 0 || (ulong)obj != 314)
return 31;
if (mono_test_marshal_variant_out_float (out obj) != 0 || ((float)obj - 3.14) / 3.14 > .001)
return 32;
if (mono_test_marshal_variant_out_double (out obj) != 0 || ((double)obj - 3.14) / 3.14 > .001)
return 33;
if (mono_test_marshal_variant_out_bstr (out obj) != 0 || (string)obj != "PI")
return 34;
VarFunc func = new VarFunc (mono_test_marshal_variant_in_callback);
if (mono_test_marshal_variant_in_sbyte_unmanaged (func) != 0)
return 35;
if (mono_test_marshal_variant_in_byte_unmanaged (func) != 0)
return 36;
if (mono_test_marshal_variant_in_short_unmanaged (func) != 0)
return 37;
if (mono_test_marshal_variant_in_ushort_unmanaged (func) != 0)
return 38;
if (mono_test_marshal_variant_in_int_unmanaged (func) != 0)
return 39;
if (mono_test_marshal_variant_in_uint_unmanaged (func) != 0)
return 40;
if (mono_test_marshal_variant_in_long_unmanaged (func) != 0)
return 41;
if (mono_test_marshal_variant_in_ulong_unmanaged (func) != 0)
return 42;
if (mono_test_marshal_variant_in_float_unmanaged (func) != 0)
return 43;
if (mono_test_marshal_variant_in_double_unmanaged (func) != 0)
return 44;
if (mono_test_marshal_variant_in_bstr_unmanaged (func) != 0)
return 45;
if (mono_test_marshal_variant_in_bool_true_unmanaged (func) != 0)
return 46;
VarRefFunc reffunc = new VarRefFunc (mono_test_marshal_variant_out_callback);
if (mono_test_marshal_variant_out_sbyte_unmanaged (reffunc) != 0)
return 50;
if (mono_test_marshal_variant_out_byte_unmanaged (reffunc) != 0)
return 51;
if (mono_test_marshal_variant_out_short_unmanaged (reffunc) != 0)
return 52;
if (mono_test_marshal_variant_out_ushort_unmanaged (reffunc) != 0)
return 53;
if (mono_test_marshal_variant_out_int_unmanaged (reffunc) != 0)
return 54;
if (mono_test_marshal_variant_out_uint_unmanaged (reffunc) != 0)
return 55;
if (mono_test_marshal_variant_out_long_unmanaged (reffunc) != 0)
return 56;
if (mono_test_marshal_variant_out_ulong_unmanaged (reffunc) != 0)
return 57;
if (mono_test_marshal_variant_out_float_unmanaged (reffunc) != 0)
return 58;
if (mono_test_marshal_variant_out_double_unmanaged (reffunc) != 0)
return 59;
if (mono_test_marshal_variant_out_bstr_unmanaged (reffunc) != 0)
return 60;
if (mono_test_marshal_variant_out_bool_true_unmanaged (reffunc) != 0)
return 61;
if (mono_test_marshal_variant_out_sbyte_byref (out obj) != 0 || (sbyte)obj != 100)
return 97;
if (mono_test_marshal_variant_out_byte_byref (out obj) != 0 || (byte)obj != 100)
return 98;
if (mono_test_marshal_variant_out_short_byref (out obj) != 0 || (short)obj != 314)
return 99;
if (mono_test_marshal_variant_out_ushort_byref (out obj) != 0 || (ushort)obj != 314)
return 100;
if (mono_test_marshal_variant_out_int_byref (out obj) != 0 || (int)obj != 314)
return 101;
if (mono_test_marshal_variant_out_uint_byref (out obj) != 0 || (uint)obj != 314)
return 102;
if (mono_test_marshal_variant_out_long_byref (out obj) != 0 || (long)obj != 314)
return 103;
if (mono_test_marshal_variant_out_ulong_byref (out obj) != 0 || (ulong)obj != 314)
return 104;
if (mono_test_marshal_variant_out_float_byref (out obj) != 0 || ((float)obj - 3.14) / 3.14 > .001)
return 105;
if (mono_test_marshal_variant_out_double_byref (out obj) != 0 || ((double)obj - 3.14) / 3.14 > .001)
return 106;
if (mono_test_marshal_variant_out_bstr_byref (out obj) != 0 || (string)obj != "PI")
return 107;
#endregion // VARIANT Tests
#region Runtime Callable Wrapper Tests
IntPtr pUnk;
if (mono_test_marshal_com_object_create (out pUnk) != 0)
return 145;
if (mono_test_marshal_com_object_ref_count (pUnk) != 1)
return 146;
if (Marshal.AddRef (pUnk) != 2)
return 147;
if (mono_test_marshal_com_object_ref_count (pUnk) != 2)
return 148;
if (Marshal.Release (pUnk) != 1)
return 149;
if (mono_test_marshal_com_object_ref_count (pUnk) != 1)
return 150;
object com_obj = Marshal.GetObjectForIUnknown (pUnk);
if (com_obj == null)
return 151;
ITest itest = com_obj as ITest;
if (itest == null)
return 152;
IntPtr pUnk2;
if (mono_test_marshal_com_object_same (out pUnk2) != 0)
return 153;
object com_obj2 = Marshal.GetObjectForIUnknown (pUnk2);
if (com_obj != com_obj2)
return 154;
if (!com_obj.Equals (com_obj2))
return 155;
IntPtr pUnk3;
if (mono_test_marshal_com_object_create (out pUnk3) != 0)
return 156;
object com_obj3 = Marshal.GetObjectForIUnknown (pUnk3);
if (com_obj == com_obj3)
return 157;
if (com_obj.Equals (com_obj3))
return 158;
// com_obj & com_obj2 share a RCW
if (Marshal.ReleaseComObject (com_obj2) != 1)
return 159;
// com_obj3 should only have one RCW
if (Marshal.ReleaseComObject (com_obj3) != 0)
return 160;
IntPtr iunknown = Marshal.GetIUnknownForObject (com_obj);
if (iunknown == IntPtr.Zero)
return 170;
if (pUnk != iunknown)
return 171;
if (TestITest (itest) != 0)
return 172;
if (TestITestPresSig (itest as ITestPresSig) != 0)
return 173;
if (TestITestDelegate (itest) != 0)
return 174;
itest = new TestClass ();
if (TestITest (itest) != 0)
return 175;
itest = (ITest)System.Activator.CreateInstance (typeof(TestActivatorClass));
if (TestITest (itest) != 0)
return 176;
#endregion // Runtime Callable Wrapper Tests
#region COM Callable Wrapper Tests
ManagedTest test = new ManagedTest ();
mono_test_marshal_ccw_itest (test);
if (test.Status != 0)
return 200;
ManagedTestPresSig test_pres_sig = new ManagedTestPresSig ();
mono_test_marshal_ccw_itest (test_pres_sig);
#endregion // COM Callable Wrapper Tests
#region SAFEARRAY tests
if (isWindows) {
/* out */
Array array;
if ((mono_test_marshal_safearray_out_1dim_vt_bstr_empty (out array) != 0) || (array.Rank != 1) || (array.Length != 0))
return 62;
if ((mono_test_marshal_safearray_out_1dim_vt_bstr (out array) != 0) || (array.Rank != 1) || (array.Length != 10))
return 63;
for (int i = 0; i < 10; ++i) {
if (i != Convert.ToInt32 (array.GetValue (i)))
return 64;
}
if ((mono_test_marshal_safearray_out_2dim_vt_i4 (out array) != 0) || (array.Rank != 2))
return 65;
if ( (array.GetLowerBound (0) != 0) || (array.GetUpperBound (0) != 3)
|| (array.GetLowerBound (1) != 0) || (array.GetUpperBound (1) != 2))
return 66;
for (int i = array.GetLowerBound (0); i <= array.GetUpperBound (0); ++i)
{
for (int j = array.GetLowerBound (1); j <= array.GetUpperBound (1); ++j) {
if ((i + 1) * 10 + (j + 1) != (int)array.GetValue (new long[] { i, j }))
return 67;
}
}
if ((mono_test_marshal_safearray_out_4dim_vt_i4 (out array) != 0) || (array.Rank != 4))
return 68;
if ( (array.GetLowerBound (0) != 15) || (array.GetUpperBound (0) != 24)
|| (array.GetLowerBound (1) != 20) || (array.GetUpperBound (1) != 22)
|| (array.GetLowerBound (2) != 5) || (array.GetUpperBound (2) != 10)
|| (array.GetLowerBound (3) != 12) || (array.GetUpperBound (3) != 18) )
return 69;
int index = 0;
for (int i = array.GetLowerBound (3); i <= array.GetUpperBound (3); ++i) {
for (int j = array.GetLowerBound (2); j <= array.GetUpperBound (2); ++j) {
for (int k = array.GetLowerBound (1); k <= array.GetUpperBound (1); ++k) {
for (int l = array.GetLowerBound (0); l <= array.GetUpperBound (0); ++l) {
if (index != (int)array.GetValue (new long[] { l, k, j, i }))
return 70;
++index;
}
}
}
}
/* in */
array = new object[] { };
if (mono_test_marshal_safearray_in_byval_1dim_empty (array) != 0)
return 71;
array = new object[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
if (mono_test_marshal_safearray_in_byval_1dim_vt_i4 (array) != 0)
return 72;
array = new object[] { 0, "1", 2, "3", 4, "5", 6, "7", 8, "9", 10, "11", 12 };
if (mono_test_marshal_safearray_in_byval_1dim_vt_mixed (array) != 0)
return 73;
if ((int)array.GetValue (0) != 0)
return 74;
array = new object[,] { { 11, 12, 13, 14 }, { 21, 22, 23, 24 } };
if (mono_test_marshal_safearray_in_byval_2dim_vt_i4 (array) != 0)
return 75;
if ((int)array.GetValue (new int[] { 0, 0 }) != 11)
return 76;
array = new object[,,] { { { "111", "112", "113" }, { "121", "122", "123" } }, { { "211", "212", "213" }, { "221", "222", "223" } } };
if (mono_test_marshal_safearray_in_byval_3dim_vt_bstr (array) != 0)
return 77;
if ((string)array.GetValue (new int[] { 0, 0, 0 }) != "111")
return 78;
array = new object[,,] { { { "111", "112", "113" }, { "121", "122", "123" } }, { { "211", "212", "213" }, { "221", "222", "223" } } };
if ((mono_test_marshal_safearray_in_byref_3dim_vt_bstr (ref array) != 0) || (array.Rank != 3) || (array.Length != 12))
return 79;
if ((string)array.GetValue (new int[] { 0, 0, 0 }) != "111")
return 80;
/* in, out, byref */
array = new object[] { };
if ((mono_test_marshal_safearray_in_out_byref_1dim_empty (ref array) != 0) || (array.Rank != 1) || (array.Length != 8))
return 81;
for (int i = 0; i < 8; ++i)
{
if (i != Convert.ToInt32 (array.GetValue (i)))
return 82;
}
array = new object[,,] { { { "111", "112", "113" }, { "121", "122", "123" } }, { { "211", "212", "213" }, { "221", "222", "223" } } };
if ((mono_test_marshal_safearray_in_out_byref_3dim_vt_bstr (ref array) != 0) || (array.Rank != 1) || (array.Length != 8))
return 83;
for (int i = 0; i < 8; ++i)
{
if (i != Convert.ToInt32 (array.GetValue (i)))
return 84;
}
array = new object[] { 1 };
if ((mono_test_marshal_safearray_in_out_byref_1dim_vt_i4 (ref array) != 0) || (array.Rank != 1) || (array.Length != 1))
{
return 85;
}
if (Convert.ToInt32 (array.GetValue (0)) != -1)
return 86;
/* in, out, byval */
array = new object[] { 1 };
if ((mono_test_marshal_safearray_in_out_byval_1dim_vt_i4 (array) != 0) || (array.Rank != 1) || (array.Length != 1))
{
return 87;
}
if (Convert.ToInt32 (array.GetValue (0)) != 12345)
return 88;
array = new object[,,] { { { "111", "112", "113" }, { "121", "122", "123" } }, { { "211", "212", "213" }, { "221", "222", "223" } } };
if ((mono_test_marshal_safearray_in_out_byval_3dim_vt_bstr (array) != 0) || (array.Rank != 3) || (array.Length != 12))
{
return 89;
}
if (Convert.ToInt32 (array.GetValue (new int[] { 1, 1, 1 })) != 111)
return 90;
if (Convert.ToInt32 (array.GetValue (new int[] { 1, 1, 2 })) != 333)
return 91;
if (Convert.ToString(array.GetValue (new int[] { 0, 1, 0 })) != "ABCDEFG")
return 92;
/* Multiple safearray parameters with various types and options */
Array array1 = new object[] { 1 };
Array array2 = new object[,] { { 11, 12, 13, 14 }, { 21, 22, 23, 24 } };
Array array3 = new object[] { 0, "1", 2, "3", 4, "5", 6, "7", 8, "9", 10, "11", 12 };
Array array4 = new object[,,] { { { "111", "112", "113" }, { "121", "122", "123" } }, { { "211", "212", "213" }, { "221", "222", "223" } } };
if ( (mono_test_marshal_safearray_mixed (array1, out array2, array3, ref array4) != 0)
|| (array1.Rank != 1) || (array1.Length != 1) || (Convert.ToInt32 (array1.GetValue (0)) != 12345)
|| (array2.Rank != 1) || (array2.Length != 10)
|| (array4.Rank != 1) || (array4.Length != 8)
)
{
return 93;
}
for (int i = 0; i < 10; ++i)
{
if (i != Convert.ToInt32 (array2.GetValue (i)))
return 94;
}
if ((int)array3.GetValue (0) != 0)
return 95;
for (int i = 0; i < 8; ++i)
{
if (i != Convert.ToInt32 (array4.GetValue (i)))
return 96;
}
}
#endregion // SafeArray Tests
#region COM Visible Test
TestVisible test_vis = new TestVisible();
IntPtr pDisp = Marshal.GetIDispatchForObject(test_vis);
if (pDisp == IntPtr.Zero)
return 200;
#endregion
}
return 0;
}
[ComImport ()]
[Guid ("00000000-0000-0000-0000-000000000001")]
[InterfaceType (ComInterfaceType.InterfaceIsIUnknown)]
public interface ITest
{
// properties need to go first since mcs puts them there
ITest Test
{
[return: MarshalAs (UnmanagedType.Interface)]
[MethodImpl (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId (5242884)]
get;
}
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SByteIn (sbyte val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void ByteIn (byte val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void ShortIn (short val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void UShortIn (ushort val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void IntIn (int val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void UIntIn (uint val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void LongIn (long val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void ULongIn (ulong val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void FloatIn (float val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void DoubleIn (double val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void ITestIn ([MarshalAs (UnmanagedType.Interface)]ITest val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void ITestOut ([MarshalAs (UnmanagedType.Interface)]out ITest val);
}
[ComImport ()]
[Guid ("00000000-0000-0000-0000-000000000001")]
[InterfaceType (ComInterfaceType.InterfaceIsIUnknown)]
public interface ITestPresSig
{
// properties need to go first since mcs puts them there
ITestPresSig Test
{
[return: MarshalAs (UnmanagedType.Interface)]
[MethodImpl (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId (5242884)]
get;
}
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
[PreserveSig ()]
int SByteIn (sbyte val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
[PreserveSig ()]
int ByteIn (byte val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
[PreserveSig ()]
int ShortIn (short val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
[PreserveSig ()]
int UShortIn (ushort val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
[PreserveSig ()]
int IntIn (int val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
[PreserveSig ()]
int UIntIn (uint val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
[PreserveSig ()]
int LongIn (long val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
[PreserveSig ()]
int ULongIn (ulong val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
[PreserveSig ()]
int FloatIn (float val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
[PreserveSig ()]
int DoubleIn (double val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
[PreserveSig ()]
int ITestIn ([MarshalAs (UnmanagedType.Interface)]ITestPresSig val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
[PreserveSig ()]
int ITestOut ([MarshalAs (UnmanagedType.Interface)]out ITestPresSig val);
}
[System.Runtime.InteropServices.GuidAttribute ("00000000-0000-0000-0000-000000000002")]
[System.Runtime.InteropServices.ComImportAttribute ()]
[System.Runtime.InteropServices.ClassInterfaceAttribute (ClassInterfaceType.None)]
public class _TestClass : ITest
{
// properties need to go first since mcs puts them there
public virtual extern ITest Test
{
[return: MarshalAs (UnmanagedType.Interface)]
[MethodImpl (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId (5242884)]
get;
}
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void SByteIn (sbyte val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void ByteIn (byte val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void ShortIn (short val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void UShortIn (ushort val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void IntIn (int val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void UIntIn (uint val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void LongIn (long val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void ULongIn (ulong val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void FloatIn (float val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void DoubleIn (double val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void ITestIn ([MarshalAs (UnmanagedType.Interface)]ITest val);
[MethodImplAttribute (MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void ITestOut ([MarshalAs (UnmanagedType.Interface)]out ITest val);
}
[System.Runtime.InteropServices.GuidAttribute ("00000000-0000-0000-0000-000000000002")]
public class TestClass : _TestClass
{
static TestClass ()
{
ExtensibleClassFactory.RegisterObjectCreationCallback (new ObjectCreationDelegate (CreateObject)); ;
}
private static System.IntPtr CreateObject (System.IntPtr aggr)
{
IntPtr pUnk3;
mono_test_marshal_com_object_create (out pUnk3);
return pUnk3;
}
}
[System.Runtime.InteropServices.GuidAttribute ("00000000-0000-0000-0000-000000000003")]
public class TestActivatorClass : _TestClass
{
static TestActivatorClass ()
{
ExtensibleClassFactory.RegisterObjectCreationCallback (new ObjectCreationDelegate (CreateObject)); ;
}
private static System.IntPtr CreateObject (System.IntPtr aggr)
{
IntPtr pUnk3;
mono_test_marshal_com_object_create (out pUnk3);
return pUnk3;
}
}
delegate void SByteInDelegate (sbyte val);
delegate void ByteInDelegate (byte val);
delegate void ShortInDelegate (short val);
delegate void UShortInDelegate (ushort val);
delegate void IntInDelegate (int val);
delegate void UIntInDelegate (uint val);
delegate void LongInDelegate (long val);
delegate void ULongInDelegate (ulong val);
delegate void FloatInDelegate (float val);
delegate void DoubleInDelegate (double val);
delegate void ITestInDelegate (ITest val);
delegate void ITestOutDelegate (out ITest val);
public class ManagedTestPresSig : ITestPresSig
{ // properties need to go first since mcs puts them there
public ITestPresSig Test
{
get
{
return new ManagedTestPresSig ();
}
}
public int SByteIn (sbyte val)
{
if (val != -100)
return 1;
return 0;
}
public int ByteIn (byte val)
{
if (val != 100)
return 2;
return 0;
}
public int ShortIn (short val)
{
if (val != -100)
return 3;
return 0;
}
public int UShortIn (ushort val)
{
if (val != 100)
return 4;
return 0;
}
public int IntIn (int val)
{
if (val != -100)
return 5;
return 0;
}
public int UIntIn (uint val)
{
if (val != 100)
return 6;
return 0;
}
public int LongIn (long val)
{
if (val != -100)
return 7;
return 0;
}
public int ULongIn (ulong val)
{
if (val != 100)
return 8;
return 0;
}
public int FloatIn (float val)
{
if (Math.Abs (val - 3.14f) > .000001)
return 9;
return 0;
}
public int DoubleIn (double val)
{
if (Math.Abs (val - 3.14f) > .000001)
return 10;
return 0;
}
public int ITestIn ([MarshalAs (UnmanagedType.Interface)]ITestPresSig val)
{
if (val == null)
return 11;
if (null == val as ManagedTestPresSig)
return 12;
return 0;
}
public int ITestOut ([MarshalAs (UnmanagedType.Interface)]out ITestPresSig val)
{
val = new ManagedTestPresSig ();
return 0;
}
}
public class ManagedTest : ITest
{
private int status = 0;
public int Status
{
get { return status; }
}
public void SByteIn (sbyte val)
{
if (val != -100)
status = 1;
}
public void ByteIn (byte val)
{
if (val != 100)
status = 2;
}
public void ShortIn (short val)
{
if (val != -100)
status = 3;
}
public void UShortIn (ushort val)
{
if (val != 100)
status = 4;
}
public void IntIn (int val)
{
if (val != -100)
status = 5;
}
public void UIntIn (uint val)
{
if (val != 100)
status = 6;
}
public void LongIn (long val)
{
if (val != -100)
status = 7;
}
public void ULongIn (ulong val)
{
if (val != 100)
status = 8;
}
public void FloatIn (float val)
{
if (Math.Abs (val - 3.14f) > .000001)
status = 9;
}
public void DoubleIn (double val)
{
if (Math.Abs (val - 3.14) > .000001)
status = 10;
}
public void ITestIn (ITest val)
{
if (val == null)
status = 11;
if (null == val as ManagedTest)
status = 12;
}
public void ITestOut (out ITest val)
{
val = new ManagedTest ();
}
public ITest Test
{
get
{
return new ManagedTest ();
}
}
}
public static int mono_test_marshal_variant_in_callback (VarEnum vt, object obj)
{
switch (vt)
{
case VarEnum.VT_I1:
if (obj.GetType () != typeof (sbyte))
return 1;
if ((sbyte)obj != -100)
return 2;
break;
case VarEnum.VT_UI1:
if (obj.GetType () != typeof (byte))
return 1;
if ((byte)obj != 100)
return 2;
break;
case VarEnum.VT_I2:
if (obj.GetType () != typeof (short))
return 1;
if ((short)obj != -100)
return 2;
break;
case VarEnum.VT_UI2:
if (obj.GetType () != typeof (ushort))
return 1;
if ((ushort)obj != 100)
return 2;
break;
case VarEnum.VT_I4:
if (obj.GetType () != typeof (int))
return 1;
if ((int)obj != -100)
return 2;
break;
case VarEnum.VT_UI4:
if (obj.GetType () != typeof (uint))
return 1;
if ((uint)obj != 100)
return 2;
break;
case VarEnum.VT_I8:
if (obj.GetType () != typeof (long))
return 1;
if ((long)obj != -100)
return 2;
break;
case VarEnum.VT_UI8:
if (obj.GetType () != typeof (ulong))
return 1;
if ((ulong)obj != 100)
return 2;
break;
case VarEnum.VT_R4:
if (obj.GetType () != typeof (float))
return 1;
if (Math.Abs ((float)obj - 3.14f) > 1e-10)
return 2;
break;
case VarEnum.VT_R8:
if (obj.GetType () != typeof (double))
return 1;
if (Math.Abs ((double)obj - 3.14) > 1e-10)
return 2;
break;
case VarEnum.VT_BSTR:
if (obj.GetType () != typeof (string))
return 1;
if ((string)obj != "PI")
return 2;
break;
case VarEnum.VT_BOOL:
if (obj.GetType () != typeof (bool))
return 1;
if ((bool)obj != true)
return 2;
break;
}
return 0;
}
public static int mono_test_marshal_variant_out_callback (VarEnum vt, ref object obj)
{
switch (vt) {
case VarEnum.VT_I1:
obj = (sbyte)-100;
break;
case VarEnum.VT_UI1:
obj = (byte)100;
break;
case VarEnum.VT_I2:
obj = (short)-100;
break;
case VarEnum.VT_UI2:
obj = (ushort)100;
break;
case VarEnum.VT_I4:
obj = (int)-100;
break;
case VarEnum.VT_UI4:
obj = (uint)100;
break;
case VarEnum.VT_I8:
obj = (long)-100;
break;
case VarEnum.VT_UI8:
obj = (ulong)100;
break;
case VarEnum.VT_R4:
obj = (float)3.14f;
break;
case VarEnum.VT_R8:
obj = (double)3.14;
break;
case VarEnum.VT_BSTR:
obj = "PI";
break;
case VarEnum.VT_BOOL:
obj = true;
break;
}
return 0;
}
public static int TestITest (ITest itest)
{
try {
ITest itest2;
itest.SByteIn (-100);
itest.ByteIn (100);
itest.ShortIn (-100);
itest.UShortIn (100);
itest.IntIn (-100);
itest.UIntIn (100);
itest.LongIn (-100);
itest.ULongIn (100);
itest.FloatIn (3.14f);
itest.DoubleIn (3.14);
itest.ITestIn (itest);
itest.ITestOut (out itest2);
}
catch (Exception ex) {
return 1;
}
return 0;
}
public static int TestITestPresSig (ITestPresSig itest)
{
ITestPresSig itest2;
if (itest.SByteIn (-100) != 0)
return 1000;
if (itest.ByteIn (100) != 0)
return 1001;
if (itest.ShortIn (-100) != 0)
return 1002;
if (itest.UShortIn (100) != 0)
return 1003;
if (itest.IntIn (-100) != 0)
return 1004;
if (itest.UIntIn (100) != 0)
return 1005;
if (itest.LongIn (-100) != 0)
return 1006;
if (itest.ULongIn (100) != 0)
return 1007;
if (itest.FloatIn (3.14f) != 0)
return 1008;
if (itest.DoubleIn (3.14) != 0)
return 1009;
if (itest.ITestIn (itest) != 0)
return 1010;
if (itest.ITestOut (out itest2) != 0)
return 1011;
return 0;
}
public static int TestITestDelegate (ITest itest)
{
try {
ITest itest2;
SByteInDelegate SByteInFcn= itest.SByteIn;
ByteInDelegate ByteInFcn = itest.ByteIn;
UShortInDelegate UShortInFcn = itest.UShortIn;
IntInDelegate IntInFcn = itest.IntIn;
UIntInDelegate UIntInFcn = itest.UIntIn;
LongInDelegate LongInFcn = itest.LongIn;
ULongInDelegate ULongInFcn = itest.ULongIn;
FloatInDelegate FloatInFcn = itest.FloatIn;
DoubleInDelegate DoubleInFcn = itest.DoubleIn;
ITestInDelegate ITestInFcn = itest.ITestIn;
ITestOutDelegate ITestOutFcn = itest.ITestOut;
SByteInFcn (-100);
ByteInFcn (100);
UShortInFcn (100);
IntInFcn (-100);
UIntInFcn (100);
LongInFcn (-100);
ULongInFcn (100);
FloatInFcn (3.14f);
DoubleInFcn (3.14);
ITestInFcn (itest);
ITestOutFcn (out itest2);
}
catch (Exception) {
return 1;
}
return 0;
}
}
public class TestVisible
{
}
| |
using System;
using UnityEngine;
namespace FMODUnity
{
public class EventNotFoundException : Exception
{
public Guid Guid;
public string Path;
public EventNotFoundException(string path)
: base("FMOD Studio event not found '" + path + "'")
{
Path = path;
}
public EventNotFoundException(Guid guid)
: base("FMOD Studio event not found " + guid.ToString("b") + "")
{
Guid = guid;
}
}
public class BusNotFoundException : Exception
{
public string Path;
public BusNotFoundException(string path)
: base("FMOD Studio bus not found '" + path + "'")
{
Path = path;
}
}
public class VCANotFoundException : Exception
{
public string Path;
public VCANotFoundException(string path)
: base("FMOD Studio VCA not found '" + path + "'")
{
Path = path;
}
}
public class BankLoadException : Exception
{
public string Path;
public FMOD.RESULT Result;
public BankLoadException(string path, FMOD.RESULT result)
: base(String.Format("FMOD Studio could not load bank '{0}' : {1} : {2}", path, result.ToString(), FMOD.Error.String(result)))
{
Path = path;
Result = result;
}
public BankLoadException(string path, string error)
: base(String.Format("FMOD Studio could not load bank '{0}' : ", path, error))
{
Path = path;
Result = FMOD.RESULT.ERR_INTERNAL;
}
}
public class SystemNotInitializedException : Exception
{
public FMOD.RESULT Result;
public string Location;
public SystemNotInitializedException(FMOD.RESULT result, string location)
: base(String.Format("FMOD Studio initialization failed : {2} : {0} : {1}", result.ToString(), FMOD.Error.String(result), location))
{
Result = result;
Location = location;
}
public SystemNotInitializedException(Exception inner)
: base("FMOD Studio initialization failed", inner)
{
}
}
public enum EmitterGameEvent
{
None,
LevelStart,
LevelEnd,
TriggerEnter,
TriggerExit,
CollisionEnter,
CollisionExit,
}
public enum LoaderGameEvent
{
None,
LevelStart,
LevelEnd,
TriggerEnter,
TriggerExit,
}
public static class RuntimeUtils
{
public const string LogFileName = "fmod.log";
public static void EnforceLibraryOrder()
{
#if UNITY_ANDROID && !UNITY_EDITOR
// First, obtain the current activity context
AndroidJavaObject activity = null;
using (var activityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
activity = activityClass.GetStatic<AndroidJavaObject>("currentActivity");
}
using (var fmodJava = new AndroidJavaClass("org.fmod.FMOD"))
{
if (fmodJava != null)
{
fmodJava.CallStatic("init", activity);
}
else
{
UnityEngine.Debug.LogWarning("FMOD Studio: Cannot initialiaze Java wrapper");
}
}
AndroidJavaClass jSystem = new AndroidJavaClass("java.lang.System");
jSystem.CallStatic("loadLibrary", FMOD.VERSION.dll);
jSystem.CallStatic("loadLibrary", FMOD.Studio.STUDIO_VERSION.dll);
#endif
#if !UNITY_IPHONE // iOS is statically linked
// Call a function in fmod.dll to make sure it's loaded before fmodstudio.dll
int temp1, temp2;
FMOD.Memory.GetStats(out temp1, out temp2);
Guid temp3;
FMOD.Studio.Util.ParseID("", out temp3);
#endif
}
public static FMOD.VECTOR ToFMODVector(this Vector3 vec)
{
FMOD.VECTOR temp;
temp.x = vec.x;
temp.y = vec.y;
temp.z = vec.z;
return temp;
}
public static FMOD.ATTRIBUTES_3D To3DAttributes(this Vector3 pos)
{
FMOD.ATTRIBUTES_3D attributes = new FMOD.ATTRIBUTES_3D();
attributes.forward = ToFMODVector(Vector3.forward);
attributes.up = ToFMODVector(Vector3.up);
attributes.position = ToFMODVector(pos);
return attributes;
}
public static FMOD.ATTRIBUTES_3D To3DAttributes(this Transform transform)
{
FMOD.ATTRIBUTES_3D attributes = new FMOD.ATTRIBUTES_3D();
attributes.forward = transform.forward.ToFMODVector();
attributes.up = transform.up.ToFMODVector();
attributes.position = transform.position.ToFMODVector();
return attributes;
}
public static FMOD.ATTRIBUTES_3D To3DAttributes(GameObject go, Rigidbody rigidbody = null)
{
FMOD.ATTRIBUTES_3D attributes = go.transform.To3DAttributes();
if (rigidbody)
{
attributes.velocity = rigidbody.velocity.ToFMODVector();
}
return attributes;
}
public static FMODPlatform GetCurrentPlatform()
{
#if UNITY_EDITOR
return FMODPlatform.PlayInEditor;
#elif UNITY_STANDALONE_WIN
return FMODPlatform.Windows;
#elif UNITY_STANDALONE_OSX
return FMODPlatform.Mac;
#elif UNITY_STANDALONE_LINUX
return FMODPlatform.Linux;
#elif UNITY_IOS
FMODPlatform result;
switch (UnityEngine.iOS.Device.generation)
{
case UnityEngine.iOS.DeviceGeneration.iPhone5:
case UnityEngine.iOS.DeviceGeneration.iPhone5C:
case UnityEngine.iOS.DeviceGeneration.iPhone5S:
case UnityEngine.iOS.DeviceGeneration.iPadAir1:
case UnityEngine.iOS.DeviceGeneration.iPadMini2Gen:
case UnityEngine.iOS.DeviceGeneration.iPhone6:
case UnityEngine.iOS.DeviceGeneration.iPhone6Plus:
case UnityEngine.iOS.DeviceGeneration.iPadMini3Gen:
case UnityEngine.iOS.DeviceGeneration.iPadAir2:
result = FMODPlatform.MobileHigh;
break;
default:
result = FMODPlatform.MobileLow;
break;
}
UnityEngine.Debug.Log(String.Format("FMOD Studio: Device {0} classed as {1}", SystemInfo.deviceModel, result.ToString()));
return result;
#elif UNITY_ANDROID
FMODPlatform result;
if (SystemInfo.processorCount <= 2)
{
result = FMODPlatform.MobileLow;
}
else if (SystemInfo.processorCount >= 8)
{
result = FMODPlatform.MobileHigh;
}
else
{
// check the clock rate on quad core systems
string freqinfo = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq";
using(global::System.IO.TextReader reader = new global::System.IO.StreamReader(freqinfo))
{
try
{
string line = reader.ReadLine();
int khz = Int32.Parse(line) / 1000;
if (khz >= 1600)
{
result = FMODPlatform.MobileHigh;
}
else
{
result = FMODPlatform.MobileLow;
}
}
catch
{
// Assume worst case
result = FMODPlatform.MobileLow;
}
}
}
UnityEngine.Debug.Log(String.Format("FMOD Studio: Device {0} classed as {1}", SystemInfo.deviceModel, result.ToString()));
return result;
#elif UNITY_WINRT_8_1
FMODPlatform result;
if (SystemInfo.processorCount <= 2)
{
result = FMODPlatform.MobileLow;
}
else
{
result = FMODPlatform.MobileHigh;
}
UnityEngine.Debug.Log(String.Format("FMOD Studio: Device {0} classed as {1}", SystemInfo.deviceModel, result.ToString()));
return result;
#elif UNITY_PS4
return FMODPlatform.PS4;
#elif UNITY_XBOXONE
return FMODPlatform.XboxOne;
#elif UNITY_PSP2
return FMODPlatform.PSVita;
#elif UNITY_WIIU
return FMODPlatform.WiiU;
#endif
}
const string BankExtension = ".bank";
public static string GetBankPath(string bankName)
{
#if UNITY_EDITOR
// For play in editor use original asset location because streaming asset folder will contain platform specific banks
string bankFolder = Settings.Instance.SourceBankPath;
if (Settings.Instance.HasPlatforms)
{
bankFolder = global::System.IO.Path.Combine(bankFolder, Settings.Instance.GetBankPlatform(FMODPlatform.PlayInEditor));
}
#elif UNITY_ANDROID
string bankFolder = null;
if (System.IO.Path.GetExtension(Application.dataPath) == ".apk")
{
bankFolder = "file:///android_asset";
}
else
{
bankFolder = String.Format("jar:file://{0}!/assets", Application.dataPath);
}
#elif UNITY_WINRT_8_1
string bankFolder = "ms-appx:///Data/StreamingAssets";
#else
string bankFolder = Application.streamingAssetsPath;
#endif
if (System.IO.Path.GetExtension(bankName) != BankExtension)
{
return String.Format("{0}/{1}.bank", bankFolder, bankName);
}
else
{
return String.Format("{0}/{1}", bankFolder, bankName);
}
}
public static string GetPluginPath(string pluginName)
{
#if UNITY_IOS
return "";
#else
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_XBOXONE || UNITY_WINRT_8_1
string pluginFileName = pluginName + ".dll";
#elif UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX
string pluginFileName = pluginName + ".bundle";
#elif UNITY_PS4
string pluginFileName = pluginName + ".prx"
#elif UNITY_ANDROID || UNITY_STANDALONE_LINUX
string pluginFileName = "lib" + pluginName + ".so";
#endif
#if UNITY_EDITOR_WIN && UNITY_EDITOR_64
string pluginFolder = Application.dataPath + "/Plugins/X86_64/";
#elif UNITY_EDITOR_WIN
string pluginFolder = Application.dataPath + "/Plugins/X86/";
#elif UNITY_STANDALONE_WIN || UNITY_PS4 || UNITY_XBOXONE || UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX || UNITY_STANDALONE_LINUX
string pluginFolder = Application.dataPath + "/Plugins/";
#elif UNITY_WINRT_8_1
string pluginFolder = "";
#elif UNITY_ANDROID
var dirInfo = new global::System.IO.DirectoryInfo(Application.persistentDataPath);
string packageName = dirInfo.Parent.Name;
string pluginFolder = "/data/data/" + packageName + "/lib/";
#else
string pluginFolder = "";
#endif
return pluginFolder + pluginFileName;
#endif
}
}
}
| |
using System;
using System.Collections.Generic;
using Monoamp.Common.system.io;
using Monoamp.Boundary;
namespace Monoamp.Common.Data.Standard.Riff
{
public abstract class RiffChunkList : RiffChunk
{
public abstract Dictionary<string, Dictionary<string, Type>> ChunkTypeDictionaryDictionary{ get; }
public readonly List<RiffChunk> chunkList;
public readonly Dictionary<string, List<RiffChunkList>> listListDictionary;
public string type;
public override UInt32 Size
{
get{ return GetSize(); }
protected set{ base.Size = value; }
}
private UInt32 GetSize()
{
UInt32 _size = 4;
foreach( RiffChunk lChunk in chunkList )
{
_size += lChunk.Size + 8;
}
return _size;
}
protected RiffChunkList( string aId, UInt32 aSize, AByteArray aByteArray, RiffChunkList aParent )
: base( aId, aSize, aByteArray, aParent )
{
chunkList = new List<RiffChunk>();
listListDictionary = new Dictionary<string, List<RiffChunkList>>();
type = aByteArray.ReadString( 4 );
try
{
while( aByteArray.Position < position + aSize - 4 )
{
ReadChunk( aByteArray );
}
}
catch( Exception aExpection )
{
Logger.Error( "Expection at RIFF Read:" + aExpection.ToString() );
}
aByteArray.SetPosition( ( int )( position + aSize ) );
}
private void ReadChunk( AByteArray aByteArray )
{
string lId = aByteArray.ReadString( 4 );
UInt32 lSize = aByteArray.ReadUInt32();
int lPositionStart = aByteArray.Position;
// Check Padding.
if( lSize % 2 == 1 )
{
if( lPositionStart + lSize <= aByteArray.Length && aByteArray.ReadByte( ( int )( lPositionStart + lSize ) ) == 0x00 )
{
lSize++;
Logger.Debug( "Padding:" + lSize );
}
aByteArray.SetPosition( lPositionStart );
}
RiffChunk lRiffWave = Construct( lId, lSize, aByteArray, this );
chunkList.Add( lRiffWave );
if( aByteArray.Position != lPositionStart + lSize )
{
Logger.Debug( "Modify Position:" + aByteArray.Position + "->" + ( lPositionStart + lSize ) );
aByteArray.SetPosition( ( int )( lPositionStart + lSize ) );
}
}
public RiffChunk Construct( string aId, UInt32 aSize, AByteArray aByteArray, RiffChunkList aParent )
{
Type[] lArgumentTypes = { typeof( string ), typeof( UInt32 ), typeof( AByteArray ), typeof( RiffChunkList ) };
object[] lArguments = { aId, aSize, aByteArray, aParent };
Type lTypeChunk = typeof( RiffUnknown );
if( ChunkTypeDictionaryDictionary.ContainsKey( type ) == true )
{
if( ChunkTypeDictionaryDictionary[type].ContainsKey( aId ) == true )
{
lTypeChunk = ChunkTypeDictionaryDictionary[type][aId];
}
}
if( lTypeChunk == typeof( RiffUnknown ) )
{
Logger.Debug( "Unknown:" + type + "," + aId );
}
else
{
Logger.Debug( "known:" + type + "," + aId );
}
return ( RiffChunk )lTypeChunk.GetConstructor( lArgumentTypes ).Invoke( lArguments );
}
public override void WriteByteArray( AByteArray aByteArrayRead, AByteArray aByteArray )
{
for( int i = 0; i < id.Length; i++ )
{
aByteArray.WriteUByte( ( Byte )id[i] );
}
aByteArray.WriteUInt32( ( UInt32 )Size );
for( int i = 0; i < type.Length; i++ )
{
aByteArray.WriteUByte( ( Byte )type[i] );
}
foreach( RiffChunk lChunk in chunkList )
{
lChunk.WriteByteArray( aByteArrayRead, aByteArray );
}
}
public void OverrideChunk( RiffChunk aChunk )
{
for( int i = 0; i < chunkList.Count; i++ )
{
if( chunkList[i].id == aChunk.id )
{
chunkList[i] = aChunk;
return;
}
}
}
public RiffChunk GetChunk( string aId )
{
for( int i = 0; i < chunkList.Count; i++ )
{
if( chunkList[i].id == aId )
{
return chunkList[i];
}
}
return null;
}
protected List<RiffChunkList> GetChunkListList( string aId, string aType )
{
if( listListDictionary.ContainsKey( aType ) == true ) {
return listListDictionary[aType];
}
List<RiffChunkList> lListList = new List<RiffChunkList>();
for( int i = 0; i < chunkList.Count; i++ )
{
if( chunkList[i].id == aId) {
RiffChunkList lRiffList = ( RiffChunkList )chunkList[i];
if( lRiffList.type == aType ) {
lListList.Add( ( RiffChunkList )chunkList[i] );
}
}
}
listListDictionary.Add( aType, lListList );
return listListDictionary[aType];
}
protected RiffChunkList GetChunkList( string aId, string aType )
{
if( listListDictionary.ContainsKey( aType ) == true )
{
return listListDictionary[aType][0];
}
List<RiffChunkList> lListList = new List<RiffChunkList>();
for( int i = 0; i < chunkList.Count; i++ )
{
if( chunkList[i].id == aId )
{
RiffChunkList lRiffList = ( RiffChunkList )chunkList[i];
if( lRiffList.type == aType )
{
lListList.Add( ( RiffChunkList )chunkList[i] );
}
}
}
listListDictionary.Add( aType, lListList );
if( listListDictionary[aType].Count < 1 )
{
Logger.Error( "List is not exist." );
}
else if( listListDictionary[aType].Count > 1 )
{
Logger.Error( "List exist more than 1." );
}
return listListDictionary[aType][0];
}
public void AddChunk( RiffChunk aRiffWave )
{
chunkList.Add( aRiffWave );
}
}
}
| |
using Lucene.Net.Attributes;
using Lucene.Net.Documents;
using Lucene.Net.Randomized.Generators;
using Lucene.Net.Support;
using Lucene.Net.Support.Threading;
using Lucene.Net.Util;
using NUnit.Framework;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Console = Lucene.Net.Support.SystemConsole;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using BytesRef = Lucene.Net.Util.BytesRef;
using Codec = Lucene.Net.Codecs.Codec;
using Directory = Lucene.Net.Store.Directory;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using Document = Documents.Document;
using FakeIOException = Lucene.Net.Store.MockDirectoryWrapper.FakeIOException;
using Field = Field;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
using InfoStream = Lucene.Net.Util.InfoStream;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper;
using Query = Lucene.Net.Search.Query;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using TermQuery = Lucene.Net.Search.TermQuery;
using TestUtil = Lucene.Net.Util.TestUtil;
using TextField = TextField;
using TopDocs = Lucene.Net.Search.TopDocs;
[TestFixture]
public class TestIndexWriterReader : LuceneTestCase
{
private readonly int NumThreads = TEST_NIGHTLY ? 5 : 3;
public static int Count(Term t, IndexReader r)
{
int count = 0;
DocsEnum td = TestUtil.Docs(Random(), r, t.Field, new BytesRef(t.Text()), MultiFields.GetLiveDocs(r), null, 0);
if (td != null)
{
while (td.NextDoc() != DocIdSetIterator.NO_MORE_DOCS)
{
var _ = td.DocID;
count++;
}
}
return count;
}
[Test]
public virtual void TestAddCloseOpen()
{
// Can't use assertNoDeletes: this test pulls a non-NRT
// reader in the end:
Directory dir1 = NewDirectory();
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
IndexWriter writer = new IndexWriter(dir1, iwc);
for (int i = 0; i < 97; i++)
{
DirectoryReader reader = writer.GetReader();
if (i == 0)
{
writer.AddDocument(DocHelper.CreateDocument(i, "x", 1 + Random().Next(5)));
}
else
{
int previous = Random().Next(i);
// a check if the reader is current here could fail since there might be
// merges going on.
switch (Random().Next(5))
{
case 0:
case 1:
case 2:
writer.AddDocument(DocHelper.CreateDocument(i, "x", 1 + Random().Next(5)));
break;
case 3:
writer.UpdateDocument(new Term("id", "" + previous), DocHelper.CreateDocument(previous, "x", 1 + Random().Next(5)));
break;
case 4:
writer.DeleteDocuments(new Term("id", "" + previous));
break;
}
}
Assert.IsFalse(reader.IsCurrent());
reader.Dispose();
}
writer.ForceMerge(1); // make sure all merging is done etc.
DirectoryReader dirReader = writer.GetReader();
writer.Commit(); // no changes that are not visible to the reader
Assert.IsTrue(dirReader.IsCurrent());
writer.Dispose();
Assert.IsTrue(dirReader.IsCurrent()); // all changes are visible to the reader
iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
writer = new IndexWriter(dir1, iwc);
Assert.IsTrue(dirReader.IsCurrent());
writer.AddDocument(DocHelper.CreateDocument(1, "x", 1 + Random().Next(5)));
Assert.IsTrue(dirReader.IsCurrent()); // segments in ram but IW is different to the readers one
writer.Dispose();
Assert.IsFalse(dirReader.IsCurrent()); // segments written
dirReader.Dispose();
dir1.Dispose();
}
[Test]
public virtual void TestUpdateDocument()
{
bool doFullMerge = true;
Directory dir1 = NewDirectory();
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
if (iwc.MaxBufferedDocs < 20)
{
iwc.SetMaxBufferedDocs(20);
}
// no merging
if (Random().NextBoolean())
{
iwc.SetMergePolicy(NoMergePolicy.NO_COMPOUND_FILES);
}
else
{
iwc.SetMergePolicy(NoMergePolicy.COMPOUND_FILES);
}
if (VERBOSE)
{
Console.WriteLine("TEST: make index");
}
IndexWriter writer = new IndexWriter(dir1, iwc);
// create the index
CreateIndexNoClose(!doFullMerge, "index1", writer);
// writer.Flush(false, true, true);
// get a reader
DirectoryReader r1 = writer.GetReader();
Assert.IsTrue(r1.IsCurrent());
string id10 = r1.Document(10).GetField("id").GetStringValue();
Document newDoc = r1.Document(10);
newDoc.RemoveField("id");
newDoc.Add(NewStringField("id", Convert.ToString(8000), Field.Store.YES));
writer.UpdateDocument(new Term("id", id10), newDoc);
Assert.IsFalse(r1.IsCurrent());
DirectoryReader r2 = writer.GetReader();
Assert.IsTrue(r2.IsCurrent());
Assert.AreEqual(0, Count(new Term("id", id10), r2));
if (VERBOSE)
{
Console.WriteLine("TEST: verify id");
}
Assert.AreEqual(1, Count(new Term("id", Convert.ToString(8000)), r2));
r1.Dispose();
Assert.IsTrue(r2.IsCurrent());
writer.Dispose();
Assert.IsTrue(r2.IsCurrent());
DirectoryReader r3 = DirectoryReader.Open(dir1);
Assert.IsTrue(r3.IsCurrent());
Assert.IsTrue(r2.IsCurrent());
Assert.AreEqual(0, Count(new Term("id", id10), r3));
Assert.AreEqual(1, Count(new Term("id", Convert.ToString(8000)), r3));
writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
Document doc = new Document();
doc.Add(NewTextField("field", "a b c", Field.Store.NO));
writer.AddDocument(doc);
Assert.IsTrue(r2.IsCurrent());
Assert.IsTrue(r3.IsCurrent());
writer.Dispose();
Assert.IsFalse(r2.IsCurrent());
Assert.IsTrue(!r3.IsCurrent());
r2.Dispose();
r3.Dispose();
dir1.Dispose();
}
[Test]
public virtual void TestIsCurrent()
{
Directory dir = NewDirectory();
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
IndexWriter writer = new IndexWriter(dir, iwc);
Document doc = new Document();
doc.Add(NewTextField("field", "a b c", Field.Store.NO));
writer.AddDocument(doc);
writer.Dispose();
iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
writer = new IndexWriter(dir, iwc);
doc = new Document();
doc.Add(NewTextField("field", "a b c", Field.Store.NO));
DirectoryReader nrtReader = writer.GetReader();
Assert.IsTrue(nrtReader.IsCurrent());
writer.AddDocument(doc);
Assert.IsFalse(nrtReader.IsCurrent()); // should see the changes
writer.ForceMerge(1); // make sure we don't have a merge going on
Assert.IsFalse(nrtReader.IsCurrent());
nrtReader.Dispose();
DirectoryReader dirReader = DirectoryReader.Open(dir);
nrtReader = writer.GetReader();
Assert.IsTrue(dirReader.IsCurrent());
Assert.IsTrue(nrtReader.IsCurrent()); // nothing was committed yet so we are still current
Assert.AreEqual(2, nrtReader.MaxDoc); // sees the actual document added
Assert.AreEqual(1, dirReader.MaxDoc);
writer.Dispose(); // close is actually a commit both should see the changes
Assert.IsTrue(nrtReader.IsCurrent());
Assert.IsFalse(dirReader.IsCurrent()); // this reader has been opened before the writer was closed / committed
dirReader.Dispose();
nrtReader.Dispose();
dir.Dispose();
}
/// <summary>
/// Test using IW.addIndexes
/// </summary>
[Test]
public virtual void TestAddIndexes()
{
bool doFullMerge = false;
Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory());
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
if (iwc.MaxBufferedDocs < 20)
{
iwc.SetMaxBufferedDocs(20);
}
// no merging
if (Random().NextBoolean())
{
iwc.SetMergePolicy(NoMergePolicy.NO_COMPOUND_FILES);
}
else
{
iwc.SetMergePolicy(NoMergePolicy.COMPOUND_FILES);
}
IndexWriter writer = new IndexWriter(dir1, iwc);
// create the index
CreateIndexNoClose(!doFullMerge, "index1", writer);
writer.Flush(false, true);
// create a 2nd index
Directory dir2 = NewDirectory();
IndexWriter writer2 = new IndexWriter(dir2, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
CreateIndexNoClose(!doFullMerge, "index2", writer2);
writer2.Dispose();
DirectoryReader r0 = writer.GetReader();
Assert.IsTrue(r0.IsCurrent());
writer.AddIndexes(dir2);
Assert.IsFalse(r0.IsCurrent());
r0.Dispose();
DirectoryReader r1 = writer.GetReader();
Assert.IsTrue(r1.IsCurrent());
writer.Commit();
Assert.IsTrue(r1.IsCurrent()); // we have seen all changes - no change after opening the NRT reader
Assert.AreEqual(200, r1.MaxDoc);
int index2df = r1.DocFreq(new Term("indexname", "index2"));
Assert.AreEqual(100, index2df);
// verify the docs are from different indexes
Document doc5 = r1.Document(5);
Assert.AreEqual("index1", doc5.Get("indexname"));
Document doc150 = r1.Document(150);
Assert.AreEqual("index2", doc150.Get("indexname"));
r1.Dispose();
writer.Dispose();
dir1.Dispose();
dir2.Dispose();
}
[Test]
public virtual void ExposeCompTermVR()
{
bool doFullMerge = false;
Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory());
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
if (iwc.MaxBufferedDocs < 20)
{
iwc.SetMaxBufferedDocs(20);
}
// no merging
if (Random().NextBoolean())
{
iwc.SetMergePolicy(NoMergePolicy.NO_COMPOUND_FILES);
}
else
{
iwc.SetMergePolicy(NoMergePolicy.COMPOUND_FILES);
}
IndexWriter writer = new IndexWriter(dir1, iwc);
CreateIndexNoClose(!doFullMerge, "index1", writer);
writer.Dispose();
dir1.Dispose();
}
[Test]
public virtual void TestAddIndexes2()
{
bool doFullMerge = false;
Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory());
IndexWriter writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
// create a 2nd index
Directory dir2 = NewDirectory();
IndexWriter writer2 = new IndexWriter(dir2, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
CreateIndexNoClose(!doFullMerge, "index2", writer2);
writer2.Dispose();
writer.AddIndexes(dir2);
writer.AddIndexes(dir2);
writer.AddIndexes(dir2);
writer.AddIndexes(dir2);
writer.AddIndexes(dir2);
IndexReader r1 = writer.GetReader();
Assert.AreEqual(500, r1.MaxDoc);
r1.Dispose();
writer.Dispose();
dir1.Dispose();
dir2.Dispose();
}
/// <summary>
/// Deletes using IW.deleteDocuments
/// </summary>
[Test]
public virtual void TestDeleteFromIndexWriter()
{
bool doFullMerge = true;
Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory());
IndexWriter writer = new IndexWriter(dir1, (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetReaderTermsIndexDivisor(2));
// create the index
CreateIndexNoClose(!doFullMerge, "index1", writer);
writer.Flush(false, true);
// get a reader
IndexReader r1 = writer.GetReader();
string id10 = r1.Document(10).GetField("id").GetStringValue();
// deleted IW docs should not show up in the next getReader
writer.DeleteDocuments(new Term("id", id10));
IndexReader r2 = writer.GetReader();
Assert.AreEqual(1, Count(new Term("id", id10), r1));
Assert.AreEqual(0, Count(new Term("id", id10), r2));
string id50 = r1.Document(50).GetField("id").GetStringValue();
Assert.AreEqual(1, Count(new Term("id", id50), r1));
writer.DeleteDocuments(new Term("id", id50));
IndexReader r3 = writer.GetReader();
Assert.AreEqual(0, Count(new Term("id", id10), r3));
Assert.AreEqual(0, Count(new Term("id", id50), r3));
string id75 = r1.Document(75).GetField("id").GetStringValue();
writer.DeleteDocuments(new TermQuery(new Term("id", id75)));
IndexReader r4 = writer.GetReader();
Assert.AreEqual(1, Count(new Term("id", id75), r3));
Assert.AreEqual(0, Count(new Term("id", id75), r4));
r1.Dispose();
r2.Dispose();
r3.Dispose();
r4.Dispose();
writer.Dispose();
// reopen the writer to verify the delete made it to the directory
writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
IndexReader w2r1 = writer.GetReader();
Assert.AreEqual(0, Count(new Term("id", id10), w2r1));
w2r1.Dispose();
writer.Dispose();
dir1.Dispose();
}
[Test, LongRunningTest]
public virtual void TestAddIndexesAndDoDeletesThreads()
{
const int numIter = 2;
int numDirs = 3;
Directory mainDir = GetAssertNoDeletesDirectory(NewDirectory());
IndexWriter mainWriter = new IndexWriter(mainDir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy()));
TestUtil.ReduceOpenFiles(mainWriter);
AddDirectoriesThreads addDirThreads = new AddDirectoriesThreads(this, numIter, mainWriter);
addDirThreads.LaunchThreads(numDirs);
addDirThreads.JoinThreads();
//Assert.AreEqual(100 + numDirs * (3 * numIter / 4) * addDirThreads.numThreads
// * addDirThreads.NUM_INIT_DOCS, addDirThreads.mainWriter.NumDocs);
Assert.AreEqual(addDirThreads.Count.Get(), addDirThreads.MainWriter.NumDocs);
addDirThreads.Close(true);
Assert.IsTrue(addDirThreads.Failures.Count == 0);
TestUtil.CheckIndex(mainDir);
IndexReader reader = DirectoryReader.Open(mainDir);
Assert.AreEqual(addDirThreads.Count.Get(), reader.NumDocs);
//Assert.AreEqual(100 + numDirs * (3 * numIter / 4) * addDirThreads.numThreads
// * addDirThreads.NUM_INIT_DOCS, reader.NumDocs);
reader.Dispose();
addDirThreads.CloseDir();
mainDir.Dispose();
}
private class AddDirectoriesThreads
{
internal virtual void InitializeInstanceFields()
{
Threads = new ThreadClass[OuterInstance.NumThreads];
}
private readonly TestIndexWriterReader OuterInstance;
internal Directory AddDir;
internal const int NUM_INIT_DOCS = 100;
internal int NumDirs;
internal ThreadClass[] Threads;
internal IndexWriter MainWriter;
internal readonly IList<Exception> Failures = new List<Exception>();
internal IndexReader[] Readers;
internal bool DidClose = false;
internal AtomicInt32 Count = new AtomicInt32(0);
internal AtomicInt32 NumaddIndexes = new AtomicInt32(0);
public AddDirectoriesThreads(TestIndexWriterReader outerInstance, int numDirs, IndexWriter mainWriter)
{
this.OuterInstance = outerInstance;
InitializeInstanceFields();
this.NumDirs = numDirs;
this.MainWriter = mainWriter;
AddDir = NewDirectory();
IndexWriter writer = new IndexWriter(AddDir, OuterInstance.NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2));
TestUtil.ReduceOpenFiles(writer);
for (int i = 0; i < NUM_INIT_DOCS; i++)
{
Document doc = DocHelper.CreateDocument(i, "addindex", 4);
writer.AddDocument(doc);
}
writer.Dispose();
Readers = new IndexReader[numDirs];
for (int i = 0; i < numDirs; i++)
{
Readers[i] = DirectoryReader.Open(AddDir);
}
}
internal virtual void JoinThreads()
{
for (int i = 0; i < OuterInstance.NumThreads; i++)
{
//#if !NETSTANDARD1_6
// try
// {
//#endif
Threads[i].Join();
//#if !NETSTANDARD1_6
// }
// catch (ThreadInterruptedException ie) // LUCENENET NOTE: Senseless to catch and rethrow the same exception type
// {
// throw new ThreadInterruptedException("Thread Interrupted Exception", ie);
// }
//#endif
}
}
internal virtual void Close(bool doWait)
{
DidClose = true;
if (doWait)
{
MainWriter.WaitForMerges();
}
MainWriter.Dispose(doWait);
}
internal virtual void CloseDir()
{
for (int i = 0; i < NumDirs; i++)
{
Readers[i].Dispose();
}
AddDir.Dispose();
}
internal virtual void Handle(Exception t)
{
Console.WriteLine(t.StackTrace);
lock (Failures)
{
Failures.Add(t);
}
}
internal virtual void LaunchThreads(int numIter)
{
for (int i = 0; i < OuterInstance.NumThreads; i++)
{
Threads[i] = new ThreadAnonymousInnerClassHelper(this, numIter);
}
for (int i = 0; i < OuterInstance.NumThreads; i++)
{
Threads[i].Start();
}
}
private class ThreadAnonymousInnerClassHelper : ThreadClass
{
private readonly AddDirectoriesThreads OuterInstance;
private int NumIter;
public ThreadAnonymousInnerClassHelper(AddDirectoriesThreads outerInstance, int numIter)
{
this.OuterInstance = outerInstance;
this.NumIter = numIter;
}
public override void Run()
{
try
{
Directory[] dirs = new Directory[OuterInstance.NumDirs];
for (int k = 0; k < OuterInstance.NumDirs; k++)
{
dirs[k] = new MockDirectoryWrapper(Random(), new RAMDirectory(OuterInstance.AddDir, NewIOContext(Random())));
}
//int j = 0;
//while (true) {
// System.out.println(Thread.currentThread().getName() + ": iter
// j=" + j);
for (int x = 0; x < NumIter; x++)
{
// only do addIndexes
OuterInstance.DoBody(x, dirs);
}
//if (numIter > 0 && j == numIter)
// break;
//doBody(j++, dirs);
//doBody(5, dirs);
//}
}
catch (Exception t)
{
OuterInstance.Handle(t);
}
}
}
internal virtual void DoBody(int j, Directory[] dirs)
{
switch (j % 4)
{
case 0:
MainWriter.AddIndexes(dirs);
MainWriter.ForceMerge(1);
break;
case 1:
MainWriter.AddIndexes(dirs);
NumaddIndexes.IncrementAndGet();
break;
case 2:
MainWriter.AddIndexes(Readers);
break;
case 3:
MainWriter.Commit();
break;
}
Count.AddAndGet(dirs.Length * NUM_INIT_DOCS);
}
}
[Test]
public virtual void TestIndexWriterReopenSegmentFullMerge()
{
DoTestIndexWriterReopenSegment(true);
}
[Test]
public virtual void TestIndexWriterReopenSegment()
{
DoTestIndexWriterReopenSegment(false);
}
/// <summary>
/// Tests creating a segment, then check to insure the segment can be seen via
/// IW.getReader
/// </summary>
public virtual void DoTestIndexWriterReopenSegment(bool doFullMerge)
{
Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory());
IndexWriter writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
IndexReader r1 = writer.GetReader();
Assert.AreEqual(0, r1.MaxDoc);
CreateIndexNoClose(false, "index1", writer);
writer.Flush(!doFullMerge, true);
IndexReader iwr1 = writer.GetReader();
Assert.AreEqual(100, iwr1.MaxDoc);
IndexReader r2 = writer.GetReader();
Assert.AreEqual(r2.MaxDoc, 100);
// add 100 documents
for (int x = 10000; x < 10000 + 100; x++)
{
Document d = DocHelper.CreateDocument(x, "index1", 5);
writer.AddDocument(d);
}
writer.Flush(false, true);
// verify the reader was reopened internally
IndexReader iwr2 = writer.GetReader();
Assert.IsTrue(iwr2 != r1);
Assert.AreEqual(200, iwr2.MaxDoc);
// should have flushed out a segment
IndexReader r3 = writer.GetReader();
Assert.IsTrue(r2 != r3);
Assert.AreEqual(200, r3.MaxDoc);
// dec ref the readers rather than close them because
// closing flushes changes to the writer
r1.Dispose();
iwr1.Dispose();
r2.Dispose();
r3.Dispose();
iwr2.Dispose();
writer.Dispose();
// test whether the changes made it to the directory
writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
IndexReader w2r1 = writer.GetReader();
// insure the deletes were actually flushed to the directory
Assert.AreEqual(200, w2r1.MaxDoc);
w2r1.Dispose();
writer.Dispose();
dir1.Dispose();
}
/*
* Delete a document by term and return the doc id
*
* public static int deleteDocument(Term term, IndexWriter writer) throws
* IOException { IndexReader reader = writer.GetReader(); TermDocs td =
* reader.termDocs(term); int doc = -1; //if (td.Next()) { // doc = td.Doc();
* //} //writer.DeleteDocuments(term); td.Dispose(); return doc; }
*/
public void CreateIndex(Random random, Directory dir1, string indexName, bool multiSegment)
{
IndexWriter w = new IndexWriter(dir1, NewIndexWriterConfig(random, TEST_VERSION_CURRENT, new MockAnalyzer(random)).SetMergePolicy(new LogDocMergePolicy()));
for (int i = 0; i < 100; i++)
{
w.AddDocument(DocHelper.CreateDocument(i, indexName, 4));
}
if (!multiSegment)
{
w.ForceMerge(1);
}
w.Dispose();
}
public static void CreateIndexNoClose(bool multiSegment, string indexName, IndexWriter w)
{
for (int i = 0; i < 100; i++)
{
w.AddDocument(DocHelper.CreateDocument(i, indexName, 4));
}
if (!multiSegment)
{
w.ForceMerge(1);
}
}
private class MyWarmer : IndexWriter.IndexReaderWarmer
{
internal int WarmCount;
public override void Warm(AtomicReader reader)
{
WarmCount++;
}
}
[Test, LongRunningTest]
public virtual void TestMergeWarmer([ValueSource(typeof(ConcurrentMergeSchedulerFactories), "Values")]Func<IConcurrentMergeScheduler> newScheduler)
{
Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory());
// Enroll warmer
MyWarmer warmer = new MyWarmer();
var config = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))
.SetMaxBufferedDocs(2)
.SetMergedSegmentWarmer(warmer)
.SetMergeScheduler(newScheduler())
.SetMergePolicy(NewLogMergePolicy());
IndexWriter writer = new IndexWriter(dir1, config);
// create the index
CreateIndexNoClose(false, "test", writer);
// get a reader to put writer into near real-time mode
IndexReader r1 = writer.GetReader();
((LogMergePolicy)writer.Config.MergePolicy).MergeFactor = 2;
//int num = AtLeast(100);
int num = 101;
for (int i = 0; i < num; i++)
{
writer.AddDocument(DocHelper.CreateDocument(i, "test", 4));
}
((IConcurrentMergeScheduler)writer.Config.MergeScheduler).Sync();
Assert.IsTrue(warmer.WarmCount > 0);
Console.WriteLine("Count {0}", warmer.WarmCount);
int count = warmer.WarmCount;
var newDocument = DocHelper.CreateDocument(17, "test", 4);
writer.AddDocument(newDocument);
writer.ForceMerge(1);
Assert.IsTrue(warmer.WarmCount > count);
writer.Dispose();
r1.Dispose();
dir1.Dispose();
}
[Test]
public virtual void TestAfterCommit([ValueSource(typeof(ConcurrentMergeSchedulerFactories), "Values")]Func<IConcurrentMergeScheduler> newScheduler)
{
Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory());
var config = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergeScheduler(newScheduler());
IndexWriter writer = new IndexWriter(dir1, config);
writer.Commit();
// create the index
CreateIndexNoClose(false, "test", writer);
// get a reader to put writer into near real-time mode
DirectoryReader r1 = writer.GetReader();
TestUtil.CheckIndex(dir1);
writer.Commit();
TestUtil.CheckIndex(dir1);
Assert.AreEqual(100, r1.NumDocs);
for (int i = 0; i < 10; i++)
{
writer.AddDocument(DocHelper.CreateDocument(i, "test", 4));
}
((IConcurrentMergeScheduler)writer.Config.MergeScheduler).Sync();
DirectoryReader r2 = DirectoryReader.OpenIfChanged(r1);
if (r2 != null)
{
r1.Dispose();
r1 = r2;
}
Assert.AreEqual(110, r1.NumDocs);
writer.Dispose();
r1.Dispose();
dir1.Dispose();
}
// Make sure reader remains usable even if IndexWriter closes
[Test]
public virtual void TestAfterClose()
{
Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory());
IndexWriter writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
// create the index
CreateIndexNoClose(false, "test", writer);
DirectoryReader r = writer.GetReader();
writer.Dispose();
TestUtil.CheckIndex(dir1);
// reader should remain usable even after IndexWriter is closed:
Assert.AreEqual(100, r.NumDocs);
Query q = new TermQuery(new Term("indexname", "test"));
IndexSearcher searcher = NewSearcher(r);
Assert.AreEqual(100, searcher.Search(q, 10).TotalHits);
try
{
DirectoryReader.OpenIfChanged(r);
Assert.Fail("failed to hit ObjectDisposedException");
}
#pragma warning disable 168
catch (ObjectDisposedException ace)
#pragma warning restore 168
{
// expected
}
r.Dispose();
dir1.Dispose();
}
// Stress test reopen during addIndexes
[Test, LongRunningTest] // LUCENENET TODO: Can this test be optimized to run faster on .NET Core 1.0?
public virtual void TestDuringAddIndexes()
{
Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory());
IndexWriter writer = new IndexWriter(
dir1,
NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))
.SetMergePolicy(NewLogMergePolicy(2)));
// create the index
CreateIndexNoClose(false, "test", writer);
writer.Commit();
Directory[] dirs = new Directory[10];
for (int i = 0; i < 10; i++)
{
dirs[i] = new MockDirectoryWrapper(Random(), new RAMDirectory(dir1, NewIOContext(Random())));
}
DirectoryReader r = writer.GetReader();
const float SECONDS = 0.5f;
long endTime = (long)(Environment.TickCount + 1000.0 * SECONDS);
ConcurrentHashSet<Exception> excs = new ConcurrentHashSet<Exception>();
// Only one thread can addIndexes at a time, because
// IndexWriter acquires a write lock in each directory:
var threads = new ThreadClass[1];
for (int i = 0; i < threads.Length; i++)
{
threads[i] = new ThreadAnonymousInnerClassHelper(writer, dirs, endTime, excs);
threads[i].SetDaemon(true);
threads[i].Start();
}
int lastCount = 0;
while (Environment.TickCount < endTime)
{
DirectoryReader r2 = DirectoryReader.OpenIfChanged(r);
if (r2 != null)
{
r.Dispose();
r = r2;
}
Query q = new TermQuery(new Term("indexname", "test"));
IndexSearcher searcher = NewSearcher(r);
int count = searcher.Search(q, 10).TotalHits;
Assert.IsTrue(count >= lastCount);
lastCount = count;
}
for (int i = 0; i < threads.Length; i++)
{
threads[i].Join();
}
// final check
DirectoryReader dr2 = DirectoryReader.OpenIfChanged(r);
if (dr2 != null)
{
r.Dispose();
r = dr2;
}
Query q2 = new TermQuery(new Term("indexname", "test"));
IndexSearcher searcher_ = NewSearcher(r);
int count_ = searcher_.Search(q2, 10).TotalHits;
Assert.IsTrue(count_ >= lastCount);
Assert.AreEqual(0, excs.Count);
r.Dispose();
if (dir1 is MockDirectoryWrapper)
{
ICollection<string> openDeletedFiles = ((MockDirectoryWrapper)dir1).OpenDeletedFiles;
Assert.AreEqual(0, openDeletedFiles.Count, "openDeleted=" + openDeletedFiles);
}
writer.Dispose();
dir1.Dispose();
}
private class ThreadAnonymousInnerClassHelper : ThreadClass
{
private IndexWriter Writer;
private Directory[] Dirs;
private long EndTime;
private ISet<Exception> Excs;
public ThreadAnonymousInnerClassHelper(IndexWriter writer, Directory[] dirs, long endTime, ISet<Exception> excs)
{
this.Writer = writer;
this.Dirs = dirs;
this.EndTime = endTime;
this.Excs = excs;
}
public override void Run()
{
do
{
try
{
Writer.AddIndexes(Dirs);
Writer.MaybeMerge();
}
catch (Exception t)
{
Excs.Add(t);
throw new Exception(t.Message, t);
}
} while (Environment.TickCount < EndTime);
}
}
private Directory GetAssertNoDeletesDirectory(Directory directory)
{
if (directory is MockDirectoryWrapper)
{
((MockDirectoryWrapper)directory).AssertNoDeleteOpenFile = true;
}
return directory;
}
// Stress test reopen during add/delete
[Test]
public virtual void TestDuringAddDelete()
{
Directory dir1 = NewDirectory();
var writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy(2)));
// create the index
CreateIndexNoClose(false, "test", writer);
writer.Commit();
DirectoryReader r = writer.GetReader();
const float SECONDS = 0.5f;
long endTime = (long)(Environment.TickCount + 1000.0 * SECONDS);
ConcurrentQueue<Exception> excs = new ConcurrentQueue<Exception>();
var threads = new ThreadClass[NumThreads];
for (int i = 0; i < NumThreads; i++)
{
threads[i] = new ThreadAnonymousInnerClassHelper2(writer, r, endTime, excs);
threads[i].SetDaemon(true);
threads[i].Start();
}
int sum = 0;
while (Environment.TickCount < endTime)
{
DirectoryReader r2 = DirectoryReader.OpenIfChanged(r);
if (r2 != null)
{
r.Dispose();
r = r2;
}
Query q = new TermQuery(new Term("indexname", "test"));
IndexSearcher searcher = NewSearcher(r);
sum += searcher.Search(q, 10).TotalHits;
}
for (int i = 0; i < NumThreads; i++)
{
threads[i].Join();
}
// at least search once
DirectoryReader dr2 = DirectoryReader.OpenIfChanged(r);
if (dr2 != null)
{
r.Dispose();
r = dr2;
}
Query q2 = new TermQuery(new Term("indexname", "test"));
IndexSearcher indSearcher = NewSearcher(r);
sum += indSearcher.Search(q2, 10).TotalHits;
Assert.IsTrue(sum > 0, "no documents found at all");
Assert.AreEqual(0, excs.Count);
writer.Dispose();
r.Dispose();
dir1.Dispose();
}
private class ThreadAnonymousInnerClassHelper2 : ThreadClass
{
private IndexWriter Writer;
private DirectoryReader r;
private long EndTime;
private ConcurrentQueue<Exception> Excs;
public ThreadAnonymousInnerClassHelper2(IndexWriter writer, DirectoryReader r, long endTime, ConcurrentQueue<Exception> excs)
{
this.Writer = writer;
this.r = r;
this.EndTime = endTime;
this.Excs = excs;
rand = new Random(Random().Next());
}
internal readonly Random rand;
public override void Run()
{
int count = 0;
do
{
try
{
for (int docUpto = 0; docUpto < 10; docUpto++)
{
Writer.AddDocument(DocHelper.CreateDocument(10 * count + docUpto, "test", 4));
}
count++;
int limit = count * 10;
for (int delUpto = 0; delUpto < 5; delUpto++)
{
int x = rand.Next(limit);
Writer.DeleteDocuments(new Term("field3", "b" + x));
}
}
catch (Exception t)
{
Excs.Enqueue(t);
throw new Exception(t.Message, t);
}
} while (Environment.TickCount < EndTime);
}
}
[Test]
public virtual void TestForceMergeDeletes()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy()));
Document doc = new Document();
doc.Add(NewTextField("field", "a b c", Field.Store.NO));
Field id = NewStringField("id", "", Field.Store.NO);
doc.Add(id);
id.SetStringValue("0");
w.AddDocument(doc);
id.SetStringValue("1");
w.AddDocument(doc);
w.DeleteDocuments(new Term("id", "0"));
IndexReader r = w.GetReader();
w.ForceMergeDeletes();
w.Dispose();
r.Dispose();
r = DirectoryReader.Open(dir);
Assert.AreEqual(1, r.NumDocs);
Assert.IsFalse(r.HasDeletions);
r.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestDeletesNumDocs()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
Document doc = new Document();
doc.Add(NewTextField("field", "a b c", Field.Store.NO));
Field id = NewStringField("id", "", Field.Store.NO);
doc.Add(id);
id.SetStringValue("0");
w.AddDocument(doc);
id.SetStringValue("1");
w.AddDocument(doc);
IndexReader r = w.GetReader();
Assert.AreEqual(2, r.NumDocs);
r.Dispose();
w.DeleteDocuments(new Term("id", "0"));
r = w.GetReader();
Assert.AreEqual(1, r.NumDocs);
r.Dispose();
w.DeleteDocuments(new Term("id", "1"));
r = w.GetReader();
Assert.AreEqual(0, r.NumDocs);
r.Dispose();
w.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestEmptyIndex()
{
// Ensures that getReader works on an empty index, which hasn't been committed yet.
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
IndexReader r = w.GetReader();
Assert.AreEqual(0, r.NumDocs);
r.Dispose();
w.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestSegmentWarmer()
{
Directory dir = NewDirectory();
AtomicBoolean didWarm = new AtomicBoolean();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2).SetReaderPooling(true).SetMergedSegmentWarmer(new IndexReaderWarmerAnonymousInnerClassHelper(this, didWarm)).
SetMergePolicy(NewLogMergePolicy(10)));
Document doc = new Document();
doc.Add(NewStringField("foo", "bar", Field.Store.NO));
for (int i = 0; i < 20; i++)
{
w.AddDocument(doc);
}
w.WaitForMerges();
w.Dispose();
dir.Dispose();
Assert.IsTrue(didWarm.Get());
}
private class IndexReaderWarmerAnonymousInnerClassHelper : IndexWriter.IndexReaderWarmer
{
private readonly TestIndexWriterReader OuterInstance;
private AtomicBoolean DidWarm;
public IndexReaderWarmerAnonymousInnerClassHelper(TestIndexWriterReader outerInstance, AtomicBoolean didWarm)
{
this.OuterInstance = outerInstance;
this.DidWarm = didWarm;
}
public override void Warm(AtomicReader r)
{
IndexSearcher s = OuterInstance.NewSearcher(r);
TopDocs hits = s.Search(new TermQuery(new Term("foo", "bar")), 10);
Assert.AreEqual(20, hits.TotalHits);
DidWarm.Set(true);
}
}
[Test]
public virtual void TestSimpleMergedSegmentWramer()
{
Directory dir = NewDirectory();
AtomicBoolean didWarm = new AtomicBoolean();
InfoStream infoStream = new InfoStreamAnonymousInnerClassHelper(this, didWarm);
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2).SetReaderPooling(true).SetInfoStream(infoStream).SetMergedSegmentWarmer(new SimpleMergedSegmentWarmer(infoStream)).SetMergePolicy(NewLogMergePolicy(10)));
Document doc = new Document();
doc.Add(NewStringField("foo", "bar", Field.Store.NO));
for (int i = 0; i < 20; i++)
{
w.AddDocument(doc);
}
w.WaitForMerges();
w.Dispose();
dir.Dispose();
Assert.IsTrue(didWarm.Get());
}
private class InfoStreamAnonymousInnerClassHelper : InfoStream
{
private readonly TestIndexWriterReader OuterInstance;
private AtomicBoolean DidWarm;
public InfoStreamAnonymousInnerClassHelper(TestIndexWriterReader outerInstance, AtomicBoolean didWarm)
{
this.OuterInstance = outerInstance;
this.DidWarm = didWarm;
}
protected override void Dispose(bool disposing)
{
}
public override void Message(string component, string message)
{
if ("SMSW".Equals(component))
{
DidWarm.Set(true);
}
}
public override bool IsEnabled(string component)
{
return true;
}
}
[Test]
public virtual void TestNoTermsIndex()
{
// Some Codecs don't honor the ReaderTermsIndexDivisor, so skip the test if
// they're picked.
AssumeFalse("PreFlex codec does not support ReaderTermsIndexDivisor!", "Lucene3x".Equals(Codec.Default.Name));
IndexWriterConfig conf = (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetReaderTermsIndexDivisor(-1);
// Don't proceed if picked Codec is in the list of illegal ones.
string format = TestUtil.GetPostingsFormat("f");
AssumeFalse("Format: " + format + " does not support ReaderTermsIndexDivisor!", (format.Equals("FSTPulsing41") || format.Equals("FSTOrdPulsing41") || format.Equals("FST41") || format.Equals("FSTOrd41") || format.Equals("SimpleText") || format.Equals("Memory") || format.Equals("MockRandom") || format.Equals("Direct")));
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, conf);
Document doc = new Document();
doc.Add(new TextField("f", "val", Field.Store.NO));
w.AddDocument(doc);
SegmentReader r = GetOnlySegmentReader(DirectoryReader.Open(w, true));
try
{
TestUtil.Docs(Random(), r, "f", new BytesRef("val"), null, null, DocsFlags.NONE);
Assert.Fail("should have failed to seek since terms index was not loaded.");
}
#pragma warning disable 168
catch (InvalidOperationException e)
#pragma warning restore 168
{
// expected - we didn't load the term index
}
finally
{
r.Dispose();
w.Dispose();
dir.Dispose();
}
}
[Test]
public virtual void TestReopenAfterNoRealChange()
{
Directory d = GetAssertNoDeletesDirectory(NewDirectory());
IndexWriter w = new IndexWriter(d, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
DirectoryReader r = w.GetReader(); // start pooling readers
DirectoryReader r2 = DirectoryReader.OpenIfChanged(r);
Assert.IsNull(r2);
w.AddDocument(new Document());
DirectoryReader r3 = DirectoryReader.OpenIfChanged(r);
Assert.IsNotNull(r3);
Assert.IsTrue(r3.Version != r.Version);
Assert.IsTrue(r3.IsCurrent());
// Deletes nothing in reality...:
w.DeleteDocuments(new Term("foo", "bar"));
// ... but IW marks this as not current:
Assert.IsFalse(r3.IsCurrent());
DirectoryReader r4 = DirectoryReader.OpenIfChanged(r3);
Assert.IsNull(r4);
// Deletes nothing in reality...:
w.DeleteDocuments(new Term("foo", "bar"));
DirectoryReader r5 = DirectoryReader.OpenIfChanged(r3, w, true);
Assert.IsNull(r5);
r3.Dispose();
w.Dispose();
d.Dispose();
}
[Test]
public virtual void TestNRTOpenExceptions()
{
// LUCENE-5262: test that several failed attempts to obtain an NRT reader
// don't leak file handles.
MockDirectoryWrapper dir = (MockDirectoryWrapper)GetAssertNoDeletesDirectory(NewMockDirectory());
AtomicBoolean shouldFail = new AtomicBoolean();
dir.FailOn(new FailureAnonymousInnerClassHelper(shouldFail));
IndexWriterConfig conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
conf.SetMergePolicy(NoMergePolicy.COMPOUND_FILES); // prevent merges from getting in the way
IndexWriter writer = new IndexWriter(dir, conf);
// create a segment and open an NRT reader
writer.AddDocument(new Document());
writer.GetReader().Dispose();
// add a new document so a new NRT reader is required
writer.AddDocument(new Document());
// try to obtain an NRT reader twice: first time it fails and closes all the
// other NRT readers. second time it fails, but also fails to close the
// other NRT reader, since it is already marked closed!
for (int i = 0; i < 2; i++)
{
shouldFail.Set(true);
try
{
writer.GetReader().Dispose();
}
#pragma warning disable 168
catch (FakeIOException e)
#pragma warning restore 168
{
// expected
if (VERBOSE)
{
Console.WriteLine("hit expected fake IOE");
}
}
}
writer.Dispose();
dir.Dispose();
}
private class FailureAnonymousInnerClassHelper : MockDirectoryWrapper.Failure
{
private readonly AtomicBoolean ShouldFail;
public FailureAnonymousInnerClassHelper(AtomicBoolean shouldFail)
{
this.ShouldFail = shouldFail;
}
public override void Eval(MockDirectoryWrapper dir)
{
// LUCENENET specific: for these to work in release mode, we have added [MethodImpl(MethodImplOptions.NoInlining)]
// to each possible target of the StackTraceHelper. If these change, so must the attribute on the target methods.
if (ShouldFail.Get() && StackTraceHelper.DoesStackTraceContainMethod("GetReadOnlyClone"))
{
if (VERBOSE)
{
Console.WriteLine("TEST: now fail; exc:");
Console.WriteLine((new Exception()).StackTrace);
}
ShouldFail.Set(false);
throw new FakeIOException();
}
}
}
/// <summary>
/// Make sure if all we do is open NRT reader against
/// writer, we don't see merge starvation.
/// </summary>
[Test, LongRunningTest]
public virtual void TestTooManySegments()
{
Directory dir = GetAssertNoDeletesDirectory(NewDirectory());
// Don't use newIndexWriterConfig, because we need a
// "sane" mergePolicy:
IndexWriterConfig iwc = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
IndexWriter w = new IndexWriter(dir, iwc);
// Create 500 segments:
for (int i = 0; i < 500; i++)
{
Document doc = new Document();
doc.Add(NewStringField("id", "" + i, Field.Store.NO));
w.AddDocument(doc);
IndexReader r = DirectoryReader.Open(w, true);
// Make sure segment count never exceeds 100:
Assert.IsTrue(r.Leaves.Count < 100);
r.Dispose();
}
w.Dispose();
dir.Dispose();
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace OfficeDevPnP.Core.Utilities
{
internal static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registered for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registered for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registered for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified ClaimsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it. Identity claim type and identity provider name (as registered in SharePoint)
/// should be specified in configuration file e.g.:
/// <appSettings>
/// <add key = "IdentityClaimType" value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" />
/// <add key = "TrustedIdentityTokenIssuerName" value="sso" />
/// </appSettings>
/// To discover trusted identity token issuer name use following cmdlet:
/// Get-SPTrustedIdentityTokenIssuer | select name
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Claims identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithClaimsIdentity(Uri targetApplicationUri, System.Security.Claims.ClaimsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithClaimsIdentity(identity, IdentityClaimType, TrustedIdentityTokenIssuerName) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Hosted app configuration
//
private static string clientId = null;
private static string issuerId = null;
private static string hostedAppHostNameOverride = null;
private static string hostedAppHostName = null;
private static string clientSecret = null;
private static string secondaryClientSecret = null;
private static string realm = null;
private static string serviceNamespace = null;
private static string identityClaimType = null;
private static string trustedIdentityTokenIssuerName = null;
//
// Environment Constants
//
private static string acsHostUrl = "accesscontrol.windows.net";
private static string globalEndPointPrefix = "accounts";
public static string AcsHostUrl
{
get
{
if (String.IsNullOrEmpty(acsHostUrl))
{
return "accesscontrol.windows.net";
}
else
{
return acsHostUrl;
}
}
set
{
acsHostUrl = value;
}
}
public static string GlobalEndPointPrefix
{
get
{
if (String.IsNullOrEmpty(globalEndPointPrefix))
{
return "accounts";
}
else
{
return globalEndPointPrefix;
}
}
set
{
globalEndPointPrefix = value;
}
}
public static string ClientId
{
get
{
if (String.IsNullOrEmpty(clientId))
{
return string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
}
else
{
return clientId;
}
}
set
{
clientId = value;
}
}
public static string IssuerId
{
get
{
if (String.IsNullOrEmpty(issuerId))
{
return string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
}
else
{
return issuerId;
}
}
set
{
issuerId = value;
}
}
public static string HostedAppHostNameOverride
{
get
{
if (String.IsNullOrEmpty(hostedAppHostNameOverride))
{
return WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
}
else
{
return hostedAppHostNameOverride;
}
}
set
{
hostedAppHostNameOverride = value;
}
}
public static string HostedAppHostName
{
get
{
if (String.IsNullOrEmpty(hostedAppHostName))
{
return WebConfigurationManager.AppSettings.Get("HostedAppHostName");
}
else
{
return hostedAppHostName;
}
}
set
{
hostedAppHostName = value;
}
}
public static string ClientSecret
{
get
{
if (String.IsNullOrEmpty(clientSecret))
{
return string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
}
else
{
return clientSecret;
}
}
set
{
clientSecret = value;
}
}
public static string SecondaryClientSecret
{
get
{
if (String.IsNullOrEmpty(secondaryClientSecret))
{
return WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
}
else
{
return secondaryClientSecret;
}
}
set
{
secondaryClientSecret = value;
}
}
public static string Realm
{
get
{
if (String.IsNullOrEmpty(realm))
{
return WebConfigurationManager.AppSettings.Get("Realm");
}
else
{
return realm;
}
}
set
{
realm = value;
}
}
public static string ServiceNamespace
{
get
{
if (String.IsNullOrEmpty(serviceNamespace))
{
return WebConfigurationManager.AppSettings.Get("Realm");
}
else
{
return serviceNamespace;
}
}
set
{
serviceNamespace = value;
}
}
public static string IdentityClaimType
{
get
{
if (String.IsNullOrEmpty(identityClaimType))
{
return WebConfigurationManager.AppSettings.Get("IdentityClaimType");
}
else
{
return identityClaimType;
}
}
set
{
identityClaimType = value;
}
}
public static string TrustedIdentityTokenIssuerName
{
get
{
if (String.IsNullOrEmpty(trustedIdentityTokenIssuerName))
{
return WebConfigurationManager.AppSettings.Get("TrustedIdentityTokenIssuerName");
}
else
{
return trustedIdentityTokenIssuerName;
}
}
set
{
trustedIdentityTokenIssuerName = value;
}
}
//private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
//private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
//private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
//private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
//private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
//private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
//private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
//private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
public static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static JsonWebTokenClaim[] GetClaimsWithClaimsIdentity(System.Security.Claims.ClaimsIdentity identity, string identityClaimType, string trustedProviderName)
{
var identityClaim = identity.Claims.Where(c => string.Equals(c.Type, identityClaimType, StringComparison.InvariantCultureIgnoreCase)).First();
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identityClaim.Value),
new JsonWebTokenClaim("nii", "trusted:" + trustedProviderName)
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using BLToolkit.Aspects;
using BLToolkit.Data;
using BLToolkit.Data.DataProvider;
using BLToolkit.Mapping;
using BLToolkit.Reflection;
using BLToolkit.Reflection.Extension;
using BLToolkit.Reflection.MetadataProvider;
namespace BLToolkit.DataAccess
{
public abstract class SqlQueryBase : DataAccessorBase
{
#region Constructors
protected SqlQueryBase()
{
}
protected SqlQueryBase(DbManager dbManager)
: base(dbManager)
{
}
protected SqlQueryBase(DbManager dbManager, bool dispose)
: base(dbManager, dispose)
{
}
#endregion
#region Protected Members
[NoInterception]
protected virtual MemberMapper[] GetFieldList(ObjectMapper om)
{
List<MemberMapper> list = new List<MemberMapper>(om.Count);
foreach (MemberMapper mm in om)
if (mm.MapMemberInfo.SqlIgnore == false)
list.Add(mm);
return list.ToArray();
}
[NoInterception]
protected virtual MemberMapper[] GetNonKeyFieldList(ObjectMapper om)
{
TypeExtension typeExt = TypeExtension.GetTypeExtension(om.TypeAccessor.OriginalType, Extensions);
List<MemberMapper> list = new List<MemberMapper>();
foreach (MemberMapper mm in om)
{
if (mm.MapMemberInfo.SqlIgnore)
continue;
MemberAccessor ma = mm.MapMemberInfo.MemberAccessor;
bool isSet;
MappingSchema.MetadataProvider.GetPrimaryKeyOrder(om.TypeAccessor.OriginalType, typeExt, ma, out isSet);
if (!isSet)
list.Add(mm);
}
return list.ToArray();
}
struct MemberOrder
{
public MemberOrder(MemberMapper memberMapper, int order)
{
MemberMapper = memberMapper;
Order = order;
}
public readonly MemberMapper MemberMapper;
public readonly int Order;
}
private static readonly Hashtable _keyList = new Hashtable();
[NoInterception]
protected internal virtual MemberMapper[] GetKeyFieldList(DbManager db, Type type)
{
string key = type.FullName + "$" + db.DataProvider.UniqueName;
MemberMapper[] mmList = (MemberMapper[])_keyList[key];
if (mmList == null)
{
TypeExtension typeExt = TypeExtension.GetTypeExtension(type, Extensions);
List<MemberOrder> list = new List<MemberOrder>();
foreach (MemberMapper mm in db.MappingSchema.GetObjectMapper(type))
{
if (mm.MapMemberInfo.SqlIgnore)
continue;
MemberAccessor ma = mm.MapMemberInfo.MemberAccessor;
if (TypeHelper.IsScalar(ma.Type))
{
bool isSet;
int order = MappingSchema.MetadataProvider.GetPrimaryKeyOrder(type, typeExt, ma, out isSet);
if (isSet)
list.Add(new MemberOrder(mm, order));
}
}
list.Sort(delegate(MemberOrder x, MemberOrder y) { return x.Order - y.Order; });
_keyList[key] = mmList = new MemberMapper[list.Count];
for (int i = 0; i < list.Count; i++)
mmList[i] = list[i].MemberMapper;
}
return mmList;
}
[NoInterception]
protected virtual void AddWherePK(DbManager db, SqlQueryInfo query, StringBuilder sb, int nParameter)
{
sb.Append("WHERE\n");
MemberMapper[] memberMappers = GetKeyFieldList(db, query.ObjectType);
if (memberMappers.Length == 0)
throw new DataAccessException(
string.Format("No primary key field(s) in the type '{0}'.", query.ObjectType.FullName));
foreach (MemberMapper mm in memberMappers)
{
SqlQueryParameterInfo p = query.AddParameter(
db.DataProvider.Convert(mm.Name + "_W", ConvertType.NameToQueryParameter).ToString(),
mm.Name);
sb.AppendFormat("\t{0} = ", db.DataProvider.Convert(p.FieldName, ConvertType.NameToQueryField));
if (nParameter < 0)
sb.AppendFormat("{0} AND\n", p.ParameterName);
else
sb.AppendFormat("{{{0}}} AND\n", nParameter);
}
sb.Remove(sb.Length - 5, 5);
}
protected SqlQueryInfo CreateSelectByKeySqlText(DbManager db, Type type)
{
ObjectMapper om = db.MappingSchema.GetObjectMapper(type);
StringBuilder sb = new StringBuilder();
SqlQueryInfo query = new SqlQueryInfo(om);
sb.Append("SELECT\n");
foreach (MemberMapper mm in GetFieldList(om))
sb.AppendFormat("\t{0},\n",
db.DataProvider.Convert(mm.Name, ConvertType.NameToQueryField));
sb.Remove(sb.Length - 2, 1);
sb.Append("FROM\n\t");
AppendTableName(sb, db, type);
AddWherePK(db, query, sb, -1);
query.QueryText = sb.ToString();
return query;
}
protected void AppendTableName(StringBuilder sb, DbManager db, Type type)
{
string database = GetDatabaseName(type);
string owner = GetOwnerName (type);
string name = GetTableName (type);
db.DataProvider.BuildTableName(sb,
database == null ? null : db.DataProvider.Convert(database, ConvertType.NameToDatabase). ToString(),
owner == null ? null : db.DataProvider.Convert(owner, ConvertType.NameToOwner). ToString(),
name == null ? null : db.DataProvider.Convert(name, ConvertType.NameToQueryTable).ToString());
sb.AppendLine();
}
protected SqlQueryInfo CreateSelectAllSqlText(DbManager db, Type type)
{
ObjectMapper om = db.MappingSchema.GetObjectMapper(type);
StringBuilder sb = new StringBuilder();
SqlQueryInfo query = new SqlQueryInfo(om);
sb.Append("SELECT\n");
foreach (MemberMapper mm in GetFieldList(om))
sb.AppendFormat("\t{0},\n",
db.DataProvider.Convert(mm.Name, ConvertType.NameToQueryField));
sb.Remove(sb.Length - 2, 1);
sb.Append("FROM\n\t");
AppendTableName(sb, db, type);
query.QueryText = sb.ToString();
return query;
}
protected SqlQueryInfo CreateInsertSqlText(DbManager db, Type type, int nParameter)
{
TypeExtension typeExt = TypeExtension.GetTypeExtension(type, Extensions);
ObjectMapper om = db.MappingSchema.GetObjectMapper(type);
List<MemberMapper> list = new List<MemberMapper>();
StringBuilder sb = new StringBuilder();
SqlQueryInfo query = new SqlQueryInfo(om);
MetadataProviderBase mp = MappingSchema.MetadataProvider;
sb.Append("INSERT INTO ");
AppendTableName(sb, db, type);
sb.Append(" (\n");
foreach (MemberMapper mm in GetFieldList(om))
{
// IT: This works incorrectly for complex mappers.
//
// [2009-03-24] ili: use mm.MemberAccessor instead of mm.ComplexMemberAccessor
// as in CreateUpdateSqlText
//
bool isSet;
if (mp.GetNonUpdatableAttribute(type, typeExt, mm.MapMemberInfo.MemberAccessor, out isSet) == null || !isSet)
{
sb.AppendFormat("\t{0},\n",
db.DataProvider.Convert(mm.Name, ConvertType.NameToQueryField));
list.Add(mm);
}
}
sb.Remove(sb.Length - 2, 1);
sb.Append(") VALUES (\n");
foreach (MemberMapper mm in list)
{
SqlQueryParameterInfo p = query.AddParameter(
db.DataProvider.Convert(mm.Name + "_P", ConvertType.NameToQueryParameter).ToString(),
mm.Name);
if (nParameter < 0)
sb.AppendFormat("\t{0},\n", p.ParameterName);
//sb.AppendFormat("\t{0},\n", db.DataProvider.Convert(p.ParameterName, ConvertType.NameToQueryParameter));
else
sb.AppendFormat("\t{{{0}}},\n", nParameter++);
}
sb.Remove(sb.Length - 2, 1);
sb.Append(")");
query.QueryText = sb.ToString();
return query;
}
protected SqlQueryInfo CreateUpdateSqlText(DbManager db, Type type, int nParameter)
{
TypeExtension typeExt = TypeExtension.GetTypeExtension(type, Extensions);
ObjectMapper om = db.MappingSchema.GetObjectMapper(type);
StringBuilder sb = new StringBuilder();
SqlQueryInfo query = new SqlQueryInfo(om);
MetadataProviderBase mp = MappingSchema.MetadataProvider;
sb.Append("UPDATE\n\t");
AppendTableName(sb, db, type);
sb.Append("\nSET\n");
MemberMapper[] fields = GetFieldList(om);
bool hasFields = false;
foreach (MemberMapper mm in fields)
{
bool isSet;
if (mp.GetNonUpdatableAttribute(type, typeExt, mm.MapMemberInfo.MemberAccessor, out isSet) != null && isSet)
continue;
mp.GetPrimaryKeyOrder(type, typeExt, mm.MapMemberInfo.MemberAccessor, out isSet);
if (isSet)
continue;
hasFields = true;
SqlQueryParameterInfo p = query.AddParameter(
db.DataProvider.Convert(mm.Name + "_P", ConvertType.NameToQueryParameter).ToString(),
mm.Name);
sb.AppendFormat("\t{0} = ", db.DataProvider.Convert(p.FieldName, ConvertType.NameToQueryField));
if (nParameter < 0)
sb.AppendFormat("{0},\n", p.ParameterName);
else
sb.AppendFormat("\t{{{0}}},\n", nParameter++);
}
if (!hasFields)
throw new DataAccessException(
string.Format("There are no fields to update in the type '{0}'.", query.ObjectType.FullName));
sb.Remove(sb.Length - 2, 1);
AddWherePK(db, query, sb, nParameter);
query.QueryText = sb.ToString();
return query;
}
protected SqlQueryInfo CreateDeleteSqlText(DbManager db, Type type, int nParameter)
{
ObjectMapper om = db.MappingSchema.GetObjectMapper(type);
StringBuilder sb = new StringBuilder();
SqlQueryInfo query = new SqlQueryInfo(om);
sb.Append("DELETE FROM\n\t");
AppendTableName(sb, db, type);
sb.AppendLine();
AddWherePK(db, query, sb, nParameter);
query.QueryText = sb.ToString();
return query;
}
[NoInterception]
protected virtual SqlQueryInfo CreateSqlText(DbManager db, Type type, string actionName)
{
switch (actionName)
{
case "SelectByKey": return CreateSelectByKeySqlText(db, type);
case "SelectAll": return CreateSelectAllSqlText (db, type);
case "Insert": return CreateInsertSqlText (db, type, -1);
case "InsertBatch": return CreateInsertSqlText (db, type, 0);
case "Update": return CreateUpdateSqlText (db, type, -1);
case "UpdateBatch": return CreateUpdateSqlText (db, type, 0);
case "Delete": return CreateDeleteSqlText (db, type, -1);
case "DeleteBatch": return CreateDeleteSqlText (db, type, 0);
default:
throw new DataAccessException(
string.Format("Unknown action '{0}'.", actionName));
}
}
private static readonly Hashtable _actionSqlQueryInfo = new Hashtable();
[NoInterception]
public virtual SqlQueryInfo GetSqlQueryInfo(DbManager db, Type type, string actionName)
{
string key = type.FullName + "$" + actionName + "$" + db.DataProvider.UniqueName + "$" + GetTableName(type);
SqlQueryInfo query = (SqlQueryInfo)_actionSqlQueryInfo[key];
if (query == null)
{
query = CreateSqlText(db, type, actionName);
_actionSqlQueryInfo[key] = query;
}
return query;
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
namespace OpenSim.ApplicationPlugins.Rest
{
public abstract class RestPlugin : IApplicationPlugin
{
#region properties
protected static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IConfig _config; // Configuration source: Rest Plugins
private IConfig _pluginConfig; // Configuration source: Plugin specific
private OpenSimBase _app; // The 'server'
private BaseHttpServer _httpd; // The server's RPC interface
private string _prefix; // URL prefix below
// which all REST URLs
// are living
// private StringWriter _sw = null;
// private RestXmlWriter _xw = null;
private string _godkey;
private int _reqk;
[ThreadStatic]
private static string _threadRequestID = String.Empty;
/// <summary>
/// Return an ever increasing request ID for logging
/// </summary>
protected string RequestID
{
get { return _reqk++.ToString(); }
set { _reqk = Convert.ToInt32(value); }
}
/// <summary>
/// Thread-constant message IDs for logging.
/// </summary>
protected string MsgID
{
get { return String.Format("[REST-{0}] #{1}", Name, _threadRequestID); }
set { _threadRequestID = value; }
}
/// <summary>
/// Returns true if Rest Plugins are enabled.
/// </summary>
public bool PluginsAreEnabled
{
get { return null != _config; }
}
/// <summary>
/// Returns true if specific Rest Plugin is enabled.
/// </summary>
public bool IsEnabled
{
get
{
return (null != _pluginConfig) && _pluginConfig.GetBoolean("enabled", false);
}
}
/// <summary>
/// OpenSimMain application
/// </summary>
public OpenSimBase App
{
get { return _app; }
}
/// <summary>
/// RPC server
/// </summary>
public BaseHttpServer HttpServer
{
get { return _httpd; }
}
/// <summary>
/// URL prefix to use for all REST handlers
/// </summary>
public string Prefix
{
get { return _prefix; }
}
/// <summary>
/// Access to GOD password string
/// </summary>
protected string GodKey
{
get { return _godkey; }
}
/// <summary>
/// Configuration of the plugin
/// </summary>
public IConfig Config
{
get { return _pluginConfig; }
}
/// <summary>
/// Name of the plugin
/// </summary>
public abstract string Name { get; }
/// <summary>
/// Return the config section name
/// </summary>
public abstract string ConfigName { get; }
// public XmlTextWriter XmlWriter
// {
// get
// {
// if (null == _xw)
// {
// _sw = new StringWriter();
// _xw = new RestXmlWriter(_sw);
// _xw.Formatting = Formatting.Indented;
// }
// return _xw;
// }
// }
// public string XmlWriterResult
// {
// get
// {
// _xw.Flush();
// _xw.Close();
// _xw = null;
// return _sw.ToString();
// }
// }
#endregion properties
#region methods
// TODO: required by IPlugin, but likely not at all right
private string m_version = "0.0";
public string Version
{
get { return m_version; }
}
public void Initialise()
{
m_log.Info("[RESTPLUGIN]: " + Name + " cannot be default-initialized!");
throw new PluginNotInitialisedException(Name);
}
/// <summary>
/// This method is called by OpenSimMain immediately after loading the
/// plugin and after basic server setup, but before running any server commands.
/// </summary>
/// <remarks>
/// Note that entries MUST be added to the active configuration files before
/// the plugin can be enabled.
/// </remarks>
public virtual void Initialise(OpenSimBase openSim)
{
RequestID = "0";
MsgID = RequestID;
try
{
if ((_config = openSim.ConfigSource.Source.Configs["RestPlugins"]) == null)
{
m_log.WarnFormat("{0} Rest Plugins not configured", MsgID);
return;
}
if (!_config.GetBoolean("enabled", false))
{
//m_log.WarnFormat("{0} Rest Plugins are disabled", MsgID);
return;
}
_app = openSim;
_httpd = openSim.HttpServer;
// Retrieve GOD key value, if any.
_godkey = _config.GetString("god_key", String.Empty);
// Retrive prefix if any.
_prefix = _config.GetString("prefix", "/admin");
// Get plugin specific config
_pluginConfig = openSim.ConfigSource.Source.Configs[ConfigName];
m_log.InfoFormat("{0} Rest Plugins Enabled", MsgID);
}
catch (Exception e)
{
// we can safely ignore this, as it just means that
// the key lookup in Configs failed, which signals to
// us that noone is interested in our services...they
// don't know what they are missing out on...
// NOTE: Under the present OpenSimulator implementation it is
// not possible for the openSimulator pointer to be null. However
// were the implementation to be changed, this could
// result in a silent initialization failure. Harmless
// except for lack of function and lack of any
// diagnostic indication as to why. The same is true if
// the HTTP server reference is bad.
// We should at least issue a message...
m_log.WarnFormat("{0} Initialization failed: {1}", MsgID, e.Message);
m_log.DebugFormat("{0} Initialization failed: {1}", MsgID, e.ToString());
}
}
public virtual void PostInitialise()
{
}
private List<RestStreamHandler> _handlers = new List<RestStreamHandler>();
private Dictionary<string, IHttpAgentHandler> _agents = new Dictionary<string, IHttpAgentHandler>();
/// <summary>
/// Add a REST stream handler to the underlying HTTP server.
/// </summary>
/// <param name="httpMethod">GET/PUT/POST/DELETE or
/// similar</param>
/// <param name="path">URL prefix</param>
/// <param name="method">RestMethod handler doing the actual work</param>
public virtual void AddRestStreamHandler(string httpMethod, string path, RestMethod method)
{
if (!IsEnabled) return;
if (!path.StartsWith(_prefix))
{
path = String.Format("{0}{1}", _prefix, path);
}
RestStreamHandler h = new RestStreamHandler(httpMethod, path, method);
_httpd.AddStreamHandler(h);
_handlers.Add(h);
m_log.DebugFormat("{0} Added REST handler {1} {2}", MsgID, httpMethod, path);
}
/// <summary>
/// Add a powerful Agent handler to the underlying HTTP
/// server.
/// </summary>
/// <param name="agentName">name of agent handler</param>
/// <param name="handler">agent handler method</param>
/// <returns>false when the plugin is disabled or the agent
/// handler could not be added. Any generated exceptions are
/// allowed to drop through to the caller, i.e. ArgumentException.
/// </returns>
public bool AddAgentHandler(string agentName, IHttpAgentHandler handler)
{
if (!IsEnabled) return false;
_agents.Add(agentName, handler);
return _httpd.AddAgentHandler(agentName, handler);
}
/// <summary>
/// Remove a powerful Agent handler from the underlying HTTP
/// server.
/// </summary>
/// <param name="agentName">name of agent handler</param>
/// <param name="handler">agent handler method</param>
/// <returns>false when the plugin is disabled or the agent
/// handler could not be removed. Any generated exceptions are
/// allowed to drop through to the caller, i.e. KeyNotFound.
/// </returns>
public bool RemoveAgentHandler(string agentName, IHttpAgentHandler handler)
{
if (!IsEnabled) return false;
if (_agents[agentName] == handler)
{
_agents.Remove(agentName);
return _httpd.RemoveAgentHandler(agentName, handler);
}
return false;
}
/// <summary>
/// Check whether the HTTP request came from god; that is, is
/// the god_key as configured in the config section supplied
/// via X-OpenSim-Godkey?
/// </summary>
/// <param name="request">HTTP request header</param>
/// <returns>true when the HTTP request came from god.</returns>
protected bool IsGod(OSHttpRequest request)
{
string[] keys = request.Headers.GetValues("X-OpenSim-Godkey");
if (null == keys) return false;
// we take the last key supplied
return keys[keys.Length - 1] == _godkey;
}
/// <summary>
/// Checks wether the X-OpenSim-Password value provided in the
/// HTTP header is indeed the password on file for the avatar
/// specified by the UUID
/// </summary>
protected bool IsVerifiedUser(OSHttpRequest request, UUID uuid)
{
// XXX under construction
return false;
}
/// <summary>
/// Clean up and remove all handlers that were added earlier.
/// </summary>
public virtual void Close()
{
foreach (RestStreamHandler h in _handlers)
{
_httpd.RemoveStreamHandler(h.HttpMethod, h.Path);
}
_handlers = null;
foreach (KeyValuePair<string, IHttpAgentHandler> h in _agents)
{
_httpd.RemoveAgentHandler(h.Key, h.Value);
}
_agents = null;
}
public virtual void Dispose()
{
Close();
}
/// <summary>
/// Return a failure message.
/// </summary>
/// <param name="method">origin of the failure message</param>
/// <param name="message">failure message</param>
/// <remarks>This should probably set a return code as
/// well. (?)</remarks>
protected string Failure(OSHttpResponse response, OSHttpStatusCode status,
string method, string format, params string[] msg)
{
string m = String.Format(format, msg);
response.StatusCode = (int) status;
response.StatusDescription = m;
m_log.ErrorFormat("{0} {1} failed: {2}", MsgID, method, m);
return String.Format("<error>{0}</error>", m);
}
/// <summary>
/// Return a failure message.
/// </summary>
/// <param name="method">origin of the failure message</param>
/// <param name="e">exception causing the failure message</param>
/// <remarks>This should probably set a return code as
/// well. (?)</remarks>
public string Failure(OSHttpResponse response, OSHttpStatusCode status,
string method, Exception e)
{
string m = String.Format("exception occurred: {0}", e.Message);
response.StatusCode = (int) status;
response.StatusDescription = m;
m_log.DebugFormat("{0} {1} failed: {2}", MsgID, method, e.ToString());
m_log.ErrorFormat("{0} {1} failed: {2}", MsgID, method, e.Message);
return String.Format("<error>{0}</error>", e.Message);
}
#endregion methods
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace HostMe.Sdk.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class PutInLine : IEquatable<PutInLine>
{
/// <summary>
/// Gets or Sets RestaurantId
/// </summary>
[DataMember(Name="restaurantId", EmitDefaultValue=true)]
public int? RestaurantId { get; set; }
/// <summary>
/// Gets or Sets ReservationTime
/// </summary>
[DataMember(Name="reservationTime", EmitDefaultValue=true)]
public DateTimeOffset? ReservationTime { get; set; }
/// <summary>
/// Gets or Sets CustomerName
/// </summary>
[DataMember(Name="customerName", EmitDefaultValue=true)]
public string CustomerName { get; set; }
/// <summary>
/// Gets or Sets GroupSize
/// </summary>
[DataMember(Name="groupSize", EmitDefaultValue=true)]
public int? GroupSize { get; set; }
/// <summary>
/// Gets or Sets NotificationUrl
/// </summary>
[DataMember(Name="notificationUrl", EmitDefaultValue=true)]
public string NotificationUrl { get; set; }
/// <summary>
/// Gets or Sets DeviceType
/// </summary>
[DataMember(Name="deviceType", EmitDefaultValue=true)]
public string DeviceType { get; set; }
/// <summary>
/// Gets or Sets Areas
/// </summary>
[DataMember(Name="areas", EmitDefaultValue=true)]
public string Areas { get; set; }
/// <summary>
/// Gets or Sets Note
/// </summary>
[DataMember(Name="note", EmitDefaultValue=true)]
public string Note { get; set; }
/// <summary>
/// Gets or Sets HighChair
/// </summary>
[DataMember(Name="highChair", EmitDefaultValue=true)]
public bool? HighChair { get; set; }
/// <summary>
/// Gets or Sets Stroller
/// </summary>
[DataMember(Name="stroller", EmitDefaultValue=true)]
public bool? Stroller { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class PutInLine {\n");
sb.Append(" RestaurantId: ").Append(RestaurantId).Append("\n");
sb.Append(" ReservationTime: ").Append(ReservationTime).Append("\n");
sb.Append(" CustomerName: ").Append(CustomerName).Append("\n");
sb.Append(" GroupSize: ").Append(GroupSize).Append("\n");
sb.Append(" NotificationUrl: ").Append(NotificationUrl).Append("\n");
sb.Append(" DeviceType: ").Append(DeviceType).Append("\n");
sb.Append(" Areas: ").Append(Areas).Append("\n");
sb.Append(" Note: ").Append(Note).Append("\n");
sb.Append(" HighChair: ").Append(HighChair).Append("\n");
sb.Append(" Stroller: ").Append(Stroller).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as PutInLine);
}
/// <summary>
/// Returns true if PutInLine instances are equal
/// </summary>
/// <param name="other">Instance of PutInLine to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PutInLine other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.RestaurantId == other.RestaurantId ||
this.RestaurantId != null &&
this.RestaurantId.Equals(other.RestaurantId)
) &&
(
this.ReservationTime == other.ReservationTime ||
this.ReservationTime != null &&
this.ReservationTime.Equals(other.ReservationTime)
) &&
(
this.CustomerName == other.CustomerName ||
this.CustomerName != null &&
this.CustomerName.Equals(other.CustomerName)
) &&
(
this.GroupSize == other.GroupSize ||
this.GroupSize != null &&
this.GroupSize.Equals(other.GroupSize)
) &&
(
this.NotificationUrl == other.NotificationUrl ||
this.NotificationUrl != null &&
this.NotificationUrl.Equals(other.NotificationUrl)
) &&
(
this.DeviceType == other.DeviceType ||
this.DeviceType != null &&
this.DeviceType.Equals(other.DeviceType)
) &&
(
this.Areas == other.Areas ||
this.Areas != null &&
this.Areas.Equals(other.Areas)
) &&
(
this.Note == other.Note ||
this.Note != null &&
this.Note.Equals(other.Note)
) &&
(
this.HighChair == other.HighChair ||
this.HighChair != null &&
this.HighChair.Equals(other.HighChair)
) &&
(
this.Stroller == other.Stroller ||
this.Stroller != null &&
this.Stroller.Equals(other.Stroller)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.RestaurantId != null)
hash = hash * 59 + this.RestaurantId.GetHashCode();
if (this.ReservationTime != null)
hash = hash * 59 + this.ReservationTime.GetHashCode();
if (this.CustomerName != null)
hash = hash * 59 + this.CustomerName.GetHashCode();
if (this.GroupSize != null)
hash = hash * 59 + this.GroupSize.GetHashCode();
if (this.NotificationUrl != null)
hash = hash * 59 + this.NotificationUrl.GetHashCode();
if (this.DeviceType != null)
hash = hash * 59 + this.DeviceType.GetHashCode();
if (this.Areas != null)
hash = hash * 59 + this.Areas.GetHashCode();
if (this.Note != null)
hash = hash * 59 + this.Note.GetHashCode();
if (this.HighChair != null)
hash = hash * 59 + this.HighChair.GetHashCode();
if (this.Stroller != null)
hash = hash * 59 + this.Stroller.GetHashCode();
return hash;
}
}
}
}
| |
// Copyright (c) Rotorz Limited. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root.
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Borodar.ReorderableList {
/// <summary>
/// Utility class for drawing reorderable lists.
/// </summary>
public static class ReorderableListGUI {
/// <summary>
/// Default list item height is 18 pixels.
/// </summary>
public const float DefaultItemHeight = 18;
/// <summary>
/// Gets or sets the zero-based index of the last item that was changed. A value of -1
/// indicates that no item was changed by list.
/// </summary>
/// <remarks>
/// <para>This property should not be set when items are added or removed.</para>
/// </remarks>
public static int IndexOfChangedItem { get; internal set; }
/// <summary>
/// Gets the control ID of the list that is currently being drawn.
/// </summary>
public static int CurrentListControlID {
get { return ReorderableListControl.CurrentListControlID; }
}
/// <summary>
/// Gets the position of the list control that is currently being drawn.
/// </summary>
/// <remarks>
/// <para>The value of this property should be ignored for <see cref="EventType.Layout"/>
/// type events when using reorderable list controls with automatic layout.</para>
/// </remarks>
/// <see cref="CurrentItemTotalPosition"/>
public static Rect CurrentListPosition {
get { return ReorderableListControl.CurrentListPosition; }
}
/// <summary>
/// Gets the zero-based index of the list item that is currently being drawn;
/// or a value of -1 if no item is currently being drawn.
/// </summary>
public static int CurrentItemIndex {
get { return ReorderableListControl.CurrentItemIndex; }
}
/// <summary>
/// Gets the total position of the list item that is currently being drawn.
/// </summary>
/// <remarks>
/// <para>The value of this property should be ignored for <see cref="EventType.Layout"/>
/// type events when using reorderable list controls with automatic layout.</para>
/// </remarks>
/// <see cref="CurrentItemIndex"/>
/// <see cref="CurrentListPosition"/>
public static Rect CurrentItemTotalPosition {
get { return ReorderableListControl.CurrentItemTotalPosition; }
}
#region Basic Item Drawers
/// <summary>
/// Default list item drawer implementation.
/// </summary>
/// <remarks>
/// <para>Always presents the label "Item drawer not implemented.".</para>
/// </remarks>
/// <param name="position">Position to draw list item control(s).</param>
/// <param name="item">Value of list item.</param>
/// <returns>
/// Unmodified value of list item.
/// </returns>
/// <typeparam name="T">Type of list item.</typeparam>
public static T DefaultItemDrawer<T>(Rect position, T item) {
GUI.Label(position, "Item drawer not implemented.");
return item;
}
/// <summary>
/// Draws text field allowing list items to be edited.
/// </summary>
/// <remarks>
/// <para>Null values are automatically changed to empty strings since null
/// values cannot be edited using a text field.</para>
/// <para>Value of <c>GUI.changed</c> is set to <c>true</c> if value of item
/// is modified.</para>
/// </remarks>
/// <param name="position">Position to draw list item control(s).</param>
/// <param name="item">Value of list item.</param>
/// <returns>
/// Modified value of list item.
/// </returns>
public static string TextFieldItemDrawer(Rect position, string item) {
if (item == null) {
item = "";
GUI.changed = true;
}
return EditorGUI.TextField(position, item);
}
#endregion
/// <summary>
/// Gets the default list control implementation.
/// </summary>
private static ReorderableListControl DefaultListControl { get; set; }
static ReorderableListGUI() {
DefaultListControl = new ReorderableListControl();
// Duplicate default styles to prevent user scripts from interferring with
// the default list control instance.
DefaultListControl.ContainerStyle = new GUIStyle(ReorderableListStyles.Container);
DefaultListControl.FooterButtonStyle = new GUIStyle(ReorderableListStyles.FooterButton);
DefaultListControl.ItemButtonStyle = new GUIStyle(ReorderableListStyles.ItemButton);
IndexOfChangedItem = -1;
}
private static GUIContent s_Temp = new GUIContent();
#region Title Control
/// <summary>
/// Draw title control for list field.
/// </summary>
/// <remarks>
/// <para>When needed, should be shown immediately before list field.</para>
/// </remarks>
/// <example>
/// <code language="csharp"><![CDATA[
/// ReorderableListGUI.Title(titleContent);
/// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer);
/// ]]></code>
/// <code language="unityscript"><![CDATA[
/// ReorderableListGUI.Title(titleContent);
/// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer);
/// ]]></code>
/// </example>
/// <param name="title">Content for title control.</param>
public static void Title(GUIContent title) {
Rect position = GUILayoutUtility.GetRect(title, ReorderableListStyles.Title);
position.height += 6;
Title(position, title);
}
/// <summary>
/// Draw title control for list field.
/// </summary>
/// <remarks>
/// <para>When needed, should be shown immediately before list field.</para>
/// </remarks>
/// <example>
/// <code language="csharp"><![CDATA[
/// ReorderableListGUI.Title("Your Title");
/// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer);
/// ]]></code>
/// <code language="unityscript"><![CDATA[
/// ReorderableListGUI.Title('Your Title');
/// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer);
/// ]]></code>
/// </example>
/// <param name="title">Text for title control.</param>
public static void Title(string title) {
s_Temp.text = title;
Title(s_Temp);
}
/// <summary>
/// Draw title control for list field with absolute positioning.
/// </summary>
/// <param name="position">Position of control.</param>
/// <param name="title">Content for title control.</param>
public static void Title(Rect position, GUIContent title) {
if (Event.current.type == EventType.Repaint)
ReorderableListStyles.Title.Draw(position, title, false, false, false, false);
}
/// <summary>
/// Draw title control for list field with absolute positioning.
/// </summary>
/// <param name="position">Position of control.</param>
/// <param name="text">Text for title control.</param>
public static void Title(Rect position, string text) {
s_Temp.text = text;
Title(position, s_Temp);
}
#endregion
#region List<T> Control
/// <summary>
/// Draw list field control.
/// </summary>
/// <param name="list">The list which can be reordered.</param>
/// <param name="drawItem">Callback to draw list item.</param>
/// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param>
/// <param name="itemHeight">Height of a single list item.</param>
/// <param name="flags">Optional flags to pass into list field.</param>
/// <typeparam name="T">Type of list item.</typeparam>
private static void DoListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, float itemHeight, ReorderableListFlags flags) {
var adaptor = new GenericListAdaptor<T>(list, drawItem, itemHeight);
ReorderableListControl.DrawControlFromState(adaptor, drawEmpty, flags);
}
/// <summary>
/// Draw list field control with absolute positioning.
/// </summary>
/// <param name="position">Position of control.</param>
/// <param name="list">The list which can be reordered.</param>
/// <param name="drawItem">Callback to draw list item.</param>
/// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param>
/// <param name="itemHeight">Height of a single list item.</param>
/// <param name="flags">Optional flags to pass into list field.</param>
/// <typeparam name="T">Type of list item.</typeparam>
private static void DoListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, float itemHeight, ReorderableListFlags flags) {
var adaptor = new GenericListAdaptor<T>(list, drawItem, itemHeight);
ReorderableListControl.DrawControlFromState(position, adaptor, drawEmpty, flags);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, float itemHeight, ReorderableListFlags flags) {
DoListField<T>(list, drawItem, drawEmpty, itemHeight, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, float itemHeight, ReorderableListFlags flags) {
DoListFieldAbsolute<T>(position, list, drawItem, drawEmpty, itemHeight, flags);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, float itemHeight) {
DoListField<T>(list, drawItem, drawEmpty, itemHeight, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, float itemHeight) {
DoListFieldAbsolute<T>(position, list, drawItem, drawEmpty, itemHeight, 0);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) {
DoListField<T>(list, drawItem, drawEmpty, DefaultItemHeight, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) {
DoListFieldAbsolute<T>(position, list, drawItem, drawEmpty, DefaultItemHeight, flags);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty) {
DoListField<T>(list, drawItem, drawEmpty, DefaultItemHeight, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty) {
DoListFieldAbsolute<T>(position, list, drawItem, drawEmpty, DefaultItemHeight, 0);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight, ReorderableListFlags flags) {
DoListField<T>(list, drawItem, null, itemHeight, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight, ReorderableListFlags flags) {
DoListFieldAbsolute<T>(position, list, drawItem, null, itemHeight, flags);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight) {
DoListField<T>(list, drawItem, null, itemHeight, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight) {
DoListFieldAbsolute<T>(position, list, drawItem, null, itemHeight, 0);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListFlags flags) {
DoListField<T>(list, drawItem, null, DefaultItemHeight, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListFlags flags) {
DoListFieldAbsolute<T>(position, list, drawItem, null, DefaultItemHeight, flags);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem) {
DoListField<T>(list, drawItem, null, DefaultItemHeight, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem) {
DoListFieldAbsolute<T>(position, list, drawItem, null, DefaultItemHeight, 0);
}
/// <summary>
/// Calculate height of list field for absolute positioning.
/// </summary>
/// <param name="itemCount">Count of items in list.</param>
/// <param name="itemHeight">Fixed height of list item.</param>
/// <param name="flags">Optional flags to pass into list field.</param>
/// <returns>
/// Required list height in pixels.
/// </returns>
public static float CalculateListFieldHeight(int itemCount, float itemHeight, ReorderableListFlags flags) {
// We need to push/pop flags so that nested controls are properly calculated.
var restoreFlags = DefaultListControl.Flags;
try {
DefaultListControl.Flags = flags;
return DefaultListControl.CalculateListHeight(itemCount, itemHeight);
}
finally {
DefaultListControl.Flags = restoreFlags;
}
}
/// <inheritdoc cref="CalculateListFieldHeight(int, float, ReorderableListFlags)"/>
public static float CalculateListFieldHeight(int itemCount, ReorderableListFlags flags) {
return CalculateListFieldHeight(itemCount, DefaultItemHeight, flags);
}
/// <inheritdoc cref="CalculateListFieldHeight(int, float, ReorderableListFlags)"/>
public static float CalculateListFieldHeight(int itemCount, float itemHeight) {
return CalculateListFieldHeight(itemCount, itemHeight, 0);
}
/// <inheritdoc cref="CalculateListFieldHeight(int, float, ReorderableListFlags)"/>
public static float CalculateListFieldHeight(int itemCount) {
return CalculateListFieldHeight(itemCount, DefaultItemHeight, 0);
}
#endregion
#region SerializedProperty Control
/// <summary>
/// Draw list field control for serializable property array.
/// </summary>
/// <param name="arrayProperty">Serializable property.</param>
/// <param name="fixedItemHeight">Use fixed height for items rather than <see cref="UnityEditor.EditorGUI.GetPropertyHeight(SerializedProperty)"/>.</param>
/// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param>
/// <param name="flags">Optional flags to pass into list field.</param>
private static void DoListField(SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) {
var adaptor = new SerializedPropertyAdaptor(arrayProperty, fixedItemHeight);
ReorderableListControl.DrawControlFromState(adaptor, drawEmpty, flags);
}
/// <summary>
/// Draw list field control for serializable property array.
/// </summary>
/// <param name="position">Position of control.</param>
/// <param name="arrayProperty">Serializable property.</param>
/// <param name="fixedItemHeight">Use fixed height for items rather than <see cref="UnityEditor.EditorGUI.GetPropertyHeight(SerializedProperty)"/>.</param>
/// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param>
/// <param name="flags">Optional flags to pass into list field.</param>
private static void DoListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) {
var adaptor = new SerializedPropertyAdaptor(arrayProperty, fixedItemHeight);
ReorderableListControl.DrawControlFromState(position, adaptor, drawEmpty, flags);
}
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) {
DoListField(arrayProperty, 0, drawEmpty, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) {
DoListFieldAbsolute(position, arrayProperty, 0, drawEmpty, flags);
}
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty, ReorderableListControl.DrawEmpty drawEmpty) {
DoListField(arrayProperty, 0, drawEmpty, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, ReorderableListControl.DrawEmptyAbsolute drawEmpty) {
DoListFieldAbsolute(position, arrayProperty, 0, drawEmpty, 0);
}
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty, ReorderableListFlags flags) {
DoListField(arrayProperty, 0, null, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, ReorderableListFlags flags) {
DoListFieldAbsolute(position, arrayProperty, 0, null, flags);
}
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty) {
DoListField(arrayProperty, 0, null, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty) {
DoListFieldAbsolute(position, arrayProperty, 0, null, 0);
}
/// <summary>
/// Calculate height of list field for absolute positioning.
/// </summary>
/// <param name="arrayProperty">Serializable property.</param>
/// <param name="flags">Optional flags to pass into list field.</param>
/// <returns>
/// Required list height in pixels.
/// </returns>
public static float CalculateListFieldHeight(SerializedProperty arrayProperty, ReorderableListFlags flags) {
// We need to push/pop flags so that nested controls are properly calculated.
var restoreFlags = DefaultListControl.Flags;
try {
DefaultListControl.Flags = flags;
return DefaultListControl.CalculateListHeight(new SerializedPropertyAdaptor(arrayProperty));
}
finally {
DefaultListControl.Flags = restoreFlags;
}
}
/// <inheritdoc cref="CalculateListFieldHeight(SerializedProperty, ReorderableListFlags)"/>
public static float CalculateListFieldHeight(SerializedProperty arrayProperty) {
return CalculateListFieldHeight(arrayProperty, 0);
}
#endregion
#region SerializedProperty Control (Fixed Item Height)
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) {
DoListField(arrayProperty, fixedItemHeight, drawEmpty, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) {
DoListFieldAbsolute(position, arrayProperty, fixedItemHeight, drawEmpty, flags);
}
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmpty drawEmpty) {
DoListField(arrayProperty, fixedItemHeight, drawEmpty, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmptyAbsolute drawEmpty) {
DoListFieldAbsolute(position, arrayProperty, fixedItemHeight, drawEmpty, 0);
}
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListFlags flags) {
DoListField(arrayProperty, fixedItemHeight, null, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListFlags flags) {
DoListFieldAbsolute(position, arrayProperty, fixedItemHeight, null, flags);
}
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty, float fixedItemHeight) {
DoListField(arrayProperty, fixedItemHeight, null, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight) {
DoListFieldAbsolute(position, arrayProperty, fixedItemHeight, null, 0);
}
#endregion
#region Adaptor Control
/// <summary>
/// Draw list field control for adapted collection.
/// </summary>
/// <param name="adaptor">Reorderable list adaptor.</param>
/// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param>
/// <param name="flags">Optional flags to pass into list field.</param>
private static void DoListField(IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags = 0) {
ReorderableListControl.DrawControlFromState(adaptor, drawEmpty, flags);
}
/// <summary>
/// Draw list field control for adapted collection.
/// </summary>
/// <param name="position">Position of control.</param>
/// <param name="adaptor">Reorderable list adaptor.</param>
/// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param>
/// <param name="flags">Optional flags to pass into list field.</param>
private static void DoListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags = 0) {
ReorderableListControl.DrawControlFromState(position, adaptor, drawEmpty, flags);
}
/// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) {
DoListField(adaptor, drawEmpty, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) {
DoListFieldAbsolute(position, adaptor, drawEmpty, flags);
}
/// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty) {
DoListField(adaptor, drawEmpty, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty) {
DoListFieldAbsolute(position, adaptor, drawEmpty, 0);
}
/// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(IReorderableListAdaptor adaptor, ReorderableListFlags flags) {
DoListField(adaptor, null, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor, ReorderableListFlags flags) {
DoListFieldAbsolute(position, adaptor, null, flags);
}
/// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(IReorderableListAdaptor adaptor) {
DoListField(adaptor, null, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor) {
DoListFieldAbsolute(position, adaptor, null, 0);
}
/// <summary>
/// Calculate height of list field for adapted collection.
/// </summary>
/// <param name="adaptor">Reorderable list adaptor.</param>
/// <param name="flags">Optional flags to pass into list field.</param>
/// <returns>
/// Required list height in pixels.
/// </returns>
public static float CalculateListFieldHeight(IReorderableListAdaptor adaptor, ReorderableListFlags flags) {
// We need to push/pop flags so that nested controls are properly calculated.
var restoreFlags = DefaultListControl.Flags;
try {
DefaultListControl.Flags = flags;
return DefaultListControl.CalculateListHeight(adaptor);
}
finally {
DefaultListControl.Flags = restoreFlags;
}
}
/// <inheritdoc cref="CalculateListFieldHeight(IReorderableListAdaptor, ReorderableListFlags)"/>
public static float CalculateListFieldHeight(IReorderableListAdaptor adaptor) {
return CalculateListFieldHeight(adaptor, 0);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace DapWebApi.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);
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using NUnit.Framework;
using QuantConnect.Brokerages.Binance;
using QuantConnect.Configuration;
using Moq;
using QuantConnect.Brokerages;
using QuantConnect.Tests.Common.Securities;
using QuantConnect.Orders;
using QuantConnect.Logging;
using System.Threading;
using QuantConnect.Lean.Engine.DataFeeds;
namespace QuantConnect.Tests.Brokerages.Binance
{
[TestFixture, Explicit("This test requires a configured and testable Binance practice account")]
public partial class BinanceBrokerageTests : BrokerageTests
{
private BinanceRestApiClient _binanceApi;
/// <summary>
/// Creates the brokerage under test and connects it
/// </summary>
/// <param name="orderProvider"></param>
/// <param name="securityProvider"></param>
/// <returns></returns>
protected override IBrokerage CreateBrokerage(IOrderProvider orderProvider, ISecurityProvider securityProvider)
{
var securities = new SecurityManager(new TimeKeeper(DateTime.UtcNow, TimeZones.NewYork))
{
{ Symbol, CreateSecurity(Symbol) }
};
var transactions = new SecurityTransactionManager(null, securities);
transactions.SetOrderProcessor(new FakeOrderProcessor());
var algorithm = new Mock<IAlgorithm>();
algorithm.Setup(a => a.Transactions).Returns(transactions);
algorithm.Setup(a => a.BrokerageModel).Returns(new BinanceBrokerageModel());
algorithm.Setup(a => a.Portfolio).Returns(new SecurityPortfolioManager(securities, transactions));
var apiKey = Config.Get("binance-api-key");
var apiSecret = Config.Get("binance-api-secret");
var apiUrl = Config.Get("binance-api-url", "https://api.binance.com");
var websocketUrl = Config.Get("binance-websocket-url", "wss://stream.binance.com:9443/ws");
_binanceApi = new BinanceRestApiClient(
new SymbolPropertiesDatabaseSymbolMapper(Market.Binance),
algorithm.Object?.Portfolio,
apiKey,
apiSecret,
apiUrl);
return new BinanceBrokerage(
apiKey,
apiSecret,
apiUrl,
websocketUrl,
algorithm.Object,
new AggregationManager(),
null
);
}
/// <summary>
/// Gets Binance symbol mapper
/// </summary>
protected ISymbolMapper SymbolMapper => new SymbolPropertiesDatabaseSymbolMapper(Market.Binance);
/// <summary>
/// Gets the symbol to be traded, must be shortable
/// </summary>
protected override Symbol Symbol => StaticSymbol;
private static Symbol StaticSymbol => Symbol.Create("ETHBTC", SecurityType.Crypto, Market.Binance);
/// <summary>
/// Gets the security type associated with the <see cref="BrokerageTests.Symbol" />
/// </summary>
protected override SecurityType SecurityType => SecurityType.Crypto;
public static TestCaseData[] OrderParameters => new[]
{
new TestCaseData(new MarketOrderTestParameters(StaticSymbol)).SetName("MarketOrder"),
new TestCaseData(new LimitOrderTestParameters(StaticSymbol, HighPrice, LowPrice)).SetName("LimitOrder"),
new TestCaseData(new StopLimitOrderTestParameters(StaticSymbol, HighPrice, LowPrice)).SetName("StopLimitOrder"),
};
/// <summary>
/// Gets a high price for the specified symbol so a limit sell won't fill
/// </summary>
private const decimal HighPrice = 0.04m;
/// <summary>
/// Gets a low price for the specified symbol so a limit buy won't fill
/// </summary>
private const decimal LowPrice = 0.01m;
/// <summary>
/// Gets the current market price of the specified security
/// </summary>
protected override decimal GetAskPrice(Symbol symbol)
{
var brokerageSymbol = SymbolMapper.GetBrokerageSymbol(symbol);
var prices = _binanceApi.GetTickers();
return prices
.FirstOrDefault(t => t.Symbol == brokerageSymbol)
.Price;
}
/// <summary>
/// Returns wether or not the brokers order methods implementation are async
/// </summary>
protected override bool IsAsync() => false;
/// <summary>
/// Gets the default order quantity. Min order 10USD.
/// </summary>
protected override decimal GetDefaultQuantity() => 0.01m;
[Test, TestCaseSource(nameof(OrderParameters))]
public override void CancelOrders(OrderTestParameters parameters)
{
base.CancelOrders(parameters);
}
[Test, TestCaseSource(nameof(OrderParameters))]
public override void LongFromZero(OrderTestParameters parameters)
{
base.LongFromZero(parameters);
}
[Test, TestCaseSource(nameof(OrderParameters))]
public override void CloseFromLong(OrderTestParameters parameters)
{
base.CloseFromLong(parameters);
}
[Test, TestCaseSource(nameof(OrderParameters))]
public override void ShortFromZero(OrderTestParameters parameters)
{
base.ShortFromZero(parameters);
}
[Test, TestCaseSource(nameof(OrderParameters))]
public override void CloseFromShort(OrderTestParameters parameters)
{
base.CloseFromShort(parameters);
}
[Test, TestCaseSource(nameof(OrderParameters))]
public override void ShortFromLong(OrderTestParameters parameters)
{
base.ShortFromLong(parameters);
}
[Test, TestCaseSource(nameof(OrderParameters))]
public override void LongFromShort(OrderTestParameters parameters)
{
base.LongFromShort(parameters);
}
[Test, Ignore("Holdings are now set to 0 swaps at the start of each launch. Not meaningful.")]
public override void GetAccountHoldings()
{
Log.Trace("");
Log.Trace("GET ACCOUNT HOLDINGS");
Log.Trace("");
var before = Brokerage.GetAccountHoldings();
Assert.AreEqual(0, before.Count());
PlaceOrderWaitForStatus(new MarketOrder(Symbol, GetDefaultQuantity(), DateTime.Now));
Thread.Sleep(3000);
var after = Brokerage.GetAccountHoldings();
Assert.AreEqual(0, after.Count());
}
protected override void ModifyOrderUntilFilled(Order order, OrderTestParameters parameters, double secondsTimeout = 90)
{
Assert.Pass("Order update not supported. Please cancel and re-create.");
}
}
}
| |
using System;
using System.Collections;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Math.EC.Endo;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Collections;
using Org.BouncyCastle.Utilities.Encoders;
namespace Org.BouncyCastle.Asn1.Sec
{
public sealed class SecNamedCurves
{
private SecNamedCurves()
{
}
private static ECCurve ConfigureCurve(ECCurve curve)
{
return curve;
}
private static ECCurve ConfigureCurveGlv(ECCurve c, GlvTypeBParameters p)
{
return c.Configure().SetEndomorphism(new GlvTypeBEndomorphism(c, p)).Create();
}
private static BigInteger FromHex(string hex)
{
return new BigInteger(1, Hex.Decode(hex));
}
/*
* secp112r1
*/
internal class Secp112r1Holder
: X9ECParametersHolder
{
private Secp112r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp112r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = (2^128 - 3) / 76439
BigInteger p = FromHex("DB7C2ABF62E35E668076BEAD208B");
BigInteger a = FromHex("DB7C2ABF62E35E668076BEAD2088");
BigInteger b = FromHex("659EF8BA043916EEDE8911702B22");
byte[] S = Hex.Decode("00F50B028E4D696E676875615175290472783FB1");
BigInteger n = FromHex("DB7C2ABF62E35E7628DFAC6561C5");
BigInteger h = BigInteger.One;
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "09487239995A5EE76B55F9C2F098"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "09487239995A5EE76B55F9C2F098"
+ "A89CE5AF8724C0A23E0E0FF77500"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp112r2
*/
internal class Secp112r2Holder
: X9ECParametersHolder
{
private Secp112r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp112r2Holder();
protected override X9ECParameters CreateParameters()
{
// p = (2^128 - 3) / 76439
BigInteger p = FromHex("DB7C2ABF62E35E668076BEAD208B");
BigInteger a = FromHex("6127C24C05F38A0AAAF65C0EF02C");
BigInteger b = FromHex("51DEF1815DB5ED74FCC34C85D709");
byte[] S = Hex.Decode("002757A1114D696E6768756151755316C05E0BD4");
BigInteger n = FromHex("36DF0AAFD8B8D7597CA10520D04B");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "4BA30AB5E892B4E1649DD0928643"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "4BA30AB5E892B4E1649DD0928643"
+ "ADCD46F5882E3747DEF36E956E97"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp128r1
*/
internal class Secp128r1Holder
: X9ECParametersHolder
{
private Secp128r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp128r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^128 - 2^97 - 1
BigInteger p = FromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF");
BigInteger a = FromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC");
BigInteger b = FromHex("E87579C11079F43DD824993C2CEE5ED3");
byte[] S = Hex.Decode("000E0D4D696E6768756151750CC03A4473D03679");
BigInteger n = FromHex("FFFFFFFE0000000075A30D1B9038A115");
BigInteger h = BigInteger.One;
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "161FF7528B899B2D0C28607CA52C5B86"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "161FF7528B899B2D0C28607CA52C5B86"
+ "CF5AC8395BAFEB13C02DA292DDED7A83"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp128r2
*/
internal class Secp128r2Holder
: X9ECParametersHolder
{
private Secp128r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp128r2Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^128 - 2^97 - 1
BigInteger p = FromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF");
BigInteger a = FromHex("D6031998D1B3BBFEBF59CC9BBFF9AEE1");
BigInteger b = FromHex("5EEEFCA380D02919DC2C6558BB6D8A5D");
byte[] S = Hex.Decode("004D696E67687561517512D8F03431FCE63B88F4");
BigInteger n = FromHex("3FFFFFFF7FFFFFFFBE0024720613B5A3");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "7B6AA5D85E572983E6FB32A7CDEBC140"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "7B6AA5D85E572983E6FB32A7CDEBC140"
+ "27B6916A894D3AEE7106FE805FC34B44"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp160k1
*/
internal class Secp160k1Holder
: X9ECParametersHolder
{
private Secp160k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp160k1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73");
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(7);
byte[] S = null;
BigInteger n = FromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3");
BigInteger h = BigInteger.One;
GlvTypeBParameters glv = new GlvTypeBParameters(
new BigInteger("9ba48cba5ebcb9b6bd33b92830b2a2e0e192f10a", 16),
new BigInteger("c39c6c3b3a36d7701b9c71a1f5804ae5d0003f4", 16),
new BigInteger[]{
new BigInteger("9162fbe73984472a0a9e", 16),
new BigInteger("-96341f1138933bc2f505", 16) },
new BigInteger[]{
new BigInteger("127971af8721782ecffa3", 16),
new BigInteger("9162fbe73984472a0a9e", 16) },
new BigInteger("9162fbe73984472a0a9d0590", 16),
new BigInteger("96341f1138933bc2f503fd44", 16),
176);
ECCurve curve = ConfigureCurveGlv(new FpCurve(p, a, b, n, h), glv);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB"
+ "938CF935318FDCED6BC28286531733C3F03C4FEE"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp160r1
*/
internal class Secp160r1Holder
: X9ECParametersHolder
{
private Secp160r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp160r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^160 - 2^31 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF");
BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC");
BigInteger b = FromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45");
byte[] S = Hex.Decode("1053CDE42C14D696E67687561517533BF3F83345");
BigInteger n = FromHex("0100000000000000000001F4C8F927AED3CA752257");
BigInteger h = BigInteger.One;
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "4A96B5688EF573284664698968C38BB913CBFC82"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "4A96B5688EF573284664698968C38BB913CBFC82"
+ "23A628553168947D59DCC912042351377AC5FB32"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp160r2
*/
internal class Secp160r2Holder
: X9ECParametersHolder
{
private Secp160r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp160r2Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73");
BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC70");
BigInteger b = FromHex("B4E134D3FB59EB8BAB57274904664D5AF50388BA");
byte[] S = Hex.Decode("B99B99B099B323E02709A4D696E6768756151751");
BigInteger n = FromHex("0100000000000000000000351EE786A818F3A1A16B");
BigInteger h = BigInteger.One;
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "52DCB034293A117E1F4FF11B30F7199D3144CE6D"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "52DCB034293A117E1F4FF11B30F7199D3144CE6D"
+ "FEAFFEF2E331F296E071FA0DF9982CFEA7D43F2E"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp192k1
*/
internal class Secp192k1Holder
: X9ECParametersHolder
{
private Secp192k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp192k1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37");
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(3);
byte[] S = null;
BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D");
BigInteger h = BigInteger.One;
GlvTypeBParameters glv = new GlvTypeBParameters(
new BigInteger("bb85691939b869c1d087f601554b96b80cb4f55b35f433c2", 16),
new BigInteger("3d84f26c12238d7b4f3d516613c1759033b1a5800175d0b1", 16),
new BigInteger[]{
new BigInteger("71169be7330b3038edb025f1", 16),
new BigInteger("-b3fb3400dec5c4adceb8655c", 16) },
new BigInteger[]{
new BigInteger("12511cfe811d0f4e6bc688b4d", 16),
new BigInteger("71169be7330b3038edb025f1", 16) },
new BigInteger("71169be7330b3038edb025f1d0f9", 16),
new BigInteger("b3fb3400dec5c4adceb8655d4c94", 16),
208);
ECCurve curve = ConfigureCurveGlv(new FpCurve(p, a, b, n, h), glv);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D"
+ "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp192r1
*/
internal class Secp192r1Holder
: X9ECParametersHolder
{
private Secp192r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp192r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^192 - 2^64 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF");
BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC");
BigInteger b = FromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1");
byte[] S = Hex.Decode("3045AE6FC8422F64ED579528D38120EAE12196D5");
BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831");
BigInteger h = BigInteger.One;
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012"
+ "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp224k1
*/
internal class Secp224k1Holder
: X9ECParametersHolder
{
private Secp224k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp224k1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^224 - 2^32 - 2^12 - 2^11 - 2^9 - 2^7 - 2^4 - 2 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFE56D");
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(5);
byte[] S = null;
BigInteger n = FromHex("010000000000000000000000000001DCE8D2EC6184CAF0A971769FB1F7");
BigInteger h = BigInteger.One;
GlvTypeBParameters glv = new GlvTypeBParameters(
new BigInteger("fe0e87005b4e83761908c5131d552a850b3f58b749c37cf5b84d6768", 16),
new BigInteger("60dcd2104c4cbc0be6eeefc2bdd610739ec34e317f9b33046c9e4788", 16),
new BigInteger[]{
new BigInteger("6b8cf07d4ca75c88957d9d670591", 16),
new BigInteger("-b8adf1378a6eb73409fa6c9c637d", 16) },
new BigInteger[]{
new BigInteger("1243ae1b4d71613bc9f780a03690e", 16),
new BigInteger("6b8cf07d4ca75c88957d9d670591", 16) },
new BigInteger("6b8cf07d4ca75c88957d9d67059037a4", 16),
new BigInteger("b8adf1378a6eb73409fa6c9c637ba7f5", 16),
240);
ECCurve curve = ConfigureCurveGlv(new FpCurve(p, a, b, n, h), glv);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C"
+ "7E089FED7FBA344282CAFBD6F7E319F7C0B0BD59E2CA4BDB556D61A5"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp224r1
*/
internal class Secp224r1Holder
: X9ECParametersHolder
{
private Secp224r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp224r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^224 - 2^96 + 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001");
BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE");
BigInteger b = FromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4");
byte[] S = Hex.Decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5");
BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D");
BigInteger h = BigInteger.One;
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21"
+ "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp256k1
*/
internal class Secp256k1Holder
: X9ECParametersHolder
{
private Secp256k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp256k1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F");
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.ValueOf(7);
byte[] S = null;
BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");
BigInteger h = BigInteger.One;
GlvTypeBParameters glv = new GlvTypeBParameters(
new BigInteger("7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", 16),
new BigInteger("5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72", 16),
new BigInteger[]{
new BigInteger("3086d221a7d46bcde86c90e49284eb15", 16),
new BigInteger("-e4437ed6010e88286f547fa90abfe4c3", 16) },
new BigInteger[]{
new BigInteger("114ca50f7a8e2f3f657c1108d9d44cfd8", 16),
new BigInteger("3086d221a7d46bcde86c90e49284eb15", 16) },
new BigInteger("3086d221a7d46bcde86c90e49284eb153dab", 16),
new BigInteger("e4437ed6010e88286f547fa90abfe4c42212", 16),
272);
ECCurve curve = ConfigureCurveGlv(new FpCurve(p, a, b, n, h), glv);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798"
+ "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp256r1
*/
internal class Secp256r1Holder
: X9ECParametersHolder
{
private Secp256r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp256r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1
BigInteger p = FromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF");
BigInteger a = FromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC");
BigInteger b = FromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B");
byte[] S = Hex.Decode("C49D360886E704936A6678E1139D26B7819F7E90");
BigInteger n = FromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
BigInteger h = BigInteger.One;
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296"
+ "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp384r1
*/
internal class Secp384r1Holder
: X9ECParametersHolder
{
private Secp384r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp384r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^384 - 2^128 - 2^96 + 2^32 - 1
BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF");
BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC");
BigInteger b = FromHex("B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF");
byte[] S = Hex.Decode("A335926AA319A27A1D00896A6773A4827ACDAC73");
BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973");
BigInteger h = BigInteger.One;
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7"
+ "3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* secp521r1
*/
internal class Secp521r1Holder
: X9ECParametersHolder
{
private Secp521r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Secp521r1Holder();
protected override X9ECParameters CreateParameters()
{
// p = 2^521 - 1
BigInteger p = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");
BigInteger a = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC");
BigInteger b = FromHex("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00");
byte[] S = Hex.Decode("D09E8800291CB85396CC6717393284AAA0DA64BA");
BigInteger n = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409");
BigInteger h = BigInteger.One;
ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66"
+ "011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect113r1
*/
internal class Sect113r1Holder
: X9ECParametersHolder
{
private Sect113r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect113r1Holder();
private const int m = 113;
private const int k = 9;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("003088250CA6E7C7FE649CE85820F7");
BigInteger b = FromHex("00E8BEE4D3E2260744188BE0E9C723");
byte[] S = Hex.Decode("10E723AB14D696E6768756151756FEBF8FCB49A9");
BigInteger n = FromHex("0100000000000000D9CCEC8A39E56F");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "009D73616F35F4AB1407D73562C10F"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "009D73616F35F4AB1407D73562C10F"
+ "00A52830277958EE84D1315ED31886"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect113r2
*/
internal class Sect113r2Holder
: X9ECParametersHolder
{
private Sect113r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect113r2Holder();
private const int m = 113;
private const int k = 9;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("00689918DBEC7E5A0DD6DFC0AA55C7");
BigInteger b = FromHex("0095E9A9EC9B297BD4BF36E059184F");
byte[] S = Hex.Decode("10C0FB15760860DEF1EEF4D696E676875615175D");
BigInteger n = FromHex("010000000000000108789B2496AF93");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "01A57A6A7B26CA5EF52FCDB8164797"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "01A57A6A7B26CA5EF52FCDB8164797"
+ "00B3ADC94ED1FE674C06E695BABA1D"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect131r1
*/
internal class Sect131r1Holder
: X9ECParametersHolder
{
private Sect131r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect131r1Holder();
private const int m = 131;
private const int k1 = 2;
private const int k2 = 3;
private const int k3 = 8;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("07A11B09A76B562144418FF3FF8C2570B8");
BigInteger b = FromHex("0217C05610884B63B9C6C7291678F9D341");
byte[] S = Hex.Decode("4D696E676875615175985BD3ADBADA21B43A97E2");
BigInteger n = FromHex("0400000000000000023123953A9464B54D");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "0081BAF91FDF9833C40F9C181343638399"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "0081BAF91FDF9833C40F9C181343638399"
+ "078C6E7EA38C001F73C8134B1B4EF9E150"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect131r2
*/
internal class Sect131r2Holder
: X9ECParametersHolder
{
private Sect131r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect131r2Holder();
private const int m = 131;
private const int k1 = 2;
private const int k2 = 3;
private const int k3 = 8;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("03E5A88919D7CAFCBF415F07C2176573B2");
BigInteger b = FromHex("04B8266A46C55657AC734CE38F018F2192");
byte[] S = Hex.Decode("985BD3ADBAD4D696E676875615175A21B43A97E3");
BigInteger n = FromHex("0400000000000000016954A233049BA98F");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "0356DCD8F2F95031AD652D23951BB366A8"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "0356DCD8F2F95031AD652D23951BB366A8"
+ "0648F06D867940A5366D9E265DE9EB240F"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect163k1
*/
internal class Sect163k1Holder
: X9ECParametersHolder
{
private Sect163k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect163k1Holder();
private const int m = 163;
private const int k1 = 3;
private const int k2 = 6;
private const int k3 = 7;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.One;
BigInteger b = BigInteger.One;
byte[] S = null;
BigInteger n = FromHex("04000000000000000000020108A2E0CC0D99F8A5EF");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "02FE13C0537BBC11ACAA07D793DE4E6D5E5C94EEE8"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "02FE13C0537BBC11ACAA07D793DE4E6D5E5C94EEE8"
+ "0289070FB05D38FF58321F2E800536D538CCDAA3D9"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect163r1
*/
internal class Sect163r1Holder
: X9ECParametersHolder
{
private Sect163r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect163r1Holder();
private const int m = 163;
private const int k1 = 3;
private const int k2 = 6;
private const int k3 = 7;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("07B6882CAAEFA84F9554FF8428BD88E246D2782AE2");
BigInteger b = FromHex("0713612DCDDCB40AAB946BDA29CA91F73AF958AFD9");
byte[] S = Hex.Decode("24B7B137C8A14D696E6768756151756FD0DA2E5C");
BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFF48AAB689C29CA710279B");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "0369979697AB43897789566789567F787A7876A654"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "0369979697AB43897789566789567F787A7876A654"
+ "00435EDB42EFAFB2989D51FEFCE3C80988F41FF883"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect163r2
*/
internal class Sect163r2Holder
: X9ECParametersHolder
{
private Sect163r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect163r2Holder();
private const int m = 163;
private const int k1 = 3;
private const int k2 = 6;
private const int k3 = 7;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.One;
BigInteger b = FromHex("020A601907B8C953CA1481EB10512F78744A3205FD");
byte[] S = Hex.Decode("85E25BFE5C86226CDB12016F7553F9D0E693A268");
BigInteger n = FromHex("040000000000000000000292FE77E70C12A4234C33");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "03F0EBA16286A2D57EA0991168D4994637E8343E36"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "03F0EBA16286A2D57EA0991168D4994637E8343E36"
+ "00D51FBC6C71A0094FA2CDD545B11C5C0C797324F1"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect193r1
*/
internal class Sect193r1Holder
: X9ECParametersHolder
{
private Sect193r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect193r1Holder();
private const int m = 193;
private const int k = 15;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("0017858FEB7A98975169E171F77B4087DE098AC8A911DF7B01");
BigInteger b = FromHex("00FDFB49BFE6C3A89FACADAA7A1E5BBC7CC1C2E5D831478814");
byte[] S = Hex.Decode("103FAEC74D696E676875615175777FC5B191EF30");
BigInteger n = FromHex("01000000000000000000000000C7F34A778F443ACC920EBA49");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "01F481BC5F0FF84A74AD6CDF6FDEF4BF6179625372D8C0C5E1"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "01F481BC5F0FF84A74AD6CDF6FDEF4BF6179625372D8C0C5E1"
+ "0025E399F2903712CCF3EA9E3A1AD17FB0B3201B6AF7CE1B05"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect193r2
*/
internal class Sect193r2Holder
: X9ECParametersHolder
{
private Sect193r2Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect193r2Holder();
private const int m = 193;
private const int k = 15;
protected override X9ECParameters CreateParameters()
{
BigInteger a = FromHex("0163F35A5137C2CE3EA6ED8667190B0BC43ECD69977702709B");
BigInteger b = FromHex("00C9BB9E8927D4D64C377E2AB2856A5B16E3EFB7F61D4316AE");
byte[] S = Hex.Decode("10B7B4D696E676875615175137C8A16FD0DA2211");
BigInteger n = FromHex("010000000000000000000000015AAB561B005413CCD4EE99D5");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "00D9B67D192E0367C803F39E1A7E82CA14A651350AAE617E8F"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "00D9B67D192E0367C803F39E1A7E82CA14A651350AAE617E8F"
+ "01CE94335607C304AC29E7DEFBD9CA01F596F927224CDECF6C"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect233k1
*/
internal class Sect233k1Holder
: X9ECParametersHolder
{
private Sect233k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect233k1Holder();
private const int m = 233;
private const int k = 74;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.One;
byte[] S = null;
BigInteger n = FromHex("8000000000000000000000000000069D5BB915BCD46EFB1AD5F173ABDF");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "017232BA853A7E731AF129F22FF4149563A419C26BF50A4C9D6EEFAD6126"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "017232BA853A7E731AF129F22FF4149563A419C26BF50A4C9D6EEFAD6126"
+ "01DB537DECE819B7F70F555A67C427A8CD9BF18AEB9B56E0C11056FAE6A3"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect233r1
*/
internal class Sect233r1Holder
: X9ECParametersHolder
{
private Sect233r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect233r1Holder();
private const int m = 233;
private const int k = 74;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.One;
BigInteger b = FromHex("0066647EDE6C332C7F8C0923BB58213B333B20E9CE4281FE115F7D8F90AD");
byte[] S = Hex.Decode("74D59FF07F6B413D0EA14B344B20A2DB049B50C3");
BigInteger n = FromHex("01000000000000000000000000000013E974E72F8A6922031D2603CFE0D7");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "00FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "00FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B"
+ "01006A08A41903350678E58528BEBF8A0BEFF867A7CA36716F7E01F81052"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect239k1
*/
internal class Sect239k1Holder
: X9ECParametersHolder
{
private Sect239k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect239k1Holder();
private const int m = 239;
private const int k = 158;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.One;
byte[] S = null;
BigInteger n = FromHex("2000000000000000000000000000005A79FEC67CB6E91F1C1DA800E478A5");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "29A0B6A887A983E9730988A68727A8B2D126C44CC2CC7B2A6555193035DC"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "29A0B6A887A983E9730988A68727A8B2D126C44CC2CC7B2A6555193035DC"
+ "76310804F12E549BDB011C103089E73510ACB275FC312A5DC6B76553F0CA"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect283k1
*/
internal class Sect283k1Holder
: X9ECParametersHolder
{
private Sect283k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect283k1Holder();
private const int m = 283;
private const int k1 = 5;
private const int k2 = 7;
private const int k3 = 12;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.One;
byte[] S = null;
BigInteger n = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE9AE2ED07577265DFF7F94451E061E163C61");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "0503213F78CA44883F1A3B8162F188E553CD265F23C1567A16876913B0C2AC2458492836"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "0503213F78CA44883F1A3B8162F188E553CD265F23C1567A16876913B0C2AC2458492836"
+ "01CCDA380F1C9E318D90F95D07E5426FE87E45C0E8184698E45962364E34116177DD2259"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect283r1
*/
internal class Sect283r1Holder
: X9ECParametersHolder
{
private Sect283r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect283r1Holder();
private const int m = 283;
private const int k1 = 5;
private const int k2 = 7;
private const int k3 = 12;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.One;
BigInteger b = FromHex("027B680AC8B8596DA5A4AF8A19A0303FCA97FD7645309FA2A581485AF6263E313B79A2F5");
byte[] S = Hex.Decode("77E2B07370EB0F832A6DD5B62DFC88CD06BB84BE");
BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEF90399660FC938A90165B042A7CEFADB307");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "05F939258DB7DD90E1934F8C70B0DFEC2EED25B8557EAC9C80E2E198F8CDBECD86B12053"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "05F939258DB7DD90E1934F8C70B0DFEC2EED25B8557EAC9C80E2E198F8CDBECD86B12053"
+ "03676854FE24141CB98FE6D4B20D02B4516FF702350EDDB0826779C813F0DF45BE8112F4"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect409k1
*/
internal class Sect409k1Holder
: X9ECParametersHolder
{
private Sect409k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect409k1Holder();
private const int m = 409;
private const int k = 87;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.One;
byte[] S = null;
BigInteger n = FromHex("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE5F83B2D4EA20400EC4557D5ED3E3E7CA5B4B5C83B8E01E5FCF");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "0060F05F658F49C1AD3AB1890F7184210EFD0987E307C84C27ACCFB8F9F67CC2C460189EB5AAAA62EE222EB1B35540CFE9023746"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "0060F05F658F49C1AD3AB1890F7184210EFD0987E307C84C27ACCFB8F9F67CC2C460189EB5AAAA62EE222EB1B35540CFE9023746"
+ "01E369050B7C4E42ACBA1DACBF04299C3460782F918EA427E6325165E9EA10E3DA5F6C42E9C55215AA9CA27A5863EC48D8E0286B"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect409r1
*/
internal class Sect409r1Holder
: X9ECParametersHolder
{
private Sect409r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect409r1Holder();
private const int m = 409;
private const int k = 87;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.One;
BigInteger b = FromHex("0021A5C2C8EE9FEB5C4B9A753B7B476B7FD6422EF1F3DD674761FA99D6AC27C8A9A197B272822F6CD57A55AA4F50AE317B13545F");
byte[] S = Hex.Decode("4099B5A457F9D69F79213D094C4BCD4D4262210B");
BigInteger n = FromHex("010000000000000000000000000000000000000000000000000001E2AAD6A612F33307BE5FA47C3C9E052F838164CD37D9A21173");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "015D4860D088DDB3496B0C6064756260441CDE4AF1771D4DB01FFE5B34E59703DC255A868A1180515603AEAB60794E54BB7996A7"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "015D4860D088DDB3496B0C6064756260441CDE4AF1771D4DB01FFE5B34E59703DC255A868A1180515603AEAB60794E54BB7996A7"
+ "0061B1CFAB6BE5F32BBFA78324ED106A7636B9C5A7BD198D0158AA4F5488D08F38514F1FDF4B4F40D2181B3681C364BA0273C706"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect571k1
*/
internal class Sect571k1Holder
: X9ECParametersHolder
{
private Sect571k1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect571k1Holder();
private const int m = 571;
private const int k1 = 2;
private const int k2 = 5;
private const int k3 = 10;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.One;
byte[] S = null;
BigInteger n = FromHex("020000000000000000000000000000000000000000000000000000000000000000000000131850E1F19A63E4B391A8DB917F4138B630D84BE5D639381E91DEB45CFE778F637C1001");
BigInteger h = BigInteger.ValueOf(4);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("02"
//+ "026EB7A859923FBC82189631F8103FE4AC9CA2970012D5D46024804801841CA44370958493B205E647DA304DB4CEB08CBBD1BA39494776FB988B47174DCA88C7E2945283A01C8972"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "026EB7A859923FBC82189631F8103FE4AC9CA2970012D5D46024804801841CA44370958493B205E647DA304DB4CEB08CBBD1BA39494776FB988B47174DCA88C7E2945283A01C8972"
+ "0349DC807F4FBF374F4AEADE3BCA95314DD58CEC9F307A54FFC61EFC006D8A2C9D4979C0AC44AEA74FBEBBB9F772AEDCB620B01A7BA7AF1B320430C8591984F601CD4C143EF1C7A3"));
return new X9ECParameters(curve, G, n, h, S);
}
}
/*
* sect571r1
*/
internal class Sect571r1Holder
: X9ECParametersHolder
{
private Sect571r1Holder() {}
internal static readonly X9ECParametersHolder Instance = new Sect571r1Holder();
private const int m = 571;
private const int k1 = 2;
private const int k2 = 5;
private const int k3 = 10;
protected override X9ECParameters CreateParameters()
{
BigInteger a = BigInteger.One;
BigInteger b = FromHex("02F40E7E2221F295DE297117B7F3D62F5C6A97FFCB8CEFF1CD6BA8CE4A9A18AD84FFABBD8EFA59332BE7AD6756A66E294AFD185A78FF12AA520E4DE739BACA0C7FFEFF7F2955727A");
byte[] S = Hex.Decode("2AA058F73A0E33AB486B0F610410C53A7F132310");
BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE661CE18FF55987308059B186823851EC7DD9CA1161DE93D5174D66E8382E9BB2FE84E47");
BigInteger h = BigInteger.ValueOf(2);
ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
//ECPoint G = curve.DecodePoint(Hex.Decode("03"
//+ "0303001D34B856296C16C0D40D3CD7750A93D1D2955FA80AA5F40FC8DB7B2ABDBDE53950F4C0D293CDD711A35B67FB1499AE60038614F1394ABFA3B4C850D927E1E7769C8EEC2D19"));
ECPoint G = curve.DecodePoint(Hex.Decode("04"
+ "0303001D34B856296C16C0D40D3CD7750A93D1D2955FA80AA5F40FC8DB7B2ABDBDE53950F4C0D293CDD711A35B67FB1499AE60038614F1394ABFA3B4C850D927E1E7769C8EEC2D19"
+ "037BF27342DA639B6DCCFFFEB73D69D78C6C27A6009CBBCA1980F8533921E8A684423E43BAB08A576291AF8F461BB2A8B3531D2F0485C19B16E2F1516E23DD3C1A4827AF1B8AC15B"));
return new X9ECParameters(curve, G, n, h, S);
}
}
private static readonly IDictionary objIds = Platform.CreateHashtable();
private static readonly IDictionary curves = Platform.CreateHashtable();
private static readonly IDictionary names = Platform.CreateHashtable();
private static void DefineCurve(
string name,
DerObjectIdentifier oid,
X9ECParametersHolder holder)
{
objIds.Add(Platform.ToLowerInvariant(name), oid);
names.Add(oid, name);
curves.Add(oid, holder);
}
static SecNamedCurves()
{
DefineCurve("secp112r1", SecObjectIdentifiers.SecP112r1, Secp112r1Holder.Instance);
DefineCurve("secp112r2", SecObjectIdentifiers.SecP112r2, Secp112r2Holder.Instance);
DefineCurve("secp128r1", SecObjectIdentifiers.SecP128r1, Secp128r1Holder.Instance);
DefineCurve("secp128r2", SecObjectIdentifiers.SecP128r2, Secp128r2Holder.Instance);
DefineCurve("secp160k1", SecObjectIdentifiers.SecP160k1, Secp160k1Holder.Instance);
DefineCurve("secp160r1", SecObjectIdentifiers.SecP160r1, Secp160r1Holder.Instance);
DefineCurve("secp160r2", SecObjectIdentifiers.SecP160r2, Secp160r2Holder.Instance);
DefineCurve("secp192k1", SecObjectIdentifiers.SecP192k1, Secp192k1Holder.Instance);
DefineCurve("secp192r1", SecObjectIdentifiers.SecP192r1, Secp192r1Holder.Instance);
DefineCurve("secp224k1", SecObjectIdentifiers.SecP224k1, Secp224k1Holder.Instance);
DefineCurve("secp224r1", SecObjectIdentifiers.SecP224r1, Secp224r1Holder.Instance);
DefineCurve("secp256k1", SecObjectIdentifiers.SecP256k1, Secp256k1Holder.Instance);
DefineCurve("secp256r1", SecObjectIdentifiers.SecP256r1, Secp256r1Holder.Instance);
DefineCurve("secp384r1", SecObjectIdentifiers.SecP384r1, Secp384r1Holder.Instance);
DefineCurve("secp521r1", SecObjectIdentifiers.SecP521r1, Secp521r1Holder.Instance);
DefineCurve("sect113r1", SecObjectIdentifiers.SecT113r1, Sect113r1Holder.Instance);
DefineCurve("sect113r2", SecObjectIdentifiers.SecT113r2, Sect113r2Holder.Instance);
DefineCurve("sect131r1", SecObjectIdentifiers.SecT131r1, Sect131r1Holder.Instance);
DefineCurve("sect131r2", SecObjectIdentifiers.SecT131r2, Sect131r2Holder.Instance);
DefineCurve("sect163k1", SecObjectIdentifiers.SecT163k1, Sect163k1Holder.Instance);
DefineCurve("sect163r1", SecObjectIdentifiers.SecT163r1, Sect163r1Holder.Instance);
DefineCurve("sect163r2", SecObjectIdentifiers.SecT163r2, Sect163r2Holder.Instance);
DefineCurve("sect193r1", SecObjectIdentifiers.SecT193r1, Sect193r1Holder.Instance);
DefineCurve("sect193r2", SecObjectIdentifiers.SecT193r2, Sect193r2Holder.Instance);
DefineCurve("sect233k1", SecObjectIdentifiers.SecT233k1, Sect233k1Holder.Instance);
DefineCurve("sect233r1", SecObjectIdentifiers.SecT233r1, Sect233r1Holder.Instance);
DefineCurve("sect239k1", SecObjectIdentifiers.SecT239k1, Sect239k1Holder.Instance);
DefineCurve("sect283k1", SecObjectIdentifiers.SecT283k1, Sect283k1Holder.Instance);
DefineCurve("sect283r1", SecObjectIdentifiers.SecT283r1, Sect283r1Holder.Instance);
DefineCurve("sect409k1", SecObjectIdentifiers.SecT409k1, Sect409k1Holder.Instance);
DefineCurve("sect409r1", SecObjectIdentifiers.SecT409r1, Sect409r1Holder.Instance);
DefineCurve("sect571k1", SecObjectIdentifiers.SecT571k1, Sect571k1Holder.Instance);
DefineCurve("sect571r1", SecObjectIdentifiers.SecT571r1, Sect571r1Holder.Instance);
}
public static X9ECParameters GetByName(
string name)
{
DerObjectIdentifier oid = GetOid(name);
return oid == null ? null : GetByOid(oid);
}
/**
* return the X9ECParameters object for the named curve represented by
* the passed in object identifier. Null if the curve isn't present.
*
* @param oid an object identifier representing a named curve, if present.
*/
public static X9ECParameters GetByOid(
DerObjectIdentifier oid)
{
X9ECParametersHolder holder = (X9ECParametersHolder)curves[oid];
return holder == null ? null : holder.Parameters;
}
/**
* return the object identifier signified by the passed in name. Null
* if there is no object identifier associated with name.
*
* @return the object identifier associated with name, if present.
*/
public static DerObjectIdentifier GetOid(
string name)
{
return (DerObjectIdentifier)objIds[Platform.ToLowerInvariant(name)];
}
/**
* return the named curve name represented by the given object identifier.
*/
public static string GetName(
DerObjectIdentifier oid)
{
return (string)names[oid];
}
/**
* returns an enumeration containing the name strings for curves
* contained in this structure.
*/
public static IEnumerable Names
{
get { return new EnumerableProxy(names.Values); }
}
}
}
| |
namespace SPD.GUI {
/// <summary>
///
/// </summary>
partial class PatientSearchControl {
/// <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 Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.listViewPatients = new System.Windows.Forms.ListView();
this.buttonPatientDataChange = new System.Windows.Forms.Button();
this.buttonAddVisit = new System.Windows.Forms.Button();
this.buttonShowVisits = new System.Windows.Forms.Button();
this.buttonPrint = new System.Windows.Forms.Button();
this.buttonAddOperation = new System.Windows.Forms.Button();
this.buttonFinalReport = new System.Windows.Forms.Button();
this.buttonShowOperations = new System.Windows.Forms.Button();
this.buttonImages = new System.Windows.Forms.Button();
this.buttonPatientShowData = new System.Windows.Forms.Button();
this.labelDiagnose = new System.Windows.Forms.Label();
this.labelProcedure = new System.Windows.Forms.Label();
this.textBoxDiagnoseFind = new System.Windows.Forms.TextBox();
this.textBoxProcedureFind = new System.Windows.Forms.TextBox();
this.buttonPlanOP = new System.Windows.Forms.Button();
this.labelPatientNrFind = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.buttonNextAction = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.comboBoxActionYear = new System.Windows.Forms.ComboBox();
this.comboBoxActionHalfYear = new System.Windows.Forms.ComboBox();
this.buttonSearchNextAction = new System.Windows.Forms.Button();
this.comboBoxActionKind = new System.Windows.Forms.ComboBox();
this.labelSizeSearchResult = new System.Windows.Forms.Label();
this.textBoxFiendPhoneNr = new System.Windows.Forms.TextBox();
this.labelFindPhoneNr = new System.Windows.Forms.Label();
this.textBoxNumberOfPatients = new System.Windows.Forms.TextBox();
this.labelStoredOperations = new System.Windows.Forms.Label();
this.labelStoredVisits = new System.Windows.Forms.Label();
this.textBoxNumberOfOperations = new System.Windows.Forms.TextBox();
this.textBoxNumberOfVisits = new System.Windows.Forms.TextBox();
this.textBoxTherapyFind = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.textBoxFindAllNameAndId = new System.Windows.Forms.TextBox();
this.buttonPrintNextAppointment = new System.Windows.Forms.Button();
this.labelLinz = new System.Windows.Forms.Label();
this.comboBoxLinz = new System.Windows.Forms.ComboBox();
this.labelAsmara = new System.Windows.Forms.Label();
this.comboBoxAsmara = new System.Windows.Forms.ComboBox();
this.labelFinished = new System.Windows.Forms.Label();
this.comboBoxFinished = new System.Windows.Forms.ComboBox();
this.DiagnoseGroup = new System.Windows.Forms.Label();
this.comboBoxDiagnoseGroups = new System.Windows.Forms.ComboBox();
this.comboBoxOPYear = new System.Windows.Forms.ComboBox();
this.labelOPs = new System.Windows.Forms.Label();
this.comboBoxOPHalfYears = new System.Windows.Forms.ComboBox();
this.buttonOPSearch = new System.Windows.Forms.Button();
this.buttonSearchAmulant = new System.Windows.Forms.Button();
this.buttonWaitList = new System.Windows.Forms.Button();
this.buttonAddToWaitList = new System.Windows.Forms.Button();
this.buttonRemoveFromWaitList = new System.Windows.Forms.Button();
this.buttonIdCardPrint = new System.Windows.Forms.Button();
this.buttonStoneReport = new System.Windows.Forms.Button();
this.buttonStonePatients = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// listViewPatients
//
this.listViewPatients.HideSelection = false;
this.listViewPatients.Location = new System.Drawing.Point(6, 55);
this.listViewPatients.MultiSelect = false;
this.listViewPatients.Name = "listViewPatients";
this.listViewPatients.Size = new System.Drawing.Size(981, 143);
this.listViewPatients.TabIndex = 18;
this.listViewPatients.UseCompatibleStateImageBehavior = false;
this.listViewPatients.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.listViewPatients_ColumnClick);
this.listViewPatients.SelectedIndexChanged += new System.EventHandler(this.listViewPatients_SelectedIndexChanged);
//
// buttonPatientDataChange
//
this.buttonPatientDataChange.Location = new System.Drawing.Point(354, 204);
this.buttonPatientDataChange.Name = "buttonPatientDataChange";
this.buttonPatientDataChange.Size = new System.Drawing.Size(74, 23);
this.buttonPatientDataChange.TabIndex = 25;
this.buttonPatientDataChange.Text = "&Change Pat.";
this.buttonPatientDataChange.UseVisualStyleBackColor = true;
this.buttonPatientDataChange.Click += new System.EventHandler(this.buttonPatientDataChange_Click);
//
// buttonAddVisit
//
this.buttonAddVisit.Location = new System.Drawing.Point(6, 204);
this.buttonAddVisit.Name = "buttonAddVisit";
this.buttonAddVisit.Size = new System.Drawing.Size(55, 23);
this.buttonAddVisit.TabIndex = 19;
this.buttonAddVisit.Text = "&Add visit";
this.buttonAddVisit.UseVisualStyleBackColor = true;
this.buttonAddVisit.Click += new System.EventHandler(this.buttonAddVisit_Click);
//
// buttonShowVisits
//
this.buttonShowVisits.Location = new System.Drawing.Point(63, 204);
this.buttonShowVisits.Name = "buttonShowVisits";
this.buttonShowVisits.Size = new System.Drawing.Size(68, 23);
this.buttonShowVisits.TabIndex = 20;
this.buttonShowVisits.Text = "&Show visits";
this.buttonShowVisits.UseVisualStyleBackColor = true;
this.buttonShowVisits.Click += new System.EventHandler(this.buttonShowVisits_Click);
//
// buttonPrint
//
this.buttonPrint.Location = new System.Drawing.Point(945, 204);
this.buttonPrint.Name = "buttonPrint";
this.buttonPrint.Size = new System.Drawing.Size(42, 23);
this.buttonPrint.TabIndex = 30;
this.buttonPrint.Text = "Prin&t";
this.buttonPrint.UseVisualStyleBackColor = true;
this.buttonPrint.Click += new System.EventHandler(this.buttonPrint_Click);
//
// buttonAddOperation
//
this.buttonAddOperation.Location = new System.Drawing.Point(133, 204);
this.buttonAddOperation.Name = "buttonAddOperation";
this.buttonAddOperation.Size = new System.Drawing.Size(52, 23);
this.buttonAddOperation.TabIndex = 21;
this.buttonAddOperation.Text = "Add &OP";
this.buttonAddOperation.UseVisualStyleBackColor = true;
this.buttonAddOperation.Click += new System.EventHandler(this.buttonAddOperation_Click);
//
// buttonFinalReport
//
this.buttonFinalReport.Location = new System.Drawing.Point(430, 204);
this.buttonFinalReport.Name = "buttonFinalReport";
this.buttonFinalReport.Size = new System.Drawing.Size(63, 23);
this.buttonFinalReport.TabIndex = 26;
this.buttonFinalReport.Text = "Final Rep.";
this.buttonFinalReport.UseVisualStyleBackColor = true;
this.buttonFinalReport.Click += new System.EventHandler(this.buttonFurtherTreatment_Click);
//
// buttonShowOperations
//
this.buttonShowOperations.Location = new System.Drawing.Point(187, 204);
this.buttonShowOperations.Name = "buttonShowOperations";
this.buttonShowOperations.Size = new System.Drawing.Size(65, 23);
this.buttonShowOperations.TabIndex = 22;
this.buttonShowOperations.Text = "Sho&w OPs";
this.buttonShowOperations.UseVisualStyleBackColor = true;
this.buttonShowOperations.Click += new System.EventHandler(this.buttonShowOperations_Click);
//
// buttonImages
//
this.buttonImages.Location = new System.Drawing.Point(799, 204);
this.buttonImages.Name = "buttonImages";
this.buttonImages.Size = new System.Drawing.Size(37, 23);
this.buttonImages.TabIndex = 28;
this.buttonImages.Text = "&Imgs.";
this.buttonImages.UseVisualStyleBackColor = true;
this.buttonImages.Click += new System.EventHandler(this.buttonImages_Click);
//
// buttonPatientShowData
//
this.buttonPatientShowData.Location = new System.Drawing.Point(310, 204);
this.buttonPatientShowData.Name = "buttonPatientShowData";
this.buttonPatientShowData.Size = new System.Drawing.Size(42, 23);
this.buttonPatientShowData.TabIndex = 24;
this.buttonPatientShowData.Text = "S&how Pat.";
this.buttonPatientShowData.UseVisualStyleBackColor = true;
this.buttonPatientShowData.Click += new System.EventHandler(this.buttonPatientShowData_Click);
//
// labelDiagnose
//
this.labelDiagnose.AutoSize = true;
this.labelDiagnose.Location = new System.Drawing.Point(127, 5);
this.labelDiagnose.Name = "labelDiagnose";
this.labelDiagnose.Size = new System.Drawing.Size(44, 13);
this.labelDiagnose.TabIndex = 29;
this.labelDiagnose.Text = "Diagno:";
//
// labelProcedure
//
this.labelProcedure.AutoSize = true;
this.labelProcedure.Location = new System.Drawing.Point(126, 32);
this.labelProcedure.Name = "labelProcedure";
this.labelProcedure.Size = new System.Drawing.Size(44, 13);
this.labelProcedure.TabIndex = 30;
this.labelProcedure.Text = "Proced:";
//
// textBoxDiagnoseFind
//
this.textBoxDiagnoseFind.Location = new System.Drawing.Point(169, 3);
this.textBoxDiagnoseFind.Name = "textBoxDiagnoseFind";
this.textBoxDiagnoseFind.Size = new System.Drawing.Size(61, 20);
this.textBoxDiagnoseFind.TabIndex = 1;
this.textBoxDiagnoseFind.TextChanged += new System.EventHandler(this.textBoxDiagnoseFind_TextChanged);
//
// textBoxProcedureFind
//
this.textBoxProcedureFind.Location = new System.Drawing.Point(169, 28);
this.textBoxProcedureFind.Name = "textBoxProcedureFind";
this.textBoxProcedureFind.Size = new System.Drawing.Size(61, 20);
this.textBoxProcedureFind.TabIndex = 11;
this.textBoxProcedureFind.TextChanged += new System.EventHandler(this.textBoxProcedureFind_TextChanged);
//
// buttonPlanOP
//
this.buttonPlanOP.Location = new System.Drawing.Point(254, 204);
this.buttonPlanOP.Name = "buttonPlanOP";
this.buttonPlanOP.Size = new System.Drawing.Size(54, 23);
this.buttonPlanOP.TabIndex = 23;
this.buttonPlanOP.Text = "P&lan OP";
this.buttonPlanOP.UseVisualStyleBackColor = true;
this.buttonPlanOP.Click += new System.EventHandler(this.buttonPlanOP_Click);
//
// labelPatientNrFind
//
this.labelPatientNrFind.AutoSize = true;
this.labelPatientNrFind.Location = new System.Drawing.Point(12, 32);
this.labelPatientNrFind.Name = "labelPatientNrFind";
this.labelPatientNrFind.Size = new System.Drawing.Size(0, 13);
this.labelPatientNrFind.TabIndex = 32;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(3, 6);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(58, 13);
this.label2.TabIndex = 31;
this.label2.Text = "Name / Id:";
//
// buttonNextAction
//
this.buttonNextAction.Location = new System.Drawing.Point(838, 204);
this.buttonNextAction.Name = "buttonNextAction";
this.buttonNextAction.Size = new System.Drawing.Size(70, 23);
this.buttonNextAction.TabIndex = 29;
this.buttonNextAction.Text = "&Next Action";
this.buttonNextAction.UseVisualStyleBackColor = true;
this.buttonNextAction.Click += new System.EventHandler(this.buttonNextAction_Click);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(875, 5);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(47, 13);
this.label3.TabIndex = 34;
this.label3.Text = "patients:";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(352, 6);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(65, 13);
this.label4.TabIndex = 33;
this.label4.Text = "Next Action:";
//
// comboBoxActionYear
//
this.comboBoxActionYear.FormattingEnabled = true;
this.comboBoxActionYear.Location = new System.Drawing.Point(414, 3);
this.comboBoxActionYear.Name = "comboBoxActionYear";
this.comboBoxActionYear.Size = new System.Drawing.Size(48, 21);
this.comboBoxActionYear.TabIndex = 3;
this.comboBoxActionYear.KeyDown += new System.Windows.Forms.KeyEventHandler(this.nextAction_KeyDown);
//
// comboBoxActionHalfYear
//
this.comboBoxActionHalfYear.FormattingEnabled = true;
this.comboBoxActionHalfYear.Location = new System.Drawing.Point(465, 3);
this.comboBoxActionHalfYear.Name = "comboBoxActionHalfYear";
this.comboBoxActionHalfYear.Size = new System.Drawing.Size(30, 21);
this.comboBoxActionHalfYear.TabIndex = 4;
this.comboBoxActionHalfYear.KeyDown += new System.Windows.Forms.KeyEventHandler(this.nextAction_KeyDown);
//
// buttonSearchNextAction
//
this.buttonSearchNextAction.Image = global::SPD.GUI.Properties.Resources.search16;
this.buttonSearchNextAction.Location = new System.Drawing.Point(568, 1);
this.buttonSearchNextAction.Name = "buttonSearchNextAction";
this.buttonSearchNextAction.Size = new System.Drawing.Size(23, 23);
this.buttonSearchNextAction.TabIndex = 6;
this.buttonSearchNextAction.UseVisualStyleBackColor = true;
this.buttonSearchNextAction.Click += new System.EventHandler(this.buttonSearchNextAction_Click);
//
// comboBoxActionKind
//
this.comboBoxActionKind.FormattingEnabled = true;
this.comboBoxActionKind.Location = new System.Drawing.Point(499, 3);
this.comboBoxActionKind.Name = "comboBoxActionKind";
this.comboBoxActionKind.Size = new System.Drawing.Size(66, 21);
this.comboBoxActionKind.TabIndex = 5;
this.comboBoxActionKind.KeyDown += new System.Windows.Forms.KeyEventHandler(this.nextAction_KeyDown);
//
// labelSizeSearchResult
//
this.labelSizeSearchResult.AutoSize = true;
this.labelSizeSearchResult.Location = new System.Drawing.Point(758, 33);
this.labelSizeSearchResult.Name = "labelSizeSearchResult";
this.labelSizeSearchResult.Size = new System.Drawing.Size(35, 13);
this.labelSizeSearchResult.TabIndex = 37;
this.labelSizeSearchResult.Text = "label1";
//
// textBoxFiendPhoneNr
//
this.textBoxFiendPhoneNr.Location = new System.Drawing.Point(60, 28);
this.textBoxFiendPhoneNr.Name = "textBoxFiendPhoneNr";
this.textBoxFiendPhoneNr.Size = new System.Drawing.Size(63, 20);
this.textBoxFiendPhoneNr.TabIndex = 10;
this.textBoxFiendPhoneNr.TextChanged += new System.EventHandler(this.textBoxFiendPhoneNr_TextChanged);
//
// labelFindPhoneNr
//
this.labelFindPhoneNr.AutoSize = true;
this.labelFindPhoneNr.Location = new System.Drawing.Point(19, 32);
this.labelFindPhoneNr.Name = "labelFindPhoneNr";
this.labelFindPhoneNr.Size = new System.Drawing.Size(41, 13);
this.labelFindPhoneNr.TabIndex = 40;
this.labelFindPhoneNr.Text = "Phone:";
//
// textBoxNumberOfPatients
//
this.textBoxNumberOfPatients.Location = new System.Drawing.Point(920, 3);
this.textBoxNumberOfPatients.Name = "textBoxNumberOfPatients";
this.textBoxNumberOfPatients.ReadOnly = true;
this.textBoxNumberOfPatients.Size = new System.Drawing.Size(60, 20);
this.textBoxNumberOfPatients.TabIndex = 9;
//
// labelStoredOperations
//
this.labelStoredOperations.AutoSize = true;
this.labelStoredOperations.Location = new System.Drawing.Point(893, 33);
this.labelStoredOperations.Name = "labelStoredOperations";
this.labelStoredOperations.Size = new System.Drawing.Size(27, 13);
this.labelStoredOperations.TabIndex = 34;
this.labelStoredOperations.Text = "ops:";
//
// labelStoredVisits
//
this.labelStoredVisits.AutoSize = true;
this.labelStoredVisits.Location = new System.Drawing.Point(798, 34);
this.labelStoredVisits.Name = "labelStoredVisits";
this.labelStoredVisits.Size = new System.Drawing.Size(33, 13);
this.labelStoredVisits.TabIndex = 34;
this.labelStoredVisits.Text = "visits:";
//
// textBoxNumberOfOperations
//
this.textBoxNumberOfOperations.Location = new System.Drawing.Point(920, 29);
this.textBoxNumberOfOperations.Name = "textBoxNumberOfOperations";
this.textBoxNumberOfOperations.ReadOnly = true;
this.textBoxNumberOfOperations.Size = new System.Drawing.Size(60, 20);
this.textBoxNumberOfOperations.TabIndex = 19;
//
// textBoxNumberOfVisits
//
this.textBoxNumberOfVisits.Location = new System.Drawing.Point(829, 31);
this.textBoxNumberOfVisits.Name = "textBoxNumberOfVisits";
this.textBoxNumberOfVisits.ReadOnly = true;
this.textBoxNumberOfVisits.Size = new System.Drawing.Size(60, 20);
this.textBoxNumberOfVisits.TabIndex = 18;
//
// textBoxTherapyFind
//
this.textBoxTherapyFind.Location = new System.Drawing.Point(286, 3);
this.textBoxTherapyFind.Name = "textBoxTherapyFind";
this.textBoxTherapyFind.Size = new System.Drawing.Size(61, 20);
this.textBoxTherapyFind.TabIndex = 2;
this.textBoxTherapyFind.TextChanged += new System.EventHandler(this.textBoxTherapyFind_TextChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(236, 6);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(49, 13);
this.label1.TabIndex = 33;
this.label1.Text = "Therapy:";
//
// textBoxFindAllNameAndId
//
this.textBoxFindAllNameAndId.Location = new System.Drawing.Point(60, 3);
this.textBoxFindAllNameAndId.Name = "textBoxFindAllNameAndId";
this.textBoxFindAllNameAndId.Size = new System.Drawing.Size(63, 20);
this.textBoxFindAllNameAndId.TabIndex = 0;
this.textBoxFindAllNameAndId.TextChanged += new System.EventHandler(this.textBoxSearchAllNameAndId_TextChanged);
//
// buttonPrintNextAppointment
//
this.buttonPrintNextAppointment.Location = new System.Drawing.Point(545, 204);
this.buttonPrintNextAppointment.Name = "buttonPrintNextAppointment";
this.buttonPrintNextAppointment.Size = new System.Drawing.Size(99, 23);
this.buttonPrintNextAppointment.TabIndex = 27;
this.buttonPrintNextAppointment.Text = "Next Appointment";
this.buttonPrintNextAppointment.UseVisualStyleBackColor = true;
this.buttonPrintNextAppointment.Click += new System.EventHandler(this.buttonPrintNextAppointment_Click);
//
// labelLinz
//
this.labelLinz.AutoSize = true;
this.labelLinz.Location = new System.Drawing.Point(597, 6);
this.labelLinz.Name = "labelLinz";
this.labelLinz.Size = new System.Drawing.Size(29, 13);
this.labelLinz.TabIndex = 43;
this.labelLinz.Text = "Linz:";
//
// comboBoxLinz
//
this.comboBoxLinz.FormattingEnabled = true;
this.comboBoxLinz.Location = new System.Drawing.Point(632, 2);
this.comboBoxLinz.Name = "comboBoxLinz";
this.comboBoxLinz.Size = new System.Drawing.Size(72, 21);
this.comboBoxLinz.TabIndex = 7;
this.comboBoxLinz.SelectedIndexChanged += new System.EventHandler(this.comboBoxLinz_SelectedIndexChanged);
//
// labelAsmara
//
this.labelAsmara.AutoSize = true;
this.labelAsmara.Location = new System.Drawing.Point(501, 33);
this.labelAsmara.Name = "labelAsmara";
this.labelAsmara.Size = new System.Drawing.Size(45, 13);
this.labelAsmara.TabIndex = 45;
this.labelAsmara.Text = "Asmara:";
//
// comboBoxAsmara
//
this.comboBoxAsmara.FormattingEnabled = true;
this.comboBoxAsmara.Location = new System.Drawing.Point(542, 29);
this.comboBoxAsmara.Name = "comboBoxAsmara";
this.comboBoxAsmara.Size = new System.Drawing.Size(56, 21);
this.comboBoxAsmara.TabIndex = 14;
this.comboBoxAsmara.SelectedIndexChanged += new System.EventHandler(this.comboBoxAsmara_SelectedIndexChanged);
//
// labelFinished
//
this.labelFinished.AutoSize = true;
this.labelFinished.Location = new System.Drawing.Point(385, 32);
this.labelFinished.Name = "labelFinished";
this.labelFinished.Size = new System.Drawing.Size(49, 13);
this.labelFinished.TabIndex = 49;
this.labelFinished.Text = "Finished:";
//
// comboBoxFinished
//
this.comboBoxFinished.FormattingEnabled = true;
this.comboBoxFinished.Location = new System.Drawing.Point(430, 27);
this.comboBoxFinished.Name = "comboBoxFinished";
this.comboBoxFinished.Size = new System.Drawing.Size(68, 21);
this.comboBoxFinished.TabIndex = 13;
this.comboBoxFinished.SelectedIndexChanged += new System.EventHandler(this.comboBoxFinished_SelectedIndexChanged);
//
// DiagnoseGroup
//
this.DiagnoseGroup.AutoSize = true;
this.DiagnoseGroup.Location = new System.Drawing.Point(726, 6);
this.DiagnoseGroup.Name = "DiagnoseGroup";
this.DiagnoseGroup.Size = new System.Drawing.Size(55, 13);
this.DiagnoseGroup.TabIndex = 51;
this.DiagnoseGroup.Text = "DigGroup:";
//
// comboBoxDiagnoseGroups
//
this.comboBoxDiagnoseGroups.FormattingEnabled = true;
this.comboBoxDiagnoseGroups.Location = new System.Drawing.Point(779, 3);
this.comboBoxDiagnoseGroups.Name = "comboBoxDiagnoseGroups";
this.comboBoxDiagnoseGroups.Size = new System.Drawing.Size(86, 21);
this.comboBoxDiagnoseGroups.TabIndex = 8;
this.comboBoxDiagnoseGroups.SelectedIndexChanged += new System.EventHandler(this.comboBoxDiagnoseGroups_SelectedIndexChanged);
//
// comboBoxOPYear
//
this.comboBoxOPYear.FormattingEnabled = true;
this.comboBoxOPYear.Location = new System.Drawing.Point(666, 29);
this.comboBoxOPYear.Name = "comboBoxOPYear";
this.comboBoxOPYear.Size = new System.Drawing.Size(52, 21);
this.comboBoxOPYear.TabIndex = 16;
//
// labelOPs
//
this.labelOPs.AutoSize = true;
this.labelOPs.Location = new System.Drawing.Point(602, 32);
this.labelOPs.Name = "labelOPs";
this.labelOPs.Size = new System.Drawing.Size(30, 13);
this.labelOPs.TabIndex = 54;
this.labelOPs.Text = "OPs:";
//
// comboBoxOPHalfYears
//
this.comboBoxOPHalfYears.FormattingEnabled = true;
this.comboBoxOPHalfYears.Location = new System.Drawing.Point(631, 29);
this.comboBoxOPHalfYears.Name = "comboBoxOPHalfYears";
this.comboBoxOPHalfYears.Size = new System.Drawing.Size(36, 21);
this.comboBoxOPHalfYears.TabIndex = 15;
//
// buttonOPSearch
//
this.buttonOPSearch.Image = global::SPD.GUI.Properties.Resources.search16;
this.buttonOPSearch.Location = new System.Drawing.Point(719, 28);
this.buttonOPSearch.Name = "buttonOPSearch";
this.buttonOPSearch.Size = new System.Drawing.Size(23, 23);
this.buttonOPSearch.TabIndex = 17;
this.buttonOPSearch.UseVisualStyleBackColor = true;
this.buttonOPSearch.Click += new System.EventHandler(this.buttonOPSearch_Click);
//
// buttonSearchAmulant
//
this.buttonSearchAmulant.Location = new System.Drawing.Point(237, 27);
this.buttonSearchAmulant.Name = "buttonSearchAmulant";
this.buttonSearchAmulant.Size = new System.Drawing.Size(47, 23);
this.buttonSearchAmulant.TabIndex = 12;
this.buttonSearchAmulant.Text = "Amblnt";
this.buttonSearchAmulant.UseVisualStyleBackColor = true;
this.buttonSearchAmulant.Click += new System.EventHandler(this.buttonSearchAmulant_Click);
//
// buttonWaitList
//
this.buttonWaitList.Location = new System.Drawing.Point(284, 27);
this.buttonWaitList.Name = "buttonWaitList";
this.buttonWaitList.Size = new System.Drawing.Size(51, 23);
this.buttonWaitList.TabIndex = 55;
this.buttonWaitList.Text = "WaitLst";
this.buttonWaitList.UseVisualStyleBackColor = true;
this.buttonWaitList.Click += new System.EventHandler(this.buttonWaitList_Click);
//
// buttonAddToWaitList
//
this.buttonAddToWaitList.Location = new System.Drawing.Point(647, 204);
this.buttonAddToWaitList.Name = "buttonAddToWaitList";
this.buttonAddToWaitList.Size = new System.Drawing.Size(71, 23);
this.buttonAddToWaitList.TabIndex = 56;
this.buttonAddToWaitList.Text = "Add Waitlist";
this.buttonAddToWaitList.UseVisualStyleBackColor = true;
this.buttonAddToWaitList.Click += new System.EventHandler(this.buttonAddToWaitList_Click);
//
// buttonRemoveFromWaitList
//
this.buttonRemoveFromWaitList.Location = new System.Drawing.Point(720, 204);
this.buttonRemoveFromWaitList.Name = "buttonRemoveFromWaitList";
this.buttonRemoveFromWaitList.Size = new System.Drawing.Size(77, 23);
this.buttonRemoveFromWaitList.TabIndex = 57;
this.buttonRemoveFromWaitList.Text = "Rem. Waitlist";
this.buttonRemoveFromWaitList.UseVisualStyleBackColor = true;
this.buttonRemoveFromWaitList.Click += new System.EventHandler(this.buttonRemoveFromWaitList_Click);
//
// buttonIdCardPrint
//
this.buttonIdCardPrint.Location = new System.Drawing.Point(910, 204);
this.buttonIdCardPrint.Name = "buttonIdCardPrint";
this.buttonIdCardPrint.Size = new System.Drawing.Size(33, 23);
this.buttonIdCardPrint.TabIndex = 58;
this.buttonIdCardPrint.Text = "ID";
this.buttonIdCardPrint.UseVisualStyleBackColor = true;
this.buttonIdCardPrint.Click += new System.EventHandler(this.buttonIdCardPrint_Click);
//
// buttonStoneReport
//
this.buttonStoneReport.Location = new System.Drawing.Point(495, 204);
this.buttonStoneReport.Name = "buttonStoneReport";
this.buttonStoneReport.Size = new System.Drawing.Size(48, 23);
this.buttonStoneReport.TabIndex = 59;
this.buttonStoneReport.Text = "Stones";
this.buttonStoneReport.UseVisualStyleBackColor = true;
this.buttonStoneReport.Click += new System.EventHandler(this.buttonStoneReport_Click);
//
// buttonStonePatients
//
this.buttonStonePatients.Location = new System.Drawing.Point(335, 27);
this.buttonStonePatients.Name = "buttonStonePatients";
this.buttonStonePatients.Size = new System.Drawing.Size(47, 23);
this.buttonStonePatients.TabIndex = 60;
this.buttonStonePatients.Text = "Stone";
this.buttonStonePatients.UseVisualStyleBackColor = true;
this.buttonStonePatients.Click += new System.EventHandler(this.buttonStonePatients_Click);
//
// PatientSearchControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.buttonStonePatients);
this.Controls.Add(this.buttonStoneReport);
this.Controls.Add(this.buttonIdCardPrint);
this.Controls.Add(this.buttonRemoveFromWaitList);
this.Controls.Add(this.buttonAddToWaitList);
this.Controls.Add(this.buttonWaitList);
this.Controls.Add(this.buttonSearchAmulant);
this.Controls.Add(this.comboBoxOPHalfYears);
this.Controls.Add(this.labelOPs);
this.Controls.Add(this.comboBoxOPYear);
this.Controls.Add(this.comboBoxDiagnoseGroups);
this.Controls.Add(this.DiagnoseGroup);
this.Controls.Add(this.comboBoxFinished);
this.Controls.Add(this.labelFinished);
this.Controls.Add(this.comboBoxAsmara);
this.Controls.Add(this.labelAsmara);
this.Controls.Add(this.comboBoxLinz);
this.Controls.Add(this.labelLinz);
this.Controls.Add(this.buttonPrintNextAppointment);
this.Controls.Add(this.textBoxFindAllNameAndId);
this.Controls.Add(this.textBoxTherapyFind);
this.Controls.Add(this.textBoxNumberOfVisits);
this.Controls.Add(this.textBoxNumberOfOperations);
this.Controls.Add(this.textBoxNumberOfPatients);
this.Controls.Add(this.labelFindPhoneNr);
this.Controls.Add(this.textBoxFiendPhoneNr);
this.Controls.Add(this.labelSizeSearchResult);
this.Controls.Add(this.buttonOPSearch);
this.Controls.Add(this.buttonSearchNextAction);
this.Controls.Add(this.comboBoxActionKind);
this.Controls.Add(this.comboBoxActionHalfYear);
this.Controls.Add(this.comboBoxActionYear);
this.Controls.Add(this.label1);
this.Controls.Add(this.label4);
this.Controls.Add(this.buttonNextAction);
this.Controls.Add(this.label2);
this.Controls.Add(this.buttonPlanOP);
this.Controls.Add(this.textBoxProcedureFind);
this.Controls.Add(this.textBoxDiagnoseFind);
this.Controls.Add(this.labelProcedure);
this.Controls.Add(this.labelDiagnose);
this.Controls.Add(this.labelPatientNrFind);
this.Controls.Add(this.labelStoredVisits);
this.Controls.Add(this.labelStoredOperations);
this.Controls.Add(this.label3);
this.Controls.Add(this.buttonPatientShowData);
this.Controls.Add(this.buttonImages);
this.Controls.Add(this.buttonShowOperations);
this.Controls.Add(this.buttonFinalReport);
this.Controls.Add(this.buttonAddOperation);
this.Controls.Add(this.buttonPrint);
this.Controls.Add(this.buttonShowVisits);
this.Controls.Add(this.buttonAddVisit);
this.Controls.Add(this.buttonPatientDataChange);
this.Controls.Add(this.listViewPatients);
this.Name = "PatientSearchControl";
this.Size = new System.Drawing.Size(990, 235);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ListView listViewPatients;
private System.Windows.Forms.Button buttonPatientDataChange;
private System.Windows.Forms.Button buttonAddVisit;
private System.Windows.Forms.Button buttonShowVisits;
private System.Windows.Forms.Button buttonPrint;
private System.Windows.Forms.Button buttonAddOperation;
private System.Windows.Forms.Button buttonFinalReport;
private System.Windows.Forms.Button buttonShowOperations;
private System.Windows.Forms.Button buttonImages;
private System.Windows.Forms.Button buttonPatientShowData;
private System.Windows.Forms.Label labelDiagnose;
private System.Windows.Forms.Label labelProcedure;
private System.Windows.Forms.TextBox textBoxDiagnoseFind;
private System.Windows.Forms.TextBox textBoxProcedureFind;
private System.Windows.Forms.Button buttonPlanOP;
private System.Windows.Forms.Label labelPatientNrFind;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button buttonNextAction;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.ComboBox comboBoxActionYear;
private System.Windows.Forms.ComboBox comboBoxActionHalfYear;
private System.Windows.Forms.Button buttonSearchNextAction;
private System.Windows.Forms.ComboBox comboBoxActionKind;
private System.Windows.Forms.Label labelSizeSearchResult;
private System.Windows.Forms.TextBox textBoxFiendPhoneNr;
private System.Windows.Forms.Label labelFindPhoneNr;
private System.Windows.Forms.TextBox textBoxNumberOfPatients;
private System.Windows.Forms.Label labelStoredOperations;
private System.Windows.Forms.Label labelStoredVisits;
private System.Windows.Forms.TextBox textBoxNumberOfOperations;
private System.Windows.Forms.TextBox textBoxNumberOfVisits;
private System.Windows.Forms.TextBox textBoxTherapyFind;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBoxFindAllNameAndId;
private System.Windows.Forms.Button buttonPrintNextAppointment;
private System.Windows.Forms.Label labelLinz;
private System.Windows.Forms.ComboBox comboBoxLinz;
private System.Windows.Forms.Label labelAsmara;
private System.Windows.Forms.ComboBox comboBoxAsmara;
private System.Windows.Forms.Label labelFinished;
private System.Windows.Forms.ComboBox comboBoxFinished;
private System.Windows.Forms.Label DiagnoseGroup;
private System.Windows.Forms.ComboBox comboBoxDiagnoseGroups;
private System.Windows.Forms.ComboBox comboBoxOPYear;
private System.Windows.Forms.Label labelOPs;
private System.Windows.Forms.ComboBox comboBoxOPHalfYears;
private System.Windows.Forms.Button buttonOPSearch;
private System.Windows.Forms.Button buttonSearchAmulant;
private System.Windows.Forms.Button buttonWaitList;
private System.Windows.Forms.Button buttonAddToWaitList;
private System.Windows.Forms.Button buttonRemoveFromWaitList;
private System.Windows.Forms.Button buttonIdCardPrint;
private System.Windows.Forms.Button buttonStoneReport;
private System.Windows.Forms.Button buttonStonePatients;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.ExceptionServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.WebSockets
{
internal sealed class WebSocketHandle
{
/// <summary>Per-thread cached StringBuilder for building of strings to send on the connection.</summary>
[ThreadStatic]
private static StringBuilder t_cachedStringBuilder;
/// <summary>Default encoding for HTTP requests. Latin alphabeta no 1, ISO/IEC 8859-1.</summary>
private static readonly Encoding s_defaultHttpEncoding = Encoding.GetEncoding(28591);
/// <summary>Size of the receive buffer to use.</summary>
private const int DefaultReceiveBufferSize = 0x1000;
/// <summary>GUID appended by the server as part of the security key response. Defined in the RFC.</summary>
private const string WSServerGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
private readonly CancellationTokenSource _abortSource = new CancellationTokenSource();
private WebSocketState _state = WebSocketState.Connecting;
private ManagedWebSocket _webSocket;
public static WebSocketHandle Create() => new WebSocketHandle();
public static bool IsValid(WebSocketHandle handle) => handle != null;
public WebSocketCloseStatus? CloseStatus => _webSocket?.CloseStatus;
public string CloseStatusDescription => _webSocket?.CloseStatusDescription;
public WebSocketState State => _webSocket?.State ?? _state;
public string SubProtocol => _webSocket?.SubProtocol;
public static void CheckPlatformSupport() { /* nop */ }
public void Dispose()
{
_state = WebSocketState.Closed;
_webSocket?.Dispose();
}
public void Abort()
{
_abortSource.Cancel();
_webSocket?.Abort();
}
public Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) =>
_webSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken);
public Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken) =>
_webSocket.ReceiveAsync(buffer, cancellationToken);
public Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) =>
_webSocket.CloseAsync(closeStatus, statusDescription, cancellationToken);
public Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) =>
_webSocket.CloseOutputAsync(closeStatus, statusDescription, cancellationToken);
public async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options)
{
// TODO: Not currently implemented:
// - ClientWebSocketOptions.Credentials
// - ClientWebSocketOptions.Proxy
// Establish connection to the server
CancellationTokenRegistration registration = cancellationToken.Register(s => ((WebSocketHandle)s).Abort(), this);
try
{
// Connect to the remote server
Socket connectedSocket = await ConnectSocketAsync(uri.Host, uri.Port, cancellationToken).ConfigureAwait(false);
Stream stream = new AsyncEventArgsNetworkStream(connectedSocket);
// Upgrade to SSL if needed
if (uri.Scheme == UriScheme.Wss)
{
var sslStream = new SslStream(stream);
await sslStream.AuthenticateAsClientAsync(
uri.Host,
options.ClientCertificates,
SecurityProtocol.AllowedSecurityProtocols,
checkCertificateRevocation: false).ConfigureAwait(false);
stream = sslStream;
}
// Create the security key and expected response, then build all of the request headers
KeyValuePair<string, string> secKeyAndSecWebSocketAccept = CreateSecKeyAndSecWebSocketAccept();
byte[] requestHeader = BuildRequestHeader(uri, options, secKeyAndSecWebSocketAccept.Key);
// Write out the header to the connection
await stream.WriteAsync(requestHeader, 0, requestHeader.Length, cancellationToken).ConfigureAwait(false);
// Parse the response and store our state for the remainder of the connection
string subprotocol = await ParseAndValidateConnectResponseAsync(stream, options, secKeyAndSecWebSocketAccept.Value, cancellationToken).ConfigureAwait(false);
_webSocket = ManagedWebSocket.CreateFromConnectedStream(stream, false, subprotocol);
// If a concurrent Abort or Dispose came in before we set _webSocket, make sure to update it appropriately
if (_state == WebSocketState.Aborted)
{
_webSocket.Abort();
}
else if (_state == WebSocketState.Closed)
{
_webSocket.Dispose();
}
}
catch (Exception exc)
{
if (_state < WebSocketState.Closed)
{
_state = WebSocketState.Closed;
}
Abort();
if (exc is WebSocketException)
{
throw;
}
throw new WebSocketException(SR.net_webstatus_ConnectFailure, exc);
}
finally
{
registration.Dispose();
}
}
/// <summary>Connects a socket to the specified host and port, subject to cancellation and aborting.</summary>
/// <param name="host">The host to which to connect.</param>
/// <param name="port">The port to which to connect on the host.</param>
/// <param name="cancellationToken">The CancellationToken to use to cancel the websocket.</param>
/// <returns>The connected Socket.</returns>
private async Task<Socket> ConnectSocketAsync(string host, int port, CancellationToken cancellationToken)
{
IPAddress[] addresses = await Dns.GetHostAddressesAsync(host).ConfigureAwait(false);
ExceptionDispatchInfo lastException = null;
foreach (IPAddress address in addresses)
{
var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
using (cancellationToken.Register(s => ((Socket)s).Dispose(), socket))
using (_abortSource.Token.Register(s => ((Socket)s).Dispose(), socket))
{
try
{
await socket.ConnectAsync(address, port).ConfigureAwait(false);
}
catch (ObjectDisposedException ode)
{
// If the socket was disposed because cancellation was requested, translate the exception
// into a new OperationCanceledException. Otherwise, let the original ObjectDisposedexception propagate.
CancellationToken token = cancellationToken.IsCancellationRequested ? cancellationToken : _abortSource.Token;
if (token.IsCancellationRequested)
{
throw new OperationCanceledException(new OperationCanceledException().Message, ode, token);
}
}
}
cancellationToken.ThrowIfCancellationRequested(); // in case of a race and socket was disposed after the await
_abortSource.Token.ThrowIfCancellationRequested();
return socket;
}
catch (Exception exc)
{
socket.Dispose();
lastException = ExceptionDispatchInfo.Capture(exc);
}
}
lastException?.Throw();
Debug.Fail("We should never get here. We should have already returned or an exception should have been thrown.");
throw new WebSocketException(SR.net_webstatus_ConnectFailure);
}
/// <summary>Creates a byte[] containing the headers to send to the server.</summary>
/// <param name="uri">The Uri of the server.</param>
/// <param name="options">The options used to configure the websocket.</param>
/// <param name="secKey">The generated security key to send in the Sec-WebSocket-Key header.</param>
/// <returns>The byte[] containing the encoded headers ready to send to the network.</returns>
private static byte[] BuildRequestHeader(Uri uri, ClientWebSocketOptions options, string secKey)
{
StringBuilder builder = t_cachedStringBuilder ?? (t_cachedStringBuilder = new StringBuilder());
Debug.Assert(builder.Length == 0, $"Expected builder to be empty, got one of length {builder.Length}");
try
{
builder.Append("GET ").Append(uri.PathAndQuery).Append(" HTTP/1.1\r\n");
// Add all of the required headers
builder.Append("Host: ").Append(uri.IdnHost).Append(":").Append(uri.Port).Append("\r\n");
builder.Append("Connection: Upgrade\r\n");
builder.Append("Upgrade: websocket\r\n");
builder.Append("Sec-WebSocket-Version: 13\r\n");
builder.Append("Sec-WebSocket-Key: ").Append(secKey).Append("\r\n");
// Add all of the additionally requested headers
foreach (string key in options.RequestHeaders.AllKeys)
{
builder.Append(key).Append(": ").Append(options.RequestHeaders[key]).Append("\r\n");
}
// Add the optional subprotocols header
if (options.RequestedSubProtocols.Count > 0)
{
builder.Append(HttpKnownHeaderNames.SecWebSocketProtocol).Append(": ");
builder.Append(options.RequestedSubProtocols[0]);
for (int i = 1; i < options.RequestedSubProtocols.Count; i++)
{
builder.Append(", ").Append(options.RequestedSubProtocols[i]);
}
builder.Append("\r\n");
}
// Add an optional cookies header
if (options.Cookies != null)
{
string header = options.Cookies.GetCookieHeader(uri);
if (!string.IsNullOrWhiteSpace(header))
{
builder.Append(HttpKnownHeaderNames.Cookie).Append(": ").Append(header).Append("\r\n");
}
}
// End the headers
builder.Append("\r\n");
// Return the bytes for the built up header
return s_defaultHttpEncoding.GetBytes(builder.ToString());
}
finally
{
// Make sure we clear the builder
builder.Clear();
}
}
/// <summary>
/// Creates a pair of a security key for sending in the Sec-WebSocket-Key header and
/// the associated response we expect to receive as the Sec-WebSocket-Accept header value.
/// </summary>
/// <returns>A key-value pair of the request header security key and expected response header value.</returns>
private static KeyValuePair<string, string> CreateSecKeyAndSecWebSocketAccept()
{
string secKey = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
using (SHA1 sha = SHA1.Create())
{
return new KeyValuePair<string, string>(
secKey,
Convert.ToBase64String(sha.ComputeHash(Encoding.ASCII.GetBytes(secKey + WSServerGuid))));
}
}
/// <summary>Read and validate the connect response headers from the server.</summary>
/// <param name="stream">The stream from which to read the response headers.</param>
/// <param name="options">The options used to configure the websocket.</param>
/// <param name="expectedSecWebSocketAccept">The expected value of the Sec-WebSocket-Accept header.</param>
/// <param name="cancellationToken">The CancellationToken to use to cancel the websocket.</param>
/// <returns>The agreed upon subprotocol with the server, or null if there was none.</returns>
private async Task<string> ParseAndValidateConnectResponseAsync(
Stream stream, ClientWebSocketOptions options, string expectedSecWebSocketAccept, CancellationToken cancellationToken)
{
// Read the first line of the response
string statusLine = await ReadResponseHeaderLineAsync(stream, cancellationToken).ConfigureAwait(false);
// Depending on the underlying sockets implementation and timing, connecting to a server that then
// immediately closes the connection may either result in an exception getting thrown from the connect
// earlier, or it may result in getting to here but reading 0 bytes. If we read 0 bytes and thus have
// an empty status line, treat it as a connect failure.
if (string.IsNullOrEmpty(statusLine))
{
throw new WebSocketException(SR.Format(SR.net_webstatus_ConnectFailure));
}
const string ExpectedStatusStart = "HTTP/1.1 ";
const string ExpectedStatusStatWithCode = "HTTP/1.1 101"; // 101 == SwitchingProtocols
// If the status line doesn't begin with "HTTP/1.1" or isn't long enough to contain a status code, fail.
if (!statusLine.StartsWith(ExpectedStatusStart, StringComparison.Ordinal) || statusLine.Length < ExpectedStatusStatWithCode.Length)
{
throw new WebSocketException(WebSocketError.HeaderError);
}
// If the status line doesn't contain a status code 101, or if it's long enough to have a status description
// but doesn't contain whitespace after the 101, fail.
if (!statusLine.StartsWith(ExpectedStatusStatWithCode, StringComparison.Ordinal) ||
(statusLine.Length > ExpectedStatusStatWithCode.Length && !char.IsWhiteSpace(statusLine[ExpectedStatusStatWithCode.Length])))
{
throw new WebSocketException(SR.net_webstatus_ConnectFailure);
}
// Read each response header. Be liberal in parsing the response header, treating
// everything to the left of the colon as the key and everything to the right as the value, trimming both.
// For each header, validate that we got the expected value.
bool foundUpgrade = false, foundConnection = false, foundSecWebSocketAccept = false;
string subprotocol = null;
string line;
while (!string.IsNullOrEmpty(line = await ReadResponseHeaderLineAsync(stream, cancellationToken).ConfigureAwait(false)))
{
int colonIndex = line.IndexOf(':');
if (colonIndex == -1)
{
throw new WebSocketException(WebSocketError.HeaderError);
}
string headerName = line.SubstringTrim(0, colonIndex);
string headerValue = line.SubstringTrim(colonIndex + 1);
// The Connection, Upgrade, and SecWebSocketAccept headers are required and with specific values.
ValidateAndTrackHeader(HttpKnownHeaderNames.Connection, "Upgrade", headerName, headerValue, ref foundConnection);
ValidateAndTrackHeader(HttpKnownHeaderNames.Upgrade, "websocket", headerName, headerValue, ref foundUpgrade);
ValidateAndTrackHeader(HttpKnownHeaderNames.SecWebSocketAccept, expectedSecWebSocketAccept, headerName, headerValue, ref foundSecWebSocketAccept);
// The SecWebSocketProtocol header is optional. We should only get it with a non-empty value if we requested subprotocols,
// and then it must only be one of the ones we requested. If we got a subprotocol other than one we requested (or if we
// already got one in a previous header), fail. Otherwise, track which one we got.
if (string.Equals(HttpKnownHeaderNames.SecWebSocketProtocol, headerName, StringComparison.OrdinalIgnoreCase) &&
!string.IsNullOrWhiteSpace(headerValue))
{
string newSubprotocol = options.RequestedSubProtocols.Find(requested => string.Equals(requested, headerValue, StringComparison.OrdinalIgnoreCase));
if (newSubprotocol == null || subprotocol != null)
{
throw new WebSocketException(
WebSocketError.UnsupportedProtocol,
SR.Format(SR.net_WebSockets_AcceptUnsupportedProtocol, string.Join(", ", options.RequestedSubProtocols), subprotocol));
}
subprotocol = newSubprotocol;
}
}
if (!foundUpgrade || !foundConnection || !foundSecWebSocketAccept)
{
throw new WebSocketException(SR.net_webstatus_ConnectFailure);
}
return subprotocol;
}
/// <summary>Validates a received header against expected values and tracks that we've received it.</summary>
/// <param name="targetHeaderName">The header name against which we're comparing.</param>
/// <param name="targetHeaderValue">The header value against which we're comparing.</param>
/// <param name="foundHeaderName">The actual header name received.</param>
/// <param name="foundHeaderValue">The actual header value received.</param>
/// <param name="foundHeader">A bool tracking whether this header has been seen.</param>
private static void ValidateAndTrackHeader(
string targetHeaderName, string targetHeaderValue,
string foundHeaderName, string foundHeaderValue,
ref bool foundHeader)
{
bool isTargetHeader = string.Equals(targetHeaderName, foundHeaderName, StringComparison.OrdinalIgnoreCase);
if (!foundHeader)
{
if (isTargetHeader)
{
if (!string.Equals(targetHeaderValue, foundHeaderValue, StringComparison.OrdinalIgnoreCase))
{
throw new WebSocketException(SR.Format(SR.net_WebSockets_InvalidResponseHeader, targetHeaderName, foundHeaderValue));
}
foundHeader = true;
}
}
else
{
if (isTargetHeader)
{
throw new WebSocketException(SR.Format(SR.net_webstatus_ConnectFailure));
}
}
}
/// <summary>Reads a line from the stream.</summary>
/// <param name="stream">The stream from which to read.</param>
/// <param name="cancellationToken">The CancellationToken used to cancel the websocket.</param>
/// <returns>The read line, or null if none could be read.</returns>
private static async Task<string> ReadResponseHeaderLineAsync(Stream stream, CancellationToken cancellationToken)
{
StringBuilder sb = t_cachedStringBuilder;
if (sb != null)
{
t_cachedStringBuilder = null;
Debug.Assert(sb.Length == 0, $"Expected empty StringBuilder");
}
else
{
sb = new StringBuilder();
}
var arr = new byte[1];
char prevChar = '\0';
try
{
// TODO: Reading one byte is extremely inefficient. The problem, however,
// is that if we read multiple bytes, we could end up reading bytes post-headers
// that are part of messages meant to be read by the managed websocket after
// the connection. The likely solution here is to wrap the stream in a BufferedStream,
// though a) that comes at the expense of an extra set of virtual calls, b)
// it adds a buffer when the managed websocket will already be using a buffer, and
// c) it's not exposed on the version of the System.IO contract we're currently using.
while (await stream.ReadAsync(arr, 0, 1, cancellationToken).ConfigureAwait(false) == 1)
{
// Process the next char
char curChar = (char)arr[0];
if (prevChar == '\r' && curChar == '\n')
{
break;
}
sb.Append(curChar);
prevChar = curChar;
}
if (sb.Length > 0 && sb[sb.Length - 1] == '\r')
{
sb.Length = sb.Length - 1;
}
return sb.ToString();
}
finally
{
sb.Clear();
t_cachedStringBuilder = sb;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.ContainerRegistry.Fluent
{
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using Microsoft.Azure.Management.Storage.Fluent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
internal partial class RegistryImpl
{
/// <summary>
/// The parameters of a storage account for the container registry.
/// If specified, the storage account must be in the same physical location as the container registry.
/// </summary>
/// <param name="storageAccount">The storage account.</param>
/// <return>The next stage.</return>
Registry.Definition.IWithCreate Registry.Definition.IWithStorageAccount.WithExistingStorageAccount(IStorageAccount storageAccount)
{
return this.WithExistingStorageAccount(storageAccount);
}
/// <summary>
/// The ID of an existing storage account for the container registry.
/// If specified, the storage account must be in the same physical location as the container registry.
/// </summary>
/// <param name="id">The resource ID of the storage account; must be in the same physical location as the container registry.</param>
/// <return>The next stage.</return>
Registry.Definition.IWithCreate Registry.Definition.IWithStorageAccountBeta.WithExistingStorageAccount(string id)
{
return this.WithExistingStorageAccount(id);
}
/// <summary>
/// The parameters for a storage account for the container registry.
/// A new storage account with default setting and specified name will be created.
/// </summary>
/// <param name="storageAccountName">The name of the storage account.</param>
/// <return>The next stage.</return>
Registry.Definition.IWithCreate Registry.Definition.IWithStorageAccountBeta.WithNewStorageAccount(string storageAccountName)
{
return this.WithNewStorageAccount(storageAccountName);
}
/// <summary>
/// The parameters for a storage account for the container registry.
/// If specified, the storage account must be in the same physical location as the container registry.
/// </summary>
/// <param name="creatable">The storage account to create.</param>
/// <return>The next stage.</return>
Registry.Definition.IWithCreate Registry.Definition.IWithStorageAccount.WithNewStorageAccount(ICreatable<Microsoft.Azure.Management.Storage.Fluent.IStorageAccount> creatable)
{
return this.WithNewStorageAccount(creatable);
}
/// <summary>
/// Begins an update for a new resource.
/// This is the beginning of the builder pattern used to update top level resources
/// in Azure. The final method completing the definition and starting the actual resource creation
/// process in Azure is Appliable.apply().
/// </summary>
/// <return>The stage of new resource update.</return>
Registry.Update.IUpdate Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.IUpdatable<Registry.Update.IUpdate>.Update()
{
return this.Update();
}
/// <summary>
/// Begins the definition of a new webhook to be added to this container registry.
/// </summary>
/// <param name="name">The name of the new webhook.</param>
/// <return>The first stage of the new webhook definition.</return>
Webhook.Definition.IBlank<Registry.Definition.IWithCreate> Registry.Definition.IWithWebhook.DefineWebhook(string name)
{
return this.DefineWebhook(name);
}
/// <summary>
/// Begins the definition of a new webhook to be added to this container registry.
/// </summary>
/// <param name="name">The name of the new webhook.</param>
/// <return>The first stage of the new webhook definition.</return>
Webhook.UpdateDefinition.IBlank<Registry.Update.IUpdate> Registry.Update.IWithWebhook.DefineWebhook(string name)
{
return this.DefineWebhook(name);
}
/// <summary>
/// Begins the description of an update of an existing webhook of this container registry.
/// </summary>
/// <param name="name">The name of an existing webhook.</param>
/// <return>The first stage of the webhook update description.</return>
Webhook.UpdateResource.IBlank<Registry.Update.IUpdate> Registry.Update.IWithWebhook.UpdateWebhook(string name)
{
return this.UpdateWebhook(name);
}
/// <summary>
/// Removes a webhook from the container registry.
/// </summary>
/// <param name="name">Name of the webhook to remove.</param>
/// <return>The next stage of the container registry update.</return>
Registry.Update.IUpdate Registry.Update.IWithWebhook.WithoutWebhook(string name)
{
return this.WithoutWebhook(name);
}
/// <summary>
/// Enable admin user.
/// </summary>
/// <return>The next stage of the definition.</return>
Registry.Definition.IWithCreate Registry.Definition.IWithAdminUserEnabled.WithRegistryNameAsAdminUser()
{
return this.WithRegistryNameAsAdminUser();
}
/// <summary>
/// Enable admin user.
/// </summary>
/// <return>The next stage of the definition.</return>
Registry.Update.IUpdate Registry.Update.IWithAdminUserEnabled.WithRegistryNameAsAdminUser()
{
return this.WithRegistryNameAsAdminUser();
}
/// <summary>
/// Disable admin user.
/// </summary>
/// <return>The next stage of the definition.</return>
Registry.Update.IUpdate Registry.Update.IWithAdminUserEnabled.WithoutRegistryNameAsAdminUser()
{
return this.WithoutRegistryNameAsAdminUser();
}
/// <summary>
/// Lists the quota usages for the specified container registry.
/// </summary>
/// <return>A representation of the future computation of this call.</return>
async Task<IReadOnlyCollection<Models.RegistryUsage>> Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistry.ListQuotaUsagesAsync(CancellationToken cancellationToken)
{
return await this.ListQuotaUsagesAsync(cancellationToken);
}
/// <summary>
/// Gets the creation date of the container registry in ISO8601 format.
/// </summary>
System.DateTime Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistry.CreationDate
{
get
{
return this.CreationDate();
}
}
/// <summary>
/// Gets the name of the storage account for the container registry; 'null' if container register SKU a managed tier.
/// </summary>
string Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistry.StorageAccountName
{
get
{
return this.StorageAccountName();
}
}
/// <summary>
/// Lists the quota usages for the specified container registry.
/// </summary>
/// <return>The list of container registry's quota usages.</return>
System.Collections.Generic.IReadOnlyCollection<Models.RegistryUsage> Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistry.ListQuotaUsages()
{
return this.ListQuotaUsages();
}
/// <summary>
/// Gets the ID of the storage account for the container registry; 'null' if container register SKU a managed tier.
/// </summary>
string Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistry.StorageAccountId
{
get
{
return this.StorageAccountId();
}
}
/// <summary>
/// Gets the value that indicates whether the admin user is enabled.
/// </summary>
bool Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistry.AdminUserEnabled
{
get
{
return this.AdminUserEnabled();
}
}
/// <summary>
/// Gets returns entry point to manage container registry webhooks.
/// </summary>
Microsoft.Azure.Management.ContainerRegistry.Fluent.IWebhookOperations Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistry.Webhooks
{
get
{
return this.Webhooks();
}
}
/// <summary>
/// Gets the SKU of the container registry.
/// </summary>
Models.Sku Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistry.Sku
{
get
{
return this.Sku();
}
}
/// <return>The login credentials for the specified container registry.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistryCredentials Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistry.GetCredentials()
{
return this.GetCredentials();
}
/// <summary>
/// Gets the URL that can be used to log into the container registry.
/// </summary>
string Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistry.LoginServerUrl
{
get
{
return this.LoginServerUrl();
}
}
/// <summary>
/// Regenerates one of the login credentials for the specified container registry.
/// </summary>
/// <param name="accessKeyType">The admin user access key name to regenerate the value for.</param>
/// <return>A representation of the future computation of this call.</return>
async Task<Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistryCredentials> Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistry.RegenerateCredentialAsync(AccessKeyType accessKeyType, CancellationToken cancellationToken)
{
return await this.RegenerateCredentialAsync(accessKeyType, cancellationToken);
}
/// <return>A representation of the future computation of this call.</return>
async Task<Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistryCredentials> Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistry.GetCredentialsAsync(CancellationToken cancellationToken)
{
return await this.GetCredentialsAsync(cancellationToken);
}
/// <summary>
/// Regenerates one of the login credentials for the specified container registry.
/// </summary>
/// <param name="accessKeyType">The admin user access key name to regenerate the value for.</param>
/// <return>The result of the regeneration.</return>
Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistryCredentials Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistry.RegenerateCredential(AccessKeyType accessKeyType)
{
return this.RegenerateCredential(accessKeyType);
}
/// <summary>
/// Creates a container registry with a 'Classic' SKU type.
/// </summary>
/// <return>The next stage of the definition.</return>
Registry.Definition.IWithStorageAccount Registry.Definition.IWithSkuBeta.WithClassicSku()
{
return this.WithClassicSku();
}
/// <summary>
/// Creates a 'managed' registry with a 'Basic' SKU type.
/// </summary>
/// <return>The next stage of the definition.</return>
Registry.Definition.IWithCreate Registry.Definition.IWithSkuBeta.WithBasicSku()
{
return this.WithBasicSku();
}
/// <summary>
/// Creates a 'managed' registry with a 'Standard' SKU type.
/// </summary>
/// <return>The next stage of the definition.</return>
Registry.Definition.IWithCreate Registry.Definition.IWithSkuBeta.WithStandardSku()
{
return this.WithStandardSku();
}
/// <summary>
/// Creates a 'managed' registry with a 'Premium' SKU type.
/// </summary>
/// <return>The next stage of the definition.</return>
Registry.Definition.IWithCreate Registry.Definition.IWithSkuBeta.WithPremiumSku()
{
return this.WithPremiumSku();
}
/// <summary>
/// Updates the current container registry to a 'managed' registry with a 'Basic' SKU type.
/// </summary>
/// <return>The next stage of the definition.</return>
Registry.Update.IUpdate Registry.Update.IWithSkuBeta.WithBasicSku()
{
return this.WithBasicSku();
}
/// <summary>
/// Updates the current container registry to a 'managed' registry with a 'Standard' SKU type.
/// </summary>
/// <return>The next stage of the definition.</return>
Registry.Update.IUpdate Registry.Update.IWithSkuBeta.WithStandardSku()
{
return this.WithStandardSku();
}
/// <summary>
/// Updates the current container registry to a 'managed' registry with a 'Premium' SKU type.
/// </summary>
/// <return>The next stage of the definition.</return>
Registry.Update.IUpdate Registry.Update.IWithSkuBeta.WithPremiumSku()
{
return this.WithPremiumSku();
}
/// <summary>
/// Gets returns entry point to manage the build tasks for the container registry.
/// </summary>
RegistryTaskRun.Definition.IBlankFromRegistry Microsoft.Azure.Management.ContainerRegistry.Fluent.IRegistry.ScheduleRun()
{
return this.ScheduleRun();
}
}
}
| |
// 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.
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/events/cloud/scheduler/v1/data.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Events.Protobuf.Cloud.Scheduler.V1 {
/// <summary>Holder for reflection information generated from google/events/cloud/scheduler/v1/data.proto</summary>
public static partial class DataReflection {
#region Descriptor
/// <summary>File descriptor for google/events/cloud/scheduler/v1/data.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static DataReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Citnb29nbGUvZXZlbnRzL2Nsb3VkL3NjaGVkdWxlci92MS9kYXRhLnByb3Rv",
"EiBnb29nbGUuZXZlbnRzLmNsb3VkLnNjaGVkdWxlci52MSInChBTY2hlZHVs",
"ZXJKb2JEYXRhEhMKC2N1c3RvbV9kYXRhGAEgASgMQiyqAilHb29nbGUuRXZl",
"bnRzLlByb3RvYnVmLkNsb3VkLlNjaGVkdWxlci5WMWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Events.Protobuf.Cloud.Scheduler.V1.SchedulerJobData), global::Google.Events.Protobuf.Cloud.Scheduler.V1.SchedulerJobData.Parser, new[]{ "CustomData" }, null, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Scheduler job data.
/// </summary>
public sealed partial class SchedulerJobData : pb::IMessage<SchedulerJobData>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<SchedulerJobData> _parser = new pb::MessageParser<SchedulerJobData>(() => new SchedulerJobData());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<SchedulerJobData> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Events.Protobuf.Cloud.Scheduler.V1.DataReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public SchedulerJobData() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public SchedulerJobData(SchedulerJobData other) : this() {
customData_ = other.customData_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public SchedulerJobData Clone() {
return new SchedulerJobData(this);
}
/// <summary>Field number for the "custom_data" field.</summary>
public const int CustomDataFieldNumber = 1;
private pb::ByteString customData_ = pb::ByteString.Empty;
/// <summary>
/// The custom data the user specified when creating the scheduler source.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public pb::ByteString CustomData {
get { return customData_; }
set {
customData_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as SchedulerJobData);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(SchedulerJobData other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (CustomData != other.CustomData) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (CustomData.Length != 0) hash ^= CustomData.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (CustomData.Length != 0) {
output.WriteRawTag(10);
output.WriteBytes(CustomData);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (CustomData.Length != 0) {
output.WriteRawTag(10);
output.WriteBytes(CustomData);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (CustomData.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(CustomData);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(SchedulerJobData other) {
if (other == null) {
return;
}
if (other.CustomData.Length != 0) {
CustomData = other.CustomData;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
CustomData = input.ReadBytes();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
CustomData = input.ReadBytes();
break;
}
}
}
}
#endif
}
#endregion
}
#endregion Designer generated code
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// OauthAccess
/// </summary>
[DataContract]
public partial class OauthAccess : IEquatable<OauthAccess>, IValidatableObject
{
public OauthAccess()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="OauthAccess" /> class.
/// </summary>
/// <param name="AccessToken">Access token information..</param>
/// <param name="Data">Data.</param>
/// <param name="ExpiresIn">ExpiresIn.</param>
/// <param name="RefreshToken">RefreshToken.</param>
/// <param name="Scope">Must be set to \"api\"..</param>
/// <param name="TokenType">TokenType.</param>
public OauthAccess(string AccessToken = default(string), List<NameValue> Data = default(List<NameValue>), string ExpiresIn = default(string), string RefreshToken = default(string), string Scope = default(string), string TokenType = default(string))
{
this.AccessToken = AccessToken;
this.Data = Data;
this.ExpiresIn = ExpiresIn;
this.RefreshToken = RefreshToken;
this.Scope = Scope;
this.TokenType = TokenType;
}
/// <summary>
/// Access token information.
/// </summary>
/// <value>Access token information.</value>
[DataMember(Name="access_token", EmitDefaultValue=false)]
public string AccessToken { get; set; }
/// <summary>
/// Gets or Sets Data
/// </summary>
[DataMember(Name="data", EmitDefaultValue=false)]
public List<NameValue> Data { get; set; }
/// <summary>
/// Gets or Sets ExpiresIn
/// </summary>
[DataMember(Name="expires_in", EmitDefaultValue=false)]
public string ExpiresIn { get; set; }
/// <summary>
/// Gets or Sets RefreshToken
/// </summary>
[DataMember(Name="refresh_token", EmitDefaultValue=false)]
public string RefreshToken { get; set; }
/// <summary>
/// Must be set to \"api\".
/// </summary>
/// <value>Must be set to \"api\".</value>
[DataMember(Name="scope", EmitDefaultValue=false)]
public string Scope { get; set; }
/// <summary>
/// Gets or Sets TokenType
/// </summary>
[DataMember(Name="token_type", EmitDefaultValue=false)]
public string TokenType { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class OauthAccess {\n");
sb.Append(" AccessToken: ").Append(AccessToken).Append("\n");
sb.Append(" Data: ").Append(Data).Append("\n");
sb.Append(" ExpiresIn: ").Append(ExpiresIn).Append("\n");
sb.Append(" RefreshToken: ").Append(RefreshToken).Append("\n");
sb.Append(" Scope: ").Append(Scope).Append("\n");
sb.Append(" TokenType: ").Append(TokenType).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as OauthAccess);
}
/// <summary>
/// Returns true if OauthAccess instances are equal
/// </summary>
/// <param name="other">Instance of OauthAccess to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(OauthAccess other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.AccessToken == other.AccessToken ||
this.AccessToken != null &&
this.AccessToken.Equals(other.AccessToken)
) &&
(
this.Data == other.Data ||
this.Data != null &&
this.Data.SequenceEqual(other.Data)
) &&
(
this.ExpiresIn == other.ExpiresIn ||
this.ExpiresIn != null &&
this.ExpiresIn.Equals(other.ExpiresIn)
) &&
(
this.RefreshToken == other.RefreshToken ||
this.RefreshToken != null &&
this.RefreshToken.Equals(other.RefreshToken)
) &&
(
this.Scope == other.Scope ||
this.Scope != null &&
this.Scope.Equals(other.Scope)
) &&
(
this.TokenType == other.TokenType ||
this.TokenType != null &&
this.TokenType.Equals(other.TokenType)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.AccessToken != null)
hash = hash * 59 + this.AccessToken.GetHashCode();
if (this.Data != null)
hash = hash * 59 + this.Data.GetHashCode();
if (this.ExpiresIn != null)
hash = hash * 59 + this.ExpiresIn.GetHashCode();
if (this.RefreshToken != null)
hash = hash * 59 + this.RefreshToken.GetHashCode();
if (this.Scope != null)
hash = hash * 59 + this.Scope.GetHashCode();
if (this.TokenType != null)
hash = hash * 59 + this.TokenType.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using CommandLineParser.Compatibility;
using CommandLineParser.Exceptions;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace CommandLineParser.Arguments
{
/// <summary>
/// Delegate for a method that converts string to a specified class
/// </summary>
/// <typeparam name="TValue">type of the converted class</typeparam>
/// <param name="stringValue">string that represents the value of TValue</param>
/// <returns>TValue loaded from string</returns>
public delegate TValue ConvertValueDelegate<TValue>(string stringValue);
/// <summary>
/// Use value argument for an argument followed by value on the command line. (e. g. --version 1.2)
/// </summary>
/// <typeparam name="TValue">type of the value of the argument.
/// Can be either builtin type or any user type (for which specific
/// conversion routine is provided - <see cref="ConvertValueHandler"/></typeparam>
/// <include file='..\Doc\CommandLineParser.xml' path='CommandLineParser/Arguments/ValueArgument/*'/>
public class ValueArgument<TValue> : Argument, IValueArgument, IArgumentWithDefaultValue, IArgumentWithForcedDefaultValue
{
#region property backing fields
private string _stringValue;
private TValue _value;
private readonly List<TValue> _values = new List<TValue>();
private CultureInfo _cultureInfo = CultureInfo.InvariantCulture;
private TValue _forcedDefaultValue;
private bool _hasForcedDefaultValue;
#endregion
#region constructor
/// <summary>
/// Creates new value argument with a <see cref="Argument.ShortName">short name</see>.
/// </summary>
/// <param name="shortName">Short name of the argument</param>
public ValueArgument(char shortName) : base(shortName) { }
/// <summary>
/// Creates new value argument with a <see cref="Argument.LongName">long name</see>.
/// </summary>
/// <param name="longName">Long name of the argument</param>
public ValueArgument(string longName) : base(longName) { }
/// <summary>
/// Creates new value argument with a <see cref="Argument.ShortName">short name</see>and <see cref="Argument.LongName">long name</see>.
/// </summary>
/// <param name="shortName">Short name of the argument</param>
/// <param name="longName">Long name of the argument </param>
public ValueArgument(char shortName, string longName) : base(shortName, longName) { }
/// <summary>
/// Creates new value argument with a <see cref="Argument.ShortName">short name</see>,
/// <see cref="Argument.LongName">long name</see> and <see cref="Argument.Description">description</see>.
/// </summary>
/// <param name="shortName">Short name of the argument</param>
/// <param name="longName">Long name of the argument </param>
/// <param name="description">description of the argument</param>
public ValueArgument(char shortName, string longName, string description)
: base(shortName, longName, description) { }
#endregion
/// <summary>
/// String read from command line as arguments <see cref="Value"/>. Available after <see cref="Parse"/> is called.
/// </summary>
/// <exception cref="InvalidOperationException">String value was read before ParseCommandLine was called or when</exception>
public string StringValue => Parsed ? _stringValue : null;
/// <summary>
/// Value of the ValueArgument, for arguments with single value.
/// Can be used only if <see cref="Argument.AllowMultiple"/> is set to false.
/// </summary>
public TValue Value
{
get
{
if (AllowMultiple)
throw new InvalidOperationException("Cannot access Value field because AllowMultiple is set to true. Use Values instead.");
return _value;
}
set
{
if (AllowMultiple)
throw new InvalidOperationException("Cannot access Value field because AllowMultiple is set to true. Use Values instead.");
_value = value;
}
}
/// <summary>
/// Default value of the argument. Restored each time <see cref="Init"/> is called.
/// </summary>
public TValue DefaultValue { get; set; }
public TValue ForcedDefaultValue
{
get => _forcedDefaultValue;
set
{
_forcedDefaultValue = value;
_hasForcedDefaultValue = true;
}
}
object IArgumentWithDefaultValue.DefaultValue => DefaultValue;
object IArgumentWithForcedDefaultValue.DefaultValue => ForcedDefaultValue;
/// <summary>
/// When set to true, argument can appear on the command line with or without value, e.g. both is allowed:
/// <code>
/// myexe.exe -Arg Value
/// OR
/// myexe.exe -Arg
/// </code>
/// </summary>
public bool ValueOptional { get; set; }
/// <summary>
/// Values of the ValueArgument - for arguments with multiple values allowed.
/// Can be used only if <see cref="Argument.AllowMultiple"/> is set to true.
/// </summary>
public List<TValue> Values
{
get
{
if (!AllowMultiple)
throw new InvalidOperationException("Cannot access Values field because AllowMultiple is set to false. Use Value instead.");
return _values;
}
}
/// <summary>
/// Value of the ValueArgument, for arguments with single value.
/// Can be used only if <see cref="Argument.AllowMultiple"/> is set to false.
/// </summary>
/// <value></value>
object IValueArgument.Value
{
get => Value;
set => Value = (TValue)value;
}
IList<object> IValueArgument.Values
{
get
{
object[] objects = new object[Values.Count];
for (int i = 0; i < Values.Count; i++)
{
objects[i] = Values[i];
}
return objects;
}
}
/// <summary>
/// Adds an item to underlying <see cref="Values"/> collection.
/// </summary>
public void AddToValues(object value)
{
Values.Add((TValue)value);
}
/// <summary>
/// Function that converts string to <typeparamref name="TValue"/> type.
/// Necessary when non-builtin type is used as <typeparamref name="TValue"/>.
/// </summary>
public ConvertValueDelegate<TValue> ConvertValueHandler { get; set; }
/// <summary>
/// This method reads the argument and the following string representing the value of the argument.
/// This string is then converted to <typeparamref name="TValue"/> (using built-in <typeparamref name="TValue"/>.Parse
/// method for built-in types or using <see cref="ConvertValueHandler"/> for user types).
/// </summary>
/// <param name="args">command line arguments</param>
/// <param name="i">index to the args array, where this argument occured.
/// The index to the next argument after the argument is processed. </param>
/// <seealso cref="ConvertValueHandler"/>
/// <exception cref="CommandLineArgumentException">Incorrect format of the command line
/// or multiple useage of an argument that is not <see cref="Argument.AllowMultiple"/> found.</exception>
public override void Parse(IList<string> args, ref int i)
{
base.Parse(args, ref i);
i++; // move the cursor to the value
if (args.Count - 1 < i)
{
if (ValueOptional)
{
if (DefaultValue != null)
{
_value = DefaultValue;
}
Parsed = true;
return;
}
throw new CommandLineArgumentException(string.Format(Messages.EXC_ARG_VALUE_MISSING2, Name), Name);
}
_stringValue = args[i];
bool canParse = true;
try { Convert(_stringValue); }
catch { canParse = false; }
if (!canParse && args[i].StartsWith("-"))
{
if (ValueOptional)
{
if (DefaultValue != null)
{
_value = DefaultValue;
}
Parsed = true;
return;
}
throw new CommandLineArgumentException(string.Format(Messages.EXC_ARG_VALUE_MISSING, Name, args[i]), Name);
}
if (!AllowMultiple)
Value = Convert(_stringValue);
else
Values.Add(Convert(_stringValue));
Parsed = true;
i++; // move to the next argument
}
/// <summary>
/// If <see cref="Argument.Bind"/> is specified, the bound field of the bound object should is updated
/// according to the value of the argument. Should be called after Parse is called. If
/// <see cref="Argument.AllowMultiple"/> is set to false, the binding fills a collection or an array with the
/// values.
/// </summary>
public override void UpdateBoundObject()
{
if (Bind == null)
return;
MemberInfo info = Bind.Value.Object.GetType().GetMember(Bind.Value.Field)[0];
Type boundType = null;
if (info is PropertyInfo) boundType = (info as PropertyInfo).PropertyType;
else if (info is FieldInfo) boundType = (info as FieldInfo).FieldType;
//multiple value argument can be bound only to a proper collection
if (AllowMultiple
&& (!(typeof(List<TValue>).IsAssignableFrom(boundType)))
&& !boundType.IsArray)
{
throw new InvalidOperationException("ValueArguments that allow multiple values can be bound only to an object implementing ICollection<TVale> and the collection must not be read only.");
}
try
{
if (!AllowMultiple || boundType.IsArray)
{
// binding of a simple value or array
object newValue;
if (!boundType.IsArray)
newValue = _value;
else
newValue = Values.ToArray();
if (info is FieldInfo)
(info as FieldInfo).SetValue(Bind.Value.Object, newValue);
if (info is PropertyInfo)
(info as PropertyInfo).SetValue(Bind.Value.Object, newValue, null);
}
else
{
ICollection<TValue> targetCollection = InitializeTargetCollection(info);
foreach (TValue value in _values)
{
targetCollection.Add(value);
}
}
}
catch (Exception e)
{
throw new CommandLineException(string.Format(Messages.EXC_BINDING, Name, Bind.Value.Field, Bind.Value.Object), e);
}
}
private ICollection<TValue> InitializeTargetCollection(MemberInfo info)
{
ICollection<TValue> targetCollection = null;
if (info is FieldInfo)
targetCollection = (ICollection<TValue>)(info as FieldInfo).GetValue(Bind.Value.Object);
else if (info is PropertyInfo)
targetCollection = (ICollection<TValue>)(info as PropertyInfo).GetValue(Bind.Value.Object, null);
if (targetCollection == null)
{
if (info is FieldInfo)
{
targetCollection = (ICollection<TValue>)Activator.CreateInstance((info as FieldInfo).FieldType);
(info as FieldInfo).SetValue(Bind.Value.Object, targetCollection);
}
else if (info is PropertyInfo)
{
targetCollection = (ICollection<TValue>)Activator.CreateInstance((info as PropertyInfo).PropertyType);
(info as PropertyInfo).SetValue(Bind.Value.Object, targetCollection, null);
}
}
targetCollection.Clear();
return targetCollection;
}
/// <summary>
/// Culture used for conversions of built-in types. InvariantCulture is used when
/// no other culture is specified.
/// </summary>
public CultureInfo CultureInfo
{
get => _cultureInfo;
set => _cultureInfo = value;
}
/// <summary>
/// Converts <paramref name="stringValue"/> to <typeparamref name="TValue"/>.
/// <see cref="ConvertValueHandler"/> is called if specified, otherwise
/// <see cref="DefaultConvert"/> is called.
/// </summary>
/// <param name="stringValue">string representing the value</param>
/// <returns>value as <typeparamref name="TValue"/></returns>
/// <exception cref="InvalidConversionException">String cannot be converted to <typeparamref name="TValue"/>.</exception>
public virtual TValue Convert(string stringValue)
{
TValue tmpValue;
if (ConvertValueHandler != null)
{
tmpValue = ConvertValueHandler(stringValue);
}
else
{
tmpValue = DefaultConvert(stringValue);
}
return tmpValue;
}
/// <summary>
/// Non-generic access to <see cref="ValueArgument{TValue}.Convert"/>
/// </summary>
/// <param name="stringValue">string representing the value</param>
/// <returns>parsed value</returns>
public object Convert_obj(string stringValue)
{
return Convert(stringValue);
}
/// <summary>
/// Converts <paramref name="stringValue"/> to <typeparamref name="TValue"/>.
/// Works only for built-in types.
/// </summary>
/// <param name="stringValue">string representing the value</param>
/// <returns>value as <typeparamref name="TValue"/></returns>
/// <exception cref="InvalidConversionException">String cannot be converted to <typeparamref name="TValue"/>.</exception>
protected virtual TValue DefaultConvert(string stringValue)
{
// If not provided, just return default value.
if (stringValue == null)
{
return default(TValue);
}
Type valueType = typeof(TValue);
// If the TValue is a nullable type, get the underlying type.
if (valueType.GetTypeInfo().IsGenericType && valueType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
valueType = Nullable.GetUnderlyingType(valueType);
}
try
{
if (valueType == typeof(String))
{
return (TValue)(object)stringValue;
}
if (typeof(Enum).IsAssignableFrom(valueType))
{
return (TValue)Enum.Parse(valueType, stringValue, true);
}
if (valueType == typeof(Guid))
{
#if NET20 || NET35
return (TValue)(object)new Guid(stringValue);
#else
return (TValue)(object)Guid.Parse(stringValue);
#endif
}
MethodInfo parseMethod2 = valueType.GetMethod("Parse", new[] { typeof(string), typeof(CultureInfo) });
if (parseMethod2 != null)
{
if (parseMethod2.IsStatic && parseMethod2.ReturnType == valueType)
{
return (TValue)parseMethod2.Invoke(null, new object[] { stringValue, _cultureInfo });
}
}
MethodInfo parseMethod1 = valueType.GetMethod("Parse", new[] { typeof(string) });
if (parseMethod1 != null)
{
if (parseMethod1.IsStatic && parseMethod1.ReturnType == valueType)
{
return (TValue)parseMethod1.Invoke(null, new object[] { stringValue });
}
}
}
catch (FormatException)
{
throw new InvalidConversionException(string.Format(Messages.EXC_ARG_VALUE_STANDARD_CONVERT_FAILED, stringValue, valueType), Name);
}
throw new InvalidConversionException(string.Format(Messages.EXC_ARG_VALUE_USER_CONVERT_MISSING, valueType, stringValue), Name);
}
/// <summary>
/// Initializes the argument.
/// </summary>
public override void Init()
{
base.Init();
_value = _hasForcedDefaultValue ? ForcedDefaultValue : DefaultValue;
_values.Clear();
_stringValue = string.Empty;
}
/// <summary>
/// Prints information about the argument value to the console.
/// </summary>
public override void PrintValueInfo()
{
if (!AllowMultiple)
{
Console.WriteLine(Messages.EXC_ARG_VALUE_PRINT, Name, _stringValue, _value, typeof(TValue).Name);
}
else
{
string valuesString = string.Join(", ", _values.Select(v => v.ToString()).ToArray());
Console.WriteLine(Messages.EXC_ARG_VALUE_PRINT_MULTIPLE, Name, Values.Count, valuesString, typeof(TValue).Name);
}
}
}
/// <summary>
/// <para>
/// Attribute for declaring a class' field a <see cref="ValueArgument{TValue}"/> and
/// thus binding a field's value to a certain command line switch argument.
/// </para>
/// <para>
/// Instead of creating an argument explicitly, you can assign a class' field an argument
/// attribute and let the CommandLineParse take care of binding the attribute to the field.
/// </para>
/// </summary>
/// <remarks>Applicable to fields and properties (public).</remarks>
/// <remarks>Use <see cref="CommandLineParser.ExtractArgumentAttributes"/> for each object
/// you where you have delcared argument attributes.</remarks>
public class ValueArgumentAttribute : ArgumentAttribute
{
private static Type _underlyingValueArgument;
/// <summary>
/// Creates proper generic <see cref="ValueArgument{TValue}"/> type for <paramref name="type"/>.
/// </summary>
/// <param name="type">type of the argument value</param>
/// <returns>generic type</returns>
private static Type CreateProperValueArgumentType(Type type)
{
Type genericType = typeof(ValueArgument<>);
Type constructedType = genericType.MakeGenericType(type);
_underlyingValueArgument = constructedType;
return _underlyingValueArgument;
}
/// <summary>
/// Creates new instance of ValueArgument. ValueArgument
/// uses underlying <see cref="ValueArgument{TValue}"/>.
/// </summary>
/// <param name="type">Type of the generic parameter of <see cref="ValueArgument{TValue}"/>. </param>
/// <param name="shortName"><see cref="Argument.ShortName">short name</see> of the underlying argument</param>
/// <remarks>
/// Parameter <paramref name="type"/> has to be either built-in
/// type or has to define a static Parse(String, CultureInfo)
/// method for reading the value from string.
/// </remarks>
public ValueArgumentAttribute(Type type, char shortName)
: base(CreateProperValueArgumentType(type), shortName) { }
/// <summary>
/// Creates new instance of ValueArgument. ValueArgument
/// uses underlying <see cref="ValueArgument{TValue}"/>.
/// </summary>
/// <param name="type">Type of the generic parameter of <see cref="ValueArgument{TValue}"/>. </param>
/// <param name="longName"><see cref="Argument.LongName">long name</see> of the underlying argument</param>
/// <remarks>
/// Parameter <paramref name="type"/> has to be either built-in
/// type or has to define a static Parse(String, CultureInfo)
/// method for reading the value from string.
/// </remarks>
public ValueArgumentAttribute(Type type, string longName)
: base(CreateProperValueArgumentType(type), longName) { }
/// <summary>
/// Creates new instance of ValueArgument. ValueArgument
/// uses underlying <see cref="ValueArgument{TValue}"/>.
/// </summary>
/// <param name="type">Type of the generic parameter of <see cref="ValueArgument{TValue}"/>.</param>
/// <param name="shortName"><see cref="Argument.ShortName">short name</see> of the underlying argument</param>
/// <param name="longName"><see cref="Argument.LongName">long name</see> of the underlying argument</param>
/// <remarks>
/// Parameter <paramref name="type"/> has to be either built-in
/// type or has to define a static Parse(String, CultureInfo)
/// method for reading the value from string.
/// </remarks>
public ValueArgumentAttribute(Type type, char shortName, string longName)
: base(CreateProperValueArgumentType(type), shortName, longName) { }
/// <summary>
/// Default value
/// </summary>
public object DefaultValue
{
get => _underlyingValueArgument.GetPropertyValue<object>("DefaultValue", Argument);
set => _underlyingValueArgument.SetPropertyValue("DefaultValue", Argument, value);
}
/// <summary>
/// Forced default value
/// </summary>
public object ForcedDefaultValue
{
get => _underlyingValueArgument.GetPropertyValue<object>("ForcedDefaultValue", Argument);
set => _underlyingValueArgument.SetPropertyValue("ForcedDefaultValue", Argument, value);
}
/// <summary>
/// When set to true, argument can appear on the command line with or without value, e.g. both is allowed:
/// <code>
/// myexe.exe -Arg Value
/// OR
/// myexe.exe -Arg
/// </code>
/// </summary>
public bool ValueOptional
{
get => _underlyingValueArgument.GetPropertyValue<bool>("ValueOptional", Argument);
set => _underlyingValueArgument.SetPropertyValue("ValueOptional", Argument, value);
}
}
}
| |
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Configuration;
using osu.Framework.Development;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.IO.Stores;
using osu.Framework.Platform;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Graphics;
using osu.Game.Graphics.Cursor;
using osu.Game.Online.API;
using osu.Framework.Graphics.Performance;
using osu.Framework.Graphics.Textures;
using osu.Framework.Logging;
using osu.Game.Database;
using osu.Game.Graphics.Textures;
using osu.Game.Input;
using osu.Game.Input.Bindings;
using osu.Game.IO;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Scoring;
using osu.Game.Skinning;
namespace osu.Game
{
/// <summary>
/// The most basic <see cref="Game"/> that can be used to host osu! components and systems.
/// Unlike <see cref="OsuGame"/>, this class will not load any kind of UI, allowing it to be used
/// for provide dependencies to test cases without interfering with them.
/// </summary>
public class OsuGameBase : Framework.Game, ICanAcceptFiles
{
protected OsuConfigManager LocalConfig;
protected BeatmapManager BeatmapManager;
protected SkinManager SkinManager;
protected RulesetStore RulesetStore;
protected FileStore FileStore;
protected ScoreStore ScoreStore;
protected KeyBindingStore KeyBindingStore;
protected SettingsStore SettingsStore;
protected CursorOverrideContainer CursorOverrideContainer;
protected override string MainResourceFile => @"osu.Game.Resources.dll";
private Container content;
protected override Container<Drawable> Content => content;
public Bindable<WorkingBeatmap> Beatmap { get; private set; }
private Bindable<bool> fpsDisplayVisible;
protected AssemblyName AssemblyName => Assembly.GetEntryAssembly()?.GetName() ?? new AssemblyName { Version = new Version() };
public bool IsDeployedBuild => AssemblyName.Version.Major > 0;
public string Version
{
get
{
if (!IsDeployedBuild)
return @"local " + (DebugUtils.IsDebug ? @"debug" : @"release");
var assembly = AssemblyName;
return $@"{assembly.Version.Major}.{assembly.Version.Minor}.{assembly.Version.Build}";
}
}
public OsuGameBase()
{
Name = @"osu!lazer";
}
private DependencyContainer dependencies;
protected override IReadOnlyDependencyContainer CreateLocalDependencies(IReadOnlyDependencyContainer parent) =>
dependencies = new DependencyContainer(base.CreateLocalDependencies(parent));
private DatabaseContextFactory contextFactory;
[BackgroundDependencyLoader]
private void load()
{
dependencies.Cache(contextFactory = new DatabaseContextFactory(Host));
dependencies.Cache(new LargeTextureStore(new RawTextureLoaderStore(new NamespacedResourceStore<byte[]>(Resources, @"Textures"))));
dependencies.CacheAs(this);
dependencies.Cache(LocalConfig);
runMigrations();
dependencies.Cache(SkinManager = new SkinManager(Host.Storage, contextFactory, Host, Audio));
dependencies.CacheAs<ISkinSource>(SkinManager);
var api = new APIAccess(LocalConfig);
dependencies.Cache(api);
dependencies.CacheAs<IAPIProvider>(api);
dependencies.Cache(RulesetStore = new RulesetStore(contextFactory));
dependencies.Cache(FileStore = new FileStore(contextFactory, Host.Storage));
dependencies.Cache(BeatmapManager = new BeatmapManager(Host.Storage, contextFactory, RulesetStore, api, Audio, Host));
dependencies.Cache(ScoreStore = new ScoreStore(Host.Storage, contextFactory, Host, BeatmapManager, RulesetStore));
dependencies.Cache(KeyBindingStore = new KeyBindingStore(contextFactory, RulesetStore));
dependencies.Cache(SettingsStore = new SettingsStore(contextFactory));
dependencies.Cache(new OsuColour());
fileImporters.Add(BeatmapManager);
fileImporters.Add(ScoreStore);
fileImporters.Add(SkinManager);
//this completely overrides the framework default. will need to change once we make a proper FontStore.
dependencies.Cache(Fonts = new FontStore { ScaleAdjust = 100 });
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/FontAwesome"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/osuFont"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Medium"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-MediumItalic"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-Basic"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-Hangul"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-CJK-Basic"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-CJK-Compatibility"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Regular"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-RegularItalic"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-SemiBold"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-SemiBoldItalic"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Bold"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-BoldItalic"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Light"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-LightItalic"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Black"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-BlackItalic"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Venera"));
Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Venera-Light"));
var defaultBeatmap = new DummyWorkingBeatmap(this);
Beatmap = new NonNullableBindable<WorkingBeatmap>(defaultBeatmap);
BeatmapManager.DefaultBeatmap = defaultBeatmap;
// tracks play so loud our samples can't keep up.
// this adds a global reduction of track volume for the time being.
Audio.Track.AddAdjustment(AdjustableProperty.Volume, new BindableDouble(0.8));
Beatmap.ValueChanged += b =>
{
var trackLoaded = lastBeatmap?.TrackLoaded ?? false;
// compare to last beatmap as sometimes the two may share a track representation (optimisation, see WorkingBeatmap.TransferTo)
if (!trackLoaded || lastBeatmap?.Track != b.Track)
{
if (trackLoaded)
{
Debug.Assert(lastBeatmap != null);
Debug.Assert(lastBeatmap.Track != null);
lastBeatmap.RecycleTrack();
}
Audio.Track.AddItem(b.Track);
}
lastBeatmap = b;
};
FileStore.Cleanup();
AddInternal(api);
GlobalActionContainer globalBinding;
CursorOverrideContainer = new CursorOverrideContainer { RelativeSizeAxes = Axes.Both };
CursorOverrideContainer.Child = globalBinding = new GlobalActionContainer(this)
{
RelativeSizeAxes = Axes.Both,
Child = content = new OsuTooltipContainer(CursorOverrideContainer.Cursor) { RelativeSizeAxes = Axes.Both }
};
base.Content.Add(new DrawSizePreservingFillContainer { Child = CursorOverrideContainer });
KeyBindingStore.Register(globalBinding);
dependencies.Cache(globalBinding);
}
private void runMigrations()
{
try
{
using (var db = contextFactory.GetForWrite())
db.Context.Migrate();
}
catch (MigrationFailedException e)
{
Logger.Error(e.InnerException ?? e, "Migration failed! We'll be starting with a fresh database.", LoggingTarget.Database);
// if we failed, let's delete the database and start fresh.
// todo: we probably want a better (non-destructive) migrations/recovery process at a later point than this.
contextFactory.ResetDatabase();
Logger.Log("Database purged successfully.", LoggingTarget.Database, LogLevel.Important);
using (var db = contextFactory.GetForWrite())
db.Context.Migrate();
}
}
private WorkingBeatmap lastBeatmap;
protected override void LoadComplete()
{
base.LoadComplete();
// TODO: This is temporary until we reimplement the local FPS display.
// It's just to allow end-users to access the framework FPS display without knowing the shortcut key.
fpsDisplayVisible = LocalConfig.GetBindable<bool>(OsuSetting.ShowFpsDisplay);
fpsDisplayVisible.ValueChanged += val => { FrameStatisticsMode = val ? FrameStatisticsMode.Minimal : FrameStatisticsMode.None; };
fpsDisplayVisible.TriggerChange();
}
public override void SetHost(GameHost host)
{
if (LocalConfig == null)
LocalConfig = new OsuConfigManager(host.Storage);
base.SetHost(host);
}
private readonly List<ICanAcceptFiles> fileImporters = new List<ICanAcceptFiles>();
public void Import(params string[] paths)
{
var extension = Path.GetExtension(paths.First());
foreach (var importer in fileImporters)
if (importer.HandledExtensions.Contains(extension)) importer.Import(paths);
}
public string[] HandledExtensions => fileImporters.SelectMany(i => i.HandledExtensions).ToArray();
}
}
| |
//---------------------------------------------------------------------
// <copyright file="AttributeEmitter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.CodeDom;
using System.Collections.Generic;
using System.Data.Metadata.Edm;
using System.Data.Services.Common;
using System.Data.Services.Design;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
namespace System.Data.EntityModel.Emitters
{
/// <summary>
/// Summary description for AttributeEmitter.
/// </summary>
internal sealed partial class AttributeEmitter
{
private const string _generatorVersion = "1.0.0";
private const string _generatorName = "System.Data.Services.Design";
private static readonly CodeAttributeDeclaration _generatedCodeAttribute = new CodeAttributeDeclaration(
new CodeTypeReference(typeof(System.CodeDom.Compiler.GeneratedCodeAttribute)),
new CodeAttributeArgument(new CodePrimitiveExpression(_generatorName)),
new CodeAttributeArgument(new CodePrimitiveExpression(_generatorVersion)));
TypeReference _typeReference;
internal TypeReference TypeReference
{
get { return _typeReference; }
}
internal AttributeEmitter(TypeReference typeReference)
{
_typeReference = typeReference;
}
/// <summary>
/// The method to be called to create the type level attributes for the ItemTypeEmitter
/// </summary>
/// <param name="emitter">The strongly typed emitter</param>
/// <param name="typeDecl">The type declaration to add the attribues to.</param>
public void EmitTypeAttributes(EntityTypeEmitter emitter, CodeTypeDeclaration typeDecl)
{
Debug.Assert(emitter != null, "emitter should not be null");
Debug.Assert(typeDecl != null, "typeDecl should not be null");
if (emitter.Generator.Version != DataServiceCodeVersion.V1)
{
EmitEpmAttributesForEntityType(emitter.Generator.EdmItemCollection, emitter.Item, typeDecl);
EmitStreamAttributesForEntityType(emitter.Item, typeDecl);
}
object[] keys = emitter.Item.KeyMembers.Select(km => (object) km.Name).ToArray();
typeDecl.CustomAttributes.Add(EmitSimpleAttribute(Utils.WebFrameworkCommonNamespace + "." + "DataServiceKeyAttribute", keys));
}
/// <summary>
/// The method to be called to create the type level attributes for the StructuredTypeEmitter
/// </summary>
/// <param name="emitter">The strongly typed emitter</param>
/// <param name="typeDecl">The type declaration to add the attribues to.</param>
public void EmitTypeAttributes(StructuredTypeEmitter emitter, CodeTypeDeclaration typeDecl)
{
Debug.Assert(emitter != null, "emitter should not be null");
Debug.Assert(typeDecl != null, "typeDecl should not be null");
// nothing to do here yet
}
/// <summary>
/// The method to be called to create the type level attributes for the SchemaTypeEmitter
/// </summary>
/// <param name="emitter">The strongly typed emitter</param>
/// <param name="typeDecl">The type declaration to add the attribues to.</param>
public void EmitTypeAttributes(SchemaTypeEmitter emitter, CodeTypeDeclaration typeDecl)
{
Debug.Assert(emitter != null, "emitter should not be null");
Debug.Assert(typeDecl != null, "typeDecl should not be null");
}
/// <summary>
/// The method to be called to create the property level attributes for the PropertyEmitter
/// </summary>
/// <param name="emitter">The strongly typed emitter</param>
/// <param name="propertyDecl">The type declaration to add the attribues to.</param>
/// <param name="additionalAttributes">Additional attributes to emit</param>
public void EmitPropertyAttributes(PropertyEmitter emitter,
CodeMemberProperty propertyDecl,
List<CodeAttributeDeclaration> additionalAttributes)
{
if (additionalAttributes != null && additionalAttributes.Count > 0)
{
try
{
propertyDecl.CustomAttributes.AddRange(additionalAttributes.ToArray());
}
catch (ArgumentNullException e)
{
emitter.Generator.AddError(Strings.InvalidAttributeSuppliedForProperty(emitter.Item.Name),
ModelBuilderErrorCode.InvalidAttributeSuppliedForProperty,
EdmSchemaErrorSeverity.Error,
e);
}
}
}
/// <summary>
/// The method to be called to create the type level attributes for the NestedTypeEmitter
/// </summary>
/// <param name="emitter">The strongly typed emitter</param>
/// <param name="typeDecl">The type declaration to add the attribues to.</param>
public void EmitTypeAttributes(ComplexTypeEmitter emitter, CodeTypeDeclaration typeDecl)
{
Debug.Assert(emitter != null, "emitter should not be null");
Debug.Assert(typeDecl != null, "typeDecl should not be null");
// not emitting System.Runtime.Serializaton.DataContractAttribute
// not emitting System.Serializable
}
#region Static Methods
/// <summary>
///
/// </summary>
/// <param name="attributeType"></param>
/// <param name="arguments"></param>
/// <returns></returns>
public CodeAttributeDeclaration EmitSimpleAttribute(string attributeType, params object[] arguments)
{
CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(TypeReference.FromString(attributeType, true));
AddAttributeArguments(attribute, arguments);
return attribute;
}
/// <summary>
///
/// </summary>
/// <param name="attribute"></param>
/// <param name="arguments"></param>
public static void AddAttributeArguments(CodeAttributeDeclaration attribute, object[] arguments)
{
foreach (object argument in arguments)
{
CodeExpression expression = argument as CodeExpression;
if (expression == null)
expression = new CodePrimitiveExpression(argument);
attribute.Arguments.Add(new CodeAttributeArgument(expression));
}
}
/// <summary>
/// Adds an XmlIgnore attribute to the given property declaration. This is
/// used to explicitly skip certain properties during XML serialization.
/// </summary>
/// <param name="propertyDecl">the property to mark with XmlIgnore</param>
public void AddIgnoreAttributes(CodeMemberProperty propertyDecl)
{
// not emitting System.Xml.Serialization.XmlIgnoreAttribute
// not emitting System.Xml.Serialization.SoapIgnoreAttribute
}
/// <summary>
/// Adds an Browsable(false) attribute to the given property declaration.
/// This is used to explicitly avoid display property in the PropertyGrid.
/// </summary>
/// <param name="propertyDecl">the property to mark with XmlIgnore</param>
public void AddBrowsableAttribute(CodeMemberProperty propertyDecl)
{
// not emitting System.ComponentModel.BrowsableAttribute
}
#endregion
/// <summary>
/// Add the GeneratedCode attribute to the code type member
/// </summary>
/// <param name="ctm">the code type member</param>
public static void AddGeneratedCodeAttribute(CodeTypeMember ctm)
{
ctm.CustomAttributes.Add(_generatedCodeAttribute);
}
/// <summary>Given a type detects if it is an open type or not</summary>
/// <param name="entityType">Input type</param>
/// <returns>true if it is an open type, false otherwise</returns>
private static bool IsOpenType(StructuralType entityType)
{
MetadataProperty isOpenTypeProperty = entityType.MetadataProperties.FirstOrDefault(x => x.Name == System.Data.Services.XmlConstants.EdmV1dot2Namespace + ":" + System.Data.Services.XmlConstants.DataWebOpenTypeAttributeName);
if (isOpenTypeProperty != null)
{
bool isOpenType;
if (!Boolean.TryParse(Convert.ToString(isOpenTypeProperty.Value, CultureInfo.InvariantCulture), out isOpenType))
{
throw new InvalidOperationException(Strings.ObjectContext_OpenTypePropertyValueIsNotCorrect(System.Data.Services.XmlConstants.DataWebOpenTypeAttributeName, entityType.Name));
}
return isOpenType;
}
else
{
return false;
}
}
/// <summary>
/// Checks if the given path corresponds to some open property on the <paramref name="baseEntityType"/>
/// </summary>
/// <param name="baseEntityType">Type to check the path for</param>
/// <param name="sourcePath">Input property path</param>
/// <returns>true if there is some open property corresponding to the path, false otherwise</returns>
bool IsOpenPropertyOnPath(StructuralType baseEntityType, String sourcePath)
{
Debug.Assert(baseEntityType != null, "Expecting non-null entity type");
if (String.IsNullOrEmpty(sourcePath))
{
return false;
}
String[] propertyPath = sourcePath.Split('/');
EdmMember entityProperty = baseEntityType.Members.SingleOrDefault(p => p.Name == propertyPath[0]);
if (entityProperty == null)
{
if (baseEntityType.BaseType != null)
{
return IsOpenPropertyOnPath(baseEntityType.BaseType as StructuralType, sourcePath);
}
else
{
return IsOpenType(baseEntityType);
}
}
else
{
StructuralType entityPropertyType = entityProperty.TypeUsage.EdmType as StructuralType;
if (entityPropertyType != null)
{
return IsOpenPropertyOnPath(entityPropertyType, String.Join("/", propertyPath, 1, propertyPath.Length - 1));
}
else
{
return false;
}
}
}
/// <summary>
/// Obtains the entity property corresponding to a given sourcePath
/// </summary>
/// <param name="baseEntityType">Entity type in which to look for property</param>
/// <param name="sourcePath">Source Path</param>
/// <returns>EdmMember object corresponding to the property given through source path</returns>
private static EdmMember GetEntityPropertyFromEpmPath(StructuralType baseEntityType, String sourcePath)
{
Debug.Assert(baseEntityType != null, "Expecting non-null entity type");
String[] propertyPath = sourcePath.Split('/');
if (!baseEntityType.Members.Any(p => p.Name == propertyPath[0]))
{
return baseEntityType.BaseType != null ? GetEntityPropertyFromEpmPath(baseEntityType.BaseType as StructuralType, sourcePath) : null;
}
else
{
EdmMember entityProperty = null;
foreach (var pathSegment in propertyPath)
{
if (baseEntityType == null)
{
return null;
}
entityProperty = baseEntityType.Members.SingleOrDefault(p => p.Name == pathSegment);
if (entityProperty == null)
{
return null;
}
baseEntityType = entityProperty.TypeUsage.EdmType as StructuralType;
}
return entityProperty;
}
}
/// <summary>
/// Returns a sequence of attributes corresponding to a complex type with recursion
/// </summary>
/// <param name="complexProperty">Complex typed property</param>
/// <param name="epmSourcePath">Source path</param>
/// <param name="epmTargetPath">Target path</param>
/// <param name="epmNsPrefix">Namespace prefix</param>
/// <param name="epmNsUri">Namespace Uri</param>
/// <param name="epmKeepContent">KeepInContent setting</param>
/// <returns>Sequence of entity property mapping information for complex type properties</returns>
private static IEnumerable<EntityPropertyMappingAttribute> GetEpmAttrsFromComplexProperty(
EdmMember complexProperty,
String epmSourcePath,
String epmTargetPath,
String epmNsPrefix,
String epmNsUri,
bool epmKeepContent)
{
Debug.Assert(complexProperty != null, "Expecting non-null complex property");
ComplexType complexType = complexProperty.TypeUsage.EdmType as ComplexType;
if (complexType == null)
{
throw new ArgumentException(Strings.ExpectingComplexTypeForMember(complexProperty.Name, complexProperty.DeclaringType.Name));
}
foreach (EdmMember subProperty in complexType.Properties)
{
String sourcePath = epmSourcePath + "/" + subProperty.Name;
String targetPath = epmTargetPath + "/" + subProperty.Name;
if (subProperty.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.ComplexType)
{
foreach (EntityPropertyMappingAttribute epmAttr in GetEpmAttrsFromComplexProperty(subProperty, sourcePath, targetPath, epmNsPrefix, epmNsUri, epmKeepContent))
{
yield return epmAttr;
}
}
else
{
yield return new EntityPropertyMappingAttribute(
sourcePath,
targetPath,
epmNsPrefix,
epmNsUri,
epmKeepContent);
}
}
}
/// <summary>
/// Given a resource type, builds the EntityPropertyMappingInfo for each EntityPropertyMappingAttribute on it
/// </summary>
/// <param name="itemCollection">EFx metadata item collection that has been loaded</param>
/// <param name="entityType">Entity type for which EntityPropertyMappingAttribute discovery is happening</param>
/// <param name="typeDecl">Type declaration to add the attributes to</param>
private void EmitEpmAttributesForEntityType(EdmItemCollection itemCollection, EntityType entityType, CodeTypeDeclaration typeDecl)
{
// Get epm information provided at the entity type declaration level
IEnumerable<MetadataProperty> extendedProperties = entityType.MetadataProperties.Where(mp => mp.PropertyKind == PropertyKind.Extended);
foreach (EpmPropertyInformation propertyInformation in GetEpmPropertyInformation(extendedProperties, entityType.Name, null))
{
EdmMember redefinedProperty = GetEntityPropertyFromEpmPath(entityType, propertyInformation.SourcePath);
if (redefinedProperty == null)
{
if (IsOpenPropertyOnPath(entityType, propertyInformation.SourcePath))
{
EmitEpmAttributeForEntityProperty(
propertyInformation,
new EdmInfo { IsComplex = false, Member = null },
typeDecl);
}
else
{
throw new InvalidOperationException(Strings.ObjectContext_UnknownPropertyNameInEpmAttributesType(propertyInformation.SourcePath, entityType.Name));
}
}
else
{
EmitEpmAttributeForEntityProperty(
propertyInformation,
new EdmInfo { IsComplex = redefinedProperty.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.ComplexType, Member = redefinedProperty },
typeDecl);
}
}
// Get epm information provided at the entity type property level
foreach (EdmMember member in entityType.Members.Where(m => m.DeclaringType == entityType))
{
EdmMember entityProperty = entityType.Properties.SingleOrDefault(p => p.DeclaringType == entityType && p.Name == member.Name);
IEnumerable<MetadataProperty> extendedMemberProperties = member.MetadataProperties.Where(mdp => mdp.PropertyKind == PropertyKind.Extended);
foreach (EpmPropertyInformation propertyInformation in GetEpmPropertyInformation(extendedMemberProperties, entityType.Name, member.Name))
{
EdmMember entityPropertyCurrent = entityProperty;
if (entityProperty.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.ComplexType && propertyInformation.PathGiven)
{
String originalPath = propertyInformation.SourcePath;
propertyInformation.SourcePath = entityProperty.Name + "/" + propertyInformation.SourcePath;
entityPropertyCurrent = GetEntityPropertyFromEpmPath(entityType, propertyInformation.SourcePath);
if (entityPropertyCurrent == null)
{
if (IsOpenPropertyOnPath(entityProperty.TypeUsage.EdmType as StructuralType, originalPath))
{
EmitEpmAttributeForEntityProperty(
propertyInformation,
new EdmInfo { IsComplex = false, Member = null },
typeDecl);
continue;
}
else
{
throw new InvalidOperationException(Strings.ObjectContext_UnknownPropertyNameInEpmAttributesMember(originalPath, member.Name, entityType.Name));
}
}
}
EmitEpmAttributeForEntityProperty(
propertyInformation,
new EdmInfo { IsComplex = entityPropertyCurrent.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.ComplexType, Member = entityPropertyCurrent },
typeDecl);
}
}
}
/// <summary>
/// Given a resource type and its resource proeperty builds the EntityPropertyMappingInfo for the EntityPropertyMappingAttribute on it
/// </summary>
/// <param name="propertyInformation">EPM information for current property</param>
/// <param name="entityProperty">Property for which to get the information</param>
/// <param name="typeDecl">Type declaration to add the attributes to</param>
private void EmitEpmAttributeForEntityProperty(
EpmPropertyInformation propertyInformation,
EdmInfo entityProperty,
CodeTypeDeclaration typeDecl)
{
if (propertyInformation.IsAtom)
{
if (entityProperty.IsComplex)
{
throw new InvalidOperationException(Strings.ObjectContext_SyndicationMappingForComplexPropertiesNotAllowed);
}
else
{
EntityPropertyMappingAttribute epmAttr = new EntityPropertyMappingAttribute(
propertyInformation.SourcePath,
propertyInformation.SyndicationItem,
propertyInformation.ContentKind,
propertyInformation.KeepInContent);
this.AddEpmAttributeToTypeDeclaration(epmAttr, typeDecl);
}
}
else
{
if (entityProperty.IsComplex)
{
foreach (EntityPropertyMappingAttribute epmAttr in GetEpmAttrsFromComplexProperty(
entityProperty.Member,
propertyInformation.SourcePath,
propertyInformation.TargetPath,
propertyInformation.NsPrefix,
propertyInformation.NsUri,
propertyInformation.KeepInContent))
{
this.AddEpmAttributeToTypeDeclaration(epmAttr, typeDecl);
}
}
else
{
EntityPropertyMappingAttribute epmAttr = new EntityPropertyMappingAttribute(
propertyInformation.SourcePath,
propertyInformation.TargetPath,
propertyInformation.NsPrefix,
propertyInformation.NsUri,
propertyInformation.KeepInContent);
this.AddEpmAttributeToTypeDeclaration(epmAttr, typeDecl);
}
}
}
/// <summary>Creates an EntityPropertyMappingAttribute and adds it to the <paramref name="typeDecl"/></summary>
/// <param name="epmAttr">Attribute to add</param>
/// <param name="typeDecl">Type declaration for which the attribute is generated</param>
private void AddEpmAttributeToTypeDeclaration(EntityPropertyMappingAttribute epmAttr, CodeTypeDeclaration typeDecl)
{
if (epmAttr.TargetSyndicationItem != SyndicationItemProperty.CustomProperty)
{
var syndicationItem = new CodeFieldReferenceExpression(
new CodeTypeReferenceExpression(typeof(SyndicationItemProperty)),
epmAttr.TargetSyndicationItem.ToString());
var contentKind = new CodeFieldReferenceExpression(
new CodeTypeReferenceExpression(typeof(SyndicationTextContentKind)),
epmAttr.TargetTextContentKind.ToString());
CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(
TypeReference.FromString(
Utils.WebFrameworkCommonNamespace + "." + "EntityPropertyMappingAttribute",
true));
AddAttributeArguments(attribute, new object[] { epmAttr.SourcePath, syndicationItem, contentKind, epmAttr.KeepInContent });
typeDecl.CustomAttributes.Add(attribute);
}
else
{
CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(
TypeReference.FromString(
Utils.WebFrameworkCommonNamespace + "." + "EntityPropertyMappingAttribute",
true));
AddAttributeArguments(attribute, new object[] { epmAttr.SourcePath, epmAttr.TargetPath, epmAttr.TargetNamespacePrefix, epmAttr.TargetNamespaceUri, epmAttr.KeepInContent });
typeDecl.CustomAttributes.Add(attribute);
}
}
/// <summary>
/// Given a resource type, generates the HasStreamAttribute for it
/// </summary>
/// <param name="entityType">Entity type for which HasStreamAttribute discovery is happening</param>
/// <param name="typeDecl">Type declaration to add the attributes to</param>
private void EmitStreamAttributesForEntityType(EntityType entityType, CodeTypeDeclaration typeDecl)
{
IEnumerable<MetadataProperty> hasStreamMetadataProperties =
entityType.MetadataProperties.Where(mp => mp.PropertyKind == PropertyKind.Extended &&
mp.Name == System.Data.Services.XmlConstants.DataWebMetadataNamespace + ":" + System.Data.Services.XmlConstants.DataWebAccessHasStreamAttribute);
MetadataProperty hasStreamMetadataProperty = null;
foreach (MetadataProperty p in hasStreamMetadataProperties)
{
if (hasStreamMetadataProperty != null)
{
throw new InvalidOperationException(
Strings.ObjectContext_MultipleValuesForSameExtendedAttributeType(
System.Data.Services.XmlConstants.DataWebAccessHasStreamAttribute,
entityType.Name));
}
hasStreamMetadataProperty = p;
}
if (hasStreamMetadataProperty == null)
{
return;
}
if (!String.Equals(Convert.ToString(hasStreamMetadataProperty.Value, CultureInfo.InvariantCulture),
System.Data.Services.XmlConstants.DataWebAccessDefaultStreamPropertyValue, StringComparison.Ordinal))
{
return;
}
CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(
TypeReference.FromString(
Utils.WebFrameworkCommonNamespace + "." + "HasStreamAttribute",
true));
typeDecl.CustomAttributes.Add(attribute);
}
/// <summary>Edm Member information used for generating attribute, necessary for supporting
/// open types which can potentioall not have any member so EdmMember property can be null
/// </summary>
private sealed class EdmInfo
{
/// <summary>Is the given type a complex type</summary>
public bool IsComplex
{
get;
set;
}
/// <summary>Corresponding EdmMember</summary>
public EdmMember Member
{
get;
set;
}
}
}
}
| |
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 Organizer.WebAPI.Areas.HelpPage.ModelDescriptions;
using Organizer.WebAPI.Areas.HelpPage.Models;
namespace Organizer.WebAPI.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);
}
}
}
}
| |
using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using System.Reflection;
using System.Web.Configuration;
using System.Configuration;
using System.EnterpriseServices;
using Hydra.Framework;
using Hydra.SharedCache.Common;
namespace Hydra.SharedCache.Version
{
//
// **********************************************************************
/// <summary>
/// Version WebService
/// </summary>
// **********************************************************************
//
[WebService(Namespace = "http://www.lbsview.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class Version
: System.Web.Services.WebService
{
//
// **********************************************************************
/// <summary>
/// Helloes the world.
/// </summary>
/// <returns></returns>
// **********************************************************************
//
[WebMethod]
[Hydra.SharedCache.Common.Attributes.SharedCacheSoapExtension(CacheInSecond = 60000)]
public string HelloWorld()
{
return DateTime.Now.ToString("dd.MM.yyyy - hh:mm:ss");
}
//
// **********************************************************************
/// <summary>
/// Gets the version of the public available release.
/// </summary>
/// <returns></returns>
// **********************************************************************
//
[WebMethod]
[Hydra.SharedCache.Common.Attributes.SharedCacheSoapExtension(CacheInSecond = 60000)]
public string GetVersion()
{
Log.Debug("****************************************************** " + DateTime.Now.ToString() + " ********************************************************");
Log.Debug("Assembly Info:");
AssemblyInfo ai = new AssemblyInfo();
Log.Debug("AsmFQName: " + ai.AsmFQName);
Log.Debug("AsmName: " + ai.AsmName);
Log.Debug("CodeBase: " + ai.CodeBase);
Log.Debug("Company: " + ai.Company);
Log.Debug("Copyright: " + ai.Copyright);
Log.Debug("Description: " + ai.Description);
Log.Debug("Product: " + ai.Product);
Log.Debug("Title: " + ai.Title);
Log.Debug("Version: " + ai.Version);
Log.Debug("Client Info:");
Log.Debug("*************************************************");
if (this.Context != null)
{
if (this.Context.Request != null)
{
if (this.Context.Request.UserLanguages != null)
{
foreach (string s in this.Context.Request.UserLanguages)
{
Log.Debug(s);
}
}
if (this.Context.Request.UserHostName != null)
Log.Debug(this.Context.Request.UserHostName);
if (this.Context.Request.UserHostAddress != null)
Log.Debug(this.Context.Request.UserHostAddress);
if (this.Context.Request.UserAgent != null)
Log.Debug(this.Context.Request.UserAgent);
if (this.Context.Request.UrlReferrer != null)
Log.Debug(this.Context.Request.UrlReferrer.ToString());
if (this.Context.Request.ServerVariables != null)
{
Log.Debug("ServerVariables:");
Log.Debug("*************************************************");
foreach (string s in this.Context.Request.ServerVariables.AllKeys)
{
Log.Debug(string.Format(" {0,-10} {1}", s, this.Context.Request.ServerVariables[s]));
}
}
if (this.Context.Request.Headers != null)
{
Log.Debug("Headers:");
Log.Debug("*************************************************");
foreach (string s in this.Context.Request.Headers.AllKeys)
{
Log.Debug(string.Format(" {0,-10} {1}", s, this.Context.Request.Headers[s]));
}
}
}
}
return Config.GetStringValueFromConfigByKey("SharedCacheVersionNumber") + " - " + DateTime.Now.ToString("hh:mm:ss");
}
}
//
// **********************************************************************
/// <summary>
/// Summary description for ConfigHandler.
/// </summary>
// **********************************************************************
//
public class Config
{
//
// **********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="Config"/> class.
/// </summary>
// **********************************************************************
//
public Config()
{ }
//
// **********************************************************************
/// <summary>
/// Get the value based on the key from the app.config
/// </summary>
/// <param name="key"><see cref="string"/> Key-Name</param>
/// <returns>string value of a applied key</returns>
// **********************************************************************
//
[System.Diagnostics.DebuggerStepThrough]
public static string GetStringValueFromConfigByKey(string key)
{
try
{
if (ConfigurationManager.AppSettings[key] != null)
return ConfigurationManager.AppSettings[key];
}
catch (FormatException e)
{
System.Diagnostics.Debug.WriteLine(((object)MethodBase.GetCurrentMethod()).ToString() + Environment.NewLine + e.ToString());
}
catch (ArgumentException e)
{
System.Diagnostics.Debug.WriteLine(((object)MethodBase.GetCurrentMethod()).ToString() + Environment.NewLine + e.ToString());
}
catch (Exception e)
{
//
// Todo: RSC: add Logging
//
System.Diagnostics.Debug.WriteLine(e);
}
return string.Empty;
}
//
// **********************************************************************
/// <summary>
/// Get the value based on the key from the app.config
/// </summary>
/// <param name="key"><see cref="string"/> Key-Name</param>
/// <returns>int value of a applied key</returns>
// **********************************************************************
//
[System.Diagnostics.DebuggerStepThrough]
public static int GetIntValueFromConfigByKey(string key)
{
try
{
if (ConfigurationManager.AppSettings[key] != null)
return int.Parse(ConfigurationManager.AppSettings[key]);
}
catch (FormatException e)
{
System.Diagnostics.Debug.WriteLine(((object)MethodBase.GetCurrentMethod()).ToString() + Environment.NewLine + e.ToString());
}
catch (ArgumentException e)
{
System.Diagnostics.Debug.WriteLine(((object)MethodBase.GetCurrentMethod()).ToString() + Environment.NewLine + e.ToString());
}
catch (Exception e)
{
//
// Todo: RSC: add Logging
//
System.Diagnostics.Debug.WriteLine(e);
}
return -1;
}
//
// **********************************************************************
/// <summary>
/// Get the value based on the key from the app.config
/// </summary>
/// <param name="key"><see cref="string"/> Key-Name</param>
/// <returns>int value of a applied key</returns>
// **********************************************************************
//
[System.Diagnostics.DebuggerStepThrough]
public static double GetDoubleValueFromConfigByKey(string key)
{
try
{
if (ConfigurationManager.AppSettings[key] != null)
return double.Parse(ConfigurationManager.AppSettings[key]);
}
catch (FormatException e)
{
System.Diagnostics.Debug.WriteLine(((object)MethodBase.GetCurrentMethod()).ToString() + Environment.NewLine + e.ToString());
}
catch (ArgumentException e)
{
System.Diagnostics.Debug.WriteLine(((object)MethodBase.GetCurrentMethod()).ToString() + Environment.NewLine + e.ToString());
}
catch (Exception e)
{
//
// Todo: RSC: add Logging
//
System.Diagnostics.Debug.WriteLine(e);
}
return -1;
}
//
// **********************************************************************
/// <summary>
/// Gets the num of defined app settings.
/// </summary>
/// <returns>A <see cref="T:System.Int32"/> Object.</returns>
// **********************************************************************
//
[System.Diagnostics.DebuggerStepThrough]
public static int GetNumOfDefinedAppSettings()
{
return ConfigurationManager.AppSettings.Count;
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
using System.Runtime.Serialization;
using ErrorEventArgs=Newtonsoft.Json.Serialization.ErrorEventArgs;
namespace Newtonsoft.Json
{
/// <summary>
/// Serializes and deserializes objects into and from the JSON format.
/// The <see cref="JsonSerializer"/> enables you to control how objects are encoded into JSON.
/// </summary>
public class JsonSerializer
{
#region Properties
private TypeNameHandling _typeNameHandling;
private FormatterAssemblyStyle _typeNameAssemblyFormat;
private PreserveReferencesHandling _preserveReferencesHandling;
private ReferenceLoopHandling _referenceLoopHandling;
private MissingMemberHandling _missingMemberHandling;
private ObjectCreationHandling _objectCreationHandling;
private NullValueHandling _nullValueHandling;
private DefaultValueHandling _defaultValueHandling;
private ConstructorHandling _constructorHandling;
private JsonConverterCollection _converters;
private IContractResolver _contractResolver;
private IReferenceResolver _referenceResolver;
private SerializationBinder _binder;
private StreamingContext _context;
/// <summary>
/// Occurs when the <see cref="JsonSerializer"/> errors during serialization and deserialization.
/// </summary>
public virtual event EventHandler<ErrorEventArgs> Error;
/// <summary>
/// Gets or sets the <see cref="IReferenceResolver"/> used by the serializer when resolving references.
/// </summary>
public virtual IReferenceResolver ReferenceResolver
{
get
{
if (_referenceResolver == null)
_referenceResolver = new DefaultReferenceResolver();
return _referenceResolver;
}
set
{
if (value == null)
throw new ArgumentNullException("value", "Reference resolver cannot be null.");
_referenceResolver = value;
}
}
/// <summary>
/// Gets or sets the <see cref="SerializationBinder"/> used by the serializer when resolving type names.
/// </summary>
public virtual SerializationBinder Binder
{
get
{
return _binder;
}
set
{
if (value == null)
throw new ArgumentNullException("value", "Serialization binder cannot be null.");
_binder = value;
}
}
/// <summary>
/// Gets or sets how type name writing and reading is handled by the serializer.
/// </summary>
public virtual TypeNameHandling TypeNameHandling
{
get { return _typeNameHandling; }
set
{
if (value < TypeNameHandling.None || value > TypeNameHandling.Auto)
throw new ArgumentOutOfRangeException("value");
_typeNameHandling = value;
}
}
/// <summary>
/// Gets or sets how a type name assembly is written and resolved by the serializer.
/// </summary>
/// <value>The type name assembly format.</value>
public virtual FormatterAssemblyStyle TypeNameAssemblyFormat
{
get { return _typeNameAssemblyFormat; }
set
{
if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full)
throw new ArgumentOutOfRangeException("value");
_typeNameAssemblyFormat = value;
}
}
/// <summary>
/// Gets or sets how object references are preserved by the serializer.
/// </summary>
public virtual PreserveReferencesHandling PreserveReferencesHandling
{
get { return _preserveReferencesHandling; }
set
{
if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All)
throw new ArgumentOutOfRangeException("value");
_preserveReferencesHandling = value;
}
}
/// <summary>
/// Get or set how reference loops (e.g. a class referencing itself) is handled.
/// </summary>
public virtual ReferenceLoopHandling ReferenceLoopHandling
{
get { return _referenceLoopHandling; }
set
{
if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize)
throw new ArgumentOutOfRangeException("value");
_referenceLoopHandling = value;
}
}
/// <summary>
/// Get or set how missing members (e.g. JSON contains a property that isn't a member on the object) are handled during deserialization.
/// </summary>
public virtual MissingMemberHandling MissingMemberHandling
{
get { return _missingMemberHandling; }
set
{
if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error)
throw new ArgumentOutOfRangeException("value");
_missingMemberHandling = value;
}
}
/// <summary>
/// Get or set how null values are handled during serialization and deserialization.
/// </summary>
public virtual NullValueHandling NullValueHandling
{
get { return _nullValueHandling; }
set
{
if (value < NullValueHandling.Include || value > NullValueHandling.Ignore)
throw new ArgumentOutOfRangeException("value");
_nullValueHandling = value;
}
}
/// <summary>
/// Get or set how null default are handled during serialization and deserialization.
/// </summary>
public virtual DefaultValueHandling DefaultValueHandling
{
get { return _defaultValueHandling; }
set
{
if (value < DefaultValueHandling.Include || value > DefaultValueHandling.Ignore)
throw new ArgumentOutOfRangeException("value");
_defaultValueHandling = value;
}
}
/// <summary>
/// Gets or sets how objects are created during deserialization.
/// </summary>
/// <value>The object creation handling.</value>
public virtual ObjectCreationHandling ObjectCreationHandling
{
get { return _objectCreationHandling; }
set
{
if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace)
throw new ArgumentOutOfRangeException("value");
_objectCreationHandling = value;
}
}
/// <summary>
/// Gets or sets how constructors are used during deserialization.
/// </summary>
/// <value>The constructor handling.</value>
public virtual ConstructorHandling ConstructorHandling
{
get { return _constructorHandling; }
set
{
if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor)
throw new ArgumentOutOfRangeException("value");
_constructorHandling = value;
}
}
/// <summary>
/// Gets a collection <see cref="JsonConverter"/> that will be used during serialization.
/// </summary>
/// <value>Collection <see cref="JsonConverter"/> that will be used during serialization.</value>
public virtual JsonConverterCollection Converters
{
get
{
if (_converters == null)
_converters = new JsonConverterCollection();
return _converters;
}
}
/// <summary>
/// Gets or sets the contract resolver used by the serializer when
/// serializing .NET objects to JSON and vice versa.
/// </summary>
public virtual IContractResolver ContractResolver
{
get
{
if (_contractResolver == null)
_contractResolver = DefaultContractResolver.Instance;
return _contractResolver;
}
set { _contractResolver = value; }
}
/// <summary>
/// Gets or sets the <see cref="StreamingContext"/> used by the serializer when invoking serialization callback methods.
/// </summary>
/// <value>The context.</value>
public virtual StreamingContext Context
{
get { return _context; }
set { _context = value; }
}
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializer"/> class.
/// </summary>
public JsonSerializer()
{
_referenceLoopHandling = JsonSerializerSettings.DefaultReferenceLoopHandling;
_missingMemberHandling = JsonSerializerSettings.DefaultMissingMemberHandling;
_nullValueHandling = JsonSerializerSettings.DefaultNullValueHandling;
_defaultValueHandling = JsonSerializerSettings.DefaultDefaultValueHandling;
_objectCreationHandling = JsonSerializerSettings.DefaultObjectCreationHandling;
_preserveReferencesHandling = JsonSerializerSettings.DefaultPreserveReferencesHandling;
_constructorHandling = JsonSerializerSettings.DefaultConstructorHandling;
_typeNameHandling = JsonSerializerSettings.DefaultTypeNameHandling;
_context = JsonSerializerSettings.DefaultContext;
_binder = DefaultSerializationBinder.Instance;
}
/// <summary>
/// Creates a new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>.
/// </summary>
/// <param name="settings">The settings to be applied to the <see cref="JsonSerializer"/>.</param>
/// <returns>A new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>.</returns>
public static JsonSerializer Create(JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = new JsonSerializer();
if (settings != null)
{
if (!CollectionUtils.IsNullOrEmpty(settings.Converters))
jsonSerializer.Converters.AddRange(settings.Converters);
jsonSerializer.TypeNameHandling = settings.TypeNameHandling;
jsonSerializer.TypeNameAssemblyFormat = settings.TypeNameAssemblyFormat;
jsonSerializer.PreserveReferencesHandling = settings.PreserveReferencesHandling;
jsonSerializer.ReferenceLoopHandling = settings.ReferenceLoopHandling;
jsonSerializer.MissingMemberHandling = settings.MissingMemberHandling;
jsonSerializer.ObjectCreationHandling = settings.ObjectCreationHandling;
jsonSerializer.NullValueHandling = settings.NullValueHandling;
jsonSerializer.DefaultValueHandling = settings.DefaultValueHandling;
jsonSerializer.ConstructorHandling = settings.ConstructorHandling;
jsonSerializer.Context = settings.Context;
if (settings.Error != null)
jsonSerializer.Error += settings.Error;
if (settings.ContractResolver != null)
jsonSerializer.ContractResolver = settings.ContractResolver;
if (settings.ReferenceResolver != null)
jsonSerializer.ReferenceResolver = settings.ReferenceResolver;
if (settings.Binder != null)
jsonSerializer.Binder = settings.Binder;
}
return jsonSerializer;
}
/// <summary>
/// Populates the JSON values onto the target object.
/// </summary>
/// <param name="reader">The <see cref="TextReader"/> that contains the JSON structure to reader values from.</param>
/// <param name="target">The target object to populate values onto.</param>
public void Populate(TextReader reader, object target)
{
Populate(new JsonTextReader(reader), target);
}
/// <summary>
/// Populates the JSON values onto the target object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to reader values from.</param>
/// <param name="target">The target object to populate values onto.</param>
public void Populate(JsonReader reader, object target)
{
PopulateInternal(reader, target);
}
internal virtual void PopulateInternal(JsonReader reader, object target)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
ValidationUtils.ArgumentNotNull(target, "target");
JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this);
serializerReader.Populate(reader, target);
}
/// <summary>
/// Deserializes the Json structure contained by the specified <see cref="JsonReader"/>.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to deserialize.</param>
/// <returns>The <see cref="Object"/> being deserialized.</returns>
public object Deserialize(JsonReader reader)
{
return Deserialize(reader, null);
}
/// <summary>
/// Deserializes the Json structure contained by the specified <see cref="StringReader"/>
/// into an instance of the specified type.
/// </summary>
/// <param name="reader">The <see cref="TextReader"/> containing the object.</param>
/// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns>
public object Deserialize(TextReader reader, Type objectType)
{
return Deserialize(new JsonTextReader(reader), objectType);
}
/// <summary>
/// Deserializes the Json structure contained by the specified <see cref="JsonReader"/>
/// into an instance of the specified type.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> containing the object.</param>
/// <typeparam name="T">The type of the object to deserialize.</typeparam>
/// <returns>The instance of <typeparamref name="T"/> being deserialized.</returns>
public T Deserialize<T>(JsonReader reader)
{
return (T)Deserialize(reader, typeof(T));
}
/// <summary>
/// Deserializes the Json structure contained by the specified <see cref="JsonReader"/>
/// into an instance of the specified type.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> containing the object.</param>
/// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns>
public object Deserialize(JsonReader reader, Type objectType)
{
return DeserializeInternal(reader, objectType);
}
internal virtual object DeserializeInternal(JsonReader reader, Type objectType)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this);
return serializerReader.Deserialize(reader, objectType);
}
/// <summary>
/// Serializes the specified <see cref="Object"/> and writes the Json structure
/// to a <c>Stream</c> using the specified <see cref="TextWriter"/>.
/// </summary>
/// <param name="textWriter">The <see cref="TextWriter"/> used to write the Json structure.</param>
/// <param name="value">The <see cref="Object"/> to serialize.</param>
public void Serialize(TextWriter textWriter, object value)
{
Serialize(new JsonTextWriter(textWriter), value);
}
/// <summary>
/// Serializes the specified <see cref="Object"/> and writes the Json structure
/// to a <c>Stream</c> using the specified <see cref="JsonWriter"/>.
/// </summary>
/// <param name="jsonWriter">The <see cref="JsonWriter"/> used to write the Json structure.</param>
/// <param name="value">The <see cref="Object"/> to serialize.</param>
public void Serialize(JsonWriter jsonWriter, object value)
{
SerializeInternal(jsonWriter, value);
}
internal virtual void SerializeInternal(JsonWriter jsonWriter, object value)
{
ValidationUtils.ArgumentNotNull(jsonWriter, "jsonWriter");
JsonSerializerInternalWriter serializerWriter = new JsonSerializerInternalWriter(this);
serializerWriter.Serialize(jsonWriter, value);
}
internal JsonConverter GetMatchingConverter(Type type)
{
return GetMatchingConverter(_converters, type);
}
internal static JsonConverter GetMatchingConverter(IList<JsonConverter> converters, Type objectType)
{
ValidationUtils.ArgumentNotNull(objectType, "objectType");
if (converters != null)
{
for (int i = 0; i < converters.Count; i++)
{
JsonConverter converter = converters[i];
if (converter.CanConvert(objectType))
return converter;
}
}
return null;
}
internal void OnError(ErrorEventArgs e)
{
EventHandler<ErrorEventArgs> error = Error;
if (error != null)
error(this, e);
}
}
}
| |
using System.Linq;
using System.Xml.Linq;
namespace WixSharp.Bootstrapper
{
/// <summary>
/// Container class for common members of the Bootstrapper packages
/// </summary>
public abstract class Package : ChainItem
{
/// <summary>
/// Specifies whether the package can be uninstalled.
/// </summary>
[Xml]
public bool? Permanent;
/// <summary>
/// Location of the package to add to the bundle. The default value is the Name attribute, if provided. At a minimum, the SourceFile or Name attribute must be specified.
/// </summary>
[Xml]
public string SourceFile;
/// <summary>
/// Specifies the description to place in the bootstrapper application data manifest for the package. By default,
/// ExePackages use the FileName field from the version information, MsiPackages use the ARPCOMMENTS property, and MspPackages
/// use the Description patch metadata property. Other package types must use this attribute to define a description in the
/// bootstrapper application data manifest.
/// </summary>
[Xml]
public string Description;
/// <summary>
/// Indicates the package must be executed elevated.
/// </summary>
[Xml]
public bool? PerMachine;
/// <summary>
/// The URL to use to download the package. The following substitutions are supported:
/// <para>{0} is replaced by the package Id.</para>
/// <para>{1} is replaced by the payload Id.</para>
/// <para>{2} is replaced by the payload file name.</para>
/// </summary>
[Xml]
public string DownloadUrl;
/// <summary>
/// A condition to evaluate before installing the package. The package will only be installed if the condition evaluates to true.
/// If the condition evaluates to false and the bundle is being installed, repaired, or modified, the package will be uninstalled.
/// </summary>
[Xml]
public string InstallCondition;
/// <summary>
/// Collection of paths to the package dependencies.
/// </summary>
public string[] Payloads = new string[0];
internal void EnsureId()
{
if (!base.IsIdSet())
{
Name = System.IO.Path.GetFileName(SourceFile);
}
}
}
/// <summary>
/// Container class for common members of the Bootstrapper chained items
/// </summary>
public abstract class ChainItem : WixEntity
{
/// <summary>
/// Specifies whether the package/item must succeed for the chain to continue.
/// The default "yes" (true) indicates that if the package fails then the chain will fail and rollback or stop.
/// If "no" is specified then the chain will continue even if the package reports failure.
/// </summary>
[Xml]
public bool? Vital;
/// <summary>
/// Emits WiX XML.
/// </summary>
/// <returns></returns>
abstract public XContainer[] ToXml();
}
/// <summary>
/// Standard WiX ExePackage.
/// </summary>
public class ExePackage : Package
{
/// <summary>
/// Initializes a new instance of the <see cref="ExePackage"/> class.
/// </summary>
public ExePackage()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ExePackage"/> class.
/// </summary>
/// <param name="path">The path.</param>
public ExePackage(string path)
{
//Name = System.IO.Path.GetFileName(path).Expand();
SourceFile = path;
}
/// <summary>
/// The command-line arguments provided to the ExePackage during install. If this attribute
/// is absent the executable will be launched with no command-line arguments
/// </summary>
[Xml]
public string InstallCommand;
/// <summary>
/// The command-line arguments to specify to indicate a repair. If the executable package can be repaired but does not require any
/// special command-line arguments to do so then set the attribute's value to blank. To indicate that the package does not support repair,
/// omit this attribute.
/// </summary>
[Xml]
public string RepairCommand;
/// <summary>
/// The command-line arguments provided to the ExePackage during uninstall. If this attribute is absent the executable will be launched
/// with no command-line arguments. To prevent an ExePackage from being uninstalled set the Permanent attribute to "yes".
/// </summary>
[Xml]
public string UninstallCommand;
/// <summary>
/// A condition that determines if the package is present on the target system.
/// This condition can use built-in variables and variables returned by searches.
/// This condition is necessary because Windows doesn't provide a method to detect the presence of an ExePackage.
/// Burn uses this condition to determine how to treat this package during a bundle action; for example, if this condition
/// is false or omitted and the bundle is being installed, Burn will install this package.
/// </summary>
[Xml]
public string DetectCondition;
/// <summary>
/// Emits WiX XML.
/// </summary>
/// <returns></returns>
public override XContainer[] ToXml()
{
var root = new XElement("ExePackage");
root.SetAttribute("Name", Name); //will respect null
if (this.IsIdSet())
root.SetAttribute("Id", Id);
root.AddAttributes(this.Attributes)
.Add(this.MapToXmlAttributes());
if (Payloads.Any())
Payloads.ForEach(p => root.Add(new XElement("Payload", new XAttribute("SourceFile", p))));
return new[] { root };
}
}
/// <summary>
/// Standard WiX MsiPackage.
/// </summary>
public class MsiPackage : Package
{
/// <summary>
/// Specifies whether the bundle will allow individual control over the installation state of Features inside the msi package. Managing
/// feature selection requires special care to ensure the install, modify, update and uninstall behavior of the package is always correct.
/// The default is "no".
/// </summary>
public bool? EnableFeatureSelection;
/// <summary>
/// Initializes a new instance of the <see cref="MsiPackage"/> class.
/// </summary>
public MsiPackage()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MsiPackage"/> class.
/// </summary>
/// <param name="path">The path.</param>
public MsiPackage(string path)
{
SourceFile = path;
}
/// <summary>
/// Specifies whether the bundle will show the UI authored into the msi package. The default is "no" which means all information is routed to
/// the bootstrapper application to provide a unified installation experience. If "yes" is specified the UI authored into the msi package will be
/// displayed on top of any bootstrapper application UI.
/// </summary>
[Xml]
public bool? DisplayInternalUI;
/// <summary>
/// MSI properties to be set based on the value of a burn engine expression. This is a KeyValue mapping expression of the following format:
/// <para><key>=<value>[;<key>=<value>]</para>
/// <para><c>Example:</c> "COMMANDARGS=[CommandArgs];GLOBAL=yes""</para>
/// </summary>
public string MsiProperties;
/// <summary>
/// Emits WiX XML.
/// </summary>
/// <returns></returns>
public override XContainer[] ToXml()
{
var root = new XElement("MsiPackage");
root.SetAttribute("Name", Name); //will respect null
if (this.IsIdSet())
root.SetAttribute("Id", Id);
root.AddAttributes(this.Attributes)
.Add(this.MapToXmlAttributes());
if (Payloads.Any())
Payloads.ForEach(p => root.Add(new XElement("Payload", new XAttribute("SourceFile", p))));
if (MsiProperties.IsNotEmpty())
MsiProperties.ToDictionary().ForEach(p =>
{
root.Add(new XElement("MsiProperty").AddAttributes("Name={0};Value={1}".FormatInline(p.Key, p.Value)));
});
return new[] { root };
}
}
//class MspPackage : ChainItem { }
//class MsuPackage : ChainItem { }
/// <summary>
/// Standard WiX PackageGroupRef.
/// </summary>
public class PackageGroupRef : ChainItem
{
/// <summary>
/// Initializes a new instance of the <see cref="PackageGroupRef"/> class.
/// </summary>
/// <param name="name">The name.</param>
public PackageGroupRef(string name)
{
this.Id = new Id(name);
}
/// <summary>
/// Emits WiX XML.
/// </summary>
/// <returns></returns>
public override XContainer[] ToXml()
{
var root = new XElement("PackageGroupRef");
if (this.IsIdSet())
root.SetAttribute("Id", Id);
root.AddAttributes(this.Attributes)
.Add(this.MapToXmlAttributes());
return new[] { root };
}
}
/// <summary>
/// Standard WiX RollbackBoundary.
/// </summary>
public class RollbackBoundary : ChainItem
{
/// <summary>
/// Emits WiX XML.
/// </summary>
/// <returns></returns>
public override XContainer[] ToXml()
{
return new[] { new XElement("RollbackBoundary") };
}
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\WorldSettings.h:395
namespace UnrealEngine
{
[ManageType("ManageWorldSettings")]
public partial class ManageWorldSettings : AWorldSettings, IManageWrapper
{
public ManageWorldSettings(IntPtr adress)
: base(adress)
{
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_NotifyBeginPlay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_NotifyMatchStarted(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_OnRep_WorldGravityZ(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_BeginPlay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_ClearCrossLevelReferences(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_Destroyed(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_ForceNetRelevant(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_ForceNetUpdate(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_GatherCurrentMovement(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_InvalidateLightingCacheDetailed(IntPtr self, bool bTranslationOnly);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_K2_DestroyActor(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_LifeSpanExpired(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_MarkComponentsAsPendingKill(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_NotifyActorBeginCursorOver(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_NotifyActorEndCursorOver(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_OnRep_AttachmentReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_OnRep_Instigator(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_OnRep_Owner(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_OnRep_ReplicatedMovement(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_OnRep_ReplicateMovement(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_OnReplicationPausedChanged(IntPtr self, bool bIsReplicationPaused);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_OutsideWorldBounds(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_PostActorCreated(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_PostInitializeComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_PostNetInit(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_PostNetReceiveLocationAndRotation(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_PostNetReceivePhysicState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_PostNetReceiveRole(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_PostRegisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_PostUnregisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_PreInitializeComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_PreRegisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_PrestreamTextures(IntPtr self, float seconds, bool bEnableStreaming, int cinematicTextureGroups);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_RegisterActorTickFunctions(IntPtr self, bool bRegister);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_RegisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_ReregisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_RerunConstructionScripts(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_Reset(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_RewindForReplay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_SetActorHiddenInGame(IntPtr self, bool bNewHidden);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_SetLifeSpan(IntPtr self, float inLifespan);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_SetReplicateMovement(IntPtr self, bool bInReplicateMovement);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_TearOff(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_TeleportSucceeded(IntPtr self, bool bIsATest);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_Tick(IntPtr self, float deltaSeconds);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_TornOff(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_UnregisterAllComponents(IntPtr self, bool bForReregister);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_BeginDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_FinishDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_MarkAsEditorOnlySubobject(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_PostCDOContruct(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_PostEditImport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_PostInitProperties(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_PostLoad(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_PostNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_PostRepNotifies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_PostSaveRoot(IntPtr self, bool bCleanupIsRequired);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_PreDestroyFromReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_PreNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_ShutdownAfterError(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_CreateCluster(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AWorldSettings_OnClusterMarkedAsPendingKill(IntPtr self);
#endregion
#region Methods
/// <summary>
/// Called from GameStateBase, calls BeginPlay on all actors
/// </summary>
public override void NotifyBeginPlay()
=> E__Supper__AWorldSettings_NotifyBeginPlay(this);
/// <summary>
/// Called from GameStateBase, used to notify native classes of match startup (such as level scripting)
/// </summary>
public override void NotifyMatchStarted()
=> E__Supper__AWorldSettings_NotifyMatchStarted(this);
public override void OnRep_WorldGravityZ()
=> E__Supper__AWorldSettings_OnRep_WorldGravityZ(this);
/// <summary>
/// Overridable native event for when play begins for this actor.
/// </summary>
protected override void BeginPlay()
=> E__Supper__AWorldSettings_BeginPlay(this);
/// <summary>
/// Do anything needed to clear out cross level references; Called from ULevel::PreSave
/// </summary>
public override void ClearCrossLevelReferences()
=> E__Supper__AWorldSettings_ClearCrossLevelReferences(this);
/// <summary>
/// Called when this actor is explicitly being destroyed during gameplay or in the editor, not called during level streaming or gameplay ending
/// </summary>
public override void Destroyed()
=> E__Supper__AWorldSettings_Destroyed(this);
/// <summary>
/// Forces this actor to be net relevant if it is not already by default
/// </summary>
public override void ForceNetRelevant()
=> E__Supper__AWorldSettings_ForceNetRelevant(this);
/// <summary>
/// Force actor to be updated to clients/demo net drivers
/// </summary>
public override void ForceNetUpdate()
=> E__Supper__AWorldSettings_ForceNetUpdate(this);
/// <summary>
/// Fills ReplicatedMovement property
/// </summary>
public override void GatherCurrentMovement()
=> E__Supper__AWorldSettings_GatherCurrentMovement(this);
/// <summary>
/// Invalidates anything produced by the last lighting build.
/// </summary>
public override void InvalidateLightingCacheDetailed(bool bTranslationOnly)
=> E__Supper__AWorldSettings_InvalidateLightingCacheDetailed(this, bTranslationOnly);
/// <summary>
/// Destroy the actor
/// </summary>
public override void DestroyActor()
=> E__Supper__AWorldSettings_K2_DestroyActor(this);
/// <summary>
/// Called when the lifespan of an actor expires (if he has one).
/// </summary>
public override void LifeSpanExpired()
=> E__Supper__AWorldSettings_LifeSpanExpired(this);
/// <summary>
/// Called to mark all components as pending kill when the actor is being destroyed
/// </summary>
public override void MarkComponentsAsPendingKill()
=> E__Supper__AWorldSettings_MarkComponentsAsPendingKill(this);
/// <summary>
/// Event when this actor has the mouse moved over it with the clickable interface.
/// </summary>
public override void NotifyActorBeginCursorOver()
=> E__Supper__AWorldSettings_NotifyActorBeginCursorOver(this);
/// <summary>
/// Event when this actor has the mouse moved off of it with the clickable interface.
/// </summary>
public override void NotifyActorEndCursorOver()
=> E__Supper__AWorldSettings_NotifyActorEndCursorOver(this);
public override void OnRep_AttachmentReplication()
=> E__Supper__AWorldSettings_OnRep_AttachmentReplication(this);
public override void OnRep_Instigator()
=> E__Supper__AWorldSettings_OnRep_Instigator(this);
protected override void OnRep_Owner()
=> E__Supper__AWorldSettings_OnRep_Owner(this);
public override void OnRep_ReplicatedMovement()
=> E__Supper__AWorldSettings_OnRep_ReplicatedMovement(this);
public override void OnRep_ReplicateMovement()
=> E__Supper__AWorldSettings_OnRep_ReplicateMovement(this);
/// <summary>
/// Called on the client when the replication paused value is changed
/// </summary>
public override void OnReplicationPausedChanged(bool bIsReplicationPaused)
=> E__Supper__AWorldSettings_OnReplicationPausedChanged(this, bIsReplicationPaused);
/// <summary>
/// Called when the Actor is outside the hard limit on world bounds
/// </summary>
public override void OutsideWorldBounds()
=> E__Supper__AWorldSettings_OutsideWorldBounds(this);
/// <summary>
/// Called when an actor is done spawning into the world (from UWorld::SpawnActor), both in the editor and during gameplay
/// <para>For actors with a root component, the location and rotation will have already been set. </para>
/// This is called before calling construction scripts, but after native components have been created
/// </summary>
public override void PostActorCreated()
=> E__Supper__AWorldSettings_PostActorCreated(this);
/// <summary>
/// Allow actors to initialize themselves on the C++ side after all of their components have been initialized, only called during gameplay
/// </summary>
public override void PostInitializeComponents()
=> E__Supper__AWorldSettings_PostInitializeComponents(this);
/// <summary>
/// Always called immediately after spawning and reading in replicated properties
/// </summary>
public override void PostNetInit()
=> E__Supper__AWorldSettings_PostNetInit(this);
/// <summary>
/// Update location and rotation from ReplicatedMovement. Not called for simulated physics!
/// </summary>
public override void PostNetReceiveLocationAndRotation()
=> E__Supper__AWorldSettings_PostNetReceiveLocationAndRotation(this);
/// <summary>
/// Update and smooth simulated physic state, replaces PostNetReceiveLocation() and PostNetReceiveVelocity()
/// </summary>
public override void PostNetReceivePhysicState()
=> E__Supper__AWorldSettings_PostNetReceivePhysicState(this);
/// <summary>
/// Always called immediately after a new Role is received from the remote.
/// </summary>
public override void PostNetReceiveRole()
=> E__Supper__AWorldSettings_PostNetReceiveRole(this);
/// <summary>
/// Called after all the components in the Components array are registered, called both in editor and during gameplay
/// </summary>
public override void PostRegisterAllComponents()
=> E__Supper__AWorldSettings_PostRegisterAllComponents(this);
/// <summary>
/// Called after all currently registered components are cleared
/// </summary>
public override void PostUnregisterAllComponents()
=> E__Supper__AWorldSettings_PostUnregisterAllComponents(this);
/// <summary>
/// Called right before components are initialized, only called during gameplay
/// </summary>
public override void PreInitializeComponents()
=> E__Supper__AWorldSettings_PreInitializeComponents(this);
/// <summary>
/// Called before all the components in the Components array are registered, called both in editor and during gameplay
/// </summary>
public override void PreRegisterAllComponents()
=> E__Supper__AWorldSettings_PreRegisterAllComponents(this);
/// <summary>
/// Calls PrestreamTextures() for all the actor's meshcomponents.
/// </summary>
/// <param name="seconds">Number of seconds to force all mip-levels to be resident</param>
/// <param name="bEnableStreaming">Whether to start (true) or stop (false) streaming</param>
/// <param name="cinematicTextureGroups">Bitfield indicating which texture groups that use extra high-resolution mips</param>
public override void PrestreamTextures(float seconds, bool bEnableStreaming, int cinematicTextureGroups)
=> E__Supper__AWorldSettings_PrestreamTextures(this, seconds, bEnableStreaming, cinematicTextureGroups);
/// <summary>
/// Virtual call chain to register all tick functions for the actor class hierarchy
/// </summary>
/// <param name="bRegister">true to register, false, to unregister</param>
protected override void RegisterActorTickFunctions(bool bRegister)
=> E__Supper__AWorldSettings_RegisterActorTickFunctions(this, bRegister);
/// <summary>
/// Ensure that all the components in the Components array are registered
/// </summary>
public override void RegisterAllComponents()
=> E__Supper__AWorldSettings_RegisterAllComponents(this);
/// <summary>
/// Will reregister all components on this actor. Does a lot of work - should only really be used in editor, generally use UpdateComponentTransforms or MarkComponentsRenderStateDirty.
/// </summary>
public override void ReregisterAllComponents()
=> E__Supper__AWorldSettings_ReregisterAllComponents(this);
/// <summary>
/// Rerun construction scripts, destroying all autogenerated components; will attempt to preserve the root component location.
/// </summary>
public override void RerunConstructionScripts()
=> E__Supper__AWorldSettings_RerunConstructionScripts(this);
/// <summary>
/// Reset actor to initial state - used when restarting level without reloading.
/// </summary>
public override void Reset()
=> E__Supper__AWorldSettings_Reset(this);
/// <summary>
/// Called on the actor before checkpoint data is applied during a replay.
/// <para>Only called if bReplayRewindable is set. </para>
/// </summary>
public override void RewindForReplay()
=> E__Supper__AWorldSettings_RewindForReplay(this);
/// <summary>
/// Sets the actor to be hidden in the game
/// </summary>
/// <param name="bNewHidden">Whether or not to hide the actor and all its components</param>
public override void SetActorHiddenInGame(bool bNewHidden)
=> E__Supper__AWorldSettings_SetActorHiddenInGame(this, bNewHidden);
/// <summary>
/// Set the lifespan of this actor. When it expires the object will be destroyed. If requested lifespan is 0, the timer is cleared and the actor will not be destroyed.
/// </summary>
public override void SetLifeSpan(float inLifespan)
=> E__Supper__AWorldSettings_SetLifeSpan(this, inLifespan);
/// <summary>
/// Set whether this actor's movement replicates to network clients.
/// </summary>
/// <param name="bInReplicateMovement">Whether this Actor's movement replicates to clients.</param>
public override void SetReplicateMovement(bool bInReplicateMovement)
=> E__Supper__AWorldSettings_SetReplicateMovement(this, bInReplicateMovement);
/// <summary>
/// Networking - Server - TearOff this actor to stop replication to clients. Will set bTearOff to true.
/// </summary>
public override void TearOff()
=> E__Supper__AWorldSettings_TearOff(this);
/// <summary>
/// Called from TeleportTo() when teleport succeeds
/// </summary>
public override void TeleportSucceeded(bool bIsATest)
=> E__Supper__AWorldSettings_TeleportSucceeded(this, bIsATest);
/// <summary>
/// Function called every frame on this Actor. Override this function to implement custom logic to be executed every frame.
/// <para>Note that Tick is disabled by default, and you will need to check PrimaryActorTick.bCanEverTick is set to true to enable it. </para>
/// </summary>
/// <param name="deltaSeconds">Game time elapsed during last frame modified by the time dilation</param>
public override void Tick(float deltaSeconds)
=> E__Supper__AWorldSettings_Tick(this, deltaSeconds);
/// <summary>
/// Networking - called on client when actor is torn off (bTearOff==true), meaning it's no longer replicated to clients.
/// <para>@see bTearOff </para>
/// </summary>
public override void TornOff()
=> E__Supper__AWorldSettings_TornOff(this);
/// <summary>
/// Unregister all currently registered components
/// </summary>
/// <param name="bForReregister">If true, RegisterAllComponents will be called immediately after this so some slow operations can be avoided</param>
public override void UnregisterAllComponents(bool bForReregister)
=> E__Supper__AWorldSettings_UnregisterAllComponents(this, bForReregister);
/// <summary>
/// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an
/// <para>asynchronous cleanup process. </para>
/// </summary>
public override void BeginDestroy()
=> E__Supper__AWorldSettings_BeginDestroy(this);
/// <summary>
/// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed.
/// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para>
/// </summary>
public override void FinishDestroy()
=> E__Supper__AWorldSettings_FinishDestroy(this);
/// <summary>
/// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds
/// </summary>
public override void MarkAsEditorOnlySubobject()
=> E__Supper__AWorldSettings_MarkAsEditorOnlySubobject(this);
/// <summary>
/// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion
/// <para>in the construction of the default materials </para>
/// </summary>
public override void PostCDOContruct()
=> E__Supper__AWorldSettings_PostCDOContruct(this);
/// <summary>
/// Called after importing property values for this object (paste, duplicate or .t3d import)
/// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para>
/// are unsupported by the script serialization
/// </summary>
public override void PostEditImport()
=> E__Supper__AWorldSettings_PostEditImport(this);
/// <summary>
/// Called after the C++ constructor and after the properties have been initialized, including those loaded from config.
/// <para>This is called before any serialization or other setup has happened. </para>
/// </summary>
public override void PostInitProperties()
=> E__Supper__AWorldSettings_PostInitProperties(this);
/// <summary>
/// Do any object-specific cleanup required immediately after loading an object.
/// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para>
/// </summary>
public override void PostLoad()
=> E__Supper__AWorldSettings_PostLoad(this);
/// <summary>
/// Called right after receiving a bunch
/// </summary>
public override void PostNetReceive()
=> E__Supper__AWorldSettings_PostNetReceive(this);
/// <summary>
/// Called right after calling all OnRep notifies (called even when there are no notifies)
/// </summary>
public override void PostRepNotifies()
=> E__Supper__AWorldSettings_PostRepNotifies(this);
/// <summary>
/// Called from within SavePackage on the passed in base/root object.
/// <para>This function is called after the package has been saved and can perform cleanup. </para>
/// </summary>
/// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param>
public override void PostSaveRoot(bool bCleanupIsRequired)
=> E__Supper__AWorldSettings_PostSaveRoot(this, bCleanupIsRequired);
/// <summary>
/// Called right before being marked for destruction due to network replication
/// </summary>
public override void PreDestroyFromReplication()
=> E__Supper__AWorldSettings_PreDestroyFromReplication(this);
/// <summary>
/// Called right before receiving a bunch
/// </summary>
public override void PreNetReceive()
=> E__Supper__AWorldSettings_PreNetReceive(this);
/// <summary>
/// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources.
/// </summary>
public override void ShutdownAfterError()
=> E__Supper__AWorldSettings_ShutdownAfterError(this);
/// <summary>
/// Called after PostLoad to create UObject cluster
/// </summary>
public override void CreateCluster()
=> E__Supper__AWorldSettings_CreateCluster(this);
/// <summary>
/// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it.
/// </summary>
public override void OnClusterMarkedAsPendingKill()
=> E__Supper__AWorldSettings_OnClusterMarkedAsPendingKill(this);
#endregion
public static implicit operator IntPtr(ManageWorldSettings self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator ManageWorldSettings(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<ManageWorldSettings>(PtrDesc);
}
}
}
| |
// 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;
namespace System
{
internal unsafe partial class Number
{
public readonly struct FloatingPointInfo
{
public static readonly FloatingPointInfo Double = new FloatingPointInfo(
denormalMantissaBits: 52,
exponentBits: 11,
maxBinaryExponent: 1023,
exponentBias: 1023,
infinityBits: 0x7FF00000_00000000
);
public static readonly FloatingPointInfo Single = new FloatingPointInfo(
denormalMantissaBits: 23,
exponentBits: 8,
maxBinaryExponent: 127,
exponentBias: 127,
infinityBits: 0x7F800000
);
public ulong ZeroBits { get; }
public ulong InfinityBits { get; }
public ulong NormalMantissaMask { get; }
public ulong DenormalMantissaMask { get; }
public int MinBinaryExponent { get; }
public int MaxBinaryExponent { get; }
public int ExponentBias { get; }
public int OverflowDecimalExponent { get; }
public ushort NormalMantissaBits { get; }
public ushort DenormalMantissaBits { get; }
public ushort ExponentBits { get; }
public FloatingPointInfo(ushort denormalMantissaBits, ushort exponentBits, int maxBinaryExponent, int exponentBias, ulong infinityBits)
{
ExponentBits = exponentBits;
DenormalMantissaBits = denormalMantissaBits;
NormalMantissaBits = (ushort)(denormalMantissaBits + 1); // we get an extra (hidden) bit for normal mantissas
OverflowDecimalExponent = (maxBinaryExponent + 2 * NormalMantissaBits) / 3;
ExponentBias = exponentBias;
MaxBinaryExponent = maxBinaryExponent;
MinBinaryExponent = 1 - maxBinaryExponent;
DenormalMantissaMask = (1UL << denormalMantissaBits) - 1;
NormalMantissaMask = (1UL << NormalMantissaBits) - 1;
InfinityBits = infinityBits;
ZeroBits = 0;
}
}
private static readonly float[] s_Pow10SingleTable = new float[]
{
1e0f, // 10^0
1e1f, // 10^1
1e2f, // 10^2
1e3f, // 10^3
1e4f, // 10^4
1e5f, // 10^5
1e6f, // 10^6
1e7f, // 10^7
1e8f, // 10^8
1e9f, // 10^9
1e10f, // 10^10
};
private static readonly double[] s_Pow10DoubleTable = new double[]
{
1e0, // 10^0
1e1, // 10^1
1e2, // 10^2
1e3, // 10^3
1e4, // 10^4
1e5, // 10^5
1e6, // 10^6
1e7, // 10^7
1e8, // 10^8
1e9, // 10^9
1e10, // 10^10
1e11, // 10^11
1e12, // 10^12
1e13, // 10^13
1e14, // 10^14
1e15, // 10^15
1e16, // 10^16
1e17, // 10^17
1e18, // 10^18
1e19, // 10^19
1e20, // 10^20
1e21, // 10^21
1e22, // 10^22
};
private static void AccumulateDecimalDigitsIntoBigInteger(ref NumberBuffer number, uint firstIndex, uint lastIndex, out BigInteger result)
{
result = new BigInteger(0);
byte* src = number.GetDigitsPointer() + firstIndex;
uint remaining = lastIndex - firstIndex;
while (remaining != 0)
{
uint count = Math.Min(remaining, 9);
uint value = DigitsToUInt32(src, (int)(count));
result.MultiplyPow10(count);
result.Add(value);
src += count;
remaining -= count;
}
}
private static ulong AssembleFloatingPointBits(in FloatingPointInfo info, ulong initialMantissa, int initialExponent, bool hasZeroTail)
{
// number of bits by which we must adjust the mantissa to shift it into the
// correct position, and compute the resulting base two exponent for the
// normalized mantissa:
uint initialMantissaBits = BigInteger.CountSignificantBits(initialMantissa);
int normalMantissaShift = info.NormalMantissaBits - (int)(initialMantissaBits);
int normalExponent = initialExponent - normalMantissaShift;
ulong mantissa = initialMantissa;
int exponent = normalExponent;
if (normalExponent > info.MaxBinaryExponent)
{
// The exponent is too large to be represented by the floating point
// type; report the overflow condition:
return info.InfinityBits;
}
else if (normalExponent < info.MinBinaryExponent)
{
// The exponent is too small to be represented by the floating point
// type as a normal value, but it may be representable as a denormal
// value. Compute the number of bits by which we need to shift the
// mantissa in order to form a denormal number. (The subtraction of
// an extra 1 is to account for the hidden bit of the mantissa that
// is not available for use when representing a denormal.)
int denormalMantissaShift = normalMantissaShift + normalExponent + info.ExponentBias - 1;
// Denormal values have an exponent of zero, so the debiased exponent is
// the negation of the exponent bias:
exponent = -info.ExponentBias;
if (denormalMantissaShift < 0)
{
// Use two steps for right shifts: for a shift of N bits, we first
// shift by N-1 bits, then shift the last bit and use its value to
// round the mantissa.
mantissa = RightShiftWithRounding(mantissa, -denormalMantissaShift, hasZeroTail);
// If the mantissa is now zero, we have underflowed:
if (mantissa == 0)
{
return info.ZeroBits;
}
// When we round the mantissa, the result may be so large that the
// number becomes a normal value. For example, consider the single
// precision case where the mantissa is 0x01ffffff and a right shift
// of 2 is required to shift the value into position. We perform the
// shift in two steps: we shift by one bit, then we shift again and
// round using the dropped bit. The initial shift yields 0x00ffffff.
// The rounding shift then yields 0x007fffff and because the least
// significant bit was 1, we add 1 to this number to round it. The
// final result is 0x00800000.
//
// 0x00800000 is 24 bits, which is more than the 23 bits available
// in the mantissa. Thus, we have rounded our denormal number into
// a normal number.
//
// We detect this case here and re-adjust the mantissa and exponent
// appropriately, to form a normal number:
if (mantissa > info.DenormalMantissaMask)
{
// We add one to the denormal_mantissa_shift to account for the
// hidden mantissa bit (we subtracted one to account for this bit
// when we computed the denormal_mantissa_shift above).
exponent = initialExponent - (denormalMantissaShift + 1) - normalMantissaShift;
}
}
else
{
mantissa <<= denormalMantissaShift;
}
}
else
{
if (normalMantissaShift < 0)
{
// Use two steps for right shifts: for a shift of N bits, we first
// shift by N-1 bits, then shift the last bit and use its value to
// round the mantissa.
mantissa = RightShiftWithRounding(mantissa, -normalMantissaShift, hasZeroTail);
// When we round the mantissa, it may produce a result that is too
// large. In this case, we divide the mantissa by two and increment
// the exponent (this does not change the value).
if (mantissa > info.NormalMantissaMask)
{
mantissa >>= 1;
exponent++;
// The increment of the exponent may have generated a value too
// large to be represented. In this case, report the overflow:
if (exponent > info.MaxBinaryExponent)
{
return info.InfinityBits;
}
}
}
else if (normalMantissaShift > 0)
{
mantissa <<= normalMantissaShift;
}
}
// Unset the hidden bit in the mantissa and assemble the floating point value
// from the computed components:
mantissa &= info.DenormalMantissaMask;
Debug.Assert((info.DenormalMantissaMask & (1UL << info.DenormalMantissaBits)) == 0);
ulong shiftedExponent = ((ulong)(exponent + info.ExponentBias)) << info.DenormalMantissaBits;
Debug.Assert((shiftedExponent & info.DenormalMantissaMask) == 0);
Debug.Assert((mantissa & ~info.DenormalMantissaMask) == 0);
Debug.Assert((shiftedExponent & ~(((1UL << info.ExponentBits) - 1) << info.DenormalMantissaBits)) == 0); // exponent fits in its place
return shiftedExponent | mantissa;
}
private static ulong ConvertBigIntegerToFloatingPointBits(ref BigInteger value, in FloatingPointInfo info, uint integerBitsOfPrecision, bool hasNonZeroFractionalPart)
{
int baseExponent = info.DenormalMantissaBits;
// When we have 64-bits or less of precision, we can just get the mantissa directly
if (integerBitsOfPrecision <= 64)
{
return AssembleFloatingPointBits(in info, value.ToUInt64(), baseExponent, !hasNonZeroFractionalPart);
}
uint topBlockIndex = Math.DivRem(integerBitsOfPrecision, 32, out uint topBlockBits);
uint middleBlockIndex = topBlockIndex - 1;
uint bottomBlockIndex = middleBlockIndex - 1;
ulong mantissa;
int exponent = baseExponent + ((int)(bottomBlockIndex) * 32);
bool hasZeroTail = !hasNonZeroFractionalPart;
// When the top 64-bits perfectly span two blocks, we can get those blocks directly
if (topBlockBits == 0)
{
mantissa = ((ulong)(value.GetBlock(middleBlockIndex)) << 32) + value.GetBlock(bottomBlockIndex);
}
else
{
// Otherwise, we need to read three blocks and combine them into a 64-bit mantissa
int bottomBlockShift = (int)(topBlockBits);
int topBlockShift = 64 - bottomBlockShift;
int middleBlockShift = topBlockShift - 32;
exponent += (int)(topBlockBits);
uint bottomBlock = value.GetBlock(bottomBlockIndex);
uint bottomBits = bottomBlock >> bottomBlockShift;
ulong middleBits = (ulong)(value.GetBlock(middleBlockIndex)) << middleBlockShift;
ulong topBits = (ulong)(value.GetBlock(topBlockIndex)) << topBlockShift;
mantissa = topBits + middleBits + bottomBits;
uint unusedBottomBlockBitsMask = (1u << (int)(topBlockBits)) - 1;
hasZeroTail &= (bottomBlock & unusedBottomBlockBitsMask) == 0;
}
for (uint i = 0; i != bottomBlockIndex; i++)
{
hasZeroTail &= (value.GetBlock(i) == 0);
}
return AssembleFloatingPointBits(in info, mantissa, exponent, hasZeroTail);
}
// get 32-bit integer from at most 9 digits
private static uint DigitsToUInt32(byte* p, int count)
{
Debug.Assert((1 <= count) && (count <= 9));
byte* end = (p + count);
uint res = (uint)(p[0] - '0');
for (p++; p < end; p++)
{
res = (10 * res) + p[0] - '0';
}
return res;
}
// get 64-bit integer from at most 19 digits
private static ulong DigitsToUInt64(byte* p, int count)
{
Debug.Assert((1 <= count) && (count <= 19));
byte* end = (p + count);
ulong res = (ulong)(p[0] - '0');
for (p++; p < end; p++)
{
res = (10 * res) + p[0] - '0';
}
return res;
}
private static ulong NumberToFloatingPointBits(ref NumberBuffer number, in FloatingPointInfo info)
{
Debug.Assert(number.GetDigitsPointer()[0] != '0');
Debug.Assert(number.Scale <= FloatingPointMaxExponent);
Debug.Assert(number.Scale >= FloatingPointMinExponent);
Debug.Assert(number.DigitsCount != 0);
// The input is of the form 0.Mantissa x 10^Exponent, where 'Mantissa' are
// the decimal digits of the mantissa and 'Exponent' is the decimal exponent.
// We decompose the mantissa into two parts: an integer part and a fractional
// part. If the exponent is positive, then the integer part consists of the
// first 'exponent' digits, or all present digits if there are fewer digits.
// If the exponent is zero or negative, then the integer part is empty. In
// either case, the remaining digits form the fractional part of the mantissa.
uint totalDigits = (uint)(number.DigitsCount);
uint positiveExponent = (uint)(Math.Max(0, number.Scale));
uint integerDigitsPresent = Math.Min(positiveExponent, totalDigits);
uint fractionalDigitsPresent = totalDigits - integerDigitsPresent;
uint fastExponent = (uint)(Math.Abs(number.Scale - integerDigitsPresent - fractionalDigitsPresent));
// When the number of significant digits is less than or equal to 15 and the
// scale is less than or equal to 22, we can take some shortcuts and just rely
// on floating-point arithmetic to compute the correct result. This is
// because each floating-point precision values allows us to exactly represent
// different whole integers and certain powers of 10, depending on the underlying
// formats exact range. Additionally, IEEE operations dictate that the result is
// computed to the infinitely precise result and then rounded, which means that
// we can rely on it to produce the correct result when both inputs are exact.
byte* src = number.GetDigitsPointer();
if ((info.DenormalMantissaBits == 23) && (totalDigits <= 7) && (fastExponent <= 10))
{
// It is only valid to do this optimization for single-precision floating-point
// values since we can lose some of the mantissa bits and would return the
// wrong value when upcasting to double.
float result = DigitsToUInt32(src, (int)(totalDigits));
float scale = s_Pow10SingleTable[fastExponent];
if (fractionalDigitsPresent != 0)
{
result /= scale;
}
else
{
result *= scale;
}
return (uint)(BitConverter.SingleToInt32Bits(result));
}
if ((totalDigits <= 15) && (fastExponent <= 22))
{
double result = DigitsToUInt64(src, (int)(totalDigits));
double scale = s_Pow10DoubleTable[fastExponent];
if (fractionalDigitsPresent != 0)
{
result /= scale;
}
else
{
result *= scale;
}
if (info.DenormalMantissaBits == 52)
{
return (ulong)(BitConverter.DoubleToInt64Bits(result));
}
else
{
Debug.Assert(info.DenormalMantissaBits == 23);
return (uint)(BitConverter.SingleToInt32Bits((float)(result)));
}
}
return NumberToFloatingPointBitsSlow(ref number, in info, positiveExponent, integerDigitsPresent, fractionalDigitsPresent);
}
private static ulong NumberToFloatingPointBitsSlow(ref NumberBuffer number, in FloatingPointInfo info, uint positiveExponent, uint integerDigitsPresent, uint fractionalDigitsPresent)
{
// To generate an N bit mantissa we require N + 1 bits of precision. The
// extra bit is used to correctly round the mantissa (if there are fewer bits
// than this available, then that's totally okay; in that case we use what we
// have and we don't need to round).
uint requiredBitsOfPrecision = (uint)(info.NormalMantissaBits + 1);
uint totalDigits = (uint)(number.DigitsCount);
uint integerDigitsMissing = positiveExponent - integerDigitsPresent;
const uint IntegerFirstIndex = 0;
uint integerLastIndex = integerDigitsPresent;
uint fractionalFirstIndex = integerLastIndex;
uint fractionalLastIndex = totalDigits;
// First, we accumulate the integer part of the mantissa into a big_integer:
AccumulateDecimalDigitsIntoBigInteger(ref number, IntegerFirstIndex, integerLastIndex, out BigInteger integerValue);
if (integerDigitsMissing > 0)
{
if (integerDigitsMissing > info.OverflowDecimalExponent)
{
return info.InfinityBits;
}
integerValue.MultiplyPow10(integerDigitsMissing);
}
// At this point, the integer_value contains the value of the integer part
// of the mantissa. If either [1] this number has more than the required
// number of bits of precision or [2] the mantissa has no fractional part,
// then we can assemble the result immediately:
uint integerBitsOfPrecision = BigInteger.CountSignificantBits(ref integerValue);
if ((integerBitsOfPrecision >= requiredBitsOfPrecision) || (fractionalDigitsPresent == 0))
{
return ConvertBigIntegerToFloatingPointBits(
ref integerValue,
in info,
integerBitsOfPrecision,
fractionalDigitsPresent != 0
);
}
// Otherwise, we did not get enough bits of precision from the integer part,
// and the mantissa has a fractional part. We parse the fractional part of
// the mantissa to obtain more bits of precision. To do this, we convert
// the fractional part into an actual fraction N/M, where the numerator N is
// computed from the digits of the fractional part, and the denominator M is
// computed as the power of 10 such that N/M is equal to the value of the
// fractional part of the mantissa.
uint fractionalDenominatorExponent = fractionalDigitsPresent;
if (number.Scale < 0)
{
fractionalDenominatorExponent += (uint)(-number.Scale);
}
if ((integerBitsOfPrecision == 0) && (fractionalDenominatorExponent - (int)(totalDigits)) > info.OverflowDecimalExponent)
{
// If there were any digits in the integer part, it is impossible to
// underflow (because the exponent cannot possibly be small enough),
// so if we underflow here it is a true underflow and we return zero.
return info.ZeroBits;
}
AccumulateDecimalDigitsIntoBigInteger(ref number, fractionalFirstIndex, fractionalLastIndex, out BigInteger fractionalNumerator);
Debug.Assert(!fractionalNumerator.IsZero());
BigInteger.Pow10(fractionalDenominatorExponent, out BigInteger fractionalDenominator);
// Because we are using only the fractional part of the mantissa here, the
// numerator is guaranteed to be smaller than the denominator. We normalize
// the fraction such that the most significant bit of the numerator is in
// the same position as the most significant bit in the denominator. This
// ensures that when we later shift the numerator N bits to the left, we
// will produce N bits of precision.
uint fractionalNumeratorBits = BigInteger.CountSignificantBits(ref fractionalNumerator);
uint fractionalDenominatorBits = BigInteger.CountSignificantBits(ref fractionalDenominator);
uint fractionalShift = 0;
if (fractionalDenominatorBits > fractionalNumeratorBits)
{
fractionalShift = fractionalDenominatorBits - fractionalNumeratorBits;
}
if (fractionalShift > 0)
{
fractionalNumerator.ShiftLeft(fractionalShift);
}
uint requiredFractionalBitsOfPrecision = requiredBitsOfPrecision - integerBitsOfPrecision;
uint remainingBitsOfPrecisionRequired = requiredFractionalBitsOfPrecision;
if (integerBitsOfPrecision > 0)
{
// If the fractional part of the mantissa provides no bits of precision
// and cannot affect rounding, we can just take whatever bits we got from
// the integer part of the mantissa. This is the case for numbers like
// 5.0000000000000000000001, where the significant digits of the fractional
// part start so far to the right that they do not affect the floating
// point representation.
//
// If the fractional shift is exactly equal to the number of bits of
// precision that we require, then no fractional bits will be part of the
// result, but the result may affect rounding. This is e.g. the case for
// large, odd integers with a fractional part greater than or equal to .5.
// Thus, we need to do the division to correctly round the result.
if (fractionalShift > remainingBitsOfPrecisionRequired)
{
return ConvertBigIntegerToFloatingPointBits(
ref integerValue,
in info,
integerBitsOfPrecision,
fractionalDigitsPresent != 0
);
}
remainingBitsOfPrecisionRequired -= fractionalShift;
}
// If there was no integer part of the mantissa, we will need to compute the
// exponent from the fractional part. The fractional exponent is the power
// of two by which we must multiply the fractional part to move it into the
// range [1.0, 2.0). This will either be the same as the shift we computed
// earlier, or one greater than that shift:
uint fractionalExponent = fractionalShift;
if (BigInteger.Compare(ref fractionalNumerator, ref fractionalDenominator) < 0)
{
fractionalExponent++;
}
fractionalNumerator.ShiftLeft(remainingBitsOfPrecisionRequired);
BigInteger.DivRem(ref fractionalNumerator, ref fractionalDenominator, out BigInteger bigFractionalMantissa, out BigInteger fractionalRemainder);
ulong fractionalMantissa = bigFractionalMantissa.ToUInt64();
bool hasZeroTail = !number.HasNonZeroTail && fractionalRemainder.IsZero();
// We may have produced more bits of precision than were required. Check,
// and remove any "extra" bits:
uint fractionalMantissaBits = BigInteger.CountSignificantBits(fractionalMantissa);
if (fractionalMantissaBits > requiredFractionalBitsOfPrecision)
{
int shift = (int)(fractionalMantissaBits - requiredFractionalBitsOfPrecision);
hasZeroTail = hasZeroTail && (fractionalMantissa & ((1UL << shift) - 1)) == 0;
fractionalMantissa >>= shift;
}
// Compose the mantissa from the integer and fractional parts:
ulong integerMantissa = integerValue.ToUInt64();
ulong completeMantissa = (integerMantissa << (int)(requiredFractionalBitsOfPrecision)) + fractionalMantissa;
// Compute the final exponent:
// * If the mantissa had an integer part, then the exponent is one less than
// the number of bits we obtained from the integer part. (It's one less
// because we are converting to the form 1.11111, with one 1 to the left
// of the decimal point.)
// * If the mantissa had no integer part, then the exponent is the fractional
// exponent that we computed.
// Then, in both cases, we subtract an additional one from the exponent, to
// account for the fact that we've generated an extra bit of precision, for
// use in rounding.
int finalExponent = (integerBitsOfPrecision > 0) ? (int)(integerBitsOfPrecision) - 2 : -(int)(fractionalExponent) - 1;
return AssembleFloatingPointBits(in info, completeMantissa, finalExponent, hasZeroTail);
}
private static ulong RightShiftWithRounding(ulong value, int shift, bool hasZeroTail)
{
// If we'd need to shift further than it is possible to shift, the answer
// is always zero:
if (shift >= 64)
{
return 0;
}
ulong extraBitsMask = (1UL << (shift - 1)) - 1;
ulong roundBitMask = (1UL << (shift - 1));
ulong lsbBitMask = 1UL << shift;
bool lsbBit = (value & lsbBitMask) != 0;
bool roundBit = (value & roundBitMask) != 0;
bool hasTailBits = !hasZeroTail || (value & extraBitsMask) != 0;
return (value >> shift) + (ShouldRoundUp(lsbBit, roundBit, hasTailBits) ? 1UL : 0);
}
private static bool ShouldRoundUp(bool lsbBit, bool roundBit, bool hasTailBits)
{
// If there are insignificant set bits, we need to round to the
// nearest; there are two cases:
// we round up if either [1] the value is slightly greater than the midpoint
// between two exactly representable values or [2] the value is exactly the
// midpoint between two exactly representable values and the greater of the
// two is even (this is "round-to-even").
return roundBit && (hasTailBits || lsbBit);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Xml;
using gov.va.medora.utils;
using gov.va.medora.utils.mock;
using gov.va.medora.mdo.dao.vista;
using System.IO;
using gov.va.medora.mdo.exceptions;
using gov.va.medora.mdo.dao.mock;
namespace gov.va.medora.mdo.dao
{
public class MockConnection : AbstractConnection
{
// Need protocols for API level calls that need to use the abstract
// factory to create their DAOs.
public const string VISTA = "VISTA";
public const string FHIE = "FHIE";
public const string RPMS = "RPMS";
private bool verifyRpc = true;
private bool updateRpc = false;
AbstractConnection _sqliteCxn;
public bool VerifyRpc
{
get { return verifyRpc; }
set { verifyRpc = value; }
}
ISystemFileHandler sysFileHandler;
public MockConnection(DataSource dataSource) : base(dataSource)
{
_sqliteCxn = new XSqliteConnection(dataSource);
}
// This constructor is needed for API level tests.
public MockConnection(string siteId, string protocol, bool updateRpc = false) : base(null)
{
this.DataSource = new DataSource();
this.DataSource.SiteId = new SiteId(siteId, "Mock");
this.DataSource.Protocol = protocol;
_sqliteCxn = new XSqliteConnection(this.DataSource);
this.Account = new MockAccount(this);
//this.Account.IsAuthenticated = true;
this.updateRpc = updateRpc;
AbstractCredentials credentials = new VistaCredentials();
credentials.AccountName = "AccessCode";
credentials.AccountPassword = "VerifyCode";
AbstractPermission permission = new MenuOption(VistaConstants.MDWS_CONTEXT);
permission.IsPrimary = true;
this.Account.Permissions.Add(permission.Name, permission);
}
public override ISystemFileHandler SystemFileHandler
{
get
{
if (sysFileHandler == null)
{
sysFileHandler = new VistaSystemFileHandler(this);
}
return sysFileHandler;
}
}
public override void connect()
{
IsConnected = true;
}
public override object authorizedConnect(AbstractCredentials credentials, AbstractPermission permission, DataSource validationDataSource)
{
IsConnected = true;
return null;
}
public override void disconnect()
{
IsConnected = false;
}
public override object query(MdoQuery query, AbstractPermission permission = null)
{
// hardcoded datetime request
if (String.Equals(query.RpcName, "ORWU DT") && String.Equals(((VistaQuery.Parameter)query.Parameters[0]).Value, "NOW"))
{
return "3010101.120101";
}
if (!IsConnected)
{
throw new NotConnectedException();
}
string reply = (string)_sqliteCxn.query(query, permission);
if (reply.Contains("M ERROR"))
{
throw new MdoException(MdoExceptionCode.VISTA_FAULT, reply);
}
return reply;
}
//internal void updateSqlite(MdoQuery oldRequest, string newRequest, string reply)
//{
// sqlite.SqliteDao sqliteDao = new sqlite.SqliteDao();
// string hashedOldQueryString = StringUtils.getMD5Hash(oldRequest.buildMessage());
// string hashedNewQueryString = StringUtils.getMD5Hash(newRequest);
// try
// {
// sqliteDao.getObject(this.xmlSource.siteId, hashedOldQueryString); // should throw exception on failure
// sqliteDao.updateObject(this.xmlSource.siteId, hashedOldQueryString, newRequest, hashedNewQueryString, reply);
// }
// catch (Exception)
// {
// // swallow
// }
//}
//internal void saveToSqlite(MdoQuery request, string reply)
//{
// sqlite.SqliteDao sqliteDao = new sqlite.SqliteDao();
// string queryString = request.buildMessage();
// string hashedQueryString = StringUtils.getMD5Hash(queryString);
// try
// {
// object savedObj = sqliteDao.getObject(this.xmlSource.siteId, hashedQueryString);
// if (savedObj as string == reply)
// {
// return;
// }
// else
// {
// sqliteDao.updateObject(this.xmlSource.siteId, hashedQueryString, reply);
// }
// }
// catch (Exception)
// {
// try
// {
// if (!sqliteDao.hasTable(this.xmlSource.siteId))
// {
// sqliteDao.createTableForSite(this.xmlSource.siteId);
// }
// sqliteDao.saveObject(this.xmlSource.siteId, queryString, reply);
// }
// catch (Exception exc)
// {
// throw new Exception("There was a problem saving the XML data to Sqlite: " + exc.Message);
// }
// }
//}
public override object query(string request, AbstractPermission permission = null)
{
throw new MethodAccessException("This query method was not expected");
}
public override string getWelcomeMessage()
{
return "Hullo from MockConnection";
}
public override bool hasPatch(string patchId)
{
return true;
}
public override string getServerTimeout()
{
return null;
}
public override object query(SqlQuery request, Delegate functionToInvoke, AbstractPermission permission = null)
{
throw new NotImplementedException();
}
public override Dictionary<string, object> getState()
{
throw new NotImplementedException();
}
public override void setState(Dictionary<string, object> session)
{
throw new NotImplementedException();
}
//public override bool isAlive()
//{
// throw new NotImplementedException();
//}
}
}
| |
//
// TreeViewBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using System.Collections.Generic;
#if MONOMAC
using MonoMac.AppKit;
using MonoMac.Foundation;
using nint = System.Int32;
#else
using AppKit;
using Foundation;
#endif
namespace Xwt.Mac
{
public class TreeViewBackend: TableViewBackend<NSOutlineView,ITreeViewEventSink>, ITreeViewBackend
{
ITreeDataSource source;
TreeSource tsource;
class TreeDelegate: NSOutlineViewDelegate
{
public TreeViewBackend Backend;
public override void ItemDidExpand (NSNotification notification)
{
Backend.EventSink.OnRowExpanded (((TreeItem)notification.UserInfo["NSObject"]).Position);
}
public override void ItemWillExpand (NSNotification notification)
{
Backend.EventSink.OnRowExpanding (((TreeItem)notification.UserInfo["NSObject"]).Position);
}
public override void ItemDidCollapse (NSNotification notification)
{
Backend.EventSink.OnRowCollapsed (((TreeItem)notification.UserInfo["NSObject"]).Position);
}
public override void ItemWillCollapse (NSNotification notification)
{
Backend.EventSink.OnRowCollapsing (((TreeItem)notification.UserInfo["NSObject"]).Position);
}
}
NSOutlineView Tree {
get { return (NSOutlineView) Table; }
}
protected override NSTableView CreateView ()
{
var t = new OutlineViewBackend (EventSink, ApplicationContext);
t.Delegate = new TreeDelegate () { Backend = this };
return t;
}
protected override string SelectionChangeEventName {
get { return "NSOutlineViewSelectionDidChangeNotification"; }
}
public TreePosition CurrentEventRow { get; internal set; }
public override NSTableColumn AddColumn (ListViewColumn col)
{
NSTableColumn tcol = base.AddColumn (col);
if (Tree.OutlineTableColumn == null)
Tree.OutlineTableColumn = tcol;
return tcol;
}
public void SetSource (ITreeDataSource source, IBackend sourceBackend)
{
this.source = source;
tsource = new TreeSource (source);
Tree.DataSource = tsource;
source.NodeInserted += (sender, e) => Tree.ReloadItem (tsource.GetItem (source.GetParent(e.Node)), true);
source.NodeDeleted += (sender, e) => Tree.ReloadItem (tsource.GetItem (e.Node), true);
source.NodeChanged += (sender, e) => Tree.ReloadItem (tsource.GetItem (e.Node), false);
source.NodesReordered += (sender, e) => Tree.ReloadItem (tsource.GetItem (e.Node), true);
}
public override object GetValue (object pos, int nField)
{
return source.GetValue ((TreePosition)pos, nField);
}
public override void SetValue (object pos, int nField, object value)
{
source.SetValue ((TreePosition)pos, nField, value);
}
public TreePosition[] SelectedRows {
get {
TreePosition[] res = new TreePosition [Table.SelectedRowCount];
int n = 0;
if (Table.SelectedRowCount > 0) {
foreach (var i in Table.SelectedRows) {
res [n] = ((TreeItem)Tree.ItemAtRow ((int)i)).Position;
}
}
return res;
}
}
public TreePosition FocusedRow {
get {
if (Table.SelectedRowCount > 0)
return ((TreeItem)Tree.ItemAtRow ((int)Table.SelectedRows.FirstIndex)).Position;
return null;
}
set {
SelectRow (value);
}
}
public override void SetCurrentEventRow (object pos)
{
CurrentEventRow = (TreePosition)pos;
}
public void SelectRow (TreePosition pos)
{
var it = tsource.GetItem (pos);
if (it != null)
Table.SelectRow ((int)Tree.RowForItem (it), Table.AllowsMultipleSelection);
}
public void UnselectRow (TreePosition pos)
{
var it = tsource.GetItem (pos);
if (it != null)
Table.DeselectRow (Tree.RowForItem (it));
}
public bool IsRowSelected (TreePosition pos)
{
var it = tsource.GetItem (pos);
return it != null && Table.IsRowSelected (Tree.RowForItem (it));
}
public bool IsRowExpanded (TreePosition pos)
{
var it = tsource.GetItem (pos);
return it != null && Tree.IsItemExpanded (it);
}
public void ExpandRow (TreePosition pos, bool expandChildren)
{
var it = tsource.GetItem (pos);
if (it != null)
Tree.ExpandItem (it, expandChildren);
}
public void CollapseRow (TreePosition pos)
{
var it = tsource.GetItem (pos);
if (it != null)
Tree.CollapseItem (it);
}
public void ScrollToRow (TreePosition pos)
{
var it = tsource.GetItem (pos);
if (it != null)
ScrollToRow ((int)Tree.RowForItem (it));
}
public void ExpandToRow (TreePosition pos)
{
var p = source.GetParent (pos);
while (p != null) {
var it = tsource.GetItem (p);
if (it == null)
break;
Tree.ExpandItem (it, false);
p = source.GetParent (p);
}
}
public bool GetDropTargetRow (double x, double y, out RowDropPosition pos, out TreePosition nodePosition)
{
// Get row
nint row = Tree.GetRow(new System.Drawing.PointF ((float)x, (float)y));
pos = RowDropPosition.Into;
nodePosition = null;
if (row >= 0) {
nodePosition = ((TreeItem)Tree.ItemAtRow (row)).Position;
}
return nodePosition != null;
}
/* protected override void OnDragOverCheck (NSDraggingInfo di, DragOverCheckEventArgs args)
{
base.OnDragOverCheck (di, args);
var row = Tree.GetRow (new System.Drawing.PointF (di.DraggingLocation.X, di.DraggingLocation.Y));
if (row != -1) {
var item = Tree.ItemAtRow (row);
Tree.SetDropItem (item, row);
}
}
protected override void OnDragOver (NSDraggingInfo di, DragOverEventArgs args)
{
base.OnDragOver (di, args);
var p = Tree.ConvertPointFromView (di.DraggingLocation, null);
var row = Tree.GetRow (p);
if (row != -1) {
Tree.SetDropRowDropOperation (row, NSTableViewDropOperation.On);
var item = Tree.ItemAtRow (row);
Tree.SetDropItem (item, 0);
}
}*/
}
class TreeItem: NSObject, ITablePosition
{
public TreePosition Position;
public TreeItem ()
{
}
public TreeItem (IntPtr p): base (p)
{
}
object ITablePosition.Position {
get { return Position; }
}
}
class TreeSource: NSOutlineViewDataSource
{
ITreeDataSource source;
// TODO: remove unused positions
Dictionary<TreePosition,TreeItem> items = new Dictionary<TreePosition, TreeItem> ();
public TreeSource (ITreeDataSource source)
{
this.source = source;
source.NodeInserted += (sender, e) => {
if (!items.ContainsKey (e.Node))
items.Add (e.Node, new TreeItem { Position = e.Node });
};
}
public TreeItem GetItem (TreePosition pos)
{
if (pos == null)
return null;
TreeItem it;
items.TryGetValue (pos, out it);
return it;
}
public override bool AcceptDrop (NSOutlineView outlineView, NSDraggingInfo info, NSObject item, nint index)
{
return false;
}
public override string[] FilesDropped (NSOutlineView outlineView, NSUrl dropDestination, NSArray items)
{
throw new NotImplementedException ();
}
public override NSObject GetChild (NSOutlineView outlineView, nint childIndex, NSObject item)
{
var treeItem = (TreeItem) item;
var pos = source.GetChild (treeItem != null ? treeItem.Position : null, (int) childIndex);
if (pos != null) {
TreeItem res;
if (!items.TryGetValue (pos, out res))
items [pos] = res = new TreeItem () { Position = pos };
return res;
}
else
return null;
}
public override nint GetChildrenCount (NSOutlineView outlineView, NSObject item)
{
var it = (TreeItem) item;
return source.GetChildrenCount (it != null ? it.Position : null);
}
public override NSObject GetObjectValue (NSOutlineView outlineView, NSTableColumn forTableColumn, NSObject byItem)
{
return byItem;
}
public override void SetObjectValue (NSOutlineView outlineView, NSObject theObject, NSTableColumn tableColumn, NSObject item)
{
}
public override bool ItemExpandable (NSOutlineView outlineView, NSObject item)
{
return GetChildrenCount (outlineView, item) > 0;
}
public override NSObject ItemForPersistentObject (NSOutlineView outlineView, NSObject theObject)
{
return null;
}
public override bool OutlineViewwriteItemstoPasteboard (NSOutlineView outlineView, NSArray items, NSPasteboard pboard)
{
return false;
}
public override NSObject PersistentObjectForItem (NSOutlineView outlineView, NSObject item)
{
return null;
}
public override void SortDescriptorsChanged (NSOutlineView outlineView, NSSortDescriptor[] oldDescriptors)
{
}
public override NSDragOperation ValidateDrop (NSOutlineView outlineView, NSDraggingInfo info, NSObject item, nint index)
{
return NSDragOperation.None;
}
protected override void Dispose (bool disposing)
{
base.Dispose (disposing);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Security.Claims;
using System.Threading;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http.Features.Authentication;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Http
{
/// <summary>
/// Represents an implementation of the HTTP Context class.
/// </summary>
public sealed class DefaultHttpContext : HttpContext
{
// The initial size of the feature collection when using the default constructor; based on number of common features
// https://github.com/dotnet/aspnetcore/issues/31249
private const int DefaultFeatureCollectionSize = 10;
// Lambdas hoisted to static readonly fields to improve inlining https://github.com/dotnet/roslyn/issues/13624
private static readonly Func<IFeatureCollection, IItemsFeature> _newItemsFeature = f => new ItemsFeature();
private static readonly Func<DefaultHttpContext, IServiceProvidersFeature> _newServiceProvidersFeature = context => new RequestServicesFeature(context, context.ServiceScopeFactory);
private static readonly Func<IFeatureCollection, IHttpAuthenticationFeature> _newHttpAuthenticationFeature = f => new HttpAuthenticationFeature();
private static readonly Func<IFeatureCollection, IHttpRequestLifetimeFeature> _newHttpRequestLifetimeFeature = f => new HttpRequestLifetimeFeature();
private static readonly Func<IFeatureCollection, ISessionFeature> _newSessionFeature = f => new DefaultSessionFeature();
private static readonly Func<IFeatureCollection, ISessionFeature?> _nullSessionFeature = f => null;
private static readonly Func<IFeatureCollection, IHttpRequestIdentifierFeature> _newHttpRequestIdentifierFeature = f => new HttpRequestIdentifierFeature();
private FeatureReferences<FeatureInterfaces> _features;
private readonly DefaultHttpRequest _request;
private readonly DefaultHttpResponse _response;
private DefaultConnectionInfo? _connection;
private DefaultWebSocketManager? _websockets;
// This is field exists to make analyzing memory dumps easier.
// https://github.com/dotnet/aspnetcore/issues/29709
internal bool _active;
/// <summary>
/// Initializes a new instance of the <see cref="DefaultHttpContext"/> class.
/// </summary>
public DefaultHttpContext()
: this(new FeatureCollection(DefaultFeatureCollectionSize))
{
Features.Set<IHttpRequestFeature>(new HttpRequestFeature());
Features.Set<IHttpResponseFeature>(new HttpResponseFeature());
Features.Set<IHttpResponseBodyFeature>(new StreamResponseBodyFeature(Stream.Null));
}
/// <summary>
/// Initializes a new instance of the <see cref="DefaultHttpContext"/> class with provided features.
/// </summary>
/// <param name="features">Initial set of features for the <see cref="DefaultHttpContext"/>.</param>
public DefaultHttpContext(IFeatureCollection features)
{
_features.Initalize(features);
_request = new DefaultHttpRequest(this);
_response = new DefaultHttpResponse(this);
}
/// <summary>
/// Reinitialize the current instant of the class with features passed in.
/// </summary>
/// <remarks>
/// This method allows the consumer to re-use the <see cref="DefaultHttpContext" /> for another request, rather than having to allocate a new instance.
/// </remarks>
/// <param name="features">The new set of features for the <see cref="DefaultHttpContext" />.</param>
public void Initialize(IFeatureCollection features)
{
var revision = features.Revision;
_features.Initalize(features, revision);
_request.Initialize(revision);
_response.Initialize(revision);
_connection?.Initialize(features, revision);
_websockets?.Initialize(features, revision);
_active = true;
}
/// <summary>
/// Uninitialize all the features in the <see cref="DefaultHttpContext" />.
/// </summary>
public void Uninitialize()
{
_features = default;
_request.Uninitialize();
_response.Uninitialize();
_connection?.Uninitialize();
_websockets?.Uninitialize();
_active = false;
}
/// <summary>
/// Gets or set the <see cref="FormOptions" /> for this instance.
/// </summary>
/// <returns>
/// <see cref="FormOptions"/>
/// </returns>
public FormOptions FormOptions { get; set; } = default!;
/// <summary>
/// Gets or sets the <see cref="IServiceScopeFactory" /> for this instance.
/// </summary>
/// <returns>
/// <see cref="IServiceScopeFactory"/>
/// </returns>
public IServiceScopeFactory ServiceScopeFactory { get; set; } = default!;
private IItemsFeature ItemsFeature =>
_features.Fetch(ref _features.Cache.Items, _newItemsFeature)!;
private IServiceProvidersFeature ServiceProvidersFeature =>
_features.Fetch(ref _features.Cache.ServiceProviders, this, _newServiceProvidersFeature)!;
private IHttpAuthenticationFeature HttpAuthenticationFeature =>
_features.Fetch(ref _features.Cache.Authentication, _newHttpAuthenticationFeature)!;
private IHttpRequestLifetimeFeature LifetimeFeature =>
_features.Fetch(ref _features.Cache.Lifetime, _newHttpRequestLifetimeFeature)!;
private ISessionFeature SessionFeature =>
_features.Fetch(ref _features.Cache.Session, _newSessionFeature)!;
private ISessionFeature? SessionFeatureOrNull =>
_features.Fetch(ref _features.Cache.Session, _nullSessionFeature);
private IHttpRequestIdentifierFeature RequestIdentifierFeature =>
_features.Fetch(ref _features.Cache.RequestIdentifier, _newHttpRequestIdentifierFeature)!;
/// <inheritdoc/>
public override IFeatureCollection Features => _features.Collection ?? ContextDisposed();
/// <inheritdoc/>
public override HttpRequest Request => _request;
/// <inheritdoc/>
public override HttpResponse Response => _response;
/// <inheritdoc/>
public override ConnectionInfo Connection => _connection ?? (_connection = new DefaultConnectionInfo(Features));
/// <inheritdoc/>
public override WebSocketManager WebSockets => _websockets ?? (_websockets = new DefaultWebSocketManager(Features));
/// <inheritdoc/>
public override ClaimsPrincipal User
{
get
{
var user = HttpAuthenticationFeature.User;
if (user == null)
{
user = new ClaimsPrincipal(new ClaimsIdentity());
HttpAuthenticationFeature.User = user;
}
return user;
}
set { HttpAuthenticationFeature.User = value; }
}
/// <inheritdoc/>
public override IDictionary<object, object?> Items
{
get { return ItemsFeature.Items; }
set { ItemsFeature.Items = value; }
}
/// <inheritdoc/>
public override IServiceProvider RequestServices
{
get { return ServiceProvidersFeature.RequestServices; }
set { ServiceProvidersFeature.RequestServices = value; }
}
/// <inheritdoc/>
public override CancellationToken RequestAborted
{
get { return LifetimeFeature.RequestAborted; }
set { LifetimeFeature.RequestAborted = value; }
}
/// <inheritdoc/>
public override string TraceIdentifier
{
get { return RequestIdentifierFeature.TraceIdentifier; }
set { RequestIdentifierFeature.TraceIdentifier = value; }
}
/// <inheritdoc/>
public override ISession Session
{
get
{
var feature = SessionFeatureOrNull;
if (feature == null)
{
throw new InvalidOperationException("Session has not been configured for this application " +
"or request.");
}
return feature.Session;
}
set
{
SessionFeature.Session = value;
}
}
// This property exists because of backwards compatibility.
// We send an anonymous object with an HttpContext property
// via DiagnosticListener in various events throughout the pipeline. Instead
// we just send the HttpContext to avoid extra allocations
/// <summary>
/// This API is used by ASP.NET Core's infrastructure and should not be used by application code.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public HttpContext HttpContext => this;
/// <inheritdoc/>
public override void Abort()
{
LifetimeFeature.Abort();
}
private static IFeatureCollection ContextDisposed()
{
ThrowContextDisposed();
return null;
}
[DoesNotReturn]
private static void ThrowContextDisposed()
{
throw new ObjectDisposedException(nameof(HttpContext), $"Request has finished and {nameof(HttpContext)} disposed.");
}
struct FeatureInterfaces
{
public IItemsFeature? Items;
public IServiceProvidersFeature? ServiceProviders;
public IHttpAuthenticationFeature? Authentication;
public IHttpRequestLifetimeFeature? Lifetime;
public ISessionFeature? Session;
public IHttpRequestIdentifierFeature? RequestIdentifier;
}
}
}
| |
// 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.IO;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.Metadata.Tests;
using Xunit;
namespace System.Reflection.PortableExecutable.Tests
{
public class PEReaderTests
{
[Fact]
public void Ctor()
{
Assert.Throws<ArgumentNullException>(() => new PEReader(null, PEStreamOptions.Default));
var invalid = new MemoryStream(new byte[] { 1, 2, 3, 4 });
// the stream should not be disposed if the arguments are bad
Assert.Throws<ArgumentOutOfRangeException>(() => new PEReader(invalid, (PEStreamOptions)int.MaxValue));
Assert.True(invalid.CanRead);
// no BadImageFormatException if we're prefetching the entire image:
var peReader0 = new PEReader(invalid, PEStreamOptions.PrefetchEntireImage | PEStreamOptions.LeaveOpen);
Assert.True(invalid.CanRead);
Assert.Throws<BadImageFormatException>(() => peReader0.PEHeaders);
invalid.Position = 0;
// BadImageFormatException if we're prefetching the entire image and metadata:
Assert.Throws<BadImageFormatException>(() => new PEReader(invalid, PEStreamOptions.PrefetchEntireImage | PEStreamOptions.PrefetchMetadata | PEStreamOptions.LeaveOpen));
Assert.True(invalid.CanRead);
invalid.Position = 0;
// the stream should be disposed if the content is bad:
Assert.Throws<BadImageFormatException>(() => new PEReader(invalid, PEStreamOptions.PrefetchMetadata));
Assert.False(invalid.CanRead);
// the stream should not be disposed if we specified LeaveOpen flag:
invalid = new MemoryStream(new byte[] { 1, 2, 3, 4 });
Assert.Throws<BadImageFormatException>(() => new PEReader(invalid, PEStreamOptions.PrefetchMetadata | PEStreamOptions.LeaveOpen));
Assert.True(invalid.CanRead);
// valid metadata:
var valid = new MemoryStream(Misc.Members);
var peReader = new PEReader(valid, PEStreamOptions.Default);
Assert.True(valid.CanRead);
peReader.Dispose();
Assert.False(valid.CanRead);
}
[Fact]
public void Ctor_Streams()
{
Assert.Throws<ArgumentException>(() => new PEReader(new CustomAccessMemoryStream(canRead: false, canSeek: false, canWrite: false)));
Assert.Throws<ArgumentException>(() => new PEReader(new CustomAccessMemoryStream(canRead: true, canSeek: false, canWrite: false)));
var s = new CustomAccessMemoryStream(canRead: true, canSeek: true, canWrite: false);
new PEReader(s);
new PEReader(s, PEStreamOptions.Default, 0);
Assert.Throws<ArgumentOutOfRangeException>(() => new PEReader(s, PEStreamOptions.Default, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new PEReader(s, PEStreamOptions.Default, 1));
}
[Fact]
public unsafe void Ctor_Loaded()
{
byte b = 1;
Assert.True(new PEReader(&b, 1, isLoadedImage: true).IsLoadedImage);
Assert.False(new PEReader(&b, 1, isLoadedImage: false).IsLoadedImage);
Assert.True(new PEReader(new MemoryStream(), PEStreamOptions.IsLoadedImage).IsLoadedImage);
Assert.False(new PEReader(new MemoryStream()).IsLoadedImage);
}
[Fact]
public void FromEmptyStream()
{
Assert.Throws<BadImageFormatException>(() => new PEReader(new MemoryStream(), PEStreamOptions.PrefetchMetadata));
Assert.Throws<BadImageFormatException>(() => new PEReader(new MemoryStream(), PEStreamOptions.PrefetchMetadata | PEStreamOptions.PrefetchEntireImage));
}
[Fact(Skip = "https://github.com/dotnet/corefx/issues/7996")]
[ActiveIssue(7996)]
public void SubStream()
{
var stream = new MemoryStream();
stream.WriteByte(0xff);
stream.Write(Misc.Members, 0, Misc.Members.Length);
stream.WriteByte(0xff);
stream.WriteByte(0xff);
stream.Position = 1;
var peReader1 = new PEReader(stream, PEStreamOptions.LeaveOpen, Misc.Members.Length);
Assert.Equal(Misc.Members.Length, peReader1.GetEntireImage().Length);
peReader1.GetMetadataReader();
stream.Position = 1;
var peReader2 = new PEReader(stream, PEStreamOptions.LeaveOpen | PEStreamOptions.PrefetchMetadata, Misc.Members.Length);
Assert.Equal(Misc.Members.Length, peReader2.GetEntireImage().Length);
peReader2.GetMetadataReader();
stream.Position = 1;
var peReader3 = new PEReader(stream, PEStreamOptions.LeaveOpen | PEStreamOptions.PrefetchEntireImage, Misc.Members.Length);
Assert.Equal(Misc.Members.Length, peReader3.GetEntireImage().Length);
peReader3.GetMetadataReader();
}
// TODO: Switch to small checked in native image.
/*
[Fact]
public void OpenNativeImage()
{
using (var reader = new PEReader(File.OpenRead(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "kernel32.dll"))))
{
Assert.False(reader.HasMetadata);
Assert.True(reader.PEHeaders.IsDll);
Assert.False(reader.PEHeaders.IsExe);
Assert.Throws<InvalidOperationException>(() => reader.GetMetadataReader());
}
}
*/
[Fact]
public void IL_LazyLoad()
{
var peStream = new MemoryStream(Misc.Members);
using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen))
{
var md = reader.GetMetadataReader();
var il = reader.GetMethodBody(md.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1)).RelativeVirtualAddress);
Assert.Equal(new byte[] { 0, 42 }, il.GetILBytes());
Assert.Equal(8, il.MaxStack);
}
}
[Fact]
public void IL_EagerLoad()
{
var peStream = new MemoryStream(Misc.Members);
using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen | PEStreamOptions.PrefetchMetadata | PEStreamOptions.PrefetchEntireImage))
{
var md = reader.GetMetadataReader();
var il = reader.GetMethodBody(md.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1)).RelativeVirtualAddress);
Assert.Equal(new byte[] { 0, 42 }, il.GetILBytes());
Assert.Equal(8, il.MaxStack);
}
}
[Fact]
public void Metadata_LazyLoad()
{
var peStream = new MemoryStream(Misc.Members);
using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen))
{
var md = reader.GetMetadataReader();
var method = md.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1));
Assert.Equal("MC1", md.GetString(method.Name));
}
}
[Fact]
public void Metadata_EagerLoad()
{
var peStream = new MemoryStream(Misc.Members);
using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen | PEStreamOptions.PrefetchMetadata))
{
var md = reader.GetMetadataReader();
var method = md.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1));
Assert.Equal("MC1", md.GetString(method.Name));
Assert.Throws<InvalidOperationException>(() => reader.GetEntireImage());
Assert.Throws<InvalidOperationException>(() => reader.GetMethodBody(method.RelativeVirtualAddress));
}
}
[Fact]
public void EntireImage_LazyLoad()
{
var peStream = new MemoryStream(Misc.Members);
using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen))
{
Assert.Equal(4608, reader.GetEntireImage().Length);
}
}
[Fact]
public void EntireImage_EagerLoad()
{
var peStream = new MemoryStream(Misc.Members);
using (var reader = new PEReader(peStream, PEStreamOptions.LeaveOpen | PEStreamOptions.PrefetchMetadata | PEStreamOptions.PrefetchEntireImage))
{
Assert.Equal(4608, reader.GetEntireImage().Length);
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void GetMethodBody_Loaded()
{
LoaderUtilities.LoadPEAndValidate(Misc.Members, reader =>
{
var md = reader.GetMetadataReader();
var il = reader.GetMethodBody(md.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1)).RelativeVirtualAddress);
Assert.Equal(new byte[] { 0, 42 }, il.GetILBytes());
Assert.Equal(8, il.MaxStack);
});
}
[Fact]
public void GetSectionData()
{
var peStream = new MemoryStream(Misc.Members);
using (var reader = new PEReader(peStream))
{
ValidateSectionData(reader);
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void GetSectionData_Loaded()
{
LoaderUtilities.LoadPEAndValidate(Misc.Members, ValidateSectionData);
}
private unsafe void ValidateSectionData(PEReader reader)
{
var relocBlob1 = reader.GetSectionData(".reloc").GetContent();
var relocBlob2 = reader.GetSectionData(0x6000).GetContent();
AssertEx.Equal(new byte[]
{
0x00, 0x20, 0x00, 0x00,
0x0C, 0x00, 0x00, 0x00,
0xD0, 0x38, 0x00, 0x00
}, relocBlob1);
AssertEx.Equal(relocBlob1, relocBlob2);
var data = reader.GetSectionData(0x5fff);
Assert.True(data.Pointer == null);
Assert.Equal(0, data.Length);
AssertEx.Equal(new byte[0], data.GetContent());
data = reader.GetSectionData(0x600B);
Assert.True(data.Pointer != null);
Assert.Equal(1, data.Length);
AssertEx.Equal(new byte[] { 0x00 }, data.GetContent());
data = reader.GetSectionData(0x600C);
Assert.True(data.Pointer == null);
Assert.Equal(0, data.Length);
AssertEx.Equal(new byte[0], data.GetContent());
data = reader.GetSectionData(0x600D);
Assert.True(data.Pointer == null);
Assert.Equal(0, data.Length);
AssertEx.Equal(new byte[0], data.GetContent());
data = reader.GetSectionData(int.MaxValue);
Assert.True(data.Pointer == null);
Assert.Equal(0, data.Length);
AssertEx.Equal(new byte[0], data.GetContent());
data = reader.GetSectionData(".nonexisting");
Assert.True(data.Pointer == null);
Assert.Equal(0, data.Length);
AssertEx.Equal(new byte[0], data.GetContent());
data = reader.GetSectionData("");
Assert.True(data.Pointer == null);
Assert.Equal(0, data.Length);
AssertEx.Equal(new byte[0], data.GetContent());
}
[Fact]
public void GetSectionData_Errors()
{
var peStream = new MemoryStream(Misc.Members);
using (var reader = new PEReader(peStream))
{
Assert.Throws<ArgumentNullException>(() => reader.GetSectionData(null));
Assert.Throws<ArgumentOutOfRangeException>(() => reader.GetSectionData(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => reader.GetSectionData(int.MinValue));
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_Args()
{
var peStream = new MemoryStream(PortablePdbs.DocumentsDll);
using (var reader = new PEReader(peStream))
{
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.False(reader.TryOpenAssociatedPortablePdb(@"b.dll", _ => null, out pdbProvider, out pdbPath));
Assert.Throws<ArgumentNullException>(() => reader.TryOpenAssociatedPortablePdb(@"b.dll", null, out pdbProvider, out pdbPath));
Assert.Throws<ArgumentNullException>(() => reader.TryOpenAssociatedPortablePdb(null, _ => null, out pdbProvider, out pdbPath));
Assert.Throws<ArgumentException>("peImagePath", () => reader.TryOpenAssociatedPortablePdb("C:\\a\\\0\\b", _ => null, out pdbProvider, out pdbPath));
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_CollocatedFile()
{
var peStream = new MemoryStream(PortablePdbs.DocumentsDll);
using (var reader = new PEReader(peStream))
{
string pathQueried = null;
Func<string, Stream> streamProvider = p =>
{
Assert.Null(pathQueried);
pathQueried = p;
return new MemoryStream(PortablePdbs.DocumentsPdb);
};
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath));
Assert.Equal(Path.Combine("pedir", "Documents.pdb"), pathQueried);
Assert.Equal(Path.Combine("pedir", "Documents.pdb"), pdbPath);
var pdbReader = pdbProvider.GetMetadataReader();
Assert.Equal(13, pdbReader.Documents.Count);
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_Embedded()
{
var peStream = new MemoryStream(PortablePdbs.DocumentsEmbeddedDll);
using (var reader = new PEReader(peStream))
{
string pathQueried = null;
Func<string, Stream> streamProvider = p =>
{
Assert.Null(pathQueried);
pathQueried = p;
return null;
};
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath));
Assert.Equal(Path.Combine("pedir", "Documents.Embedded.pdb"), pathQueried);
Assert.Null(pdbPath);
var pdbReader = pdbProvider.GetMetadataReader();
Assert.Equal(13, pdbReader.Documents.Count);
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_EmbeddedOnly()
{
var peStream = new MemoryStream(PortablePdbs.DocumentsEmbeddedDll);
using (var reader = new PEReader(peStream))
{
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.True(reader.TryOpenAssociatedPortablePdb(@"x", _ => null, out pdbProvider, out pdbPath));
Assert.Null(pdbPath);
var pdbReader = pdbProvider.GetMetadataReader();
Assert.Equal(13, pdbReader.Documents.Count);
}
}
[Fact]
public unsafe void TryOpenAssociatedPortablePdb_EmbeddedUnused()
{
var peStream = new MemoryStream(PortablePdbs.DocumentsEmbeddedDll);
using (var reader = new PEReader(peStream))
{
var embeddedReader = reader.ReadEmbeddedPortablePdbDebugDirectoryData(reader.ReadDebugDirectory()[2]).GetMetadataReader();
var embeddedBytes = new BlobReader(embeddedReader.MetadataPointer, embeddedReader.MetadataLength).ReadBytes(embeddedReader.MetadataLength);
string pathQueried = null;
Func<string, Stream> streamProvider = p =>
{
Assert.Null(pathQueried);
pathQueried = p;
return new MemoryStream(embeddedBytes);
};
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath));
Assert.Equal(Path.Combine("pedir", "Documents.Embedded.pdb"), pathQueried);
Assert.Equal(Path.Combine("pedir", "Documents.Embedded.pdb"), pdbPath);
var pdbReader = pdbProvider.GetMetadataReader();
Assert.Equal(13, pdbReader.Documents.Count);
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_UnixStylePath()
{
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"/abc/def.xyz", id, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
string pathQueried = null;
Func<string, Stream> streamProvider = p =>
{
Assert.Null(pathQueried);
pathQueried = p;
return null;
};
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.False(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath));
Assert.Equal(Path.Combine("pedir", "def.xyz"), pathQueried);
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_WindowsSpecificPath()
{
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"C:def.xyz", id, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
string pathQueried = null;
Func<string, Stream> streamProvider = p =>
{
Assert.Null(pathQueried);
pathQueried = p;
return null;
};
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.False(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath));
Assert.Equal(Path.Combine("pedir", "def.xyz"), pathQueried);
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_WindowsInvalidCharacters()
{
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"/a/*/c*.pdb", id, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
string pathQueried = null;
Func<string, Stream> streamProvider = p =>
{
Assert.Null(pathQueried);
pathQueried = p;
return null;
};
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.False(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath));
Assert.Equal(PathUtilities.CombinePathWithRelativePath("pedir", "c*.pdb"), pathQueried);
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_DuplicateEntries_CodeView()
{
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0);
ddBuilder.AddReproducibleEntry();
ddBuilder.AddCodeViewEntry(@"/a/b/c.pdb", id, portablePdbVersion: 0x0100);
ddBuilder.AddCodeViewEntry(@"/a/b/d.pdb", id, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
string pathQueried = null;
Func<string, Stream> streamProvider = p =>
{
Assert.Null(pathQueried);
pathQueried = p;
return null;
};
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.False(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath));
Assert.Equal(PathUtilities.CombinePathWithRelativePath("pedir", "c.pdb"), pathQueried);
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_DuplicateEntries_Embedded()
{
var pdbBuilder1 = new BlobBuilder();
pdbBuilder1.WriteBytes(PortablePdbs.DocumentsPdb);
var pdbBuilder2 = new BlobBuilder();
pdbBuilder2.WriteByte(1);
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0x0100);
ddBuilder.AddReproducibleEntry();
ddBuilder.AddEmbeddedPortablePdbEntry(pdbBuilder1, portablePdbVersion: 0x0100);
ddBuilder.AddEmbeddedPortablePdbEntry(pdbBuilder2, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
string pathQueried = null;
Func<string, Stream> streamProvider = p =>
{
Assert.Null(pathQueried);
pathQueried = p;
return null;
};
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath));
Assert.Equal(PathUtilities.CombinePathWithRelativePath("pedir", "a.pdb"), pathQueried);
Assert.Null(pdbPath);
Assert.Equal(13, pdbProvider.GetMetadataReader().Documents.Count);
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_CodeViewVsEmbedded_NonMatchingPdbId()
{
var pdbBuilder = new BlobBuilder();
pdbBuilder.WriteBytes(PortablePdbs.DocumentsPdb);
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0x0100);
ddBuilder.AddEmbeddedPortablePdbEntry(pdbBuilder, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
string pathQueried = null;
Func<string, Stream> streamProvider = p =>
{
Assert.Null(pathQueried);
pathQueried = p;
// Doesn't match the id
return new MemoryStream(PortablePdbs.DocumentsPdb);
};
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath));
Assert.Null(pdbPath);
Assert.Equal(PathUtilities.CombinePathWithRelativePath("pedir", "a.pdb"), pathQueried);
Assert.Equal(13, pdbProvider.GetMetadataReader().Documents.Count);
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_BadPdbFile_FallbackToEmbedded()
{
var pdbBuilder = new BlobBuilder();
pdbBuilder.WriteBytes(PortablePdbs.DocumentsPdb);
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0x0100);
ddBuilder.AddEmbeddedPortablePdbEntry(pdbBuilder, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
string pathQueried = null;
Func<string, Stream> streamProvider = p =>
{
Assert.Null(pathQueried);
pathQueried = p;
// Bad PDB
return new MemoryStream(new byte[] { 0x01 });
};
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), streamProvider, out pdbProvider, out pdbPath));
Assert.Null(pdbPath);
Assert.Equal(PathUtilities.CombinePathWithRelativePath("pedir", "a.pdb"), pathQueried);
Assert.Equal(13, pdbProvider.GetMetadataReader().Documents.Count);
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_ExpectedExceptionFromStreamProvider_FallbackOnEmbedded_Valid()
{
var pdbBuilder = new BlobBuilder();
pdbBuilder.WriteBytes(PortablePdbs.DocumentsPdb);
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0x0100);
ddBuilder.AddEmbeddedPortablePdbEntry(pdbBuilder, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new IOException(); }, out pdbProvider, out pdbPath));
Assert.Null(pdbPath);
Assert.Equal(13, pdbProvider.GetMetadataReader().Documents.Count);
Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new BadImageFormatException(); }, out pdbProvider, out pdbPath));
Assert.Null(pdbPath);
Assert.Equal(13, pdbProvider.GetMetadataReader().Documents.Count);
Assert.True(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new FileNotFoundException(); }, out pdbProvider, out pdbPath));
Assert.Null(pdbPath);
Assert.Equal(13, pdbProvider.GetMetadataReader().Documents.Count);
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_ExpectedExceptionFromStreamProvider_FallbackOnEmbedded_Invalid()
{
var pdbBuilder = new BlobBuilder();
pdbBuilder.WriteBytes(new byte[] { 0x01 });
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0x0100);
ddBuilder.AddEmbeddedPortablePdbEntry(pdbBuilder, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
MetadataReaderProvider pdbProvider;
string pdbPath;
// reports the first error:
Assert.Throws<IOException>(() =>
reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new IOException(); }, out pdbProvider, out pdbPath));
// reports the first error:
AssertEx.Throws<BadImageFormatException>(() =>
reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new BadImageFormatException("Bang!"); }, out pdbProvider, out pdbPath),
e => Assert.Equal("Bang!", e.Message));
// file doesn't exist, fall back to embedded without reporting FileNotFoundExeception
Assert.Throws<BadImageFormatException>(() =>
reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new FileNotFoundException(); }, out pdbProvider, out pdbPath));
Assert.Throws<BadImageFormatException>(() =>
reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => null, out pdbProvider, out pdbPath));
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_ExpectedExceptionFromStreamProvider_NoFallback()
{
var pdbBuilder = new BlobBuilder();
pdbBuilder.WriteBytes(PortablePdbs.DocumentsPdb);
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.Throws<IOException>(() =>
reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new IOException(); }, out pdbProvider, out pdbPath));
AssertEx.Throws<BadImageFormatException>(() =>
reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new BadImageFormatException("Bang!"); }, out pdbProvider, out pdbPath),
e => Assert.Equal("Bang!", e.Message));
// file doesn't exist and no embedded => return false
Assert.False(reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new FileNotFoundException(); }, out pdbProvider, out pdbPath));
}
}
[Fact]
public void TryOpenAssociatedPortablePdb_BadStreamProvider()
{
var pdbBuilder = new BlobBuilder();
pdbBuilder.WriteBytes(PortablePdbs.DocumentsPdb);
var id = new BlobContentId(Guid.Parse("18091B06-32BB-46C2-9C3B-7C9389A2F6C6"), 0x12345678);
var ddBuilder = new DebugDirectoryBuilder();
ddBuilder.AddCodeViewEntry(@"/a/b/a.pdb", id, portablePdbVersion: 0x0100);
var peStream = new MemoryStream(TestBuilders.BuildPEWithDebugDirectory(ddBuilder));
using (var reader = new PEReader(peStream))
{
MetadataReaderProvider pdbProvider;
string pdbPath;
// pass-thru:
Assert.Throws<ArgumentException>(() =>
reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { throw new ArgumentException(); }, out pdbProvider, out pdbPath));
Assert.Throws<InvalidOperationException>(() =>
reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { return new TestStream(canRead: false, canWrite: true, canSeek: true); }, out pdbProvider, out pdbPath));
Assert.Throws<InvalidOperationException>(() =>
reader.TryOpenAssociatedPortablePdb(Path.Combine("pedir", "file.exe"), _ => { return new TestStream(canRead: true, canWrite: true, canSeek: false); }, out pdbProvider, out pdbPath));
}
}
[Fact]
public void Dispose()
{
var peStream = new MemoryStream(PortablePdbs.DocumentsEmbeddedDll);
var reader = new PEReader(peStream);
MetadataReaderProvider pdbProvider;
string pdbPath;
Assert.True(reader.TryOpenAssociatedPortablePdb(@"x", _ => null, out pdbProvider, out pdbPath));
Assert.NotNull(pdbProvider);
Assert.Null(pdbPath);
var ddEntries = reader.ReadDebugDirectory();
var ddCodeView = ddEntries[0];
var ddEmbedded = ddEntries[2];
var embeddedPdbProvider = reader.ReadEmbeddedPortablePdbDebugDirectoryData(ddEmbedded);
// dispose the PEReader:
reader.Dispose();
Assert.False(reader.IsEntireImageAvailable);
Assert.Throws<ObjectDisposedException>(() => reader.PEHeaders);
Assert.Throws<ObjectDisposedException>(() => reader.HasMetadata);
Assert.Throws<ObjectDisposedException>(() => reader.GetMetadata());
Assert.Throws<ObjectDisposedException>(() => reader.GetSectionData(1000));
Assert.Throws<ObjectDisposedException>(() => reader.GetMetadataReader());
Assert.Throws<ObjectDisposedException>(() => reader.GetMethodBody(0));
Assert.Throws<ObjectDisposedException>(() => reader.GetEntireImage());
Assert.Throws<ObjectDisposedException>(() => reader.ReadDebugDirectory());
Assert.Throws<ObjectDisposedException>(() => reader.ReadCodeViewDebugDirectoryData(ddCodeView));
Assert.Throws<ObjectDisposedException>(() => reader.ReadEmbeddedPortablePdbDebugDirectoryData(ddEmbedded));
MetadataReaderProvider __;
string ___;
Assert.Throws<ObjectDisposedException>(() => reader.TryOpenAssociatedPortablePdb(@"x", _ => null, out __, out ___));
// ok to use providers after PEReader disposed:
var pdbReader = pdbProvider.GetMetadataReader();
Assert.Equal(13, pdbReader.Documents.Count);
pdbReader = embeddedPdbProvider.GetMetadataReader();
Assert.Equal(13, pdbReader.Documents.Count);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using SuperSocket.Channel;
using SuperSocket.ProtoBase;
namespace SuperSocket.Server
{
public class AppSession : IAppSession, ILogger, ILoggerAccessor
{
private IChannel _channel;
protected internal IChannel Channel
{
get { return _channel; }
}
public AppSession()
{
}
void IAppSession.Initialize(IServerInfo server, IChannel channel)
{
if (channel is IChannelWithSessionIdentifier channelWithSessionIdentifier)
SessionID = channelWithSessionIdentifier.SessionIdentifier;
else
SessionID = Guid.NewGuid().ToString();
Server = server;
StartTime = DateTimeOffset.Now;
_channel = channel;
State = SessionState.Initialized;
}
public string SessionID { get; private set; }
public DateTimeOffset StartTime { get; private set; }
public SessionState State { get; private set; } = SessionState.None;
public IServerInfo Server { get; private set; }
IChannel IAppSession.Channel
{
get { return _channel; }
}
public object DataContext { get; set; }
public EndPoint RemoteEndPoint
{
get { return _channel?.RemoteEndPoint; }
}
public EndPoint LocalEndPoint
{
get { return _channel?.LocalEndPoint; }
}
public DateTimeOffset LastActiveTime
{
get { return _channel?.LastActiveTime ?? DateTimeOffset.MinValue; }
}
public event AsyncEventHandler Connected;
public event AsyncEventHandler<CloseEventArgs> Closed;
private Dictionary<object, object> _items;
public object this[object name]
{
get
{
var items = _items;
if (items == null)
return null;
object value;
if (items.TryGetValue(name, out value))
return value;
return null;
}
set
{
lock (this)
{
var items = _items;
if (items == null)
items = _items = new Dictionary<object, object>();
items[name] = value;
}
}
}
protected virtual ValueTask OnSessionClosedAsync(CloseEventArgs e)
{
return new ValueTask();
}
internal async ValueTask FireSessionClosedAsync(CloseEventArgs e)
{
State = SessionState.Closed;
await OnSessionClosedAsync(e);
var closeEventHandler = Closed;
if (closeEventHandler == null)
return;
await closeEventHandler.Invoke(this, e);
}
protected virtual ValueTask OnSessionConnectedAsync()
{
return new ValueTask();
}
internal async ValueTask FireSessionConnectedAsync()
{
State = SessionState.Connected;
await OnSessionConnectedAsync();
var connectedEventHandler = Connected;
if (connectedEventHandler == null)
return;
await connectedEventHandler.Invoke(this, EventArgs.Empty);
}
ValueTask IAppSession.SendAsync(ReadOnlyMemory<byte> data)
{
return _channel.SendAsync(data);
}
ValueTask IAppSession.SendAsync<TPackage>(IPackageEncoder<TPackage> packageEncoder, TPackage package)
{
return _channel.SendAsync(packageEncoder, package);
}
void IAppSession.Reset()
{
ClearEvent(ref Connected);
ClearEvent(ref Closed);
_items?.Clear();
State = SessionState.None;
_channel = null;
DataContext = null;
StartTime = default(DateTimeOffset);
Server = null;
Reset();
}
protected virtual void Reset()
{
}
private void ClearEvent<TEventHandler>(ref TEventHandler sessionEvent)
where TEventHandler : Delegate
{
if (sessionEvent == null)
return;
foreach (var handler in sessionEvent.GetInvocationList())
{
sessionEvent = Delegate.Remove(sessionEvent, handler) as TEventHandler;
}
}
public virtual async ValueTask CloseAsync()
{
await CloseAsync(CloseReason.LocalClosing);
}
public virtual async ValueTask CloseAsync(CloseReason reason)
{
var channel = Channel;
if (channel == null)
return;
try
{
await channel.CloseAsync(reason);
}
catch
{
}
}
#region ILogger
ILogger GetLogger()
{
return (Server as ILoggerAccessor).Logger;
}
void ILogger.Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
GetLogger().Log<TState>(logLevel, eventId, state, exception, (s, e) =>
{
return $"Session[{this.SessionID}]: {formatter(s, e)}";
});
}
bool ILogger.IsEnabled(LogLevel logLevel)
{
return GetLogger().IsEnabled(logLevel);
}
IDisposable ILogger.BeginScope<TState>(TState state)
{
return GetLogger().BeginScope<TState>(state);
}
public ILogger Logger => this as ILogger;
#endregion
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using gcoc = Google.Cloud.OsLogin.Common;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.OsLogin.V1Beta.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedOsLoginServiceClientTest
{
[xunit::FactAttribute]
public void DeletePosixAccountRequestObject()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeletePosixAccountRequest request = new DeletePosixAccountRequest
{
PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeletePosixAccount(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
client.DeletePosixAccount(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeletePosixAccountRequestObjectAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeletePosixAccountRequest request = new DeletePosixAccountRequest
{
PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeletePosixAccountAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
await client.DeletePosixAccountAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeletePosixAccountAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeletePosixAccount()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeletePosixAccountRequest request = new DeletePosixAccountRequest
{
PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeletePosixAccount(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
client.DeletePosixAccount(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeletePosixAccountAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeletePosixAccountRequest request = new DeletePosixAccountRequest
{
PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeletePosixAccountAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
await client.DeletePosixAccountAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeletePosixAccountAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeletePosixAccountResourceNames()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeletePosixAccountRequest request = new DeletePosixAccountRequest
{
PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeletePosixAccount(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
client.DeletePosixAccount(request.PosixAccountName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeletePosixAccountResourceNamesAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeletePosixAccountRequest request = new DeletePosixAccountRequest
{
PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeletePosixAccountAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
await client.DeletePosixAccountAsync(request.PosixAccountName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeletePosixAccountAsync(request.PosixAccountName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteSshPublicKeyRequestObject()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteSshPublicKey(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteSshPublicKeyRequestObjectAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteSshPublicKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteSshPublicKeyAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteSshPublicKey()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteSshPublicKey(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteSshPublicKeyAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteSshPublicKeyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteSshPublicKeyAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteSshPublicKeyResourceNames()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteSshPublicKey(request.SshPublicKeyName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteSshPublicKeyResourceNamesAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteSshPublicKeyAsync(request.SshPublicKeyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteSshPublicKeyAsync(request.SshPublicKeyName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetLoginProfileRequestObject()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetLoginProfileRequest request = new GetLoginProfileRequest
{
UserName = gcoc::UserName.FromUser("[USER]"),
ProjectId = "project_id43ad98b0",
SystemId = "system_id43548ac1",
};
LoginProfile expectedResponse = new LoginProfile
{
Name = "name1c9368b0",
PosixAccounts =
{
new gcoc::PosixAccount(),
},
SshPublicKeys =
{
{
"key8a0b6e3c",
new gcoc::SshPublicKey()
},
},
};
mockGrpcClient.Setup(x => x.GetLoginProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
LoginProfile response = client.GetLoginProfile(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetLoginProfileRequestObjectAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetLoginProfileRequest request = new GetLoginProfileRequest
{
UserName = gcoc::UserName.FromUser("[USER]"),
ProjectId = "project_id43ad98b0",
SystemId = "system_id43548ac1",
};
LoginProfile expectedResponse = new LoginProfile
{
Name = "name1c9368b0",
PosixAccounts =
{
new gcoc::PosixAccount(),
},
SshPublicKeys =
{
{
"key8a0b6e3c",
new gcoc::SshPublicKey()
},
},
};
mockGrpcClient.Setup(x => x.GetLoginProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<LoginProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
LoginProfile responseCallSettings = await client.GetLoginProfileAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
LoginProfile responseCancellationToken = await client.GetLoginProfileAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetLoginProfile()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetLoginProfileRequest request = new GetLoginProfileRequest
{
UserName = gcoc::UserName.FromUser("[USER]"),
};
LoginProfile expectedResponse = new LoginProfile
{
Name = "name1c9368b0",
PosixAccounts =
{
new gcoc::PosixAccount(),
},
SshPublicKeys =
{
{
"key8a0b6e3c",
new gcoc::SshPublicKey()
},
},
};
mockGrpcClient.Setup(x => x.GetLoginProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
LoginProfile response = client.GetLoginProfile(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetLoginProfileAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetLoginProfileRequest request = new GetLoginProfileRequest
{
UserName = gcoc::UserName.FromUser("[USER]"),
};
LoginProfile expectedResponse = new LoginProfile
{
Name = "name1c9368b0",
PosixAccounts =
{
new gcoc::PosixAccount(),
},
SshPublicKeys =
{
{
"key8a0b6e3c",
new gcoc::SshPublicKey()
},
},
};
mockGrpcClient.Setup(x => x.GetLoginProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<LoginProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
LoginProfile responseCallSettings = await client.GetLoginProfileAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
LoginProfile responseCancellationToken = await client.GetLoginProfileAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetLoginProfileResourceNames()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetLoginProfileRequest request = new GetLoginProfileRequest
{
UserName = gcoc::UserName.FromUser("[USER]"),
};
LoginProfile expectedResponse = new LoginProfile
{
Name = "name1c9368b0",
PosixAccounts =
{
new gcoc::PosixAccount(),
},
SshPublicKeys =
{
{
"key8a0b6e3c",
new gcoc::SshPublicKey()
},
},
};
mockGrpcClient.Setup(x => x.GetLoginProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
LoginProfile response = client.GetLoginProfile(request.UserName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetLoginProfileResourceNamesAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetLoginProfileRequest request = new GetLoginProfileRequest
{
UserName = gcoc::UserName.FromUser("[USER]"),
};
LoginProfile expectedResponse = new LoginProfile
{
Name = "name1c9368b0",
PosixAccounts =
{
new gcoc::PosixAccount(),
},
SshPublicKeys =
{
{
"key8a0b6e3c",
new gcoc::SshPublicKey()
},
},
};
mockGrpcClient.Setup(x => x.GetLoginProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<LoginProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
LoginProfile responseCallSettings = await client.GetLoginProfileAsync(request.UserName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
LoginProfile responseCancellationToken = await client.GetLoginProfileAsync(request.UserName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSshPublicKeyRequestObject()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetSshPublicKeyRequest request = new GetSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.GetSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey response = client.GetSshPublicKey(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSshPublicKeyRequestObjectAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetSshPublicKeyRequest request = new GetSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.GetSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey responseCallSettings = await client.GetSshPublicKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gcoc::SshPublicKey responseCancellationToken = await client.GetSshPublicKeyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSshPublicKey()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetSshPublicKeyRequest request = new GetSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.GetSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey response = client.GetSshPublicKey(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSshPublicKeyAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetSshPublicKeyRequest request = new GetSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.GetSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey responseCallSettings = await client.GetSshPublicKeyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gcoc::SshPublicKey responseCancellationToken = await client.GetSshPublicKeyAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSshPublicKeyResourceNames()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetSshPublicKeyRequest request = new GetSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.GetSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey response = client.GetSshPublicKey(request.SshPublicKeyName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSshPublicKeyResourceNamesAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
GetSshPublicKeyRequest request = new GetSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.GetSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey responseCallSettings = await client.GetSshPublicKeyAsync(request.SshPublicKeyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gcoc::SshPublicKey responseCancellationToken = await client.GetSshPublicKeyAsync(request.SshPublicKeyName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ImportSshPublicKeyRequestObject()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest
{
ParentAsUserName = gcoc::UserName.FromUser("[USER]"),
SshPublicKey = new gcoc::SshPublicKey(),
ProjectId = "project_id43ad98b0",
};
ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse
{
LoginProfile = new LoginProfile(),
};
mockGrpcClient.Setup(x => x.ImportSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
ImportSshPublicKeyResponse response = client.ImportSshPublicKey(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ImportSshPublicKeyRequestObjectAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest
{
ParentAsUserName = gcoc::UserName.FromUser("[USER]"),
SshPublicKey = new gcoc::SshPublicKey(),
ProjectId = "project_id43ad98b0",
};
ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse
{
LoginProfile = new LoginProfile(),
};
mockGrpcClient.Setup(x => x.ImportSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ImportSshPublicKeyResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
ImportSshPublicKeyResponse responseCallSettings = await client.ImportSshPublicKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ImportSshPublicKeyResponse responseCancellationToken = await client.ImportSshPublicKeyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ImportSshPublicKey1()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest
{
ParentAsUserName = gcoc::UserName.FromUser("[USER]"),
SshPublicKey = new gcoc::SshPublicKey(),
};
ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse
{
LoginProfile = new LoginProfile(),
};
mockGrpcClient.Setup(x => x.ImportSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
ImportSshPublicKeyResponse response = client.ImportSshPublicKey(request.Parent, request.SshPublicKey);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ImportSshPublicKey1Async()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest
{
ParentAsUserName = gcoc::UserName.FromUser("[USER]"),
SshPublicKey = new gcoc::SshPublicKey(),
};
ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse
{
LoginProfile = new LoginProfile(),
};
mockGrpcClient.Setup(x => x.ImportSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ImportSshPublicKeyResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
ImportSshPublicKeyResponse responseCallSettings = await client.ImportSshPublicKeyAsync(request.Parent, request.SshPublicKey, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ImportSshPublicKeyResponse responseCancellationToken = await client.ImportSshPublicKeyAsync(request.Parent, request.SshPublicKey, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ImportSshPublicKey1ResourceNames()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest
{
ParentAsUserName = gcoc::UserName.FromUser("[USER]"),
SshPublicKey = new gcoc::SshPublicKey(),
};
ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse
{
LoginProfile = new LoginProfile(),
};
mockGrpcClient.Setup(x => x.ImportSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
ImportSshPublicKeyResponse response = client.ImportSshPublicKey(request.ParentAsUserName, request.SshPublicKey);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ImportSshPublicKey1ResourceNamesAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest
{
ParentAsUserName = gcoc::UserName.FromUser("[USER]"),
SshPublicKey = new gcoc::SshPublicKey(),
};
ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse
{
LoginProfile = new LoginProfile(),
};
mockGrpcClient.Setup(x => x.ImportSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ImportSshPublicKeyResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
ImportSshPublicKeyResponse responseCallSettings = await client.ImportSshPublicKeyAsync(request.ParentAsUserName, request.SshPublicKey, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ImportSshPublicKeyResponse responseCancellationToken = await client.ImportSshPublicKeyAsync(request.ParentAsUserName, request.SshPublicKey, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ImportSshPublicKey2()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest
{
ParentAsUserName = gcoc::UserName.FromUser("[USER]"),
SshPublicKey = new gcoc::SshPublicKey(),
ProjectId = "project_id43ad98b0",
};
ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse
{
LoginProfile = new LoginProfile(),
};
mockGrpcClient.Setup(x => x.ImportSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
ImportSshPublicKeyResponse response = client.ImportSshPublicKey(request.Parent, request.SshPublicKey, request.ProjectId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ImportSshPublicKey2Async()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest
{
ParentAsUserName = gcoc::UserName.FromUser("[USER]"),
SshPublicKey = new gcoc::SshPublicKey(),
ProjectId = "project_id43ad98b0",
};
ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse
{
LoginProfile = new LoginProfile(),
};
mockGrpcClient.Setup(x => x.ImportSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ImportSshPublicKeyResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
ImportSshPublicKeyResponse responseCallSettings = await client.ImportSshPublicKeyAsync(request.Parent, request.SshPublicKey, request.ProjectId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ImportSshPublicKeyResponse responseCancellationToken = await client.ImportSshPublicKeyAsync(request.Parent, request.SshPublicKey, request.ProjectId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ImportSshPublicKey2ResourceNames()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest
{
ParentAsUserName = gcoc::UserName.FromUser("[USER]"),
SshPublicKey = new gcoc::SshPublicKey(),
ProjectId = "project_id43ad98b0",
};
ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse
{
LoginProfile = new LoginProfile(),
};
mockGrpcClient.Setup(x => x.ImportSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
ImportSshPublicKeyResponse response = client.ImportSshPublicKey(request.ParentAsUserName, request.SshPublicKey, request.ProjectId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ImportSshPublicKey2ResourceNamesAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest
{
ParentAsUserName = gcoc::UserName.FromUser("[USER]"),
SshPublicKey = new gcoc::SshPublicKey(),
ProjectId = "project_id43ad98b0",
};
ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse
{
LoginProfile = new LoginProfile(),
};
mockGrpcClient.Setup(x => x.ImportSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ImportSshPublicKeyResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
ImportSshPublicKeyResponse responseCallSettings = await client.ImportSshPublicKeyAsync(request.ParentAsUserName, request.SshPublicKey, request.ProjectId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ImportSshPublicKeyResponse responseCancellationToken = await client.ImportSshPublicKeyAsync(request.ParentAsUserName, request.SshPublicKey, request.ProjectId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateSshPublicKeyRequestObject()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
SshPublicKey = new gcoc::SshPublicKey(),
UpdateMask = new wkt::FieldMask(),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.UpdateSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey response = client.UpdateSshPublicKey(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateSshPublicKeyRequestObjectAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
SshPublicKey = new gcoc::SshPublicKey(),
UpdateMask = new wkt::FieldMask(),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.UpdateSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey responseCallSettings = await client.UpdateSshPublicKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gcoc::SshPublicKey responseCancellationToken = await client.UpdateSshPublicKeyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateSshPublicKey1()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
SshPublicKey = new gcoc::SshPublicKey(),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.UpdateSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey response = client.UpdateSshPublicKey(request.Name, request.SshPublicKey);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateSshPublicKey1Async()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
SshPublicKey = new gcoc::SshPublicKey(),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.UpdateSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey responseCallSettings = await client.UpdateSshPublicKeyAsync(request.Name, request.SshPublicKey, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gcoc::SshPublicKey responseCancellationToken = await client.UpdateSshPublicKeyAsync(request.Name, request.SshPublicKey, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateSshPublicKey1ResourceNames()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
SshPublicKey = new gcoc::SshPublicKey(),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.UpdateSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey response = client.UpdateSshPublicKey(request.SshPublicKeyName, request.SshPublicKey);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateSshPublicKey1ResourceNamesAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
SshPublicKey = new gcoc::SshPublicKey(),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.UpdateSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey responseCallSettings = await client.UpdateSshPublicKeyAsync(request.SshPublicKeyName, request.SshPublicKey, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gcoc::SshPublicKey responseCancellationToken = await client.UpdateSshPublicKeyAsync(request.SshPublicKeyName, request.SshPublicKey, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateSshPublicKey2()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
SshPublicKey = new gcoc::SshPublicKey(),
UpdateMask = new wkt::FieldMask(),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.UpdateSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey response = client.UpdateSshPublicKey(request.Name, request.SshPublicKey, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateSshPublicKey2Async()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
SshPublicKey = new gcoc::SshPublicKey(),
UpdateMask = new wkt::FieldMask(),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.UpdateSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey responseCallSettings = await client.UpdateSshPublicKeyAsync(request.Name, request.SshPublicKey, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gcoc::SshPublicKey responseCancellationToken = await client.UpdateSshPublicKeyAsync(request.Name, request.SshPublicKey, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateSshPublicKey2ResourceNames()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
SshPublicKey = new gcoc::SshPublicKey(),
UpdateMask = new wkt::FieldMask(),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.UpdateSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey response = client.UpdateSshPublicKey(request.SshPublicKeyName, request.SshPublicKey, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateSshPublicKey2ResourceNamesAsync()
{
moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict);
UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest
{
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
SshPublicKey = new gcoc::SshPublicKey(),
UpdateMask = new wkt::FieldMask(),
};
gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey
{
Key = "key8a0b6e3c",
ExpirationTimeUsec = -3860803259883837145L,
Fingerprint = "fingerprint009e6052",
SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"),
};
mockGrpcClient.Setup(x => x.UpdateSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null));
OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null);
gcoc::SshPublicKey responseCallSettings = await client.UpdateSshPublicKeyAsync(request.SshPublicKeyName, request.SshPublicKey, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gcoc::SshPublicKey responseCancellationToken = await client.UpdateSshPublicKeyAsync(request.SshPublicKeyName, request.SshPublicKey, request.UpdateMask, 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;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Reflection.Runtime.General;
using System.Reflection.Runtime.Assemblies;
namespace System.Reflection.Runtime.TypeParsing
{
//
// String tokenizer for typenames passed to the GetType() api's.
//
internal sealed class TypeLexer
{
public TypeLexer(String s)
{
// Turn the string into a char array with a NUL terminator.
char[] chars = new char[s.Length + 1];
s.CopyTo(0, chars, 0, s.Length);
_chars = chars;
_index = 0;
}
public TokenType Peek
{
get
{
SkipWhiteSpace();
char c = _chars[_index];
return CharToToken(c);
}
}
public TokenType PeekSecond
{
get
{
SkipWhiteSpace();
int index = _index + 1;
while (Char.IsWhiteSpace(_chars[index]))
index++;
char c = _chars[index];
return CharToToken(c);
}
}
public void Skip()
{
Debug.Assert(_index != _chars.Length);
SkipWhiteSpace();
_index++;
}
// Return the next token and skip index past it unless already at end of string
// or the token is not a reserved token.
public TokenType GetNextToken()
{
TokenType tokenType = Peek;
if (tokenType == TokenType.End || tokenType == TokenType.Other)
return tokenType;
Skip();
return tokenType;
}
//
// Lex the next segment as part of a type name. (Do not use for assembly names.)
//
// Note that unescaped "."'s do NOT terminate the identifier, but unescaped "+"'s do.
//
// Terminated by the first non-escaped reserved character ('[', ']', '+', '&', '*' or ',')
//
public String GetNextIdentifier()
{
SkipWhiteSpace();
int src = _index;
char[] buffer = new char[_chars.Length];
int dst = 0;
for (;;)
{
char c = _chars[src];
TokenType token = CharToToken(c);
if (token != TokenType.Other)
break;
src++;
if (c == '\\')
{
c = _chars[src];
if (c != NUL)
src++;
if (!c.NeedsEscapingInTypeName())
{
// If we got here, a backslash was used to escape a character that is not legal to escape inside a type name.
//
// Common sense would dictate throwing an ArgumentException but that's not what the desktop CLR does.
// The desktop CLR treats this case by returning FALSE from TypeName::TypeNameParser::GetIdentifier().
// Unfortunately, no one checks this return result. Instead, the CLR keeps parsing (unfortunately, the lexer
// was left in some strange state by the previous failure but typically, this goes unnoticed) and eventually, tries to resolve
// a Type whose name is the empty string. When it can't resolve that type, the CLR throws a TypeLoadException()
// complaining about be unable to find a type with the empty name.
//
// To emulate this accidental behavior, we'll throw a special exception that's caught by the TypeParser.
//
throw new IllegalEscapeSequenceException();
}
}
buffer[dst++] = c;
}
_index = src;
return new String(buffer, 0, dst);
}
//
// Lex the next segment as the assembly name at the end of an assembly-qualified type name. (Do not use for
// assembly names embedded inside generic type arguments.)
//
// Terminated by NUL. There are no escape characters defined by the typename lexer (however, AssemblyName
// does have its own escape rules.)
//
public RuntimeAssemblyName GetNextAssemblyName()
{
SkipWhiteSpace();
int src = _index;
char[] buffer = new char[_chars.Length];
int dst = 0;
for (;;)
{
char c = _chars[src];
if (c == NUL)
break;
src++;
buffer[dst++] = c;
}
_index = src;
String fullName = new String(buffer, 0, dst);
return AssemblyNameParser.Parse(fullName);
}
//
// Lex the next segment as an assembly name embedded inside a generic argument type.
//
// Terminated by an unescaped ']'.
//
public RuntimeAssemblyName GetNextEmbeddedAssemblyName()
{
SkipWhiteSpace();
int src = _index;
char[] buffer = new char[_chars.Length];
int dst = 0;
for (;;)
{
char c = _chars[src];
if (c == NUL)
throw new ArgumentException();
if (c == ']')
break;
src++;
// Backslash can be used to escape a ']' - any other backslash character is left alone (along with the backslash)
// for the AssemblyName parser to handle.
if (c == '\\' && _chars[src] == ']')
{
c = _chars[src++];
}
buffer[dst++] = c;
}
_index = src;
String fullName = new String(buffer, 0, dst);
return AssemblyNameParser.Parse(fullName);
}
//
// Classify a character as a TokenType. (Fortunately, all tokens in typename strings other than identifiers are single-character tokens.)
//
private static TokenType CharToToken(char c)
{
switch (c)
{
case NUL:
return TokenType.End;
case '[':
return TokenType.OpenSqBracket;
case ']':
return TokenType.CloseSqBracket;
case ',':
return TokenType.Comma;
case '+':
return TokenType.Plus;
case '*':
return TokenType.Asterisk;
case '&':
return TokenType.Ampersand;
default:
return TokenType.Other;
}
}
//
// The desktop typename parser has a strange attitude towards whitespace. It throws away whitespace between punctuation tokens and whitespace
// preceeding identifiers or assembly names (and this cannot be escaped away). But whitespace between the end of an identifier
// and the punctuation that ends it is *not* ignored.
//
// In other words, GetType(" Foo") searches for "Foo" but GetType("Foo ") searches for "Foo ".
//
// Whitespace between the end of an assembly name and the punction mark that ends it is also not ignored by this parser,
// but this is irrelevant since the assembly name is then turned over to AssemblyName for parsing, which *does* ignore trailing whitespace.
//
private void SkipWhiteSpace()
{
while (Char.IsWhiteSpace(_chars[_index]))
_index++;
}
private int _index;
private readonly char[] _chars;
private const char NUL = (char)0;
public sealed class IllegalEscapeSequenceException : Exception
{
}
}
internal enum TokenType
{
End = 0, //At end of string
OpenSqBracket = 1, //'['
CloseSqBracket = 2, //']'
Comma = 3, //','
Plus = 4, //'+'
Asterisk = 5, //'*'
Ampersand = 6, //'&'
Other = 7, //Type identifier, AssemblyName or embedded AssemblyName.
}
}
| |
// This file is part of Wintermute Engine
// For conditions of distribution and use, see copyright notice in license.txt
// http://dead-code.org/redir.php?target=wme
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using DeadCode.WME.Core;
namespace DeadCode.WME.WindowEdit
{
public partial class WindowDoc
{
private Size GridSize
{
get
{
if (ParentForm as FrmMain != null) return ((FrmMain)ParentForm).GridSize;
else return new Size(0, 0);
}
}
private Color SelectionColor
{
get
{
if (ParentForm as FrmMain != null) return ((FrmMain)ParentForm).SelectionColor;
else return Color.Red;
}
}
private Color BoxColor
{
get
{
if (ParentForm as FrmMain != null) return ((FrmMain)ParentForm).BoxColor;
else return Color.FromArgb(100, 0, 0, 255);
}
}
private HotSpot CurrentSpot = null;
private bool IsResizing = false;
private bool IsMoving = false;
private bool IsAdding = false;
private bool IsAboutToAdd = false;
private bool UndoPending = false;
private Point StartPoint;
private Type ControlToAdd = null;
//////////////////////////////////////////////////////////////////////////
private void OnMouseDown(object sender, MouseEventArgs e)
{
if (Canvas == null) return;
if(e.Button==MouseButtons.Right)
{
CancelResizeMove();
return;
}
if (e.Button == MouseButtons.Left)
{
if (IsAboutToAdd)
{
DeselectAll();
IsAboutToAdd = false;
IsAdding = true;
StartPoint = new Point(e.X, e.Y);
if (GridSize.Width > 0)
StartPoint.X -= ((StartPoint.X + Canvas.HorizontalScroll.Value) % GridSize.Width);
if (GridSize.Height > 0)
StartPoint.Y -= ((StartPoint.Y + Canvas.VerticalScroll.Value) % GridSize.Height);
AddingRect = Rectangle.Empty;
return;
}
CurrentSpot = null;
for (int i = HotSpots.Count - 1; i >= 0; i--)
{
HotSpot Spot = HotSpots[i];
if (Spot.Rect.Contains(new Point(e.X, e.Y)))
{
CurrentSpot = Spot;
break;
}
}
if (CurrentSpot != null && CurrentSpot.Owner != null)
{
bool IsControl = (Control.ModifierKeys & Keys.Control) == Keys.Control;
bool IsShift = (Control.ModifierKeys & Keys.Shift) == Keys.Shift;
if (CurrentSpot.IsResize() && e.Button == MouseButtons.Left)
{
UndoPending = true;
IsResizing = true;
}
else
{
if (IsControl || IsShift)
{
CurrentSpot.Owner.EditorSelected = !CurrentSpot.Owner.EditorSelected;
if (CurrentSpot.Owner.EditorSelected) SetOrigPos(CurrentSpot.Owner);
}
else
{
if (!CurrentSpot.Owner.EditorSelected)
{
if (!(CurrentSpot.Owner is RectangleResizer)) DeselectAll();
CurrentSpot.Owner.EditorSelected = true;
SetOrigPos(CurrentSpot.Owner);
}
}
if (CurrentSpot.Owner.EditorSelected && e.Button == MouseButtons.Left)
{
if (RectResizer == null || RectResizer.Window != CurrentSpot.Owner as WUIWindow)
{
UndoPending = true;
IsMoving = true;
}
}
}
StartPoint = new Point(e.X, e.Y);
}
else
{
DeselectAll();
RectResizer = null;
}
RefreshTree(true);
// invoke selection changed
OnSelectionChanged(LayoutTree, new EventArgs());
}
}
//////////////////////////////////////////////////////////////////////////
private void OnMouseUp(object sender, MouseEventArgs e)
{
if (IsAdding)
{
CreateControl(ControlToAdd, AddingRect);
}
IsAdding = false;
IsResizing = false;
IsMoving = false;
CurrentSpot = null;
UndoPending = false;
UpdateScrollSize();
}
//////////////////////////////////////////////////////////////////////////
private void OnMouseMove(object sender, MouseEventArgs e)
{
if (Canvas == null) return;
if (IsAdding || IsAboutToAdd)
{
Canvas.Cursor = Cursors.Cross;
if (IsAdding)
{
Point EndPoint = new Point(e.X, e.Y);
if (GridSize.Width > 0)
EndPoint.X -= ((EndPoint.X + Canvas.HorizontalScroll.Value) % GridSize.Width);
if (GridSize.Height > 0)
EndPoint.Y -= ((EndPoint.Y + Canvas.VerticalScroll.Value) % GridSize.Height);
AddingRect = new Rectangle(StartPoint.X, StartPoint.Y, EndPoint.X - StartPoint.X, EndPoint.Y - StartPoint.Y);
UpdateScrollSize();
}
}
else if (IsMoving)
{
int MoveX = e.X - StartPoint.X;
int MoveY = e.Y - StartPoint.Y;
if (MoveX != 0 || MoveY != 0)
{
if (UndoPending)
{
SaveUndoState("Move control");
UndoPending = false;
}
foreach (IEditorResizable It in SelectedItems)
{
if (RectResizer != null && !(It is RectangleResizer)) continue;
// check if some of the parents is selected
if (It is WUIObject)
{
bool IsParentSelected = false;
WUIObject Parent = ((WUIObject)It).Parent;
while (Parent != null)
{
if (Parent.EditorSelected)
{
IsParentSelected = true;
break;
}
Parent = Parent.Parent;
}
if (IsParentSelected) continue;
}
It.X = It.OrigRect.X + MoveX;
It.Y = It.OrigRect.Y + MoveY;
if (GridSize.Width > 0)
It.X -= (It.X % GridSize.Width);
if (GridSize.Height > 0)
It.Y -= (It.Y % GridSize.Height);
}
RefreshProps = true;
UpdateScrollSize();
}
}
else if (IsResizing)
{
int DeltaX = e.X - StartPoint.X;
int DeltaY = e.Y - StartPoint.Y;
if (DeltaX != 0 || DeltaY != 0)
{
if (UndoPending)
{
SaveUndoState("Resize control");
UndoPending = false;
}
foreach (IEditorResizable It in SelectedItems)
{
if (RectResizer != null && !(It is RectangleResizer)) continue;
bool ChangeX = false;
bool ChangeY = false;
bool ChangeWidth = false;
bool ChangeHeight = false;
switch (CurrentSpot.Type)
{
case HotSpot.HotSpotType.ResizeE:
It.Width = It.OrigRect.Width + DeltaX;
ChangeWidth = true;
break;
case HotSpot.HotSpotType.ResizeW:
It.X = It.OrigRect.X + DeltaX;
ChangeX = true;
It.Width = It.OrigRect.Width - DeltaX;
ChangeWidth = true;
break;
case HotSpot.HotSpotType.ResizeS:
It.Height = It.OrigRect.Height + DeltaY;
ChangeHeight = true;
break;
case HotSpot.HotSpotType.ResizeN:
It.Y = It.OrigRect.Y + DeltaY;
ChangeY = true;
It.Height = It.OrigRect.Height - DeltaY;
ChangeHeight = true;
break;
case HotSpot.HotSpotType.ResizeSE:
It.Width = It.OrigRect.Width + DeltaX;
ChangeWidth = true;
It.Height = It.OrigRect.Height + DeltaY;
ChangeHeight = true;
break;
case HotSpot.HotSpotType.ResizeSW:
It.X = It.OrigRect.X + DeltaX;
ChangeX = true;
It.Width = It.OrigRect.Width - DeltaX;
ChangeWidth = true;
It.Height = It.OrigRect.Height + DeltaY;
ChangeHeight = true;
break;
case HotSpot.HotSpotType.ResizeNE:
It.Width = It.OrigRect.Width + DeltaX;
ChangeWidth = true;
It.Y = It.OrigRect.Y + DeltaY;
ChangeY = true;
It.Height = It.OrigRect.Height - DeltaY;
ChangeHeight = true;
break;
case HotSpot.HotSpotType.ResizeNW:
It.X = It.OrigRect.X + DeltaX;
ChangeX = true;
It.Width = It.OrigRect.Width - DeltaX;
ChangeWidth = true;
It.Y = It.OrigRect.Y + DeltaY;
ChangeY = true;
It.Height = It.OrigRect.Height - DeltaY;
ChangeHeight = true;
break;
}
if (ChangeWidth)
{
int OrigWidth = It.Width;
if (GridSize.Width > 0)
{
It.Width -= It.Width % GridSize.Width;
It.Width = Math.Max(It.Width, GridSize.Width);
}
else It.Width = Math.Max(It.Width, 10);
if (ChangeX) It.X += OrigWidth - It.Width;
}
if (ChangeHeight)
{
int OrigHeight = It.Height;
if (GridSize.Height > 0)
{
It.Height -= It.Height % GridSize.Height;
It.Height = Math.Max(It.Height, GridSize.Height);
}
else It.Width = Math.Max(It.Height, 10);
if (ChangeY) It.Y += OrigHeight - It.Height;
}
}
RefreshProps = true;
UpdateScrollSize();
}
}
else
{
for (int i = HotSpots.Count - 1; i >= 0; i--)
{
HotSpot Spot = HotSpots[i];
if (Spot.Rect.Contains(new Point(e.X, e.Y)))
{
switch (Spot.Type)
{
case HotSpot.HotSpotType.Container:
Canvas.Cursor = Cursors.Default;
break;
case HotSpot.HotSpotType.Control:
Canvas.Cursor = Cursors.SizeAll;
break;
case HotSpot.HotSpotType.ResizeE:
case HotSpot.HotSpotType.ResizeW:
Canvas.Cursor = Cursors.SizeWE;
break;
case HotSpot.HotSpotType.ResizeN:
case HotSpot.HotSpotType.ResizeS:
Canvas.Cursor = Cursors.SizeNS;
break;
case HotSpot.HotSpotType.ResizeNE:
case HotSpot.HotSpotType.ResizeSW:
Canvas.Cursor = Cursors.SizeNESW;
break;
case HotSpot.HotSpotType.ResizeNW:
case HotSpot.HotSpotType.ResizeSE:
Canvas.Cursor = Cursors.SizeNWSE;
break;
}
return;
}
}
Canvas.Cursor = Cursors.Default;
}
}
//////////////////////////////////////////////////////////////////////////
private void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
DeleteSelectedItems();
return;
}
else if (e.KeyCode == Keys.Escape)
{
CancelResizeMove();
}
// handle arrow keys
int MoveX = 0;
int MoveY = 0;
int ResizeX = 0;
int ResizeY = 0;
int Step = e.Control ? 5 : 1;
if (e.KeyCode == Keys.Left)
{
if (e.Shift) ResizeX = -Step;
else MoveX = -Step;
}
else if (e.KeyCode == Keys.Right)
{
if (e.Shift) ResizeX = Step;
else MoveX = Step;
}
else if (e.KeyCode == Keys.Up)
{
if (e.Shift) ResizeY = -Step;
else MoveY = -Step;
}
else if (e.KeyCode == Keys.Down)
{
if (e.Shift) ResizeY = Step;
else MoveY = Step;
}
else if (e.KeyCode == Keys.Space)
{
foreach (WUIObject It in SelectedItems)
{
It.Visible = !It.Visible;
}
RefreshProps = true;
UpdateScrollSize();
}
// keyboard movement
if(MoveX != 0 || MoveY != 0)
{
if (SelectedItems.Length > 0) SaveUndoState("Keyboard move");
foreach(IEditorResizable It in SelectedItems)
{
if (RectResizer != null && !(It is RectangleResizer)) continue;
// check if some of the parents is selected
if (It is WUIObject)
{
bool IsParentSelected = false;
WUIObject Parent = ((WUIObject)It).Parent;
while (Parent != null)
{
if (Parent.EditorSelected)
{
IsParentSelected = true;
break;
}
Parent = Parent.Parent;
}
if (IsParentSelected) continue;
}
It.X += MoveX;
It.Y += MoveY;
}
RefreshProps = true;
UpdateScrollSize();
}
// keyboard resize
if (ResizeX != 0 || ResizeY != 0)
{
if (SelectedItems.Length > 0) SaveUndoState("Keyboard resize");
foreach (IEditorResizable It in SelectedItems)
{
if (RectResizer != null && !(It is RectangleResizer)) continue;
if (It is WUIEntity) continue;
It.Width += ResizeX;
It.Height += ResizeY;
if (It.Width < 1) It.Width = 1;
if (It.Height < 1) It.Height = 1;
}
RefreshProps = true;
UpdateScrollSize();
}
}
//////////////////////////////////////////////////////////////////////////
private void CancelResizeMove()
{
if(IsMoving || IsResizing)
{
foreach (IEditorResizable It in SelectedItems)
{
if (RectResizer != null && !(It is RectangleResizer)) continue;
It.X = It.OrigRect.X;
It.Y = It.OrigRect.Y;
It.Width = It.OrigRect.Width;
It.Height = It.OrigRect.Height;
}
}
IsMoving = false;
IsResizing = false;
IsAdding = false;
IsAboutToAdd = false;
UndoPending = false;
RefreshProps = true;
UpdateScrollSize();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ResourceManager
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// </summary>
public partial class SubscriptionClient : ServiceClient<SubscriptionClient>, ISubscriptionClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Gets Azure subscription credentials.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Client Api Version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
public virtual ISubscriptionsOperations Subscriptions { get; private set; }
public virtual ITenantsOperations Tenants { get; private set; }
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SubscriptionClient(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SubscriptionClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SubscriptionClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SubscriptionClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SubscriptionClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SubscriptionClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SubscriptionClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SubscriptionClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.Subscriptions = new SubscriptionsOperations(this);
this.Tenants = new TenantsOperations(this);
this.BaseUri = new Uri("https://management.azure.com");
this.ApiVersion = "2015-11-01";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new ResourceJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings.Converters.Add(new ResourceJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics.CodeAnalysis;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Collections.Generic;
namespace System.Net.Http
{
public class HttpRequestMessage : IDisposable
{
private const int MessageNotYetSent = 0;
private const int MessageAlreadySent = 1;
// Track whether the message has been sent.
// The message shouldn't be sent again if this field is equal to MessageAlreadySent.
private int _sendStatus = MessageNotYetSent;
private HttpMethod _method;
private Uri _requestUri;
private HttpRequestHeaders _headers;
private Version _version;
private HttpContent _content;
private bool _disposed;
private IDictionary<String, Object> _properties;
public Version Version
{
get { return _version; }
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
CheckDisposed();
_version = value;
}
}
public HttpContent Content
{
get { return _content; }
set
{
CheckDisposed();
if (HttpEventSource.Log.IsEnabled())
{
if (value == null)
{
HttpEventSource.ContentNull(this);
}
else
{
HttpEventSource.Associate(this, value);
}
}
// It's OK to set a 'null' content, even if the method is POST/PUT.
_content = value;
}
}
public HttpMethod Method
{
get { return _method; }
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
CheckDisposed();
_method = value;
}
}
public Uri RequestUri
{
get { return _requestUri; }
set
{
if ((value != null) && (value.IsAbsoluteUri) && (!HttpUtilities.IsHttpUri(value)))
{
throw new ArgumentException(SR.net_http_client_http_baseaddress_required, "value");
}
CheckDisposed();
// It's OK to set 'null'. HttpClient will add the 'BaseAddress'. If there is no 'BaseAddress'
// sending this message will throw.
_requestUri = value;
}
}
public HttpRequestHeaders Headers
{
get
{
if (_headers == null)
{
_headers = new HttpRequestHeaders();
}
return _headers;
}
}
public IDictionary<String, Object> Properties
{
get
{
if (_properties == null)
{
_properties = new Dictionary<String, Object>();
}
return _properties;
}
}
public HttpRequestMessage()
: this(HttpMethod.Get, (Uri)null)
{
}
public HttpRequestMessage(HttpMethod method, Uri requestUri)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, ".ctor", "Method: " + method + ", Uri: '" + requestUri + "'");
InitializeValues(method, requestUri);
if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, ".ctor", null);
}
[SuppressMessage("Microsoft.Design", "CA1057:StringUriOverloadsCallSystemUriOverloads",
Justification = "It is OK to provide 'null' values. A Uri instance is created from 'requestUri' if it is != null.")]
public HttpRequestMessage(HttpMethod method, string requestUri)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, ".ctor", "Method: " + method + ", Uri: '" + requestUri + "'");
// It's OK to have a 'null' request Uri. If HttpClient is used, the 'BaseAddress' will be added.
// If there is no 'BaseAddress', sending this request message will throw.
// Note that we also allow the string to be empty: null and empty are considered equivalent.
if (string.IsNullOrEmpty(requestUri))
{
InitializeValues(method, null);
}
else
{
InitializeValues(method, new Uri(requestUri, UriKind.RelativeOrAbsolute));
}
if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, ".ctor", null);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("Method: ");
sb.Append(_method);
sb.Append(", RequestUri: '");
sb.Append(_requestUri == null ? "<null>" : _requestUri.ToString());
sb.Append("', Version: ");
sb.Append(_version);
sb.Append(", Content: ");
sb.Append(_content == null ? "<null>" : _content.GetType().ToString());
sb.Append(", Headers:\r\n");
sb.Append(HeaderUtilities.DumpHeaders(_headers, _content == null ? null : _content.Headers));
return sb.ToString();
}
private void InitializeValues(HttpMethod method, Uri requestUri)
{
if (method == null)
{
throw new ArgumentNullException("method");
}
if ((requestUri != null) && (requestUri.IsAbsoluteUri) && (!HttpUtilities.IsHttpUri(requestUri)))
{
throw new ArgumentException(SR.net_http_client_http_baseaddress_required, "requestUri");
}
_method = method;
_requestUri = requestUri;
_version = HttpUtilities.DefaultRequestVersion;
}
internal bool MarkAsSent()
{
return Interlocked.Exchange(ref _sendStatus, MessageAlreadySent) == MessageNotYetSent;
}
#region IDisposable Members
protected virtual void Dispose(bool disposing)
{
// The reason for this type to implement IDisposable is that it contains instances of types that implement
// IDisposable (content).
if (disposing && !_disposed)
{
_disposed = true;
if (_content != null)
{
_content.Dispose();
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(this.GetType().ToString());
}
}
}
}
| |
/***************************************************************************
* MassStorageDap.cs
*
* Copyright (C) 2006 Novell and Gabriel Burt
* Written by Gabriel Burt (gabriel.burt@gmail.com)
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* 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.IO;
using System.Collections;
using System.Collections.Generic;
using Hal;
using Banshee.Winforms;
using Banshee.Dap;
using Banshee.Base;
public static class PluginModuleEntry
{
public static Type [] GetTypes()
{
return new Type [] {
typeof(Banshee.Dap.MassStorage.MassStorageDap)
};
}
}
namespace Banshee.Dap.MassStorage
{
[DapProperties(DapType = DapType.Generic)]
public class MassStorageDap : Banshee.Dap.DapDevice
{
//private static Gnome.Vfs.VolumeMonitor monitor;
private static System.IO.FileSystemWatcher monitor;
static MassStorageDap()
{
/* if(!Gnome.Vfs.Vfs.Initialized) {
Gnome.Vfs.Vfs.Initialize();
}*/
//monitor = new FileSystemWatcher();// Gnome.Vfs.VolumeMonitor.Get();
//monitor.Changed += new FileSystemEventHandler(monitor_Changed);
}
static void monitor_Changed(object sender, FileSystemEventArgs e)
{
//throw new Exception("The method or operation is not implemented.");
}
private bool mounted = false, ui_initialized = false;
private List<TrackInfo> uncopiedTracks = new List<TrackInfo>();
protected Hal.Device usb_device = null;
protected Hal.Device player_device = null;
protected DriveInfo volume_device = null;
//protected Gnome.Vfs.Volume volume = null;
protected System.IO.DirectoryInfo volume = null;
public override InitializeResult Initialize(Hal.Device halDevice)
{
//volume_device = halDevice;
volume_device = new DriveInfo(halDevice.Udi);
player_device = halDevice;
/* try {
//volume_device.Parent;
usb_device = new Hal.Device(player_device["storage.physical_device"]);
} catch {
return InitializeResult.Invalid;
}
*/
if(volume_device.DriveType != DriveType.Removable) {
return InitializeResult.Invalid;
}
/*if(!volume_device.PropertyExists("volume.is_mounted") ||
!volume_device.GetPropertyBoolean("volume.is_mounted")) {
return WaitForVolumeMount(volume_device);
}*/
/*
if(player_device["portable_audio_player.type"] == "ipod") {
if(File.Exists(IsAudioPlayerPath)) {
LogCore.Instance.PushInformation(
"Mass Storage Support Loading iPod",
"The USB mass storage audio player support is loading an iPod because it has an .is_audio_player file. " +
"If you aren't running Rockbox or don't know what you're doing, things might not behave as expected.",
false);
} else {
LogCore.Instance.PushInformation(
"Mass Storage Support Ignoring iPod",
"The USB mass storage audio player support ignored an iPod. " +
"Either Banshee's iPod support is broken or missing, or the iPod itself may be corrupted.",
false);
return InitializeResult.Invalid;
}
}
*/
/*
// Detect player via HAL property or presence of .is_audo_player file in root
if(player_device["portable_audio_player.access_method"] != "storage" &&
!File.Exists(IsAudioPlayerPath)) {
return InitializeResult.Invalid;
}
*/
// Allow the HAL values to be overridden by corresponding key=value pairs in .is_audio_player
/* if(File.Exists(IsAudioPlayerPath)) {
StreamReader reader = null;
try {
reader = new StreamReader(IsAudioPlayerPath);
string line;
while((line = reader.ReadLine()) != null) {
string [] pieces = line.Split('=');
if(line.StartsWith("#") || pieces == null || pieces.Length != 2)
continue;
string key = pieces[0], val = pieces[1];
switch(key) {
case "audio_folders":
AudioFolders = val.Split(',');
break;
case "output_formats":
PlaybackFormats = val.Split(',');
break;
case "folder_depth":
FolderDepth = Int32.Parse(val);
break;
case "input_formats":
case "playlist_format":
case "playlist_path":
default:
Console.WriteLine("Unsupported key: {0}", key);
break;
}
}
} catch(Exception e) {
LogCore.Instance.PushWarning("Error parsing .is_audio_player file", e.ToString(), false);
} finally {
if(reader != null)
reader.Close();
}
}
*/
//volume = monitor.
/*if(volume == null) {
// Gnome VFS doesn't know volume is mounted yet
monitor.VolumeMounted += OnVolumeMounted;
is_read_only = true;
} else {
mounted = true;
is_read_only = volume.IsReadOnly;
}
*/
base.Initialize(player_device);
// Configure the extensions and mimetypes this DAP supports
List<string> extensions = new List<string>();
List<string> mimetypes = new List<string>();
foreach(string format in PlaybackFormats) {
string codec = Banshee.Dap.CodecType.GetCodec(format);
extensions.AddRange(CodecType.GetExtensions(codec));
mimetypes.AddRange(CodecType.GetMimeTypes(codec));
}
SupportedExtensions = extensions.ToArray();
SupportedPlaybackMimeTypes = mimetypes.ToArray();
// Install properties
/*
if(usb_device.PropertyExists("usb.vendor")) {
InstallProperty(Catalog.GetString("Vendor"), usb_device["usb.vendor"]);
} else if(player_device.PropertyExists("info.vendor")) {
InstallProperty(Catalog.GetString("Vendor"), player_device["info.vendor"]);
}
if(AudioFolders.Length > 1 || AudioFolders[0] != "") {
InstallProperty(String.Format(
Catalog.GetPluralString("Audio Folder", "Audio Folders", AudioFolders.Length), AudioFolders.Length),
System.String.Join("\n", AudioFolders)
);
}
*/
if(FolderDepth != -1) {
InstallProperty(Catalog.GetString("Required Folder Depth"), FolderDepth.ToString());
}
/*if(PlaybackFormats.Length > 0) {
InstallProperty(String.Format(
Catalog.GetPluralString("Audio Format", "Audio Formats", PlaybackFormats.Length), PlaybackFormats.Length),
System.String.Join("\n", PlaybackFormats)
);
}*/
if (PlaybackFormats.Length > 0)
{
string formats = string.Empty; ;
for (int i = 0; i < PlaybackFormats.Length; i++)
{
formats += PlaybackFormats[i] + "\n";
}
InstallProperty("Audio Formats", formats);
}
// Don't continue until the UI is initialized
/*if(!Globals.UIManager.IsInitialized) {
Globals.UIManager.Initialized += OnUIManagerInitialized;
} else {
}
if(ui_initialized && mounted) {
}
*/
// FIXME probably should be able to cancel at some point when you can actually sync
ui_initialized = true;
ReloadDatabase();
CanCancelSave = false;
return InitializeResult.Valid;
}
/*public void OnVolumeMounted(object o, Fil args)
{
if(args.Volume.DevicePath == volume_device["block.device"]) {
monitor.VolumeMounted -= OnVolumeMounted;
volume = args.Volume;
is_read_only = volume.IsReadOnly;
mounted = true;
if(ui_initialized)
ReloadDatabase();
}
}*/
public override void Dispose()
{
// FIXME anything else to do here?
volume = null;
base.Dispose();
}
private void OnUIManagerInitialized(object o, EventArgs args)
{
ui_initialized = true;
if(mounted)
ReloadDatabase();
}
private void ReloadDatabase()
{
ClearTracks(false);
ImportManager importer = new ImportManager();
importer.Title = Catalog.GetString("Loading Songs");
importer.CancelMessage = Catalog.GetString("The audio device song loading process is currently running. Would you like to stop it?");
importer.ProgressMessage = Catalog.GetString("Loading {0} of {1}");
importer.ImportRequested += HandleImportRequested;
foreach(string music_dir in AudioFolders) {
importer.QueueSource(System.IO.Path.Combine(MountPoint, music_dir));
}
}
private void HandleImportRequested(object o, ImportEventArgs args)
{
try {
TrackInfo track = new MassStorageTrackInfo(new SafeUri(args.FileName));
args.ReturnMessage = String.Format("{0} - {1}", track.Artist, track.Title);
AddTrack(track);
} catch {
args.ReturnMessage = Catalog.GetString("Scanning") + "...";
}
QueuePropertiesChanged();
}
private uint properties_timeout = 0;
private void QueuePropertiesChanged() {
if(properties_timeout == 0) {
// properties_timeout = GLib.Timeout.Add(100, );
DoPropertiesChanged();
}
}
private bool DoPropertiesChanged()
{
OnPropertiesChanged();
properties_timeout = 0;
return false;
}
public override void Synchronize()
{
System.Windows.Forms.Application.DoEvents();
List<TrackInfo> tracksToCopy;
lock(uncopiedTracks) {
tracksToCopy = new List<TrackInfo>(uncopiedTracks);
uncopiedTracks.Clear();
}
int count = 1;
foreach(TrackInfo track in tracksToCopy) {
UpdateSaveProgress(
String.Format(Catalog.GetString("Copying {0} of {1}"), count, tracksToCopy.Count),
String.Format("{0} - {1}", track.DisplayArtist, track.DisplayTitle),
count / tracksToCopy.Count);
CopyTrack(track);
count++;
}
FinishSave();
}
public override void Eject()
{
// If we're playing a track on the device, stop playing it before trying to eject
if(PlayerEngineCore.CurrentTrack is MassStorageTrackInfo) {
LogCore.Instance.PushInformation(
Catalog.GetString("Song Playing on Device"),
Catalog.GetString("Before you can eject your device, you need to start playing a song that is not on it. This is a known bug."),
true
);
//PlayerEngineCore.StateChanged += HandleStopped;
//PlayerEngineCore.Close();
} else {
Unmount();
}
}
private void HandleStopped(object o, Banshee.MediaEngine.PlayerEngineStateArgs args)
{
if(args.State == Banshee.MediaEngine.PlayerEngineState.Idle) {
PlayerEngineCore.StateChanged -= HandleStopped;
Unmount();
}
}
private void Unmount()
{
//Cornel - volume in win32 refers to the filesystem
// I will just eject the device here
//if(volume != null)
// volume.Unmount(UnmountCallback);
}
private void UnmountCallback(bool succeeded, string error, string detailed_error)
{
/*if(succeeded) {
volume.Eject(EjectCallback);
} else {
LogCore.Instance.PushWarning(
String.Format(Catalog.GetString("Failed to Unmount {0}"), Name),
Catalog.GetString("Make sure no other programs are using it."),
true
);
}*/
}
private void EjectCallback(bool succeeded, string error, string detailed_error)
{
/*if(succeeded) {
base.Eject();
} else {
LogCore.Instance.PushWarning(
String.Format(Catalog.GetString("Failed to Eject {0}"), Name),
error,
false
);
}*/
}
public override void AddTrack(TrackInfo track)
{
if(track == null || IsReadOnly && !tracks.Contains(track))
return;
tracks.Add(track);
OnTrackAdded(track);
if(!(track is MassStorageTrackInfo)) {
lock(uncopiedTracks) {
uncopiedTracks.Add(track);
}
}
}
private void CopyTrack(TrackInfo track)
{
if(track == null)
return;
string new_path = GetTrackPath(track);
try {
Console.WriteLine("have path {0} for track {1}", new_path, track.Uri);
// If it already is on the device but it's out of date, remove it
if(File.Exists(new_path) && File.GetLastWriteTime(track.Uri.LocalPath) > File.GetLastWriteTime(new_path))
RemoveTrack(new MassStorageTrackInfo(new SafeUri(new_path)));
if(!File.Exists(new_path)) {
Directory.CreateDirectory(Path.GetDirectoryName(new_path));
File.Copy(track.Uri.LocalPath, new_path);
TrackInfo new_track = new MassStorageTrackInfo(new SafeUri(new_path));
// Add the new MassStorageTrackInfo and remove the old TrackInfo from the treeview
tracks.Add(new_track);
OnTrackAdded(new_track);
}
tracks.Remove(track);
} catch (Exception e) {
LogCore.Instance.PushInformation("Unable to copy file", new_path + e.ToString(), false);
}
}
protected override void OnTrackRemoved(TrackInfo track)
{
if(IsReadOnly)
return;
Remover.Enqueue(track);
}
private void HandleRemoveRequested(object o, QueuedOperationArgs args)
{
TrackInfo track = args.Object as TrackInfo;
args.ReturnMessage = String.Format("{0} - {1}", track.DisplayArtist, track.DisplayTitle);
if(!(track is MassStorageTrackInfo)) {
lock(uncopiedTracks) {
uncopiedTracks.Remove(track);
}
}
// FIXME shouldn't need to check for this
// Make sure it's on the drive
if(track.Uri.LocalPath.IndexOf(MountPoint) == -1)
return;
try {
File.Delete(track.Uri.LocalPath);
//Console.WriteLine("Deleted {0}", track.Uri.LocalPath);
} catch {
LogCore.Instance.PushInformation("Could not delete file", track.Uri.LocalPath, false);
}
// trim empty parent directories
try {
string old_dir = Path.GetDirectoryName(track.Uri.LocalPath);
while(old_dir != null && old_dir != String.Empty) {
Directory.Delete(old_dir);
old_dir = Path.GetDirectoryName(old_dir);
}
} catch {}
}
public override System.Drawing.Icon GetIcon(int size)
{
string prefix = "multimedia-player.png";
System.Drawing.Icon icon = IconThemeUtils.LoadIcon(ConfigureDefines.ICON_THEME_DIR + @"\" + prefix);//prefix + ((IconId == null) ? "" : "-" + IconId), size);
return icon == null ? base.GetIcon(size) : icon;
}
private string GetTrackPath(TrackInfo track)
{
string file_path = WritePath;
string artist = FileNamePattern.Escape(track.Artist);
string album = FileNamePattern.Escape(track.Album);
string number_title = FileNamePattern.Escape(track.TrackNumberTitle);
// If the folder_depth property exists, we have to put the files in a hiearchy of
// the exact given depth (not including the mount point/audio_folder).
if(FolderDepth != -1) {
int depth = FolderDepth;
if(depth == 0) {
// Artist - Album - 01 - Title
file_path = System.IO.Path.Combine(file_path, String.Format("{0} - {1} - {2}", artist, album, number_title));
} else if(depth == 1) {
// Artist - Album/01 - Title
file_path = System.IO.Path.Combine(file_path, String.Format("{0} - {1}", artist, album));
file_path = System.IO.Path.Combine(file_path, number_title);
} else if(depth == 2) {
// Artist/Album/01 - Title
file_path = System.IO.Path.Combine(file_path, artist);
file_path = System.IO.Path.Combine(file_path, album);
file_path = System.IO.Path.Combine(file_path, number_title);
} else {
// If the *required* depth is more than 2..go nuts!
for(int i = 0; i < depth - 2; i++) {
file_path = System.IO.Path.Combine(file_path, artist.Substring(0, Math.Min(i, artist.Length)).Trim());
}
// Finally add on the Artist/Album/01 - Track
file_path = System.IO.Path.Combine(file_path, artist);
file_path = System.IO.Path.Combine(file_path, album);
file_path = System.IO.Path.Combine(file_path, number_title);
}
} else {
file_path = System.IO.Path.Combine(file_path, FileNamePattern.CreateFromTrackInfo(track));
}
file_path += Path.GetExtension(track.Uri.LocalPath);
return file_path;
}
private QueuedOperationManager remover;
public QueuedOperationManager Remover {
get {
if(remover == null) {
lock(this) {
if(remover == null) {
remover = new QueuedOperationManager();
remover.ActionMessage = String.Format(Catalog.GetString("Removing songs from {0}"), Name);
remover.ProgressMessage = Catalog.GetString("Removing {0} of {1}");
remover.OperationRequested += HandleRemoveRequested;
}
}
}
return remover;
}
set { remover = value; }
}
public virtual string IconId {
get {
return null;
}
}
private string name = null;
public override string Name {
get {
if(name == null) {
/* if(player_device.PropertyExists("info.product")) {
name = player_device["info.product"];
} else if(volume_device.PropertyExists("volume.label") &&
volume_device["volume.label"].Length > 0) {
name = volume_device["volume.label"];
*/
if(!string.IsNullOrEmpty(player_device.Name))
{
name = player_device.Name;
} else {
name = GenericName;
}
}
return name;
}
}
private static string generic_name = Catalog.GetString("Audio Device");
public override string GenericName {
get {
return generic_name;
}
}
ulong storage_capacity = 0;
public override ulong StorageCapacity {
get {
if(storage_capacity == 0) {
return player_device.Capacity;
}
return storage_capacity;
}
}
public ulong StorageFree {
get {
return player_device.FreeSpace;
}
}
public override ulong StorageUsed {
get {
return Math.Max(StorageCapacity - StorageFree, 0);
}
}
private bool is_read_only;
public override bool IsReadOnly {
get {
return is_read_only;
}
}
public override bool IsPlaybackSupported {
get {
return true;
}
}
private string mount_point = null;
public string MountPoint {
get {
if(mount_point == null) {
mount_point = player_device.Udi;
}
return mount_point;
}
}
private int folder_depth = -2;
public int FolderDepth {
//Cornel what is the purpose of this ?
get {
if(folder_depth == -2) {
/*if(player_device.PropertyExists("portable_audio_player.folder_depth")) {
folder_depth = player_device.GetPropertyInteger("portable_audio_player.folder_depth");
} else {
folder_depth = -1;
}*/
return 0;
}
return folder_depth;
}
protected set { folder_depth = value; }
}
private string write_path = null;
public string WritePath {
get {
if(write_path == null) {
write_path = MountPoint;
// According to the HAL spec, the first folder listed in the audio_folders property
// is the folder to write files to.
if(AudioFolders != null && AudioFolders.Length > 0) {
write_path = System.IO.Path.Combine(write_path, AudioFolders[0]);
}
}
return write_path;
}
protected set { write_path = value; }
}
// The path relative to the mount point where music is stored
private string [] audio_folders = null;
public string [] AudioFolders {
get {
if(audio_folders == null) {
/*if(player_device.PropertyExists("portable_audio_player.audio_folders")) {
audio_folders = player_device.GetPropertyStringList("portable_audio_player.audio_folders");
} else {*/
// Cornel - For now use default
audio_folders = new string [] {""};
//}
}
return audio_folders;
}
protected set {
audio_folders = value;
WritePath = null;
}
}
private string [] playback_formats = null;
public string [] PlaybackFormats {
get {
//Cornel - need to figure this out
/*if(playback_formats == null) {
if(player_device.PropertyExists("portable_audio_player.output_formats")) {
playback_formats = player_device.GetPropertyStringList("portable_audio_player.output_formats");
} else {
// If no playback formats are set, default to MP3 and Ogg
playback_formats = new string [] {"audio/mp3", "audio/ogg"};
}
}*/
playback_formats = new string[] { "audio/mp3", "audio/ogg" };
return playback_formats;
}
protected set { playback_formats = value; }
}
protected string IsAudioPlayerPath {
get { return Path.Combine(MountPoint, ".is_audio_player"); }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reactive.Disposables;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Controls.Platform;
using Avalonia.Controls.Primitives.PopupPositioning;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Input.Raw;
using Avalonia.Platform;
using Avalonia.Rendering;
namespace Avalonia.DesignerSupport.Remote
{
class WindowStub : IWindowImpl, IPopupImpl
{
public Action Deactivated { get; set; }
public Action Activated { get; set; }
public IPlatformHandle Handle { get; }
public Size MaxAutoSizeHint { get; }
public Size ClientSize { get; }
public Size? FrameSize => null;
public double RenderScaling { get; } = 1.0;
public double DesktopScaling => 1.0;
public IEnumerable<object> Surfaces { get; }
public Action<RawInputEventArgs> Input { get; set; }
public Action<Rect> Paint { get; set; }
public Action<Size, PlatformResizeReason> Resized { get; set; }
public Action<double> ScalingChanged { get; set; }
public Func<bool> Closing { get; set; }
public Action Closed { get; set; }
public Action LostFocus { get; set; }
public IMouseDevice MouseDevice { get; } = new MouseDevice();
public IPopupImpl CreatePopup() => new WindowStub(this);
public PixelPoint Position { get; set; }
public Action<PixelPoint> PositionChanged { get; set; }
public WindowState WindowState { get; set; }
public Action<WindowState> WindowStateChanged { get; set; }
public Action<WindowTransparencyLevel> TransparencyLevelChanged { get; set; }
public Action<bool> ExtendClientAreaToDecorationsChanged { get; set; }
public Thickness ExtendedMargins { get; } = new Thickness();
public Thickness OffScreenMargin { get; } = new Thickness();
public WindowStub(IWindowImpl parent = null)
{
if (parent != null)
PopupPositioner = new ManagedPopupPositioner(new ManagedPopupPositionerPopupImplHelper(parent,
(_, size, __) =>
{
Resize(size, PlatformResizeReason.Unspecified);
}));
}
public IRenderer CreateRenderer(IRenderRoot root) => new ImmediateRenderer(root);
public void Dispose()
{
}
public void Invalidate(Rect rect)
{
}
public void SetInputRoot(IInputRoot inputRoot)
{
}
public Point PointToClient(PixelPoint p) => p.ToPoint(1);
public PixelPoint PointToScreen(Point p) => PixelPoint.FromPoint(p, 1);
public void SetCursor(ICursorImpl cursor)
{
}
public void Show(bool activate, bool isDialog)
{
}
public void Hide()
{
}
public void BeginMoveDrag(PointerPressedEventArgs e)
{
}
public void BeginResizeDrag(WindowEdge edge, PointerPressedEventArgs e)
{
}
public void Activate()
{
}
public void Resize(Size clientSize, PlatformResizeReason reason)
{
}
public void Move(PixelPoint point)
{
}
public IScreenImpl Screen { get; } = new ScreenStub();
public void SetMinMaxSize(Size minSize, Size maxSize)
{
}
public void SetTitle(string title)
{
}
public void ShowDialog(IWindowImpl parent)
{
}
public void SetSystemDecorations(SystemDecorations enabled)
{
}
public void SetIcon(IWindowIconImpl icon)
{
}
public void ShowTaskbarIcon(bool value)
{
}
public void CanResize(bool value)
{
}
public void SetTopmost(bool value)
{
}
public void SetParent(IWindowImpl parent)
{
}
public void SetEnabled(bool enable)
{
}
public void SetExtendClientAreaToDecorationsHint(bool extendIntoClientAreaHint)
{
}
public void SetExtendClientAreaChromeHints(ExtendClientAreaChromeHints hints)
{
}
public void SetExtendClientAreaTitleBarHeightHint(double titleBarHeight)
{
}
public IPopupPositioner PopupPositioner { get; }
public Action GotInputWhenDisabled { get; set; }
public void SetTransparencyLevelHint(WindowTransparencyLevel transparencyLevel) { }
public void SetWindowManagerAddShadowHint(bool enabled)
{
}
public WindowTransparencyLevel TransparencyLevel { get; private set; }
public bool IsClientAreaExtendedToDecorations { get; }
public bool NeedsManagedDecorations => false;
public AcrylicPlatformCompensationLevels AcrylicCompensationLevels { get; } = new AcrylicPlatformCompensationLevels(1, 1, 1);
}
class ClipboardStub : IClipboard
{
public Task<string> GetTextAsync() => Task.FromResult("");
public Task SetTextAsync(string text) => Task.CompletedTask;
public Task ClearAsync() => Task.CompletedTask;
public Task SetDataObjectAsync(IDataObject data) => Task.CompletedTask;
public Task<string[]> GetFormatsAsync() => Task.FromResult(new string[0]);
public Task<object> GetDataAsync(string format) => Task.FromResult((object)null);
}
class CursorFactoryStub : ICursorFactory
{
public ICursorImpl GetCursor(StandardCursorType cursorType) => new CursorStub();
public ICursorImpl CreateCursor(IBitmapImpl cursor, PixelPoint hotSpot) => new CursorStub();
private class CursorStub : ICursorImpl
{
public void Dispose() { }
}
}
class IconLoaderStub : IPlatformIconLoader
{
class IconStub : IWindowIconImpl
{
public void Save(Stream outputStream)
{
}
}
public IWindowIconImpl LoadIcon(string fileName) => new IconStub();
public IWindowIconImpl LoadIcon(Stream stream) => new IconStub();
public IWindowIconImpl LoadIcon(IBitmapImpl bitmap) => new IconStub();
}
class SystemDialogsStub : ISystemDialogImpl
{
public Task<string[]> ShowFileDialogAsync(FileDialog dialog, Window parent) =>
Task.FromResult((string[])null);
public Task<string> ShowFolderDialogAsync(OpenFolderDialog dialog, Window parent) =>
Task.FromResult((string)null);
}
class ScreenStub : IScreenImpl
{
public int ScreenCount => 1;
public IReadOnlyList<Screen> AllScreens { get; } =
new Screen[] { new Screen(1, new PixelRect(0, 0, 4000, 4000), new PixelRect(0, 0, 4000, 4000), true) };
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Concurrent;
using QuantConnect.Data;
using QuantConnect.Data.Market;
namespace QuantConnect.Securities
{
/// <summary>
/// Base class caching caching spot for security data and any other temporary properties.
/// </summary>
/// <remarks>
/// This class is virtually unused and will soon be made obsolete.
/// This comment made in a remark to prevent obsolete errors in all users algorithms
/// </remarks>
public class SecurityCache
{
// this is used to prefer quote bar data over the tradebar data
private DateTime _lastQuoteBarUpdate;
private BaseData _lastData;
private readonly ConcurrentDictionary<Type, BaseData> _dataByType = new ConcurrentDictionary<Type, BaseData>();
/// <summary>
/// Gets the most recent price submitted to this cache
/// </summary>
public decimal Price { get; private set; }
/// <summary>
/// Gets the most recent open submitted to this cache
/// </summary>
public decimal Open { get; private set; }
/// <summary>
/// Gets the most recent high submitted to this cache
/// </summary>
public decimal High { get; private set; }
/// <summary>
/// Gets the most recent low submitted to this cache
/// </summary>
public decimal Low { get; private set; }
/// <summary>
/// Gets the most recent close submitted to this cache
/// </summary>
public decimal Close { get; private set; }
/// <summary>
/// Gets the most recent bid submitted to this cache
/// </summary>
public decimal BidPrice { get; private set; }
/// <summary>
/// Gets the most recent ask submitted to this cache
/// </summary>
public decimal AskPrice { get; private set; }
/// <summary>
/// Gets the most recent bid size submitted to this cache
/// </summary>
public decimal BidSize { get; private set; }
/// <summary>
/// Gets the most recent ask size submitted to this cache
/// </summary>
public decimal AskSize { get; private set; }
/// <summary>
/// Gets the most recent volume submitted to this cache
/// </summary>
public decimal Volume { get; private set; }
/// <summary>
/// Gets the most recent open interest submitted to this cache
/// </summary>
public long OpenInterest { get; private set; }
/// <summary>
/// Add a new market data point to the local security cache for the current market price.
/// Rules:
/// Don't cache fill forward data.
/// Always return the last observation.
/// If two consecutive data has the same time stamp and one is Quotebars and the other Tradebar, prioritize the Quotebar.
/// </summary>
public void AddData(BaseData data)
{
var openInterest = data as OpenInterest;
if (openInterest != null)
{
OpenInterest = (long)openInterest.Value;
return;
}
var tick = data as Tick;
if (tick?.TickType == TickType.OpenInterest)
{
OpenInterest = (long)tick.Value;
return;
}
// Only cache non fill-forward data.
if (data.IsFillForward) return;
// Always keep track of the last obesrvation
_dataByType[data.GetType()] = data;
// don't set _lastData if receive quotebar then tradebar w/ same end time. this
// was implemented to grant preference towards using quote data in the fill
// models and provide a level of determinism on the values exposed via the cache.
if (_lastData == null
|| _lastQuoteBarUpdate != data.EndTime
|| data.DataType != MarketDataType.TradeBar )
{
_lastData = data;
}
if (tick != null)
{
if (tick.Value != 0) Price = tick.Value;
if (tick.TickType == TickType.Trade && tick.Quantity != 0)
{
Volume = tick.Quantity;
}
if (tick.TickType == TickType.Quote)
{
if (tick.BidPrice != 0) BidPrice = tick.BidPrice;
if (tick.BidSize != 0) BidSize = tick.BidSize;
if (tick.AskPrice != 0) AskPrice = tick.AskPrice;
if (tick.AskSize != 0) AskSize = tick.AskSize;
}
return;
}
var bar = data as IBar;
if (bar != null)
{
if (_lastQuoteBarUpdate != data.EndTime)
{
if (bar.Open != 0) Open = bar.Open;
if (bar.High != 0) High = bar.High;
if (bar.Low != 0) Low = bar.Low;
if (bar.Close != 0)
{
Price = bar.Close;
Close = bar.Close;
}
}
var tradeBar = bar as TradeBar;
if (tradeBar != null)
{
if (tradeBar.Volume != 0) Volume = tradeBar.Volume;
}
var quoteBar = bar as QuoteBar;
if (quoteBar != null)
{
_lastQuoteBarUpdate = quoteBar.EndTime;
if (quoteBar.Ask != null && quoteBar.Ask.Close != 0) AskPrice = quoteBar.Ask.Close;
if (quoteBar.Bid != null && quoteBar.Bid.Close != 0) BidPrice = quoteBar.Bid.Close;
if (quoteBar.LastBidSize != 0) BidSize = quoteBar.LastBidSize;
if (quoteBar.LastAskSize != 0) AskSize = quoteBar.LastAskSize;
}
}
else if (data.DataType != MarketDataType.Auxiliary)
{
Price = data.Price;
}
}
/// <summary>
/// Stores the specified data instance in the cache WITHOUT updating any of the cache properties, such as Price
/// </summary>
/// <param name="data"></param>
public void StoreData(BaseData data)
{
_dataByType[data.GetType()] = data;
}
/// <summary>
/// Get last data packet recieved for this security
/// </summary>
/// <returns>BaseData type of the security</returns>
public BaseData GetData()
{
return _lastData;
}
/// <summary>
/// Get last data packet recieved for this security of the specified ty[e
/// </summary>
/// <typeparam name="T">The data type</typeparam>
/// <returns>The last data packet, null if none received of type</returns>
public T GetData<T>()
where T : BaseData
{
BaseData data;
_dataByType.TryGetValue(typeof(T), out data);
return data as T;
}
/// <summary>
/// Reset cache storage and free memory
/// </summary>
public void Reset()
{
_dataByType.Clear();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Application.DataContext;
using JetBrains.Application.Diagnostics;
using JetBrains.Application.UI.Actions;
using JetBrains.Application.UI.ActionsRevised.Menu;
using JetBrains.Collections;
using JetBrains.ProjectModel;
using JetBrains.ProjectModel.DataContext;
using JetBrains.ReSharper.Features.ReSpeller.SpellEngine;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Caches;
using JetBrains.ReSharper.Psi.Modules;
using JetBrains.Util;
using JetBrains.Util.Extension;
namespace JetBrains.ReSharper.Plugins.Unity.Core.Feature.Internal
{
[Action("Unity_Internal_DumpSpellCheckWordLists", "Dump Spell Check Word Lists")]
public class DumpSpellCheckWordListsAction : IExecutableAction
{
public bool Update(IDataContext context, ActionPresentation presentation, DelegateUpdate nextUpdate)
{
return true;
}
public void Execute(IDataContext context, DelegateExecute nextExecute)
{
var solution = context.GetData(ProjectModelDataConstants.SOLUTION);
if (solution == null)
return;
var wordsPerAssembly = new OneToSetMap<string, string>(valueComparer: StringComparer.InvariantCultureIgnoreCase);
var abbreviationsWithOriginalWord = new OneToSetMap<string, string>(valueComparer: StringComparer.InvariantCultureIgnoreCase);
// TODO: This should be in a background task
var psiModules = solution.GetComponent<IPsiModules>();
var symbolCache = solution.GetComponent<ISymbolCache>();
foreach (var assemblyPsiModule in psiModules.GetAssemblyModules().OrderBy(m => m.DisplayName))
{
if (!ShouldProcessAssembly(assemblyPsiModule))
continue;
var symbolScope = symbolCache.GetSymbolScope(assemblyPsiModule, false, true);
var typeElements = symbolScope.GetAllTypeElementsGroupedByName();
foreach (var typeElement in typeElements)
{
if (!typeElement.CanBeVisibleToSolution())
continue;
AddWords(wordsPerAssembly, abbreviationsWithOriginalWord, assemblyPsiModule,
typeElement is IInterface ? typeElement.ShortName.RemoveStart("I") : typeElement.ShortName);
foreach (var namespaceName in typeElement.GetClrName().NamespaceNames)
AddWords(wordsPerAssembly, abbreviationsWithOriginalWord, assemblyPsiModule, namespaceName);
// TODO: Should we skip enum values?
// It's unlikely that a user would name a method or variable after a value such as AdvertisingNetwork.Aarki,
// but on the other hand, if it's used in a comment, it'll show up as a typo.
foreach (var typeMember in typeElement.GetMembers())
{
if (!ShouldProcessTypeMember(typeMember))
continue;
// Don't use any enum values as abbreviations. Avoids false positives with ALL_UPPER_CASE style
AddWords(wordsPerAssembly,
typeElement is IEnum ? new OneToSetMap<string, string>() : abbreviationsWithOriginalWord,
assemblyPsiModule, typeMember.ShortName);
// TODO: Include parameter names?
// Respeller will not check parameter names of overriding or implementing functions, so this is
// probably unnecessary
}
}
}
// Case insensitive. There will not be duplicates
var allWords = (from pair in wordsPerAssembly
from word in pair.Value
select word).ToJetHashSet(StringComparer.InvariantCultureIgnoreCase);
var spellService = solution.GetComponent<ISpellService>();
var unknownWords = (from word in allWords
where !spellService.CheckWordSpelling(word)
select word).ToJetHashSet(StringComparer.InvariantCultureIgnoreCase);
// Add abbreviations separately. If added to the dictionary, we don't get typo warnings, but we can get
// naming standard inspection warnings. E.g. BlahBlahAABB is converted to BlahBlahAabb. Don't add anything
// that's already known, but the spell checker will only check for words of 4 characters or more.
// TODO: Ideally, we should disable AbbreviationsSettingsProvider, or we'll ignore our own abbreviations
// Merge files by hand
var unknownAbbreviations = (from word in abbreviationsWithOriginalWord.Keys
where (word.Length > 1 && word.Length < 4) || !spellService.CheckWordSpelling(word)
select word).ToJetHashSet();
Dumper.DumpToNotepad(w =>
{
w.WriteLine("Abbreviations:");
w.WriteLine();
foreach (var (abbr, originalWords) in abbreviationsWithOriginalWord.OrderBy(kv => kv.Key))
{
w.Write(abbr);
w.Write(": ");
foreach (var word in originalWords)
{
w.Write(word);
w.Write(", ");
}
w.WriteLine();
}
});
// Remove non-abbreviations, known typos or exclusions. Yes, this is all done by hand
RemoveNonAbbreviations(unknownAbbreviations);
RemoveTyposAndExclusions(unknownWords);
// Dump all words for diagnostics
Dumper.DumpToNotepad(w =>
{
w.WriteLine("All words");
w.WriteLine();
foreach (var (assembly, words) in wordsPerAssembly)
{
w.WriteLine("Words for assembly: " + assembly);
w.WriteLine();
foreach (var word in words.OrderBy(IdentityFunc<string>.Instance))
w.WriteLine(word.ToLowerInvariant());
w.WriteLine();
}
});
// Dump all abbreviations, so we can avoid naming standards inspections when an abbreviation is used.
// E.g. BlahBlahAABB is accepted instead of converted to BlahBlahAabb
Dumper.DumpToNotepad(w =>
{
w.WriteLine("Abbreviations");
w.WriteLine();
foreach (var abbreviation in unknownAbbreviations.OrderBy(IdentityFunc<string>.Instance))
w.WriteLine(abbreviation.ToUpperInvariant());
});
// Dump all unknown words, minus abbreviations, for use as a dictionary
Dumper.DumpToNotepad(w =>
{
var dictionary = new JetHashSet<string>(unknownWords, StringComparer.InvariantCultureIgnoreCase);
dictionary.ExceptWith(abbreviationsWithOriginalWord.Keys);
w.WriteLine("Dictionary (unknown words minus abbreviations)");
w.WriteLine();
w.WriteLine(dictionary.Count); // Hunspell dictionaries start with the number of words
foreach (var word in dictionary.OrderBy(IdentityFunc<string>.Instance))
w.WriteLine(word.ToLowerInvariant());
});
}
private static bool ShouldProcessAssembly(IAssemblyPsiModule assemblyPsiModule)
{
var name = assemblyPsiModule.Assembly.AssemblyName.Name;
return !name.StartsWith("System") && !name.StartsWith("Microsoft") && name != "netstandard" &&
name != "mscorlib" && !name.StartsWith("nunit") && !name.StartsWith("Boo") &&
name != "unityplastic" && !name.StartsWith("UnityScript", StringComparison.InvariantCultureIgnoreCase) &&
name != "JetBrains.Annotations" && name != "Unity.Rider.Editor";
}
private static bool ShouldProcessTypeMember(ITypeMember typeMember)
{
// Note that UnityEditor has a lot of InternalsVisibleTo, including for Unity.Collections and Unity.Entities
// so make sure these projects are not part of the solution used to run this action!
if (!typeMember.CanBeVisibleToSolution() || typeMember is IConstructor || typeMember is IAccessor)
return false;
// Ignore Unity.Mathematics swizzling operators (all combinations of x,y,z and w)
if (IsSwizzlingProperty(typeMember))
return false;
if (typeMember.GetContainingType() is IEnum enumTypeElement)
{
if (typeMember.ShortName == "iPhoneAndiPad" || typeMember.ShortName == "SetiPhoneLaunchScreenType")
return false; // "andi", "seti"
// Don't do anything with the AdvertisingNetwork enum. It's full of weird names that would be nice to
// not show typos for in comments (e.g. AerServ), but we have to split that into words, so we get "aer"
// and "serv" as words in the dictionary, which are not useful
// Same goes for Stores
if (enumTypeElement.GetClrName().FullName == "UnityEngine.Analytics.AdvertisingNetwork"
|| enumTypeElement.GetClrName().FullName == "UnityEngine.Monetization.Store")
{
return false;
}
}
return true;
}
private static bool IsSwizzlingProperty(ITypeMember typeMember)
{
// E.g. Unity.Mathematics.bool2.wwww
if (!(typeMember is IProperty))
return false;
if (typeMember.GetContainingType()?.GetContainingNamespace().QualifiedName != "Unity.Mathematics")
return false;
if (typeMember.ShortName.Length != 4)
return false;
return typeMember.ShortName.All(letter => letter == 'x' || letter == 'y' || letter == 'z' || letter == 'w');
}
private static void AddWords(OneToSetMap<string, string> wordsPerAssembly,
OneToSetMap<string, string> abbreviationsWithOriginalWord,
IAssemblyPsiModule assemblyPsiModule, string name)
{
var textParts = TextSplitter.Split(name);
foreach (var textPart in textParts.Where(tp => tp.Type == TextPartType.Word))
{
if (textPart.Text == textPart.Text.ToUpperInvariant())
{
if (textPart.Text.Length > 1)
abbreviationsWithOriginalWord.Add(textPart.Text, name);
}
else
wordsPerAssembly.Add(assemblyPsiModule.Assembly.AssemblyName.Name, textPart.Text);
}
}
private static void RemoveNonAbbreviations(ICollection<string> unknownAbbreviations)
{
// Remove known words (which would be done by the spell checker, but that only works for a min of 4 letters)
// ReSharper disable StringLiteralTypo
unknownAbbreviations.Remove("ADD");
unknownAbbreviations.Remove("AND");
unknownAbbreviations.Remove("GET");
unknownAbbreviations.Remove("GO");
unknownAbbreviations.Remove("GRAIDENT"); // Typo fixed in later versions
unknownAbbreviations.Remove("KEY");
unknownAbbreviations.Remove("LO"); // GetLODs
unknownAbbreviations.Remove("MAX");
unknownAbbreviations.Remove("MIN");
unknownAbbreviations.Remove("OFF");
unknownAbbreviations.Remove("ON");
unknownAbbreviations.Remove("PUT");
unknownAbbreviations.Remove("TEXTMESHPRO");
unknownAbbreviations.Remove("UP");
// ReSharper restore StringLiteralTypo
}
private static void RemoveTyposAndExclusions(ICollection<string> unknownWords)
{
// ReSharper disable StringLiteralTypo
unknownWords.Remove("adaptor");
unknownWords.Remove("contoller");
unknownWords.Remove("corlib");
unknownWords.Remove("deprected");
unknownWords.Remove("doesnt");
unknownWords.Remove("dont");
unknownWords.Remove("hugarian");
unknownWords.Remove("iconwarning");
unknownWords.Remove("joyn");
unknownWords.Remove("jvalue");
unknownWords.Remove("memoryless");
unknownWords.Remove("mikk");
unknownWords.Remove("modelview");
unknownWords.Remove("normalizesafe");
unknownWords.Remove("occlucion");
unknownWords.Remove("pptr");
unknownWords.Remove("projectsafe");
unknownWords.Remove("ptitle");
unknownWords.Remove("quat");
unknownWords.Remove("recieve");
unknownWords.Remove("recv");
unknownWords.Remove("regen");
unknownWords.Remove("resonace");
unknownWords.Remove("rolloff");
unknownWords.Remove("serbo");
unknownWords.Remove("smallcaps");
unknownWords.Remove("smartupdate");
unknownWords.Remove("smoothstep");
unknownWords.Remove("textfirst");
unknownWords.Remove("texure");
unknownWords.Remove("theshold");
unknownWords.Remove("timeu");
unknownWords.Remove("treshold");
unknownWords.Remove("vdecl");
unknownWords.Remove("xywh");
unknownWords.Remove("zoomer");
// Maths
unknownWords.Remove("asdouble");
unknownWords.Remove("asfloat");
unknownWords.Remove("asint");
unknownWords.Remove("aslong");
unknownWords.Remove("asuint");
unknownWords.Remove("asulong");
unknownWords.Remove("ceillog");
unknownWords.Remove("ceilpow");
unknownWords.Remove("cmax");
unknownWords.Remove("cmin");
unknownWords.Remove("cnoise");
unknownWords.Remove("countbits");
unknownWords.Remove("csum");
unknownWords.Remove("distancesq");
unknownWords.Remove("floorlog");
unknownWords.Remove("frac");
unknownWords.Remove("hashwide");
unknownWords.Remove("isfinite");
unknownWords.Remove("isinf");
unknownWords.Remove("ispow");
unknownWords.Remove("lengthsq");
unknownWords.Remove("lzcnt");
unknownWords.Remove("modf");
unknownWords.Remove("pnoise");
unknownWords.Remove("psrdnoise");
unknownWords.Remove("psrnoise");
unknownWords.Remove("reversebits");
unknownWords.Remove("rsqrt");
unknownWords.Remove("snoise");
unknownWords.Remove("srdnoise");
unknownWords.Remove("srnoise");
unknownWords.Remove("trunc");
unknownWords.Remove("tzcnt");
unknownWords.Remove("unitexp");
unknownWords.Remove("unitlog");
// ReSharper restore StringLiteralTypo
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class ObjectCreationExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
public ObjectCreationExpressionSignatureHelpProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture)
{
}
internal override ISignatureHelpProvider CreateSignatureHelpProvider()
{
return new ObjectCreationExpressionSignatureHelpProvider();
}
#region "Regular tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutParameters()
{
var markup = @"
class C
{
void foo()
{
var c = [|new C($$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutParametersMethodXmlComments()
{
var markup = @"
class C
{
/// <summary>
/// Summary for C
/// </summary>
C() { }
void Foo()
{
C c = [|new C($$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C()", "Summary for C", null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn1()
{
var markup = @"
class C
{
C(int a, int b) { }
void Foo()
{
C c = [|new C($$2, 3|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlCommentsOn1()
{
var markup = @"
class C
{
/// <summary>
/// Summary for C
/// </summary>
/// <param name=""a"">Param a</param>
/// <param name=""b"">Param b</param>
C(int a, int b) { }
void Foo()
{
C c = [|new C($$2, 3|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", "Summary for C", "Param a", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn2()
{
var markup = @"
class C
{
C(int a, int b) { }
void Foo()
{
C c = [|new C(2, $$3|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlComentsOn2()
{
var markup = @"
class C
{
/// <summary>
/// Summary for C
/// </summary>
/// <param name=""a"">Param a</param>
/// <param name=""b"">Param b</param>
C(int a, int b) { }
void Foo()
{
C c = [|new C(2, $$3|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", "Summary for C", "Param b", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutClosingParen()
{
var markup = @"
class C
{
void foo()
{
var c = [|new C($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutClosingParenWithParameters()
{
var markup = @"
class C
{
C(int a, int b) { }
void Foo()
{
C c = [|new C($$2, 3
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutClosingParenWithParametersOn2()
{
var markup = @"
class C
{
C(int a, int b) { }
void Foo()
{
C c = [|new C(2, $$3
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnLambda()
{
var markup = @"
using System;
class C
{
void foo()
{
var bar = [|new Action<int, int>($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("Action<int, int>(void (int, int) target)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
#endregion
#region "Current Parameter Name"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestCurrentParameterName()
{
var markup = @"
class C
{
C(int a, string b)
{
}
void foo()
{
var c = [|new C(b: string.Empty, $$a: 2|]);
}
}";
await VerifyCurrentParameterNameAsync(markup, "a");
}
#endregion
#region "Trigger tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerParens()
{
var markup = @"
class C
{
void foo()
{
var c = [|new C($$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerComma()
{
var markup = @"
class C
{
C(int a, string b)
{
}
void foo()
{
var c = [|new C(2,$$string.Empty|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, string b)", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestNoInvocationOnSpace()
{
var markup = @"
class C
{
C(int a, string b)
{
}
void foo()
{
var c = [|new C(2, $$string.Empty|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestTriggerCharacters()
{
char[] expectedCharacters = { ',', '(' };
char[] unexpectedCharacters = { ' ', '[', '<' };
VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters);
}
#endregion
#region "EditorBrowsable tests"
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Constructor_BrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new Foo($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public Foo(int x)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Constructor_BrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new Foo($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Foo(int x)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Constructor_BrowsableAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Foo($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public Foo()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Constructor_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
new Foo($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public Foo(int x)
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Foo(long y)
{
}
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("Foo(long y)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
#endregion
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
class D
{
}
#endif
void foo()
{
var x = new D($$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"D()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj2", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
class D
{
}
#endif
#if BAR
void foo()
{
var x = new D($$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"D()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj3", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
[WorkItem(1067933)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvokedWithNoToken()
{
var markup = @"
// new foo($$";
await TestAsync(markup);
}
[WorkItem(1078993)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestSigHelpInIncorrectObjectCreationExpression()
{
var markup = @"
class C
{
void foo(C c)
{
foo([|new C{$$|]
}
}";
await TestAsync(markup);
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using EarLab.Viewers;
using EarLab.ReaderWriters;
namespace EarLab.DataViewer
{
/// <summary>
/// Summary description for MainForm.
/// </summary>
public class MainForm : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.MainMenu mainMenu;
private System.Windows.Forms.MenuItem fileMenuItem;
private System.Windows.Forms.MenuItem openMenuItem;
private System.Windows.Forms.MenuItem seperatorMenuItem1;
private System.Windows.Forms.MenuItem exitMenuItem;
private System.Windows.Forms.OpenFileDialog openFileDialog;
private System.Windows.Forms.MenuItem closeMenuItem;
private System.Windows.Forms.MenuItem aboutMenuItem;
private System.Windows.Forms.MenuItem dataviewerMenuItem;
private System.Windows.Forms.MenuItem earlabMenuItem;
private System.Windows.Forms.PictureBox pictureBox;
private System.Windows.Forms.MenuItem helpMenuItem;
private System.Windows.Forms.MenuItem helpIndexMenuItem;
private System.Windows.Forms.MenuItem menuItem3;
private EarLab.Viewers.Layouts.ILayout viewerControl;
//private EarLab.Viewers.Layouts.LayoutFullScrollable viewerControl;
public MainForm(string[] args)
{
// Required for Windows Form Designer support
InitializeComponent();
// Since we are working with en-US style numbers from Desktop Earlab
System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-US", false);
System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo;
if (args.Length == 1 && args[0] != "" && File.Exists(args[0]))
this.OpenFile(args[0]);
else if (args.Length > 0 && args[0].Contains("?"))
System.Console.WriteLine("DataViewer.exe [filename]");
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MainForm));
this.mainMenu = new System.Windows.Forms.MainMenu();
this.fileMenuItem = new System.Windows.Forms.MenuItem();
this.openMenuItem = new System.Windows.Forms.MenuItem();
this.closeMenuItem = new System.Windows.Forms.MenuItem();
this.seperatorMenuItem1 = new System.Windows.Forms.MenuItem();
this.exitMenuItem = new System.Windows.Forms.MenuItem();
this.aboutMenuItem = new System.Windows.Forms.MenuItem();
this.helpMenuItem = new System.Windows.Forms.MenuItem();
this.helpIndexMenuItem = new System.Windows.Forms.MenuItem();
this.menuItem3 = new System.Windows.Forms.MenuItem();
this.dataviewerMenuItem = new System.Windows.Forms.MenuItem();
this.earlabMenuItem = new System.Windows.Forms.MenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.SuspendLayout();
//
// mainMenu
//
this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.fileMenuItem,
this.aboutMenuItem});
//
// fileMenuItem
//
this.fileMenuItem.Index = 0;
this.fileMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.openMenuItem,
this.closeMenuItem,
this.seperatorMenuItem1,
this.exitMenuItem});
this.fileMenuItem.Text = "&File";
//
// openMenuItem
//
this.openMenuItem.Index = 0;
this.openMenuItem.Text = "&Open...";
this.openMenuItem.Click += new System.EventHandler(this.openMenuItem_Click);
//
// closeMenuItem
//
this.closeMenuItem.Enabled = false;
this.closeMenuItem.Index = 1;
this.closeMenuItem.Text = "&Close";
this.closeMenuItem.Click += new System.EventHandler(this.closeMenuItem_Click);
//
// seperatorMenuItem1
//
this.seperatorMenuItem1.Index = 2;
this.seperatorMenuItem1.Text = "-";
//
// exitMenuItem
//
this.exitMenuItem.Index = 3;
this.exitMenuItem.Text = "E&xit";
this.exitMenuItem.Click += new System.EventHandler(this.exitMenuItem_Click);
//
// aboutMenuItem
//
this.aboutMenuItem.Index = 1;
this.aboutMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.helpMenuItem,
this.helpIndexMenuItem,
this.menuItem3,
this.dataviewerMenuItem,
this.earlabMenuItem});
this.aboutMenuItem.MergeOrder = 2;
this.aboutMenuItem.ShowShortcut = false;
this.aboutMenuItem.Text = "&Help";
//
// helpMenuItem
//
this.helpMenuItem.Index = 0;
this.helpMenuItem.Text = "Show Help...";
this.helpMenuItem.Click += new System.EventHandler(this.helpMenuItem_Click);
//
// helpIndexMenuItem
//
this.helpIndexMenuItem.Index = 1;
this.helpIndexMenuItem.Text = "Show Help Index...";
this.helpIndexMenuItem.Click += new System.EventHandler(this.helpIndexMenuItem_Click);
//
// menuItem3
//
this.menuItem3.Index = 2;
this.menuItem3.Text = "-";
//
// dataviewerMenuItem
//
this.dataviewerMenuItem.Index = 3;
this.dataviewerMenuItem.Text = "About DataViewer Application...";
this.dataviewerMenuItem.Click += new System.EventHandler(this.dataviewerMenuItem_Click);
//
// earlabMenuItem
//
this.earlabMenuItem.Index = 4;
this.earlabMenuItem.Text = "About EarLab at Boston University...";
this.earlabMenuItem.Click += new System.EventHandler(this.earlabMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.Filter = "EarLab Files|*.index;*.metadata|EarLab Metadata XML File (*.metadata)|*.metadata|" +
"EarLab XML Spike Metadata File (*.index)|*.index";
this.openFileDialog.Title = "File Open...";
//
// pictureBox
//
this.pictureBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pictureBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.pictureBox.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox.Image")));
this.pictureBox.Location = new System.Drawing.Point(0, 0);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(712, 401);
this.pictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox.TabIndex = 0;
this.pictureBox.TabStop = false;
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(712, 401);
this.Controls.Add(this.pictureBox);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Menu = this.mainMenu;
this.MinimumSize = new System.Drawing.Size(600, 400);
this.Name = "MainForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "EarLab DataViewer";
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
EarLab.Utilities.EnableVisualStyles.EnableApplication();
Application.Run(new MainForm(args));
}
private void OpenFile(string fileName)
{
// let the screen update, so it isn't garbled
Application.DoEvents();
if (this.viewerControl != null)
{
this.viewerControl.Close();
this.Controls.Remove((Control)this.viewerControl);
((Control)this.viewerControl).Dispose();
this.pictureBox.Visible = true;
// we need this to allow the computer some time to display the picture box
Application.DoEvents();
}
if (fileName.EndsWith(".metadata"))
viewerControl = new EarLab.Viewers.Layouts.LayoutFullScrollable();
else
viewerControl = new EarLab.Viewers.Layouts.LayoutScatterFullScrollable();
viewerControl.CriticalError += new EarLab.Viewers.Layouts.CriticalErrorHandler(viewerControl_CriticalError);
this.Controls.Add((Control)viewerControl);
((Control)viewerControl).Location = new Point(2,2);
((Control)viewerControl).Size = new Size(this.ClientRectangle.Width-4, this.ClientRectangle.Height-4);
((Control)viewerControl).Anchor = (AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right);
string returnString = viewerControl.Read(fileName);
if (returnString == "0")
{
viewerControl.MainMenu = this.mainMenu;
this.closeMenuItem.Enabled = true;
this.pictureBox.Visible = false;
}
else
{
MessageBox.Show(this, returnString, "File Open Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
this.closeMenuItem_Click(this, new System.EventArgs());
}
}
#region Menu Events
private void openMenuItem_Click(object sender, System.EventArgs e)
{
if (this.openFileDialog.ShowDialog() == DialogResult.OK
&& this.openFileDialog.FileName.EndsWith(".metadata") || this.openFileDialog.FileName.EndsWith(".index"))
this.OpenFile(this.openFileDialog.FileName);
}
private void closeMenuItem_Click(object sender, System.EventArgs e)
{
this.viewerControl.Close();
this.Controls.Remove((Control)this.viewerControl);
((Control)this.viewerControl).Dispose();
this.closeMenuItem.Enabled = false;
this.pictureBox.Visible = true;
this.Text = "EarLab DataViewer";
}
private void exitMenuItem_Click(object sender, System.EventArgs e)
{
Application.Exit();
}
#endregion
private void dataviewerMenuItem_Click(object sender, System.EventArgs e)
{
DataViewerDialog dataViewerDialog = new DataViewerDialog();
dataViewerDialog.ShowDialog(this);
}
private void earlabMenuItem_Click(object sender, System.EventArgs e)
{
EarLabDialog earlabDialog = new EarLabDialog();
earlabDialog.ShowDialog(this);
}
private void viewerControl_CriticalError(string message)
{
MessageBox.Show(this, message, "File Open Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
this.closeMenuItem_Click(this, new System.EventArgs());
}
private void helpMenuItem_Click(object sender, System.EventArgs e)
{
Help.ShowHelp(this, Path.Combine(Application.StartupPath, "DataViewer.chm"));
}
private void helpIndexMenuItem_Click(object sender, System.EventArgs e)
{
Help.ShowHelpIndex(this, Path.Combine(Application.StartupPath, "DataViewer.chm"));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Collections
{
public sealed partial class BitArray : System.Collections.ICollection, System.Collections.IEnumerable, System.ICloneable
{
public BitArray(bool[] values) { }
public BitArray(byte[] bytes) { }
public BitArray(System.Collections.BitArray bits) { }
public BitArray(int length) { }
public BitArray(int length, bool defaultValue) { }
public BitArray(int[] values) { }
public bool this[int index] { get { throw null; } set { } }
public int Length { get { throw null; } set { } }
public int Count { get { throw null; } }
public bool IsReadOnly { get { throw null; } }
public bool IsSynchronized { get { throw null; } }
public object Clone() { throw null; }
public object SyncRoot { get { throw null; } }
public System.Collections.BitArray And(System.Collections.BitArray value) { throw null; }
public bool Get(int index) { throw null; }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
public System.Collections.BitArray Not() { throw null; }
public System.Collections.BitArray Or(System.Collections.BitArray value) { throw null; }
public void Set(int index, bool value) { }
public void SetAll(bool value) { }
public void CopyTo(System.Array array, int index) { }
public System.Collections.BitArray Xor(System.Collections.BitArray value) { throw null; }
public System.Collections.BitArray RightShift(int count) { throw null; }
public System.Collections.BitArray LeftShift(int count) { throw null; }
}
public static partial class StructuralComparisons
{
public static System.Collections.IComparer StructuralComparer { get { throw null; } }
public static System.Collections.IEqualityComparer StructuralEqualityComparer { get { throw null; } }
}
}
namespace System.Collections.Generic
{
public static class CollectionExtensions
{
public static TValue GetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key) { throw null; }
public static TValue GetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue) { throw null; }
public static bool TryAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value) { throw null; }
public static bool Remove<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, out TValue value) { throw null; }
}
public abstract partial class Comparer<T> : System.Collections.Generic.IComparer<T>, System.Collections.IComparer
{
protected Comparer() { }
public static System.Collections.Generic.Comparer<T> Default { get { throw null; } }
public abstract int Compare(T x, T y);
public static System.Collections.Generic.Comparer<T> Create(System.Comparison<T> comparison) { throw null; }
int System.Collections.IComparer.Compare(object x, object y) { throw null; }
}
public partial class Dictionary<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
{
public Dictionary() { }
public Dictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary) { }
public Dictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary, System.Collections.Generic.IEqualityComparer<TKey> comparer) { }
public Dictionary(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>> collection) { }
public Dictionary(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>> collection, System.Collections.Generic.IEqualityComparer<TKey> comparer) { }
public Dictionary(System.Collections.Generic.IEqualityComparer<TKey> comparer) { }
protected Dictionary(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public Dictionary(int capacity) { }
public Dictionary(int capacity, System.Collections.Generic.IEqualityComparer<TKey> comparer) { }
public System.Collections.Generic.IEqualityComparer<TKey> Comparer { get { throw null; } }
public int Count { get { throw null; } }
public TValue this[TKey key] { get { throw null; } set { } }
public System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection Keys { get { throw null; } }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.IsReadOnly { get { throw null; } }
System.Collections.Generic.ICollection<TKey> System.Collections.Generic.IDictionary<TKey, TValue>.Keys { get { throw null; } }
System.Collections.Generic.ICollection<TValue> System.Collections.Generic.IDictionary<TKey, TValue>.Values { get { throw null; } }
System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Keys { get { throw null; } }
System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Values { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
bool System.Collections.IDictionary.IsFixedSize { get { throw null; } }
bool System.Collections.IDictionary.IsReadOnly { get { throw null; } }
object System.Collections.IDictionary.this[object key] { get { throw null; } set { } }
System.Collections.ICollection System.Collections.IDictionary.Keys { get { throw null; } }
System.Collections.ICollection System.Collections.IDictionary.Values { get { throw null; } }
public System.Collections.Generic.Dictionary<TKey, TValue>.ValueCollection Values { get { throw null; } }
public void Add(TKey key, TValue value) { }
public void Clear() { }
public bool ContainsKey(TKey key) { throw null; }
public bool ContainsValue(TValue value) { throw null; }
public System.Collections.Generic.Dictionary<TKey, TValue>.Enumerator GetEnumerator() { throw null; }
public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public virtual void OnDeserialization(object sender) { }
public bool Remove(TKey key) { throw null; }
public bool Remove(TKey key, out TValue value) { throw null; }
public bool TryAdd(TKey key, TValue value) { throw null; }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int index) { }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; }
System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>.GetEnumerator() { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
void System.Collections.IDictionary.Add(object key, object value) { }
bool System.Collections.IDictionary.Contains(object key) { throw null; }
System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { throw null; }
void System.Collections.IDictionary.Remove(object key) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public bool TryGetValue(TKey key, out TValue value) { throw null; }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.IDictionaryEnumerator, System.Collections.IEnumerator, System.IDisposable
{
public System.Collections.Generic.KeyValuePair<TKey, TValue> Current { get { throw null; } }
System.Collections.DictionaryEntry System.Collections.IDictionaryEnumerator.Entry { get { throw null; } }
object System.Collections.IDictionaryEnumerator.Key { get { throw null; } }
object System.Collections.IDictionaryEnumerator.Value { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
public bool MoveNext() { throw null; }
void System.Collections.IEnumerator.Reset() { }
}
public sealed partial class KeyCollection : System.Collections.Generic.ICollection<TKey>, System.Collections.Generic.IEnumerable<TKey>, System.Collections.Generic.IReadOnlyCollection<TKey>, System.Collections.ICollection, System.Collections.IEnumerable
{
public KeyCollection(System.Collections.Generic.Dictionary<TKey, TValue> dictionary) { }
public int Count { get { throw null; } }
bool System.Collections.Generic.ICollection<TKey>.IsReadOnly { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
public void CopyTo(TKey[] array, int index) { }
public System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection.Enumerator GetEnumerator() { throw null; }
void System.Collections.Generic.ICollection<TKey>.Add(TKey item) { }
void System.Collections.Generic.ICollection<TKey>.Clear() { }
bool System.Collections.Generic.ICollection<TKey>.Contains(TKey item) { throw null; }
bool System.Collections.Generic.ICollection<TKey>.Remove(TKey item) { throw null; }
System.Collections.Generic.IEnumerator<TKey> System.Collections.Generic.IEnumerable<TKey>.GetEnumerator() { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<TKey>, System.Collections.IEnumerator, System.IDisposable
{
public TKey Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
public bool MoveNext() { throw null; }
void System.Collections.IEnumerator.Reset() { }
}
}
public sealed partial class ValueCollection : System.Collections.Generic.ICollection<TValue>, System.Collections.Generic.IEnumerable<TValue>, System.Collections.Generic.IReadOnlyCollection<TValue>, System.Collections.ICollection, System.Collections.IEnumerable
{
public ValueCollection(System.Collections.Generic.Dictionary<TKey, TValue> dictionary) { }
public int Count { get { throw null; } }
bool System.Collections.Generic.ICollection<TValue>.IsReadOnly { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
public void CopyTo(TValue[] array, int index) { }
public System.Collections.Generic.Dictionary<TKey, TValue>.ValueCollection.Enumerator GetEnumerator() { throw null; }
void System.Collections.Generic.ICollection<TValue>.Add(TValue item) { }
void System.Collections.Generic.ICollection<TValue>.Clear() { }
bool System.Collections.Generic.ICollection<TValue>.Contains(TValue item) { throw null; }
bool System.Collections.Generic.ICollection<TValue>.Remove(TValue item) { throw null; }
System.Collections.Generic.IEnumerator<TValue> System.Collections.Generic.IEnumerable<TValue>.GetEnumerator() { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<TValue>, System.Collections.IEnumerator, System.IDisposable
{
public TValue Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
public bool MoveNext() { throw null; }
void System.Collections.IEnumerator.Reset() { }
}
}
}
public abstract partial class EqualityComparer<T> : System.Collections.Generic.IEqualityComparer<T>, System.Collections.IEqualityComparer
{
protected EqualityComparer() { }
public static System.Collections.Generic.EqualityComparer<T> Default { get { throw null; } }
public abstract bool Equals(T x, T y);
public abstract int GetHashCode(T obj);
bool System.Collections.IEqualityComparer.Equals(object x, object y) { throw null; }
int System.Collections.IEqualityComparer.GetHashCode(object obj) { throw null; }
}
public partial class HashSet<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.ISet<T>, System.Collections.IEnumerable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
{
public HashSet() { }
public HashSet(int capacity) { }
public HashSet(int capacity, System.Collections.Generic.IEqualityComparer<T> comparer) { }
public HashSet(System.Collections.Generic.IEnumerable<T> collection) { }
public HashSet(System.Collections.Generic.IEnumerable<T> collection, System.Collections.Generic.IEqualityComparer<T> comparer) { }
public HashSet(System.Collections.Generic.IEqualityComparer<T> comparer) { }
protected HashSet(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public System.Collections.Generic.IEqualityComparer<T> Comparer { get { throw null; } }
public int Count { get { throw null; } }
bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { throw null; } }
public bool Add(T item) { throw null; }
public void Clear() { }
public bool Contains(T item) { throw null; }
public void CopyTo(T[] array) { }
public void CopyTo(T[] array, int arrayIndex) { }
public void CopyTo(T[] array, int arrayIndex, int count) { }
public static IEqualityComparer<HashSet<T>> CreateSetComparer() { throw null; }
public void ExceptWith(System.Collections.Generic.IEnumerable<T> other) { }
public System.Collections.Generic.HashSet<T>.Enumerator GetEnumerator() { throw null; }
public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public void IntersectWith(System.Collections.Generic.IEnumerable<T> other) { }
public bool IsProperSubsetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; }
public bool IsProperSupersetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; }
public bool IsSubsetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; }
public bool IsSupersetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; }
public virtual void OnDeserialization(object sender) { }
public bool Overlaps(System.Collections.Generic.IEnumerable<T> other) { throw null; }
public bool Remove(T item) { throw null; }
public int RemoveWhere(System.Predicate<T> match) { throw null; }
public bool SetEquals(System.Collections.Generic.IEnumerable<T> other) { throw null; }
public void SymmetricExceptWith(System.Collections.Generic.IEnumerable<T> other) { }
void System.Collections.Generic.ICollection<T>.Add(T item) { }
System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public void TrimExcess() { }
public bool TryGetValue(T equalValue, out T actualValue) { throw null; }
public void UnionWith(System.Collections.Generic.IEnumerable<T> other) { }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable
{
public T Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
public bool MoveNext() { throw null; }
void System.Collections.IEnumerator.Reset() { }
}
}
public partial class LinkedList<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
{
public LinkedList() { }
public LinkedList(System.Collections.Generic.IEnumerable<T> collection) { }
protected LinkedList(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public int Count { get { throw null; } }
public System.Collections.Generic.LinkedListNode<T> First { get { throw null; } }
public System.Collections.Generic.LinkedListNode<T> Last { get { throw null; } }
bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
public System.Collections.Generic.LinkedListNode<T> AddAfter(System.Collections.Generic.LinkedListNode<T> node, T value) { throw null; }
public void AddAfter(System.Collections.Generic.LinkedListNode<T> node, System.Collections.Generic.LinkedListNode<T> newNode) { }
public System.Collections.Generic.LinkedListNode<T> AddBefore(System.Collections.Generic.LinkedListNode<T> node, T value) { throw null; }
public void AddBefore(System.Collections.Generic.LinkedListNode<T> node, System.Collections.Generic.LinkedListNode<T> newNode) { }
public System.Collections.Generic.LinkedListNode<T> AddFirst(T value) { throw null; }
public void AddFirst(System.Collections.Generic.LinkedListNode<T> node) { }
public System.Collections.Generic.LinkedListNode<T> AddLast(T value) { throw null; }
public void AddLast(System.Collections.Generic.LinkedListNode<T> node) { }
public void Clear() { }
public bool Contains(T value) { throw null; }
public void CopyTo(T[] array, int index) { }
public System.Collections.Generic.LinkedListNode<T> Find(T value) { throw null; }
public System.Collections.Generic.LinkedListNode<T> FindLast(T value) { throw null; }
public System.Collections.Generic.LinkedList<T>.Enumerator GetEnumerator() { throw null; }
public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public virtual void OnDeserialization(object sender) { }
public bool Remove(T value) { throw null; }
public void Remove(System.Collections.Generic.LinkedListNode<T> node) { }
public void RemoveFirst() { }
public void RemoveLast() { }
void System.Collections.Generic.ICollection<T>.Add(T value) { }
System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
{
public T Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public bool MoveNext() { throw null; }
void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(Object sender) { }
void System.Collections.IEnumerator.Reset() { }
}
}
public sealed partial class LinkedListNode<T>
{
public LinkedListNode(T value) { }
public System.Collections.Generic.LinkedList<T> List { get { throw null; } }
public System.Collections.Generic.LinkedListNode<T> Next { get { throw null; } }
public System.Collections.Generic.LinkedListNode<T> Previous { get { throw null; } }
public T Value { get { throw null; } set { } }
}
public partial class List<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.IReadOnlyList<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList
{
public List() { }
public List(System.Collections.Generic.IEnumerable<T> collection) { }
public List(int capacity) { }
public int Capacity { get { throw null; } set { } }
public int Count { get { throw null; } }
public T this[int index] { get { throw null; } set { } }
bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
bool System.Collections.IList.IsFixedSize { get { throw null; } }
bool System.Collections.IList.IsReadOnly { get { throw null; } }
object System.Collections.IList.this[int index] { get { throw null; } set { } }
public void Add(T item) { }
public void AddRange(System.Collections.Generic.IEnumerable<T> collection) { }
public System.Collections.ObjectModel.ReadOnlyCollection<T> AsReadOnly() { throw null; }
public int BinarySearch(T item) { throw null; }
public int BinarySearch(T item, System.Collections.Generic.IComparer<T> comparer) { throw null; }
public int BinarySearch(int index, int count, T item, System.Collections.Generic.IComparer<T> comparer) { throw null; }
public void Clear() { }
public bool Contains(T item) { throw null; }
public List<TOutput> ConvertAll<TOutput>(System.Converter<T,TOutput> converter) { throw null; }
public void CopyTo(T[] array) { }
public void CopyTo(T[] array, int arrayIndex) { }
public void CopyTo(int index, T[] array, int arrayIndex, int count) { }
public bool Exists(System.Predicate<T> match) { throw null; }
public T Find(System.Predicate<T> match) { throw null; }
public System.Collections.Generic.List<T> FindAll(System.Predicate<T> match) { throw null; }
public int FindIndex(int startIndex, int count, System.Predicate<T> match) { throw null; }
public int FindIndex(int startIndex, System.Predicate<T> match) { throw null; }
public int FindIndex(System.Predicate<T> match) { throw null; }
public T FindLast(System.Predicate<T> match) { throw null; }
public int FindLastIndex(int startIndex, int count, System.Predicate<T> match) { throw null; }
public int FindLastIndex(int startIndex, System.Predicate<T> match) { throw null; }
public int FindLastIndex(System.Predicate<T> match) { throw null; }
public void ForEach(System.Action<T> action) { }
public System.Collections.Generic.List<T>.Enumerator GetEnumerator() { throw null; }
public System.Collections.Generic.List<T> GetRange(int index, int count) { throw null; }
public int IndexOf(T item) { throw null; }
public int IndexOf(T item, int index) { throw null; }
public int IndexOf(T item, int index, int count) { throw null; }
public void Insert(int index, T item) { }
public void InsertRange(int index, System.Collections.Generic.IEnumerable<T> collection) { }
public int LastIndexOf(T item) { throw null; }
public int LastIndexOf(T item, int index) { throw null; }
public int LastIndexOf(T item, int index, int count) { throw null; }
public bool Remove(T item) { throw null; }
public int RemoveAll(System.Predicate<T> match) { throw null; }
public void RemoveAt(int index) { }
public void RemoveRange(int index, int count) { }
public void Reverse() { }
public void Reverse(int index, int count) { }
public void Sort() { }
public void Sort(System.Collections.Generic.IComparer<T> comparer) { }
public void Sort(System.Comparison<T> comparison) { }
public void Sort(int index, int count, System.Collections.Generic.IComparer<T> comparer) { }
System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int arrayIndex) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
int System.Collections.IList.Add(object item) { throw null; }
bool System.Collections.IList.Contains(object item) { throw null; }
int System.Collections.IList.IndexOf(object item) { throw null; }
void System.Collections.IList.Insert(int index, object item) { }
void System.Collections.IList.Remove(object item) { }
public T[] ToArray() { throw null; }
public void TrimExcess() { }
public bool TrueForAll(System.Predicate<T> match) { throw null; }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable
{
public T Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
public bool MoveNext() { throw null; }
void System.Collections.IEnumerator.Reset() { }
}
}
public partial class Queue<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable
{
public Queue() { }
public Queue(System.Collections.Generic.IEnumerable<T> collection) { }
public Queue(int capacity) { }
public int Count { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
public void Clear() { }
public bool Contains(T item) { throw null; }
public void CopyTo(T[] array, int arrayIndex) { }
public T Dequeue() { throw null; }
public void Enqueue(T item) { }
public System.Collections.Generic.Queue<T>.Enumerator GetEnumerator() { throw null; }
public T Peek() { throw null; }
System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public T[] ToArray() { throw null; }
public void TrimExcess() { }
public bool TryDequeue(out T result) { throw null; }
public bool TryPeek(out T result) { throw null; }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable
{
public T Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
public bool MoveNext() { throw null; }
void System.Collections.IEnumerator.Reset() { }
}
}
public partial class SortedDictionary<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable
{
public SortedDictionary() { }
public SortedDictionary(System.Collections.Generic.IComparer<TKey> comparer) { }
public SortedDictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary) { }
public SortedDictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary, System.Collections.Generic.IComparer<TKey> comparer) { }
public System.Collections.Generic.IComparer<TKey> Comparer { get { throw null; } }
public int Count { get { throw null; } }
public TValue this[TKey key] { get { throw null; } set { } }
public System.Collections.Generic.SortedDictionary<TKey, TValue>.KeyCollection Keys { get { throw null; } }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.IsReadOnly { get { throw null; } }
System.Collections.Generic.ICollection<TKey> System.Collections.Generic.IDictionary<TKey, TValue>.Keys { get { throw null; } }
System.Collections.Generic.ICollection<TValue> System.Collections.Generic.IDictionary<TKey, TValue>.Values { get { throw null; } }
System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Keys { get { throw null; } }
System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Values { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
bool System.Collections.IDictionary.IsFixedSize { get { throw null; } }
bool System.Collections.IDictionary.IsReadOnly { get { throw null; } }
object System.Collections.IDictionary.this[object key] { get { throw null; } set { } }
System.Collections.ICollection System.Collections.IDictionary.Keys { get { throw null; } }
System.Collections.ICollection System.Collections.IDictionary.Values { get { throw null; } }
public System.Collections.Generic.SortedDictionary<TKey, TValue>.ValueCollection Values { get { throw null; } }
public void Add(TKey key, TValue value) { }
public void Clear() { }
public bool ContainsKey(TKey key) { throw null; }
public bool ContainsValue(TValue value) { throw null; }
public void CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int index) { }
public System.Collections.Generic.SortedDictionary<TKey, TValue>.Enumerator GetEnumerator() { throw null; }
public bool Remove(TKey key) { throw null; }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; }
System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>.GetEnumerator() { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
void System.Collections.IDictionary.Add(object key, object value) { }
bool System.Collections.IDictionary.Contains(object key) { throw null; }
System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { throw null; }
void System.Collections.IDictionary.Remove(object key) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public bool TryGetValue(TKey key, out TValue value) { throw null; }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.IDictionaryEnumerator, System.Collections.IEnumerator, System.IDisposable
{
public System.Collections.Generic.KeyValuePair<TKey, TValue> Current { get { throw null; } }
System.Collections.DictionaryEntry System.Collections.IDictionaryEnumerator.Entry { get { throw null; } }
object System.Collections.IDictionaryEnumerator.Key { get { throw null; } }
object System.Collections.IDictionaryEnumerator.Value { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
public bool MoveNext() { throw null; }
void System.Collections.IEnumerator.Reset() { }
}
public sealed partial class KeyCollection : System.Collections.Generic.ICollection<TKey>, System.Collections.Generic.IEnumerable<TKey>, System.Collections.Generic.IReadOnlyCollection<TKey>, System.Collections.ICollection, System.Collections.IEnumerable
{
public KeyCollection(System.Collections.Generic.SortedDictionary<TKey, TValue> dictionary) { }
public int Count { get { throw null; } }
bool System.Collections.Generic.ICollection<TKey>.IsReadOnly { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
public void CopyTo(TKey[] array, int index) { }
public System.Collections.Generic.SortedDictionary<TKey, TValue>.KeyCollection.Enumerator GetEnumerator() { throw null; }
void System.Collections.Generic.ICollection<TKey>.Add(TKey item) { }
void System.Collections.Generic.ICollection<TKey>.Clear() { }
bool System.Collections.Generic.ICollection<TKey>.Contains(TKey item) { throw null; }
bool System.Collections.Generic.ICollection<TKey>.Remove(TKey item) { throw null; }
System.Collections.Generic.IEnumerator<TKey> System.Collections.Generic.IEnumerable<TKey>.GetEnumerator() { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<TKey>, System.Collections.IEnumerator, System.IDisposable
{
public TKey Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
public bool MoveNext() { throw null; }
void System.Collections.IEnumerator.Reset() { }
}
}
public sealed partial class ValueCollection : System.Collections.Generic.ICollection<TValue>, System.Collections.Generic.IEnumerable<TValue>, System.Collections.Generic.IReadOnlyCollection<TValue>, System.Collections.ICollection, System.Collections.IEnumerable
{
public ValueCollection(System.Collections.Generic.SortedDictionary<TKey, TValue> dictionary) { }
public int Count { get { throw null; } }
bool System.Collections.Generic.ICollection<TValue>.IsReadOnly { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
public void CopyTo(TValue[] array, int index) { }
public System.Collections.Generic.SortedDictionary<TKey, TValue>.ValueCollection.Enumerator GetEnumerator() { throw null; }
void System.Collections.Generic.ICollection<TValue>.Add(TValue item) { }
void System.Collections.Generic.ICollection<TValue>.Clear() { }
bool System.Collections.Generic.ICollection<TValue>.Contains(TValue item) { throw null; }
bool System.Collections.Generic.ICollection<TValue>.Remove(TValue item) { throw null; }
System.Collections.Generic.IEnumerator<TValue> System.Collections.Generic.IEnumerable<TValue>.GetEnumerator() { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<TValue>, System.Collections.IEnumerator, System.IDisposable
{
public TValue Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
public bool MoveNext() { throw null; }
void System.Collections.IEnumerator.Reset() { }
}
}
}
public partial class SortedList<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable
{
public SortedList() { }
public SortedList(System.Collections.Generic.IComparer<TKey> comparer) { }
public SortedList(System.Collections.Generic.IDictionary<TKey, TValue> dictionary) { }
public SortedList(System.Collections.Generic.IDictionary<TKey, TValue> dictionary, System.Collections.Generic.IComparer<TKey> comparer) { }
public SortedList(int capacity) { }
public SortedList(int capacity, System.Collections.Generic.IComparer<TKey> comparer) { }
public int Capacity { get { throw null; } set { } }
public System.Collections.Generic.IComparer<TKey> Comparer { get { throw null; } }
public int Count { get { throw null; } }
public TValue this[TKey key] { get { throw null; } set { } }
public System.Collections.Generic.IList<TKey> Keys { get { throw null; } }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.IsReadOnly { get { throw null; } }
System.Collections.Generic.ICollection<TKey> System.Collections.Generic.IDictionary<TKey, TValue>.Keys { get { throw null; } }
System.Collections.Generic.ICollection<TValue> System.Collections.Generic.IDictionary<TKey, TValue>.Values { get { throw null; } }
System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Keys { get { throw null; } }
System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Values { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
bool System.Collections.IDictionary.IsFixedSize { get { throw null; } }
bool System.Collections.IDictionary.IsReadOnly { get { throw null; } }
object System.Collections.IDictionary.this[object key] { get { throw null; } set { } }
System.Collections.ICollection System.Collections.IDictionary.Keys { get { throw null; } }
System.Collections.ICollection System.Collections.IDictionary.Values { get { throw null; } }
public System.Collections.Generic.IList<TValue> Values { get { throw null; } }
public void Add(TKey key, TValue value) { }
public void Clear() { }
public bool ContainsKey(TKey key) { throw null; }
public bool ContainsValue(TValue value) { throw null; }
public System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> GetEnumerator() { throw null; }
public int IndexOfKey(TKey key) { throw null; }
public int IndexOfValue(TValue value) { throw null; }
public bool Remove(TKey key) { throw null; }
public void RemoveAt(int index) { }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int arrayIndex) { }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; }
System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>.GetEnumerator() { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int arrayIndex) { }
void System.Collections.IDictionary.Add(object key, object value) { }
bool System.Collections.IDictionary.Contains(object key) { throw null; }
System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { throw null; }
void System.Collections.IDictionary.Remove(object key) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public void TrimExcess() { }
public bool TryGetValue(TKey key, out TValue value) { throw null; }
}
public partial class SortedSet<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.ISet<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
{
public SortedSet() { }
public SortedSet(System.Collections.Generic.IComparer<T> comparer) { }
public SortedSet(System.Collections.Generic.IEnumerable<T> collection) { }
public SortedSet(System.Collections.Generic.IEnumerable<T> collection, System.Collections.Generic.IComparer<T> comparer) { }
protected SortedSet(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public System.Collections.Generic.IComparer<T> Comparer { get { throw null; } }
public int Count { get { throw null; } }
public T Max { get { throw null; } }
public T Min { get { throw null; } }
bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
public bool Add(T item) { throw null; }
public virtual void Clear() { }
public virtual bool Contains(T item) { throw null; }
public void CopyTo(T[] array) { }
public void CopyTo(T[] array, int index) { }
public void CopyTo(T[] array, int index, int count) { }
public static IEqualityComparer<SortedSet<T>> CreateSetComparer() { throw null; }
public static IEqualityComparer<SortedSet<T>> CreateSetComparer(IEqualityComparer<T> memberEqualityComparer) { throw null; }
public void ExceptWith(System.Collections.Generic.IEnumerable<T> other) { }
public System.Collections.Generic.SortedSet<T>.Enumerator GetEnumerator() { throw null; }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
protected virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public virtual System.Collections.Generic.SortedSet<T> GetViewBetween(T lowerValue, T upperValue) { throw null; }
public virtual void IntersectWith(System.Collections.Generic.IEnumerable<T> other) { }
public bool IsProperSubsetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; }
public bool IsProperSupersetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; }
public bool IsSubsetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; }
public bool IsSupersetOf(System.Collections.Generic.IEnumerable<T> other) { throw null; }
protected virtual void OnDeserialization(object sender) { }
void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(object sender) { }
public bool Overlaps(System.Collections.Generic.IEnumerable<T> other) { throw null; }
public bool Remove(T item) { throw null; }
public int RemoveWhere(System.Predicate<T> match) { throw null; }
public System.Collections.Generic.IEnumerable<T> Reverse() { throw null; }
public bool SetEquals(System.Collections.Generic.IEnumerable<T> other) { throw null; }
public void SymmetricExceptWith(System.Collections.Generic.IEnumerable<T> other) { }
void System.Collections.Generic.ICollection<T>.Add(T item) { }
System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public bool TryGetValue(T equalValue, out T actualValue) { throw null; }
public void UnionWith(System.Collections.Generic.IEnumerable<T> other) { }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
{
public T Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public bool MoveNext() { throw null; }
void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(object sender) { }
void System.Collections.IEnumerator.Reset() { }
}
}
public partial class Stack<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable
{
public Stack() { }
public Stack(System.Collections.Generic.IEnumerable<T> collection) { }
public Stack(int capacity) { }
public int Count { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
public void Clear() { }
public bool Contains(T item) { throw null; }
public void CopyTo(T[] array, int arrayIndex) { }
public System.Collections.Generic.Stack<T>.Enumerator GetEnumerator() { throw null; }
public T Peek() { throw null; }
public T Pop() { throw null; }
public void Push(T item) { }
System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int arrayIndex) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public T[] ToArray() { throw null; }
public void TrimExcess() { }
public bool TryPeek(out T result) { throw null; }
public bool TryPop(out T result) { throw null; }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable
{
public T Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
public bool MoveNext() { throw null; }
void System.Collections.IEnumerator.Reset() { }
}
}
}
| |
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using AllReady.Areas.Admin.Controllers;
using AllReady.Areas.Admin.Features.Campaigns;
using AllReady.Areas.Admin.Models;
using AllReady.Models;
using AllReady.Services;
using AllReady.UnitTest.Extensions;
using MediatR;
using Microsoft.AspNetCore.Http;
using Moq;
using Xunit;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System;
using AllReady.Extensions;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
namespace AllReady.UnitTest.Areas.Admin.Controllers
{
public class CampaignAdminControllerTests
{
[Fact]
public void IndexSendsCampaignListQueryWithCorrectDataWhenUserIsOrgAdmin()
{
int OrganizationId = 99;
var mockMediator = new Mock<IMediator>();
CampaignController controller = new CampaignController(mockMediator.Object, null);
List<Claim> claims = new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, UserType.OrgAdmin.ToString()),
new Claim(AllReady.Security.ClaimTypes.Organization, OrganizationId.ToString())
};
controller.SetClaims(claims);
controller.Index();
mockMediator.Verify(mock => mock.Send(It.Is<CampaignListQuery>(q => q.OrganizationId == OrganizationId)));
}
[Fact]
public void IndexSendsCampaignListQueryWithCorrectDataWhenUserIsNotOrgAdmin()
{
var mockMediator = new Mock<IMediator>();
CampaignController controller = new CampaignController(mockMediator.Object, null);
List<Claim> claims = new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, UserType.OrgAdmin.ToString()),
};
controller.SetClaims(claims);
controller.Index();
mockMediator.Verify(mock => mock.Send(It.Is<CampaignListQuery>(q => q.OrganizationId == null)));
}
[Fact]
public void IndexReturnsCorrectViewModel()
{
IndexReturnsCorrectDataWhenUserIsOrgAdmin();
IndexReturnsCorrectDataWhenUserIsNotOrgAdmin();
}
public void IndexReturnsCorrectDataWhenUserIsOrgAdmin()
{
int OrganizationId = 99;
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(x => x.Send(It.Is<CampaignListQuery>(c => c.OrganizationId == OrganizationId)))
.Returns((CampaignListQuery q) => {
List<CampaignSummaryModel> ret = new List<CampaignSummaryModel>();
ret.Add(new CampaignSummaryModel { OrganizationId = OrganizationId });
return ret;
}
);
CampaignController controller = new CampaignController(mockMediator.Object, null);
List<Claim> claims = new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, UserType.OrgAdmin.ToString()),
new Claim(AllReady.Security.ClaimTypes.Organization, OrganizationId.ToString())
};
controller.SetClaims(claims);
ViewResult view = (ViewResult)controller.Index();
mockMediator.Verify(mock => mock.Send(It.Is<CampaignListQuery>(c => c.OrganizationId == OrganizationId)));
// Org admin should only see own campaigns
IEnumerable<CampaignSummaryModel> viewModel = (IEnumerable<CampaignSummaryModel>)view.ViewData.Model;
Assert.NotNull(viewModel);
Assert.Equal(viewModel.Count(), 1);
Assert.Equal(viewModel.First().OrganizationId, OrganizationId);
}
public void IndexReturnsCorrectDataWhenUserIsNotOrgAdmin()
{
int OrganizationId = 99;
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(x => x.Send(It.Is<CampaignListQuery>(c => c.OrganizationId == null)))
.Returns((CampaignListQuery q) => {
// return some models
List<CampaignSummaryModel> ret = new List<CampaignSummaryModel>();
ret.Add(new CampaignSummaryModel { OrganizationId = OrganizationId });
ret.Add(new CampaignSummaryModel { OrganizationId = OrganizationId + 1 });
return ret;
}
);
CampaignController controller = new CampaignController(mockMediator.Object, null);
List<Claim> claims = new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, UserType.SiteAdmin.ToString()),
};
controller.SetClaims(claims);
// All campaigns returned when not OrgAdmin
ViewResult view = (ViewResult)controller.Index();
// verify the fetch was called
mockMediator.Verify(mock => mock.Send(It.Is<CampaignListQuery>(c => c.OrganizationId == null)));
// Site admin should only see all campaigns
IEnumerable<CampaignSummaryModel> viewModel = (IEnumerable<CampaignSummaryModel>)view.ViewData.Model;
Assert.NotNull(viewModel);
Assert.Equal(viewModel.Count(), 2);
}
[Fact]
public async Task DetailsSendsCampaignDetailQueryWithCorrectCampaignId()
{
int CAMPAIGN_ID = 100;
int ORGANIZATION_ID = 99;
var mockMediator = new Mock<IMediator>();
// model is not null
mockMediator.Setup(mock => mock.SendAsync(It.Is<CampaignDetailQuery>(c => c.CampaignId == CAMPAIGN_ID))).ReturnsAsync(new CampaignDetailModel { OrganizationId = ORGANIZATION_ID, Id = CAMPAIGN_ID }).Verifiable();
CampaignController controller = new CampaignController(mockMediator.Object, null);
controller.SetClaims(new List<Claim>()); // create a User for the controller
var view = await controller.Details(CAMPAIGN_ID);
mockMediator.Verify(mock => mock.SendAsync(It.Is<CampaignDetailQuery>(c => c.CampaignId == CAMPAIGN_ID)));
}
[Fact]
public async Task DetailsReturnsHttpNotFoundResultWhenVieModelIsNull()
{
CampaignController controller;
MockMediatorCampaignDetailQuery(out controller);
Assert.IsType<NotFoundResult>(await controller.Details(It.IsAny<int>()));
}
[Fact]
public async Task DetailsReturnsHttpUnauthorizedResultIfUserIsNotOrgAdmin()
{
var controller = CampaignControllerWithDetailQuery(UserType.BasicUser.ToString(), It.IsAny<int>());
Assert.IsType<UnauthorizedResult>(await controller.Details(It.IsAny<int>()));
}
[Fact]
public async Task DetailsReturnsCorrectViewWhenViewModelIsNotNullAndUserIsOrgAdmin()
{
var controller = CampaignControllerWithDetailQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
Assert.IsType<ViewResult>(await controller.Details(It.IsAny<int>()));
}
[Fact]
public async Task DetailsReturnsCorrectViewModelWhenViewModelIsNotNullAndUserIsOrgAdmin()
{
int CAMPAIGN_ID = 100;
int ORGANIZATION_ID = 99;
var mockMediator = new Mock<IMediator>();
// model is not null
mockMediator.Setup(mock => mock.SendAsync(It.Is<CampaignDetailQuery>(c=>c.CampaignId == CAMPAIGN_ID))).ReturnsAsync(new CampaignDetailModel { OrganizationId = ORGANIZATION_ID, Id = CAMPAIGN_ID }).Verifiable();
// user is org admin
CampaignController controller = new CampaignController(mockMediator.Object, null);
controller.SetClaims(new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, UserType.OrgAdmin.ToString()),
new Claim(AllReady.Security.ClaimTypes.Organization, ORGANIZATION_ID.ToString())
});
ViewResult view = (ViewResult)(await controller.Details(CAMPAIGN_ID));
CampaignDetailModel viewModel = (CampaignDetailModel)view.ViewData.Model;
Assert.Equal(viewModel.Id, CAMPAIGN_ID);
Assert.Equal(viewModel.OrganizationId, ORGANIZATION_ID);
}
[Fact]
public void CreateReturnsCorrectViewWithCorrectViewModel()
{
var mockMediator = new Mock<IMediator>();
CampaignController controller = new CampaignController(mockMediator.Object, null);
ViewResult view = (ViewResult) controller.Create();
CampaignSummaryModel viewModel = (CampaignSummaryModel)view.ViewData.Model;
Assert.Equal(view.ViewName, "Edit");
Assert.NotNull(viewModel);
}
[Fact]
public async Task EditGetSendsCampaignSummaryQueryWithCorrectCampaignId()
{
int CAMPAIGN_ID = 100;
var mockMediator = new Mock<IMediator>();
// model is not null
mockMediator.Setup(mock => mock.SendAsync(It.Is<CampaignSummaryQuery>(c => c.CampaignId == CAMPAIGN_ID))).ReturnsAsync(new CampaignSummaryModel { Id = CAMPAIGN_ID });
CampaignController controller = new CampaignController(mockMediator.Object, null);
controller.SetClaims(new List<Claim>()); // create a User for the controller
var view = await controller.Edit(CAMPAIGN_ID);
mockMediator.Verify(mock => mock.SendAsync(It.Is<CampaignSummaryQuery>(c => c.CampaignId == CAMPAIGN_ID)));
}
[Fact]
public async Task EditGetReturnsHttpNotFoundResultWhenViewModelIsNull()
{
CampaignController controller;
MockMediatorCampaignSummaryQuery(out controller);
Assert.IsType<NotFoundResult>(await controller.Edit(It.IsAny<int>()));
}
[Fact]
public async Task EditGetReturnsHttpUnauthorizedResultWhenUserIsNotAnOrgAdmin()
{
var controller = CampaignControllerWithSummaryQuery(UserType.BasicUser.ToString(), It.IsAny<int>());
Assert.IsType<UnauthorizedResult>(await controller.Edit(It.IsAny<int>()));
}
[Fact]
public async Task EditGetReturnsCorrectViewModelWhenUserIsOrgAdmin()
{
var controller = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
Assert.IsType<ViewResult>(await controller.Edit(It.IsAny<int>()));
}
[Fact]
public async Task EditPostReturnsBadRequestWhenCampaignIsNull()
{
var controller = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
var result = await controller.Edit(null, null);
Assert.IsType<BadRequestResult>(result);
}
[Fact]
public async Task EditPostAddsCorrectKeyAndErrorMessageToModelStateWhenCampaignEndDateIsLessThanCampainStartDate()
{
var campaignSummaryModel = new CampaignSummaryModel { OrganizationId = 1, StartDate = DateTime.Now.AddDays(1), EndDate = DateTime.Now.AddDays(-1)};
var sut = new CampaignController(null, null);
sut.SetClaims(new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, UserType.OrgAdmin.ToString()),
new Claim(AllReady.Security.ClaimTypes.Organization, campaignSummaryModel.OrganizationId.ToString())
});
await sut.Edit(campaignSummaryModel, null);
var modelStateErrorCollection = sut.ModelState.GetErrorMessagesByKey(nameof(CampaignSummaryModel.EndDate));
Assert.Equal(modelStateErrorCollection.Single().ErrorMessage, "The end date must fall on or after the start date.");
}
[Fact]
public async Task EditPostInsertsCampaign()
{
int OrganizationId = 99;
int NewCampaignId = 100;
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(x => x.SendAsync(It.IsAny<EditCampaignCommand>()))
.Returns((EditCampaignCommand q) => Task.FromResult<int>(NewCampaignId) );
var mockImageService = new Mock<IImageService>();
CampaignController controller = new CampaignController(mockMediator.Object, mockImageService.Object);
List<Claim> claims = new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, UserType.OrgAdmin.ToString()),
new Claim(AllReady.Security.ClaimTypes.Organization, OrganizationId.ToString())
};
controller.SetClaims(claims);
var model = MassiveTrafficLightOutage_model;
model.OrganizationId = OrganizationId;
// verify the model is valid
var validationContext = new ValidationContext(model, null, null);
var validationResults = new List<ValidationResult>();
Validator.TryValidateObject(model, validationContext, validationResults);
Assert.Equal(0, validationResults.Count());
var file = FormFile("image/jpeg");
RedirectToActionResult view = (RedirectToActionResult) await controller.Edit(model, file);
// verify the edit(add) is called
mockMediator.Verify(mock => mock.SendAsync(It.Is<EditCampaignCommand>(c => c.Campaign.OrganizationId == OrganizationId)));
// verify that the next route
Assert.Equal(view.RouteValues["area"], "Admin");
Assert.Equal(view.RouteValues["id"], NewCampaignId);
}
[Fact]
public async Task EditPostReturnsHttpUnauthorizedResultWhenUserIsNotAnOrgAdmin()
{
var controller = CampaignControllerWithSummaryQuery(UserType.BasicUser.ToString(), It.IsAny<int>());
var result = await controller.Edit(new CampaignSummaryModel { OrganizationId = It.IsAny<int>() }, null);
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async Task EditPostRedirectsToCorrectActionWithCorrectRouteValuesWhenModelStateIsValid()
{
var controller = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
var result = await controller.Edit(new CampaignSummaryModel { Name = "Foo", OrganizationId = It.IsAny<int>() }, null);
//TODO: test result for correct Action name and Route values
Assert.IsType<RedirectToActionResult>(result);
}
[Fact]
public async Task EditPostAddsErrorToModelStateWhenInvalidImageFormatIsSupplied()
{
var controller = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
var file = FormFile("");
await controller.Edit(new CampaignSummaryModel { Name = "Foo", OrganizationId = It.IsAny<int>() }, file);
Assert.False(controller.ModelState.IsValid);
Assert.True(controller.ModelState.ContainsKey("ImageUrl"));
//TODO: test that the value associated with the key is correct
}
[Fact]
public async Task EditPostReturnsCorrectViewModelWhenInvalidImageFormatIsSupplied()
{
int ORGANIZATION_ID = 100;
var mockMediator = new Mock<IMediator>();
var mockImageService = new Mock<IImageService>();
var sut = new CampaignController(mockMediator.Object, mockImageService.Object);
sut.SetClaims(new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, UserType.OrgAdmin.ToString()),
new Claim(AllReady.Security.ClaimTypes.Organization, ORGANIZATION_ID.ToString())
});
var file = FormFile("audio/mpeg3");
CampaignSummaryModel model = MassiveTrafficLightOutage_model;
model.OrganizationId = ORGANIZATION_ID;
ViewResult view = (ViewResult)(await sut.Edit(model, file));
CampaignSummaryModel viewModel = (CampaignSummaryModel)view.ViewData.Model;
Assert.True(Object.ReferenceEquals(model, viewModel));
}
[Fact]
public async Task EditPostUploadsImageToImageService()
{
const int organizationId = 1;
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
var mockImageService = new Mock<IImageService>();
var sut = new CampaignController(mockMediator.Object, mockImageService.Object);
sut.SetClaims(new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, UserType.OrgAdmin.ToString()),
new Claim(AllReady.Security.ClaimTypes.Organization, organizationId.ToString())
});
var file = FormFile("image/jpeg");
await sut.Edit(new CampaignSummaryModel { Name = "Foo", OrganizationId = organizationId, Id = campaignId}, file);
mockImageService.Verify(mock => mock.UploadCampaignImageAsync(
It.Is<int>(i => i == organizationId),
It.Is<int>(i => i == campaignId),
It.Is<IFormFile>(i => i == file)), Times.Once);
}
[Fact]
public void EditPostHasHttpPostAttribute()
{
HttpPostAttribute attr = (HttpPostAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.Edit), new Type[] { typeof(CampaignSummaryModel), typeof(IFormFile) }).GetCustomAttribute(typeof(HttpPostAttribute));
Assert.NotNull(attr);
}
[Fact]
public void EditPostHasValidateAntiForgeryTokenttribute()
{
ValidateAntiForgeryTokenAttribute attr = (ValidateAntiForgeryTokenAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.Edit), new Type[] { typeof(CampaignSummaryModel), typeof(IFormFile) }).GetCustomAttribute(typeof(ValidateAntiForgeryTokenAttribute));
Assert.NotNull(attr);
}
[Fact]
public async Task DeleteSendsCampaignSummaryQueryWithCorrectCampaignId()
{
int ORGANIZATION_ID = 99;
int CAMPAIGN_ID = 100;
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.Is<CampaignSummaryQuery>(c => c.CampaignId == CAMPAIGN_ID))).ReturnsAsync(new CampaignSummaryModel { Id = CAMPAIGN_ID, OrganizationId = ORGANIZATION_ID });
CampaignController controller = new CampaignController(mockMediator.Object, null);
controller.SetClaims(new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, UserType.OrgAdmin.ToString()),
new Claim(AllReady.Security.ClaimTypes.Organization, ORGANIZATION_ID.ToString())
});
ViewResult view = (ViewResult)(await controller.Delete(CAMPAIGN_ID));
mockMediator.Verify(mock => mock.SendAsync(It.Is<CampaignSummaryQuery>(c => c.CampaignId == CAMPAIGN_ID)), Times.Once);
}
[Fact]
public async Task DeleteReturnsHttpNotFoundResultWhenCampaignIsNotFound()
{
CampaignController controller;
MockMediatorCampaignSummaryQuery(out controller);
Assert.IsType<NotFoundResult>(await controller.Delete(It.IsAny<int>()));
}
[Fact]
public async Task DeleteReturnsHttpUnauthorizedResultWhenUserIsNotOrgAdmin()
{
var controller = CampaignControllerWithSummaryQuery(UserType.BasicUser.ToString(), It.IsAny<int>());
Assert.IsType<UnauthorizedResult>(await controller.Delete(It.IsAny<int>()));
}
[Fact]
public async Task DeleteReturnsCorrectViewWhenUserIsOrgAdmin()
{
var controller = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
Assert.IsType<ViewResult>(await controller.Delete(It.IsAny<int>()));
}
[Fact]
public async Task DeleteReturnsCorrectViewModelWhenUserIsOrgAdmin()
{
int ORGANIZATION_ID = 99;
int CAMPAIGN_ID = 100;
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.Is<CampaignSummaryQuery>(c => c.CampaignId == CAMPAIGN_ID))).ReturnsAsync(new CampaignSummaryModel { Id = CAMPAIGN_ID, OrganizationId = ORGANIZATION_ID });
CampaignController controller = new CampaignController(mockMediator.Object, null);
controller.SetClaims(new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, UserType.OrgAdmin.ToString()),
new Claim(AllReady.Security.ClaimTypes.Organization, ORGANIZATION_ID.ToString())
});
ViewResult view = (ViewResult)(await controller.Delete(CAMPAIGN_ID));
CampaignSummaryModel viewModel = (CampaignSummaryModel)view.ViewData.Model;
Assert.Equal(viewModel.Id, CAMPAIGN_ID);
}
public async Task DeleteConfirmedSendsCampaignSummaryQueryWithCorrectCampaignId()
{
const int campaignId = 1;
var mediator = new Mock<IMediator>();
var sut = new CampaignController(mediator.Object, null);
await sut.DeleteConfirmed(campaignId);
mediator.Verify(mock => mock.SendAsync(It.Is<CampaignSummaryQuery>(i => i.CampaignId == campaignId)), Times.Once);
}
[Fact]
public async Task DetailConfirmedReturnsHttpUnauthorizedResultWhenUserIsNotOrgAdmin()
{
var controller = CampaignControllerWithSummaryQuery(UserType.BasicUser.ToString(), It.IsAny<int>());
Assert.IsType<UnauthorizedResult>(await controller.DeleteConfirmed(It.IsAny<int>()));
}
[Fact]
public async Task DetailConfirmedSendsDeleteCampaignCommandWithCorrectCampaignIdWhenUserIsOrgAdmin()
{
const int organizationId = 1;
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>())).ReturnsAsync(new CampaignSummaryModel { OrganizationId = organizationId });
var sut = new CampaignController(mockMediator.Object, null);
sut.SetClaims(new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, UserType.OrgAdmin.ToString()),
new Claim(AllReady.Security.ClaimTypes.Organization, organizationId.ToString())
});
await sut.DeleteConfirmed(campaignId);
mockMediator.Verify(mock => mock.SendAsync(It.Is<DeleteCampaignCommand>(i => i.CampaignId == campaignId)), Times.Once);
}
[Fact]
public async Task DetailConfirmedRedirectsToCorrectActionWithCorrectRouteValuesWhenUserIsOrgAdmin()
{
const int organizationId = 1;
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>())).ReturnsAsync(new CampaignSummaryModel { OrganizationId = organizationId });
var sut = new CampaignController(mockMediator.Object, null);
sut.SetClaims(new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, UserType.OrgAdmin.ToString()),
new Claim(AllReady.Security.ClaimTypes.Organization, organizationId.ToString())
});
var routeValues = new Dictionary<string, object> { ["area"] = "Admin" };
var result = await sut.DeleteConfirmed(campaignId) as RedirectToActionResult;
Assert.Equal(result.ActionName, nameof(CampaignController.Index));
Assert.Equal(result.RouteValues, routeValues);
}
[Fact]
public void DeleteConfirmedHasHttpPostAttribute()
{
HttpPostAttribute attr = (HttpPostAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.DeleteConfirmed), new Type[] { typeof(int) }).GetCustomAttribute(typeof(HttpPostAttribute));
Assert.NotNull(attr);
}
[Fact]
public void DeleteConfirmedHasActionNameAttributeWithCorrectName()
{
ActionNameAttribute attr = (ActionNameAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.DeleteConfirmed), new Type[] { typeof(int) }).GetCustomAttribute(typeof(ActionNameAttribute));
Assert.Equal(attr.Name, "Delete");
}
[Fact]
public void DeleteConfirmedHasValidateAntiForgeryTokenAttribute()
{
ValidateAntiForgeryTokenAttribute attr = (ValidateAntiForgeryTokenAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.DeleteConfirmed), new Type[] { typeof(int) }).GetCustomAttribute(typeof(ValidateAntiForgeryTokenAttribute));
Assert.NotNull(attr);
}
[Fact]
public async Task LockUnlockReturnsHttpUnauthorizedResultWhenUserIsNotSiteAdmin()
{
CampaignController controller = new CampaignController(null, null);
controller.SetClaims(new List<Claim> { new Claim(AllReady.Security.ClaimTypes.UserType, UserType.OrgAdmin.ToString()) });
Assert.IsType<UnauthorizedResult>(await controller.LockUnlock(100));
}
[Fact]
public async Task LockUnlockSendsLockUnlockCampaignCommandWithCorrectCampaignIdWhenUserIsSiteAdmin()
{
int CAMPAIGN_ID = 99;
var mockMediator = new Mock<IMediator>();
CampaignController controller = new CampaignController(mockMediator.Object, null);
List<Claim> claims = new List<Claim> { new Claim(AllReady.Security.ClaimTypes.UserType, UserType.SiteAdmin.ToString()) };
controller.SetClaims(claims);
await controller.LockUnlock(CAMPAIGN_ID);
mockMediator.Verify(mock => mock.SendAsync(It.Is<LockUnlockCampaignCommand>(q => q.CampaignId == CAMPAIGN_ID)), Times.Once);
}
[Fact]
public async Task LockUnlockRedirectsToCorrectActionWithCorrectRouteValuesWhenUserIsSiteAdmin()
{
int CAMPAIGN_ID = 100;
var mockMediator = new Mock<IMediator>();
CampaignController controller = new CampaignController(mockMediator.Object, null);
List<Claim> claims = new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, UserType.SiteAdmin.ToString()),
};
controller.SetClaims(claims);
RedirectToActionResult view = (RedirectToActionResult)await controller.LockUnlock(CAMPAIGN_ID);
// verify the next route
Assert.Equal(view.ActionName, nameof(CampaignController.Details));
Assert.Equal(view.RouteValues["area"], "Admin");
Assert.Equal(view.RouteValues["id"], CAMPAIGN_ID);
}
[Fact]
public void LockUnlockHasHttpPostAttribute()
{
HttpPostAttribute attr = (HttpPostAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.LockUnlock), new Type[] { typeof(int) }).GetCustomAttribute(typeof(HttpPostAttribute));
Assert.NotNull(attr);
}
[Fact]
public void LockUnlockdHasValidateAntiForgeryTokenAttribute()
{
ValidateAntiForgeryTokenAttribute attr = (ValidateAntiForgeryTokenAttribute)typeof(CampaignController).GetMethod(nameof(CampaignController.LockUnlock), new Type[] { typeof(int) }).GetCustomAttribute(typeof(ValidateAntiForgeryTokenAttribute));
Assert.NotNull(attr);
}
#region Helper Methods
private static Mock<IMediator> MockMediatorCampaignDetailQuery(out CampaignController controller)
{
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignDetailQuery>())).ReturnsAsync(null).Verifiable();
controller = new CampaignController(mockMediator.Object, null);
return mockMediator;
}
private static Mock<IMediator> MockMediatorCampaignSummaryQuery(out CampaignController controller)
{
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>())).ReturnsAsync(null).Verifiable();
controller = new CampaignController(mockMediator.Object, null);
return mockMediator;
}
private static CampaignController CampaignControllerWithDetailQuery(string userType, int organizationId)
{
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignDetailQuery>())).ReturnsAsync(new CampaignDetailModel { OrganizationId = organizationId }).Verifiable();
var controller = new CampaignController(mockMediator.Object, null);
controller.SetClaims(new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, userType),
new Claim(AllReady.Security.ClaimTypes.Organization, organizationId.ToString())
});
return controller;
}
private static CampaignController CampaignControllerWithSummaryQuery(string userType, int organizationId)
{
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>()))
.ReturnsAsync(new CampaignSummaryModel { OrganizationId = organizationId, Location = new LocationEditModel() }).Verifiable();
var mockImageService = new Mock<IImageService>();
var controller = new CampaignController(mockMediator.Object, mockImageService.Object);
controller.SetClaims(new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, userType),
new Claim(AllReady.Security.ClaimTypes.Organization, organizationId.ToString())
});
return controller;
}
private static IFormFile FormFile(string fileType)
{
var mockFormFile = new Mock<IFormFile>();
mockFormFile.Setup(mock => mock.ContentType).Returns(fileType);
return mockFormFile.Object;
}
#endregion
#region "Test Models"
public static LocationEditModel BogusAve_model {
get {
return new LocationEditModel() {
Address1 = "25 Bogus Ave",
City = "Agincourt",
State = "Ontario",
Country = "Canada",
PostalCode = "M1T2T9"
};
}
}
public static OrganizationEditModel AgincourtAware_model {
get {
return new OrganizationEditModel() {
Name = "Agincourt Awareness",
Location = BogusAve_model,
WebUrl = "http://www.AgincourtAwareness.ca",
LogoUrl = "http://www.AgincourtAwareness.ca/assets/LogoLarge.png" };
}
}
public static CampaignSummaryModel MassiveTrafficLightOutage_model {
get {
return new CampaignSummaryModel() {
Description = "Preparations to be ready to deal with a wide-area traffic outage.",
EndDate = DateTime.Today.AddMonths(1),
ExternalUrl = "http://agincourtaware.trafficlightoutage.com",
ExternalUrlText = "Agincourt Aware: Traffic Light Outage",
Featured = false,
FileUpload = null,
FullDescription = "<h1><strong>Massive Traffic Light Outage Plan</strong></h1>\r\n<p>The Massive Traffic Light Outage Plan (MTLOP) is the official plan to handle a major traffic light failure.</p>\r\n<p>In the event of a wide-area traffic light outage, an alternative method of controlling traffic flow will be necessary. The MTLOP calls for the recruitment and training of volunteers to be ready to direct traffic at designated intersections and to schedule and follow-up with volunteers in the event of an outage.</p>",
Id = 0,
ImageUrl = null,
Location = BogusAve_model,
Locked = false,
Name = "Massive Traffic Light Outage Plan",
PrimaryContactEmail = "mlong@agincourtawareness.com",
PrimaryContactFirstName = "Miles",
PrimaryContactLastName = "Long",
PrimaryContactPhoneNumber = "416-555-0119",
StartDate = DateTime.Today,
TimeZoneId = "Eastern Standard Time",
};
}
}
#endregion
}
}
| |
using System;
using System.Linq;
using NUnit.Framework;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Text;
using System.Text;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.CodeActions;
using RefactoringEssentials.Tests.Common;
namespace RefactoringEssentials.Tests
{
public abstract class DiagnosticTestBase
{
static MetadataReference mscorlib;
static MetadataReference systemAssembly;
static MetadataReference systemXmlLinq;
static MetadataReference systemCore;
internal static MetadataReference[] DefaultMetadataReferences;
static Dictionary<string, CodeFixProvider> providers = new Dictionary<string, CodeFixProvider>();
static DiagnosticTestBase()
{
try
{
mscorlib = MetadataReference.CreateFromFile(typeof(Console).Assembly.Location);
systemAssembly = MetadataReference.CreateFromFile(typeof(System.ComponentModel.BrowsableAttribute).Assembly.Location);
systemXmlLinq = MetadataReference.CreateFromFile(typeof(System.Xml.Linq.XElement).Assembly.Location);
systemCore = MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location);
DefaultMetadataReferences = new[] {
mscorlib,
systemAssembly,
systemCore,
systemXmlLinq
};
foreach (var provider in typeof(DiagnosticAnalyzerCategories).Assembly.GetTypes().Where(t => t.GetCustomAttributes(typeof(ExportCodeFixProviderAttribute), false).Length > 0))
{
//var attr = (ExportCodeFixProviderAttribute)provider.GetCustomAttributes(typeof(ExportCodeFixProviderAttribute), false) [0];
var codeFixProvider = (CodeFixProvider)Activator.CreateInstance(provider);
foreach (var id in codeFixProvider.FixableDiagnosticIds)
{
if (providers.ContainsKey(id))
{
Console.WriteLine("Provider " + id + " already added.");
continue;
}
providers.Add(id, codeFixProvider);
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
public static string GetUniqueName()
{
return Guid.NewGuid().ToString("D");
}
internal class TestWorkspace : Workspace
{
readonly static HostServices services = Microsoft.CodeAnalysis.Host.Mef.MefHostServices.DefaultHost;/* MefHostServices.Create(new [] {
typeof(MefHostServices).Assembly,
typeof(Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions).Assembly
});*/
public TestWorkspace(string workspaceKind = "Test") : base(services, workspaceKind)
{
/*
foreach (var a in MefHostServices.DefaultAssemblies)
{
Console.WriteLine(a.FullName);
}*/
}
public void ChangeDocument(DocumentId id, SourceText text)
{
ApplyDocumentTextChanged(id, text);
}
protected override void ApplyDocumentTextChanged(DocumentId id, SourceText text)
{
base.ApplyDocumentTextChanged(id, text);
var document = CurrentSolution.GetDocument(id);
if (document != null)
OnDocumentTextChanged(id, text, PreservationMode.PreserveValue);
}
public override bool CanApplyChange(ApplyChangesKind feature)
{
return true;
}
public void Open(ProjectInfo projectInfo)
{
var sInfo = SolutionInfo.Create(
SolutionId.CreateNewId(),
VersionStamp.Create(),
null,
new[] { projectInfo }
);
OnSolutionAdded(sInfo);
}
}
protected static void RunFix(Workspace workspace, ProjectId projectId, DocumentId documentId, Diagnostic diagnostic, int index = 0)
{
CodeFixProvider provider;
if (providers.TryGetValue(diagnostic.Id, out provider))
{
Assert.IsNotNull(provider, "null provider for : " + diagnostic.Id);
var document = workspace.CurrentSolution.GetProject(projectId).GetDocument(documentId);
var actions = new List<CodeAction>();
var context = new CodeFixContext(document, diagnostic, (fix, diags) => actions.Add(fix), default(CancellationToken));
provider.RegisterCodeFixesAsync(context).Wait();
if (!actions.Any())
{
Assert.Fail("Provider has no fix for " + diagnostic.Id + " at " + diagnostic.Location.SourceSpan);
return;
}
foreach (var op in actions[index].GetOperationsAsync(default(CancellationToken)).Result)
{
op.Apply(workspace, default(CancellationToken));
}
}
else
{
Assert.Fail("No code fix provider found for :" + diagnostic.Id);
}
}
protected static void Test<T>(string input, int expectedDiagnostics = 1, string output = null, int issueToFix = -1, int actionToRun = 0) where T : DiagnosticAnalyzer, new()
{
Assert.Fail("Use Analyze");
}
protected static void Test<T>(string input, string output, int fixIndex = 0)
where T : DiagnosticAnalyzer, new()
{
Assert.Fail("Use Analyze");
}
protected static void TestIssue<T>(string input, int issueCount = 1)
where T : DiagnosticAnalyzer, new()
{
Assert.Fail("Use Analyze");
}
protected static void TestWrongContextWithSubIssue<T>(string input, string id) where T : DiagnosticAnalyzer, new()
{
Assert.Fail("Use AnalyzeWithRule");
}
protected static void TestWithSubIssue<T>(string input, string output, string subIssue, int fixIndex = 0) where T : DiagnosticAnalyzer, new()
{
Assert.Fail("Use AnalyzeWithRule");
}
class TestDiagnosticAnalyzer<T> : DiagnosticAnalyzer
{
readonly DiagnosticAnalyzer t;
public TestDiagnosticAnalyzer(DiagnosticAnalyzer t)
{
this.t = t;
}
#region IDiagnosticAnalyzer implementation
public override void Initialize(AnalysisContext context)
{
t.Initialize(context);
}
public override System.Collections.Immutable.ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return t.SupportedDiagnostics;
}
}
#endregion
}
protected static TextSpan GetWholeSpan(Diagnostic d)
{
int start = d.Location.SourceSpan.Start;
int end = d.Location.SourceSpan.End;
foreach (var a in d.AdditionalLocations)
{
start = Math.Min(start, a.SourceSpan.Start);
end = Math.Max(start, a.SourceSpan.End);
}
return TextSpan.FromBounds(start, end);
}
protected static void Analyze<T>(Func<string, SyntaxTree> parseTextFunc, Func<SyntaxTree[], Compilation> createCompilationFunc, string language, string input, string output = null, int issueToFix = -1, int actionToRun = 0, Action<int, Diagnostic> diagnosticCheck = null) where T : DiagnosticAnalyzer, new()
{
var text = new StringBuilder();
var expectedDiagnosics = new List<TextSpan>();
int start = -1;
for (int i = 0; i < input.Length; i++)
{
char ch = input[i];
if (ch == '$')
{
if (start < 0)
{
start = text.Length;
continue;
}
expectedDiagnosics.Add(TextSpan.FromBounds(start, text.Length));
start = -1;
}
else
{
text.Append(ch);
}
}
var syntaxTree = parseTextFunc(text.ToString());
Compilation compilation = createCompilationFunc(new[] { syntaxTree });
var diagnostics = new List<Diagnostic>();
var compilationWithAnalyzers = compilation.WithAnalyzers(System.Collections.Immutable.ImmutableArray<DiagnosticAnalyzer>.Empty.Add(new T()));
var result = compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().Result;
diagnostics.AddRange(result);
diagnostics.Sort((d1, d2) => d1.Location.SourceSpan.Start.CompareTo(d2.Location.SourceSpan.Start));
expectedDiagnosics.Sort((d1, d2) => d1.Start.CompareTo(d2.Start));
if (expectedDiagnosics.Count != diagnostics.Count)
{
foreach (var diag in diagnostics)
{
Console.WriteLine(diag.Id + "/" + diag.GetMessage() + "/" + diag.Location.SourceSpan);
}
Assert.Fail("Diagnostic count mismatch expected: " + expectedDiagnosics.Count + " was " + diagnostics.Count);
}
for (int i = 0; i < expectedDiagnosics.Count; i++)
{
var d = diagnostics[i];
var wholeSpan = GetWholeSpan(d);
if (wholeSpan != expectedDiagnosics[i])
{
Assert.Fail("Diagnostic " + i + " span mismatch expected: " + expectedDiagnosics[i] + " but was " + wholeSpan);
}
if (diagnosticCheck != null)
diagnosticCheck(i, d);
}
if (output == null)
return;
var workspace = new TestWorkspace();
var projectId = ProjectId.CreateNewId();
var documentId = DocumentId.CreateNewId(projectId);
workspace.Open(ProjectInfo.Create(
projectId,
VersionStamp.Create(),
"a", "a.exe", language, null, null, null, null,
new[] {
DocumentInfo.Create(
documentId,
"a.cs",
null,
SourceCodeKind.Regular,
TextLoader.From(TextAndVersion.Create(SourceText.From(text.ToString()), VersionStamp.Create())))
}
));
if (issueToFix < 0)
{
diagnostics.Reverse();
foreach (var v in diagnostics)
{
RunFix(workspace, projectId, documentId, v);
}
}
else
{
RunFix(workspace, projectId, documentId, diagnostics.ElementAt(issueToFix), actionToRun);
}
var txt = workspace.CurrentSolution.GetProject(projectId).GetDocument(documentId).GetTextAsync().Result.ToString();
output = Utils.HomogenizeEol(output);
txt = Utils.HomogenizeEol(txt);
if (output != txt)
{
Console.WriteLine("expected:");
Console.WriteLine(output);
Console.WriteLine("got:");
Console.WriteLine(txt);
Console.WriteLine("-----Mismatch:");
for (int i = 0; i < txt.Length; i++)
{
if (i >= output.Length)
{
Console.Write("#");
continue;
}
if (txt[i] != output[i])
{
Console.Write("#");
continue;
}
Console.Write(txt[i]);
}
Assert.Fail();
}
}
protected static void AnalyzeWithRule<T>(Func<string, SyntaxTree> parseTextFunc, Func<SyntaxTree[], Compilation> createCompilationFunc, string language, string input, string ruleId, string output = null, int issueToFix = -1, int actionToRun = 0, Action<int, Diagnostic> diagnosticCheck = null) where T : DiagnosticAnalyzer, new()
{
var text = new StringBuilder();
var expectedDiagnosics = new List<TextSpan>();
int start = -1;
for (int i = 0; i < input.Length; i++)
{
char ch = input[i];
if (ch == '$')
{
if (start < 0)
{
start = text.Length;
continue;
}
expectedDiagnosics.Add(TextSpan.FromBounds(start, text.Length));
start = -1;
}
else
{
text.Append(ch);
}
}
var syntaxTree = parseTextFunc(text.ToString());
Compilation compilation = createCompilationFunc(new[] { syntaxTree });
var diagnostics = new List<Diagnostic>();
var compilationWithAnalyzers = compilation.WithAnalyzers(System.Collections.Immutable.ImmutableArray<DiagnosticAnalyzer>.Empty.Add(new T()));
diagnostics.AddRange(compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().Result);
if (expectedDiagnosics.Count != diagnostics.Count)
{
Console.WriteLine("Diagnostics: " + diagnostics.Count);
foreach (var diag in diagnostics)
{
Console.WriteLine(diag.Id + "/" + diag.GetMessage());
}
Assert.Fail("Diagnostic count mismatch expected: " + expectedDiagnosics.Count + " but was:" + diagnostics.Count);
}
for (int i = 0; i < expectedDiagnosics.Count; i++)
{
var d = diagnostics[i];
var wholeSpan = GetWholeSpan(d);
if (wholeSpan != expectedDiagnosics[i])
{
Assert.Fail("Diagnostic " + i + " span mismatch expected: " + expectedDiagnosics[i] + " but was " + wholeSpan);
}
if (diagnosticCheck != null)
diagnosticCheck(i, d);
}
if (output == null)
return;
var workspace = new TestWorkspace();
var projectId = ProjectId.CreateNewId();
var documentId = DocumentId.CreateNewId(projectId);
workspace.Open(ProjectInfo.Create(
projectId,
VersionStamp.Create(),
"", "", language, null, null, null, null,
new[] {
DocumentInfo.Create(
documentId,
"a.cs",
null,
SourceCodeKind.Regular,
TextLoader.From(TextAndVersion.Create(SourceText.From(text.ToString()), VersionStamp.Create())))
}
));
if (issueToFix < 0)
{
diagnostics.Reverse();
foreach (var v in diagnostics)
{
RunFix(workspace, projectId, documentId, v);
}
}
else
{
RunFix(workspace, projectId, documentId, diagnostics.ElementAt(issueToFix), actionToRun);
}
var txt = workspace.CurrentSolution.GetProject(projectId).GetDocument(documentId).GetTextAsync().Result.ToString();
txt = Utils.HomogenizeEol(txt);
output = Utils.HomogenizeEol(output);
if (output != txt)
{
Console.WriteLine("expected:");
Console.WriteLine(output);
Console.WriteLine("got:");
Console.WriteLine(txt);
Assert.Fail();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Core;
using Nop.Core.Data;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Orders;
using Nop.Services.Catalog;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Directory;
using Nop.Services.Events;
using Nop.Services.Localization;
using Nop.Services.Security;
using Nop.Services.Stores;
namespace Nop.Services.Orders
{
/// <summary>
/// Shopping cart service
/// </summary>
public partial class ShoppingCartService : IShoppingCartService
{
#region Fields
private readonly IRepository<ShoppingCartItem> _sciRepository;
private readonly IWorkContext _workContext;
private readonly IStoreContext _storeContext;
private readonly ICurrencyService _currencyService;
private readonly IProductService _productService;
private readonly ILocalizationService _localizationService;
private readonly IProductAttributeParser _productAttributeParser;
private readonly ICheckoutAttributeService _checkoutAttributeService;
private readonly ICheckoutAttributeParser _checkoutAttributeParser;
private readonly IPriceFormatter _priceFormatter;
private readonly ICustomerService _customerService;
private readonly ShoppingCartSettings _shoppingCartSettings;
private readonly IEventPublisher _eventPublisher;
private readonly IPermissionService _permissionService;
private readonly IAclService _aclService;
private readonly IStoreMappingService _storeMappingService;
private readonly IGenericAttributeService _genericAttributeService;
private readonly IProductAttributeService _productAttributeService;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
/// <param name="sciRepository">Shopping cart repository</param>
/// <param name="workContext">Work context</param>
/// <param name="storeContext">Store context</param>
/// <param name="currencyService">Currency service</param>
/// <param name="productService">Product settings</param>
/// <param name="localizationService">Localization service</param>
/// <param name="productAttributeParser">Product attribute parser</param>
/// <param name="checkoutAttributeService">Checkout attribute service</param>
/// <param name="checkoutAttributeParser">Checkout attribute parser</param>
/// <param name="priceFormatter">Price formatter</param>
/// <param name="customerService">Customer service</param>
/// <param name="shoppingCartSettings">Shopping cart settings</param>
/// <param name="eventPublisher">Event publisher</param>
/// <param name="permissionService">Permission service</param>
/// <param name="aclService">ACL service</param>
/// <param name="storeMappingService">Store mapping service</param>
/// <param name="genericAttributeService">Generic attribute service</param>
/// <param name="productAttributeService">Product attribute service</param>
public ShoppingCartService(IRepository<ShoppingCartItem> sciRepository,
IWorkContext workContext, IStoreContext storeContext,
ICurrencyService currencyService,
IProductService productService, ILocalizationService localizationService,
IProductAttributeParser productAttributeParser,
ICheckoutAttributeService checkoutAttributeService,
ICheckoutAttributeParser checkoutAttributeParser,
IPriceFormatter priceFormatter,
ICustomerService customerService,
ShoppingCartSettings shoppingCartSettings,
IEventPublisher eventPublisher,
IPermissionService permissionService,
IAclService aclService,
IStoreMappingService storeMappingService,
IGenericAttributeService genericAttributeService,
IProductAttributeService productAttributeService)
{
this._sciRepository = sciRepository;
this._workContext = workContext;
this._storeContext = storeContext;
this._currencyService = currencyService;
this._productService = productService;
this._localizationService = localizationService;
this._productAttributeParser = productAttributeParser;
this._checkoutAttributeService = checkoutAttributeService;
this._checkoutAttributeParser = checkoutAttributeParser;
this._priceFormatter = priceFormatter;
this._customerService = customerService;
this._shoppingCartSettings = shoppingCartSettings;
this._eventPublisher = eventPublisher;
this._permissionService = permissionService;
this._aclService = aclService;
this._storeMappingService = storeMappingService;
this._genericAttributeService = genericAttributeService;
this._productAttributeService = productAttributeService;
}
#endregion
#region Methods
/// <summary>
/// Delete shopping cart item
/// </summary>
/// <param name="shoppingCartItem">Shopping cart item</param>
/// <param name="resetCheckoutData">A value indicating whether to reset checkout data</param>
/// <param name="ensureOnlyActiveCheckoutAttributes">A value indicating whether to ensure that only active checkout attributes are attached to the current customer</param>
public virtual void DeleteShoppingCartItem(ShoppingCartItem shoppingCartItem, bool resetCheckoutData = true,
bool ensureOnlyActiveCheckoutAttributes = false)
{
if (shoppingCartItem == null)
throw new ArgumentNullException("shoppingCartItem");
var customer = shoppingCartItem.Customer;
var storeId = shoppingCartItem.StoreId;
//reset checkout data
if (resetCheckoutData)
{
_customerService.ResetCheckoutData(shoppingCartItem.Customer, shoppingCartItem.StoreId);
}
//delete item
_sciRepository.Delete(shoppingCartItem);
//reset "HasShoppingCartItems" property used for performance optimization
customer.HasShoppingCartItems = customer.ShoppingCartItems.Count > 0;
_customerService.UpdateCustomer(customer);
//validate checkout attributes
if (ensureOnlyActiveCheckoutAttributes &&
//only for shopping cart items (ignore wishlist)
shoppingCartItem.ShoppingCartType == ShoppingCartType.ShoppingCart)
{
var cart = customer.ShoppingCartItems
.Where(x => x.ShoppingCartType == ShoppingCartType.ShoppingCart)
.LimitPerStore(storeId)
.ToList();
var checkoutAttributesXml = customer.GetAttribute<string>(SystemCustomerAttributeNames.CheckoutAttributes, _genericAttributeService, storeId);
checkoutAttributesXml = _checkoutAttributeParser.EnsureOnlyActiveAttributes(checkoutAttributesXml, cart);
_genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CheckoutAttributes, checkoutAttributesXml, storeId);
}
//event notification
_eventPublisher.EntityDeleted(shoppingCartItem);
}
/// <summary>
/// Deletes expired shopping cart items
/// </summary>
/// <param name="olderThanUtc">Older than date and time</param>
/// <returns>Number of deleted items</returns>
public virtual int DeleteExpiredShoppingCartItems(DateTime olderThanUtc)
{
var query = from sci in _sciRepository.Table
where sci.UpdatedOnUtc < olderThanUtc
select sci;
var cartItems = query.ToList();
foreach (var cartItem in cartItems)
_sciRepository.Delete(cartItem);
return cartItems.Count;
}
/// <summary>
/// Validates required products (products which require other variant to be added to the cart)
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="shoppingCartType">Shopping cart type</param>
/// <param name="product">Product</param>
/// <param name="storeId">Store identifier</param>
/// <param name="automaticallyAddRequiredProductsIfEnabled">Automatically add required products if enabled</param>
/// <returns>Warnings</returns>
public virtual IList<string> GetRequiredProductWarnings(Customer customer,
ShoppingCartType shoppingCartType, Product product,
int storeId, bool automaticallyAddRequiredProductsIfEnabled)
{
if (customer == null)
throw new ArgumentNullException("customer");
if (product == null)
throw new ArgumentNullException("product");
var cart = customer.ShoppingCartItems
.Where(sci => sci.ShoppingCartType == shoppingCartType)
.LimitPerStore(storeId)
.ToList();
var warnings = new List<string>();
if (product.RequireOtherProducts)
{
var requiredProducts = new List<Product>();
foreach (var id in product.ParseRequiredProductIds())
{
var rp = _productService.GetProductById(id);
if (rp != null)
requiredProducts.Add(rp);
}
foreach (var rp in requiredProducts)
{
//ensure that product is in the cart
bool alreadyInTheCart = false;
foreach (var sci in cart)
{
if (sci.ProductId == rp.Id)
{
alreadyInTheCart = true;
break;
}
}
//not in the cart
if (!alreadyInTheCart)
{
if (product.AutomaticallyAddRequiredProducts)
{
//add to cart (if possible)
if (automaticallyAddRequiredProductsIfEnabled)
{
//pass 'false' for 'automaticallyAddRequiredProductsIfEnabled' to prevent circular references
var addToCartWarnings = AddToCart(customer, rp, shoppingCartType, storeId, "", decimal.Zero, 1, false);
if (addToCartWarnings.Count > 0)
{
//a product wasn't atomatically added for some reasons
//don't display specific errors from 'addToCartWarnings' variable
//display only generic error
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.RequiredProductWarning"), rp.GetLocalized(x => x.Name)));
}
}
else
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.RequiredProductWarning"), rp.GetLocalized(x => x.Name)));
}
}
else
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.RequiredProductWarning"), rp.GetLocalized(x => x.Name)));
}
}
}
}
return warnings;
}
/// <summary>
/// Validates a product for standard properties
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="shoppingCartType">Shopping cart type</param>
/// <param name="product">Product</param>
/// <param name="selectedAttributes">Selected attributes</param>
/// <param name="customerEnteredPrice">Customer entered price</param>
/// <param name="quantity">Quantity</param>
/// <returns>Warnings</returns>
public virtual IList<string> GetStandardWarnings(Customer customer, ShoppingCartType shoppingCartType,
Product product, string selectedAttributes, decimal customerEnteredPrice,
int quantity)
{
if (customer == null)
throw new ArgumentNullException("customer");
if (product == null)
throw new ArgumentNullException("product");
var warnings = new List<string>();
//deleted
if (product.Deleted )
{
warnings.Add(_localizationService.GetResource("ShoppingCart.ProductDeleted"));
return warnings;
}
//published
if (!product.Published)
{
warnings.Add(_localizationService.GetResource("ShoppingCart.ProductUnpublished"));
}
//we can add only simple products
if (product.ProductType != ProductType.SimpleProduct)
{
warnings.Add("This is not simple product");
}
//ACL
if (!_aclService.Authorize(product, customer))
{
warnings.Add(_localizationService.GetResource("ShoppingCart.ProductUnpublished"));
}
//Store mapping
if (!_storeMappingService.Authorize(product, _storeContext.CurrentStore.Id))
{
warnings.Add(_localizationService.GetResource("ShoppingCart.ProductUnpublished"));
}
//disabled "add to cart" button
if (shoppingCartType == ShoppingCartType.ShoppingCart && product.DisableBuyButton)
{
warnings.Add(_localizationService.GetResource("ShoppingCart.BuyingDisabled"));
}
//disabled "add to wishlist" button
if (shoppingCartType == ShoppingCartType.Wishlist && product.DisableWishlistButton)
{
warnings.Add(_localizationService.GetResource("ShoppingCart.WishlistDisabled"));
}
//call for price
if (shoppingCartType == ShoppingCartType.ShoppingCart && product.CallForPrice)
{
warnings.Add(_localizationService.GetResource("Products.CallForPrice"));
}
//customer entered price
if (product.CustomerEntersPrice)
{
if (customerEnteredPrice < product.MinimumCustomerEnteredPrice ||
customerEnteredPrice > product.MaximumCustomerEnteredPrice)
{
decimal minimumCustomerEnteredPrice = _currencyService.ConvertFromPrimaryStoreCurrency(product.MinimumCustomerEnteredPrice, _workContext.WorkingCurrency);
decimal maximumCustomerEnteredPrice = _currencyService.ConvertFromPrimaryStoreCurrency(product.MaximumCustomerEnteredPrice, _workContext.WorkingCurrency);
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.CustomerEnteredPrice.RangeError"),
_priceFormatter.FormatPrice(minimumCustomerEnteredPrice, false, false),
_priceFormatter.FormatPrice(maximumCustomerEnteredPrice, false, false)));
}
}
//quantity validation
var hasQtyWarnings = false;
if (quantity < product.OrderMinimumQuantity)
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.MinimumQuantity"), product.OrderMinimumQuantity));
hasQtyWarnings = true;
}
if (quantity > product.OrderMaximumQuantity)
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.MaximumQuantity"), product.OrderMaximumQuantity));
hasQtyWarnings = true;
}
var allowedQuantities = product.ParseAllowedQuatities();
if (allowedQuantities.Length > 0 && !allowedQuantities.Contains(quantity))
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.AllowedQuantities"), string.Join(", ", allowedQuantities)));
}
var validateOutOfStock = shoppingCartType == ShoppingCartType.ShoppingCart || !_shoppingCartSettings.AllowOutOfStockItemsToBeAddedToWishlist;
if (validateOutOfStock && !hasQtyWarnings)
{
switch (product.ManageInventoryMethod)
{
case ManageInventoryMethod.DontManageStock:
{
//do nothing
}
break;
case ManageInventoryMethod.ManageStock:
{
if ((BackorderMode)product.BackorderMode == BackorderMode.NoBackorders)
{
if (product.StockQuantity < quantity)
{
int maximumQuantityCanBeAdded = product.StockQuantity;
if (maximumQuantityCanBeAdded <= 0)
warnings.Add(_localizationService.GetResource("ShoppingCart.OutOfStock"));
else
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.QuantityExceedsStock"), maximumQuantityCanBeAdded));
}
}
}
break;
case ManageInventoryMethod.ManageStockByAttributes:
{
var combination = product
.ProductVariantAttributeCombinations
.FirstOrDefault(x => _productAttributeParser.AreProductAttributesEqual(x.AttributesXml, selectedAttributes));
if (combination != null)
{
//combination exists
//let's check stock level
if (!combination.AllowOutOfStockOrders && combination.StockQuantity < quantity)
{
int maximumQuantityCanBeAdded = combination.StockQuantity;
if (maximumQuantityCanBeAdded <= 0)
{
warnings.Add(_localizationService.GetResource("ShoppingCart.OutOfStock"));
}
else
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.QuantityExceedsStock"), maximumQuantityCanBeAdded));
}
}
}
else
{
//combination doesn't exist
if (product.AllowAddingOnlyExistingAttributeCombinations)
{
//maybe, is it better to display something like "No such product/combination" message?
warnings.Add(_localizationService.GetResource("ShoppingCart.OutOfStock"));
}
}
}
break;
default:
break;
}
}
//availability dates
bool availableStartDateError = false;
if (product.AvailableStartDateTimeUtc.HasValue)
{
DateTime now = DateTime.UtcNow;
DateTime availableStartDateTime = DateTime.SpecifyKind(product.AvailableStartDateTimeUtc.Value, DateTimeKind.Utc);
if (availableStartDateTime.CompareTo(now) > 0)
{
warnings.Add(_localizationService.GetResource("ShoppingCart.NotAvailable"));
availableStartDateError = true;
}
}
if (product.AvailableEndDateTimeUtc.HasValue && !availableStartDateError)
{
DateTime now = DateTime.UtcNow;
DateTime availableEndDateTime = DateTime.SpecifyKind(product.AvailableEndDateTimeUtc.Value, DateTimeKind.Utc);
if (availableEndDateTime.CompareTo(now) < 0)
{
warnings.Add(_localizationService.GetResource("ShoppingCart.NotAvailable"));
}
}
return warnings;
}
/// <summary>
/// Validates shopping cart item attributes
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="shoppingCartType">Shopping cart type</param>
/// <param name="product">Product</param>
/// <param name="quantity">Quantity</param>
/// <param name="selectedAttributes">Selected attributes</param>
/// <returns>Warnings</returns>
public virtual IList<string> GetShoppingCartItemAttributeWarnings(Customer customer,
ShoppingCartType shoppingCartType,
Product product,
int quantity = 1,
string selectedAttributes = "")
{
if (product == null)
throw new ArgumentNullException("product");
var warnings = new List<string>();
//ensure it's our attributes
var pva1Collection = _productAttributeParser.ParseProductVariantAttributes(selectedAttributes);
foreach (var pva1 in pva1Collection)
{
if (pva1.Product != null)
{
if (pva1.Product.Id != product.Id)
{
warnings.Add("Attribute error");
}
}
else
{
warnings.Add("Attribute error");
return warnings;
}
}
//validate required product attributes (whether they're chosen/selected/entered)
var pva2Collection = _productAttributeService.GetProductVariantAttributesByProductId(product.Id);
foreach (var pva2 in pva2Collection)
{
if (pva2.IsRequired)
{
bool found = false;
//selected product attributes
foreach (var pva1 in pva1Collection)
{
if (pva1.Id == pva2.Id)
{
var pvaValuesStr = _productAttributeParser.ParseValues(selectedAttributes, pva1.Id);
foreach (string str1 in pvaValuesStr)
{
if (!String.IsNullOrEmpty(str1.Trim()))
{
found = true;
break;
}
}
}
}
//if not found
if (!found)
{
var notFoundWarning = !string.IsNullOrEmpty(pva2.TextPrompt) ?
pva2.TextPrompt :
string.Format(_localizationService.GetResource("ShoppingCart.SelectAttribute"), pva2.ProductAttribute.GetLocalized(a => a.Name));
warnings.Add(notFoundWarning);
}
}
if (pva2.AttributeControlType == AttributeControlType.ReadonlyCheckboxes)
{
//customers cannot edit read-only attributes
var allowedReadOnlyValueIds = _productAttributeService.GetProductVariantAttributeValues(pva2.Id)
.Where(x => x.IsPreSelected)
.Select(x => x.Id)
.ToArray();
var selectedReadOnlyValueIds = _productAttributeParser.ParseProductVariantAttributeValues(selectedAttributes)
.Where(x => x.ProductVariantAttributeId == pva2.Id)
.Select(x => x.Id)
.ToArray();
if (!CommonHelper.ArraysEqual(allowedReadOnlyValueIds, selectedReadOnlyValueIds))
{
warnings.Add("You cannot change read-only values");
}
}
}
//validation rules
foreach (var pva in pva2Collection)
{
if (!pva.ValidationRulesAllowed())
continue;
//minimum length
if (pva.ValidationMinLength.HasValue)
{
if (pva.AttributeControlType == AttributeControlType.TextBox ||
pva.AttributeControlType == AttributeControlType.MultilineTextbox)
{
var valuesStr = _productAttributeParser.ParseValues(selectedAttributes, pva.Id);
var enteredText = valuesStr.FirstOrDefault();
int enteredTextLength = String.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;
if (pva.ValidationMinLength.Value > enteredTextLength)
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.TextboxMinimumLength"), pva.ProductAttribute.GetLocalized(a => a.Name), pva.ValidationMinLength.Value));
}
}
}
//maximum length
if (pva.ValidationMaxLength.HasValue)
{
if (pva.AttributeControlType == AttributeControlType.TextBox ||
pva.AttributeControlType == AttributeControlType.MultilineTextbox)
{
var valuesStr = _productAttributeParser.ParseValues(selectedAttributes, pva.Id);
var enteredText = valuesStr.FirstOrDefault();
int enteredTextLength = String.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;
if (pva.ValidationMaxLength.Value < enteredTextLength)
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.TextboxMaximumLength"), pva.ProductAttribute.GetLocalized(a => a.Name), pva.ValidationMaxLength.Value));
}
}
}
}
if (warnings.Count > 0)
return warnings;
//validate bundled products
var pvaValues = _productAttributeParser.ParseProductVariantAttributeValues(selectedAttributes);
foreach (var pvaValue in pvaValues)
{
if (pvaValue.AttributeValueType == AttributeValueType.AssociatedToProduct)
{
//associated product (bundle)
var associatedProduct = _productService.GetProductById(pvaValue.AssociatedProductId);
if (associatedProduct != null)
{
var totalQty = quantity*pvaValue.Quantity;
var associatedProductWarnings = GetShoppingCartItemWarnings(customer,
shoppingCartType, associatedProduct, _storeContext.CurrentStore.Id,
"", decimal.Zero, totalQty, false, true, true, true, true);
foreach (var associatedProductWarning in associatedProductWarnings)
{
var paName = pvaValue.ProductVariantAttribute.ProductAttribute.GetLocalized(a => a.Name);
var pvavName = pvaValue.GetLocalized(a => a.Name);
warnings.Add(
string.Format(
_localizationService.GetResource("ShoppingCart.AssociatedAttributeWarning"), paName,
pvavName, associatedProductWarning));
}
}
else
{
warnings.Add(string.Format("Associated product cannot be loaded - {0}",
pvaValue.AssociatedProductId));
}
}
}
return warnings;
}
/// <summary>
/// Validates shopping cart item (gift card)
/// </summary>
/// <param name="shoppingCartType">Shopping cart type</param>
/// <param name="product">Product</param>
/// <param name="selectedAttributes">Selected attributes</param>
/// <returns>Warnings</returns>
public virtual IList<string> GetShoppingCartItemGiftCardWarnings(ShoppingCartType shoppingCartType,
Product product, string selectedAttributes)
{
if (product == null)
throw new ArgumentNullException("product");
var warnings = new List<string>();
//gift cards
if (product.IsGiftCard)
{
string giftCardRecipientName = string.Empty;
string giftCardRecipientEmail = string.Empty;
string giftCardSenderName = string.Empty;
string giftCardSenderEmail = string.Empty;
string giftCardMessage = string.Empty;
_productAttributeParser.GetGiftCardAttribute(selectedAttributes,
out giftCardRecipientName, out giftCardRecipientEmail,
out giftCardSenderName, out giftCardSenderEmail, out giftCardMessage);
if (String.IsNullOrEmpty(giftCardRecipientName))
warnings.Add(_localizationService.GetResource("ShoppingCart.RecipientNameError"));
if (product.GiftCardType == GiftCardType.Virtual)
{
//validate for virtual gift cards only
if (String.IsNullOrEmpty(giftCardRecipientEmail) || !CommonHelper.IsValidEmail(giftCardRecipientEmail))
warnings.Add(_localizationService.GetResource("ShoppingCart.RecipientEmailError"));
}
if (String.IsNullOrEmpty(giftCardSenderName))
warnings.Add(_localizationService.GetResource("ShoppingCart.SenderNameError"));
if (product.GiftCardType == GiftCardType.Virtual)
{
//validate for virtual gift cards only
if (String.IsNullOrEmpty(giftCardSenderEmail) || !CommonHelper.IsValidEmail(giftCardSenderEmail))
warnings.Add(_localizationService.GetResource("ShoppingCart.SenderEmailError"));
}
}
return warnings;
}
/// <summary>
/// Validates shopping cart item
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="shoppingCartType">Shopping cart type</param>
/// <param name="product">Product</param>
/// <param name="storeId">Store identifier</param>
/// <param name="selectedAttributes">Selected attributes</param>
/// <param name="customerEnteredPrice">Customer entered price</param>
/// <param name="quantity">Quantity</param>
/// <param name="automaticallyAddRequiredProductsIfEnabled">Automatically add required products if enabled</param>
/// <param name="getStandardWarnings">A value indicating whether we should validate a product for standard properties</param>
/// <param name="getAttributesWarnings">A value indicating whether we should validate product attributes</param>
/// <param name="getGiftCardWarnings">A value indicating whether we should validate gift card properties</param>
/// <param name="getRequiredProductVariantWarnings">A value indicating whether we should validate required products (products which require other products to be added to the cart)</param>
/// <returns>Warnings</returns>
public virtual IList<string> GetShoppingCartItemWarnings(Customer customer, ShoppingCartType shoppingCartType,
Product product, int storeId,
string selectedAttributes, decimal customerEnteredPrice,
int quantity, bool automaticallyAddRequiredProductsIfEnabled,
bool getStandardWarnings = true, bool getAttributesWarnings = true,
bool getGiftCardWarnings = true, bool getRequiredProductVariantWarnings = true)
{
if (product == null)
throw new ArgumentNullException("product");
var warnings = new List<string>();
//standard properties
if (getStandardWarnings)
warnings.AddRange(GetStandardWarnings(customer, shoppingCartType, product, selectedAttributes, customerEnteredPrice, quantity));
//selected attributes
if (getAttributesWarnings)
warnings.AddRange(GetShoppingCartItemAttributeWarnings(customer, shoppingCartType, product, quantity, selectedAttributes));
//gift cards
if (getGiftCardWarnings)
warnings.AddRange(GetShoppingCartItemGiftCardWarnings(shoppingCartType, product, selectedAttributes));
//required products
if (getRequiredProductVariantWarnings)
warnings.AddRange(GetRequiredProductWarnings(customer, shoppingCartType, product, storeId, automaticallyAddRequiredProductsIfEnabled));
return warnings;
}
/// <summary>
/// Validates whether this shopping cart is valid
/// </summary>
/// <param name="shoppingCart">Shopping cart</param>
/// <param name="checkoutAttributes">Checkout attributes</param>
/// <param name="validateCheckoutAttributes">A value indicating whether to validate checkout attributes</param>
/// <returns>Warnings</returns>
public virtual IList<string> GetShoppingCartWarnings(IList<ShoppingCartItem> shoppingCart,
string checkoutAttributes, bool validateCheckoutAttributes)
{
var warnings = new List<string>();
bool hasStandartProducts = false;
bool hasRecurringProducts = false;
foreach (var sci in shoppingCart)
{
var product = sci.Product;
if (product == null)
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.CannotLoadProduct"), sci.ProductId));
return warnings;
}
if (product.IsRecurring)
hasRecurringProducts = true;
else
hasStandartProducts = true;
}
//don't mix standard and recurring products
if (hasStandartProducts && hasRecurringProducts)
warnings.Add(_localizationService.GetResource("ShoppingCart.CannotMixStandardAndAutoshipProducts"));
//recurring cart validation
if (hasRecurringProducts)
{
int cycleLength = 0;
var cyclePeriod = RecurringProductCyclePeriod.Days;
int totalCycles = 0;
string cyclesError = shoppingCart.GetRecurringCycleInfo(_localizationService,
out cycleLength, out cyclePeriod, out totalCycles);
if (!string.IsNullOrEmpty(cyclesError))
{
warnings.Add(cyclesError);
return warnings;
}
}
//validate checkout attributes
if (validateCheckoutAttributes)
{
//selected attributes
var ca1Collection = _checkoutAttributeParser.ParseCheckoutAttributes(checkoutAttributes);
//existing checkout attributes
var ca2Collection = _checkoutAttributeService.GetAllCheckoutAttributes(_storeContext.CurrentStore.Id, !shoppingCart.RequiresShipping());
foreach (var ca2 in ca2Collection)
{
if (ca2.IsRequired)
{
bool found = false;
//selected checkout attributes
foreach (var ca1 in ca1Collection)
{
if (ca1.Id == ca2.Id)
{
var caValuesStr = _checkoutAttributeParser.ParseValues(checkoutAttributes, ca1.Id);
foreach (string str1 in caValuesStr)
if (!String.IsNullOrEmpty(str1.Trim()))
{
found = true;
break;
}
}
}
//if not found
if (!found)
{
if (!string.IsNullOrEmpty(ca2.GetLocalized(a => a.TextPrompt)))
warnings.Add(ca2.GetLocalized(a => a.TextPrompt));
else
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.SelectAttribute"), ca2.GetLocalized(a => a.Name)));
}
}
}
//now validation rules
//minimum length
foreach (var ca in ca2Collection)
{
if (ca.ValidationMinLength.HasValue)
{
if (ca.AttributeControlType == AttributeControlType.TextBox ||
ca.AttributeControlType == AttributeControlType.MultilineTextbox)
{
var valuesStr = _checkoutAttributeParser.ParseValues(checkoutAttributes, ca.Id);
var enteredText = valuesStr.FirstOrDefault();
int enteredTextLength = String.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;
if (ca.ValidationMinLength.Value > enteredTextLength)
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.TextboxMinimumLength"), ca.GetLocalized(a => a.Name), ca.ValidationMinLength.Value));
}
}
}
//maximum length
if (ca.ValidationMaxLength.HasValue)
{
if (ca.AttributeControlType == AttributeControlType.TextBox ||
ca.AttributeControlType == AttributeControlType.MultilineTextbox)
{
var valuesStr = _checkoutAttributeParser.ParseValues(checkoutAttributes, ca.Id);
var enteredText = valuesStr.FirstOrDefault();
int enteredTextLength = String.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;
if (ca.ValidationMaxLength.Value < enteredTextLength)
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.TextboxMaximumLength"), ca.GetLocalized(a => a.Name), ca.ValidationMaxLength.Value));
}
}
}
}
}
return warnings;
}
/// <summary>
/// Finds a shopping cart item in the cart
/// </summary>
/// <param name="shoppingCart">Shopping cart</param>
/// <param name="shoppingCartType">Shopping cart type</param>
/// <param name="product">Product</param>
/// <param name="selectedAttributes">Selected attributes</param>
/// <param name="customerEnteredPrice">Price entered by a customer</param>
/// <returns>Found shopping cart item</returns>
public virtual ShoppingCartItem FindShoppingCartItemInTheCart(IList<ShoppingCartItem> shoppingCart,
ShoppingCartType shoppingCartType,
Product product,
string selectedAttributes = "",
decimal customerEnteredPrice = decimal.Zero)
{
if (shoppingCart == null)
throw new ArgumentNullException("shoppingCart");
if (product == null)
throw new ArgumentNullException("product");
foreach (var sci in shoppingCart.Where(a => a.ShoppingCartType == shoppingCartType))
{
if (sci.ProductId == product.Id)
{
//attributes
bool attributesEqual = _productAttributeParser.AreProductAttributesEqual(sci.AttributesXml, selectedAttributes);
//gift cards
bool giftCardInfoSame = true;
if (sci.Product.IsGiftCard)
{
string giftCardRecipientName1 = string.Empty;
string giftCardRecipientEmail1 = string.Empty;
string giftCardSenderName1 = string.Empty;
string giftCardSenderEmail1 = string.Empty;
string giftCardMessage1 = string.Empty;
_productAttributeParser.GetGiftCardAttribute(selectedAttributes,
out giftCardRecipientName1, out giftCardRecipientEmail1,
out giftCardSenderName1, out giftCardSenderEmail1, out giftCardMessage1);
string giftCardRecipientName2 = string.Empty;
string giftCardRecipientEmail2 = string.Empty;
string giftCardSenderName2 = string.Empty;
string giftCardSenderEmail2 = string.Empty;
string giftCardMessage2 = string.Empty;
_productAttributeParser.GetGiftCardAttribute(sci.AttributesXml,
out giftCardRecipientName2, out giftCardRecipientEmail2,
out giftCardSenderName2, out giftCardSenderEmail2, out giftCardMessage2);
if (giftCardRecipientName1.ToLowerInvariant() != giftCardRecipientName2.ToLowerInvariant() ||
giftCardSenderName1.ToLowerInvariant() != giftCardSenderName2.ToLowerInvariant())
giftCardInfoSame = false;
}
//price is the same (for products which require customers to enter a price)
bool customerEnteredPricesEqual = true;
if (sci.Product.CustomerEntersPrice)
customerEnteredPricesEqual = Math.Round(sci.CustomerEnteredPrice, 2) == Math.Round(customerEnteredPrice, 2);
//found?
if (attributesEqual && giftCardInfoSame && customerEnteredPricesEqual)
return sci;
}
}
return null;
}
/// <summary>
/// Add a product to shopping cart
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="product">Product</param>
/// <param name="shoppingCartType">Shopping cart type</param>
/// <param name="storeId">Store identifier</param>
/// <param name="selectedAttributes">Selected attributes</param>
/// <param name="customerEnteredPrice">The price enter by a customer</param>
/// <param name="quantity">Quantity</param>
/// <param name="automaticallyAddRequiredProductsIfEnabled">Automatically add required products if enabled</param>
/// <returns>Warnings</returns>
public virtual IList<string> AddToCart(Customer customer, Product product,
ShoppingCartType shoppingCartType, int storeId, string selectedAttributes,
decimal customerEnteredPrice, int quantity, bool automaticallyAddRequiredProductsIfEnabled)
{
if (customer == null)
throw new ArgumentNullException("customer");
if (product == null)
throw new ArgumentNullException("product");
var warnings = new List<string>();
if (shoppingCartType == ShoppingCartType.ShoppingCart && !_permissionService.Authorize(StandardPermissionProvider.EnableShoppingCart, customer))
{
warnings.Add("Shopping cart is disabled");
return warnings;
}
if (shoppingCartType == ShoppingCartType.Wishlist && !_permissionService.Authorize(StandardPermissionProvider.EnableWishlist, customer))
{
warnings.Add("Wishlist is disabled");
return warnings;
}
if (quantity <= 0)
{
warnings.Add(_localizationService.GetResource("ShoppingCart.QuantityShouldPositive"));
return warnings;
}
//reset checkout info
_customerService.ResetCheckoutData(customer, storeId);
var cart = customer.ShoppingCartItems
.Where(sci => sci.ShoppingCartType == shoppingCartType)
.LimitPerStore(storeId)
.ToList();
var shoppingCartItem = FindShoppingCartItemInTheCart(cart,
shoppingCartType, product, selectedAttributes, customerEnteredPrice);
if (shoppingCartItem != null)
{
//update existing shopping cart item
int newQuantity = shoppingCartItem.Quantity + quantity;
warnings.AddRange(GetShoppingCartItemWarnings(customer, shoppingCartType, product,
storeId, selectedAttributes,
customerEnteredPrice, newQuantity, automaticallyAddRequiredProductsIfEnabled));
if (warnings.Count == 0)
{
shoppingCartItem.AttributesXml = selectedAttributes;
shoppingCartItem.Quantity = newQuantity;
shoppingCartItem.UpdatedOnUtc = DateTime.UtcNow;
_customerService.UpdateCustomer(customer);
//event notification
_eventPublisher.EntityUpdated(shoppingCartItem);
}
}
else
{
//new shopping cart item
warnings.AddRange(GetShoppingCartItemWarnings(customer, shoppingCartType, product,
storeId, selectedAttributes, customerEnteredPrice, quantity, automaticallyAddRequiredProductsIfEnabled));
if (warnings.Count == 0)
{
//maximum items validation
switch (shoppingCartType)
{
case ShoppingCartType.ShoppingCart:
{
if (cart.Count >= _shoppingCartSettings.MaximumShoppingCartItems)
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.MaximumShoppingCartItems"), _shoppingCartSettings.MaximumShoppingCartItems));
return warnings;
}
}
break;
case ShoppingCartType.Wishlist:
{
if (cart.Count >= _shoppingCartSettings.MaximumWishlistItems)
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.MaximumWishlistItems"), _shoppingCartSettings.MaximumWishlistItems));
return warnings;
}
}
break;
default:
break;
}
DateTime now = DateTime.UtcNow;
shoppingCartItem = new ShoppingCartItem()
{
ShoppingCartType = shoppingCartType,
StoreId = storeId,
Product = product,
AttributesXml = selectedAttributes,
CustomerEnteredPrice = customerEnteredPrice,
Quantity = quantity,
CreatedOnUtc = now,
UpdatedOnUtc = now
};
customer.ShoppingCartItems.Add(shoppingCartItem);
_customerService.UpdateCustomer(customer);
//updated "HasShoppingCartItems" property used for performance optimization
customer.HasShoppingCartItems = customer.ShoppingCartItems.Count > 0;
_customerService.UpdateCustomer(customer);
//event notification
_eventPublisher.EntityInserted(shoppingCartItem);
}
}
return warnings;
}
/// <summary>
/// Updates the shopping cart item
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="shoppingCartItemId">Shopping cart item identifier</param>
/// <param name="selectedAttributes">New shopping cart item attributes</param>
/// <param name="customerEnteredPrice">New customer entered price</param>
/// <param name="quantity">New shopping cart item quantity</param>
/// <param name="resetCheckoutData">A value indicating whether to reset checkout data</param>
/// <returns>Warnings</returns>
public virtual IList<string> UpdateShoppingCartItem(Customer customer,
int shoppingCartItemId, string selectedAttributes,
decimal customerEnteredPrice, int quantity, bool resetCheckoutData)
{
if (customer == null)
throw new ArgumentNullException("customer");
var warnings = new List<string>();
var shoppingCartItem = customer.ShoppingCartItems.FirstOrDefault(sci => sci.Id == shoppingCartItemId);
if (shoppingCartItem != null)
{
if (resetCheckoutData)
{
//reset checkout data
_customerService.ResetCheckoutData(customer, shoppingCartItem.StoreId);
}
if (quantity > 0)
{
//check warnings
warnings.AddRange(GetShoppingCartItemWarnings(customer, shoppingCartItem.ShoppingCartType,
shoppingCartItem.Product, shoppingCartItem.StoreId,
selectedAttributes, customerEnteredPrice, quantity, false));
if (warnings.Count == 0)
{
//if everything is OK, then update a shopping cart item
shoppingCartItem.Quantity = quantity;
shoppingCartItem.AttributesXml = selectedAttributes;
shoppingCartItem.CustomerEnteredPrice = customerEnteredPrice;
shoppingCartItem.UpdatedOnUtc = DateTime.UtcNow;
_customerService.UpdateCustomer(customer);
//event notification
_eventPublisher.EntityUpdated(shoppingCartItem);
}
}
else
{
//delete a shopping cart item
DeleteShoppingCartItem(shoppingCartItem, resetCheckoutData, true);
}
}
return warnings;
}
/// <summary>
/// Migrate shopping cart
/// </summary>
/// <param name="fromCustomer">From customer</param>
/// <param name="toCustomer">To customer</param>
/// <param name="includeCouponCodes">A value indicating whether to coupon codes (discount and gift card) should be also re-applied</param>
public virtual void MigrateShoppingCart(Customer fromCustomer, Customer toCustomer, bool includeCouponCodes)
{
if (fromCustomer == null)
throw new ArgumentNullException("fromCustomer");
if (toCustomer == null)
throw new ArgumentNullException("toCustomer");
if (fromCustomer.Id == toCustomer.Id)
return; //the same customer
//shopping cart items
var fromCart = fromCustomer.ShoppingCartItems.ToList();
for (int i = 0; i < fromCart.Count; i++)
{
var sci = fromCart[i];
AddToCart(toCustomer, sci.Product, sci.ShoppingCartType, sci.StoreId,
sci.AttributesXml, sci.CustomerEnteredPrice, sci.Quantity, false);
}
for (int i = 0; i < fromCart.Count; i++)
{
var sci = fromCart[i];
DeleteShoppingCartItem(sci);
}
//migrate gift card and discount coupon codes
if (includeCouponCodes)
{
//discount
var discountCouponCode = fromCustomer.GetAttribute<string>(SystemCustomerAttributeNames.DiscountCouponCode);
if (!String.IsNullOrEmpty(discountCouponCode))
_genericAttributeService.SaveAttribute(toCustomer, SystemCustomerAttributeNames.DiscountCouponCode, discountCouponCode);
//gift card
foreach (var gcCode in fromCustomer.ParseAppliedGiftCardCouponCodes())
toCustomer.ApplyGiftCardCouponCode(gcCode);
//save customer
_customerService.UpdateCustomer(toCustomer);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing;
using System.Security.Permissions;
using System.Threading;
using System.Windows.Forms;
using System.Collections;
using Aga.Controls.Tree.NodeControls;
using Aga.Controls.Threading;
namespace Aga.Controls.Tree
{
/// <summary>
/// Extensible advanced <see cref="TreeView"/> implemented in 100% managed C# code.
/// Features: Model/View architecture. Multiple column per node. Ability to select
/// multiple tree nodes. Different types of controls for each node column:
/// <see cref="CheckBox"/>, Icon, Label... Drag and Drop highlighting. Load on
/// demand of nodes. Incremental search of nodes.
/// </summary>
public partial class TreeViewAdv : Control
{
private const int LeftMargin = 7;
internal const int ItemDragSensivity = 4;
private readonly int _columnHeaderHeight;
private const int DividerWidth = 9;
private const int DividerCorrectionGap = -2;
private Pen _linePen;
private Pen _markPen;
private bool _suspendUpdate;
private bool _needFullUpdate;
private bool _fireSelectionEvent;
private NodePlusMinus _plusMinus;
private ToolTip _toolTip;
private DrawContext _measureContext;
private TreeColumn _hotColumn;
private IncrementalSearch _search;
private List<TreeNodeAdv> _expandingNodes = new List<TreeNodeAdv>();
private AbortableThreadPool _threadPool = new AbortableThreadPool();
#region Public Events
[Category("Action")]
public event ItemDragEventHandler ItemDrag;
private void OnItemDrag(MouseButtons buttons, object item)
{
if (ItemDrag != null)
ItemDrag(this, new ItemDragEventArgs(buttons, item));
}
[Category("Behavior")]
public event EventHandler<TreeNodeAdvMouseEventArgs> NodeMouseClick;
private void OnNodeMouseClick(TreeNodeAdvMouseEventArgs args)
{
if (NodeMouseClick != null)
NodeMouseClick(this, args);
}
[Category("Behavior")]
public event EventHandler<TreeNodeAdvMouseEventArgs> NodeMouseDoubleClick;
private void OnNodeMouseDoubleClick(TreeNodeAdvMouseEventArgs args)
{
if (NodeMouseDoubleClick != null)
NodeMouseDoubleClick(this, args);
}
[Category("Behavior")]
public event EventHandler<TreeColumnEventArgs> ColumnWidthChanged;
internal void OnColumnWidthChanged(TreeColumn column)
{
if (ColumnWidthChanged != null)
ColumnWidthChanged(this, new TreeColumnEventArgs(column));
}
[Category("Behavior")]
public event EventHandler<TreeColumnEventArgs> ColumnReordered;
internal void OnColumnReordered(TreeColumn column)
{
if (ColumnReordered != null)
ColumnReordered(this, new TreeColumnEventArgs(column));
}
[Category("Behavior")]
public event EventHandler<TreeColumnEventArgs> ColumnClicked;
internal void OnColumnClicked(TreeColumn column)
{
if (ColumnClicked != null)
ColumnClicked(this, new TreeColumnEventArgs(column));
}
[Category("Behavior")]
public event EventHandler SelectionChanged;
internal void OnSelectionChanged()
{
if (SuspendSelectionEvent)
_fireSelectionEvent = true;
else
{
_fireSelectionEvent = false;
if (SelectionChanged != null)
SelectionChanged(this, EventArgs.Empty);
}
}
[Category("Behavior")]
public event EventHandler<TreeViewAdvEventArgs> Collapsing;
private void OnCollapsing(TreeNodeAdv node)
{
if (Collapsing != null)
Collapsing(this, new TreeViewAdvEventArgs(node));
}
[Category("Behavior")]
public event EventHandler<TreeViewAdvEventArgs> Collapsed;
private void OnCollapsed(TreeNodeAdv node)
{
if (Collapsed != null)
Collapsed(this, new TreeViewAdvEventArgs(node));
}
[Category("Behavior")]
public event EventHandler<TreeViewAdvEventArgs> Expanding;
private void OnExpanding(TreeNodeAdv node)
{
if (Expanding != null)
Expanding(this, new TreeViewAdvEventArgs(node));
}
[Category("Behavior")]
public event EventHandler<TreeViewAdvEventArgs> Expanded;
private void OnExpanded(TreeNodeAdv node)
{
if (Expanded != null)
Expanded(this, new TreeViewAdvEventArgs(node));
}
[Category("Behavior")]
public event EventHandler GridLineStyleChanged;
private void OnGridLineStyleChanged()
{
if (GridLineStyleChanged != null)
GridLineStyleChanged(this, EventArgs.Empty);
}
[Category("Behavior")]
public event ScrollEventHandler Scroll;
protected virtual void OnScroll(ScrollEventArgs e)
{
if (Scroll != null)
Scroll(this, e);
}
[Category("Behavior")]
public event EventHandler<TreeViewRowDrawEventArgs> RowDraw;
protected virtual void OnRowDraw(PaintEventArgs e, TreeNodeAdv node, DrawContext context, int row, Rectangle rowRect)
{
if (RowDraw != null)
{
TreeViewRowDrawEventArgs args = new TreeViewRowDrawEventArgs(e.Graphics, e.ClipRectangle, node, context, row, rowRect);
RowDraw(this, args);
}
}
/// <summary>
/// Fires when control is going to draw. Can be used to change text or back color
/// </summary>
[Category("Behavior")]
public event EventHandler<DrawEventArgs> DrawControl;
internal bool DrawControlMustBeFired()
{
return DrawControl != null;
}
internal void FireDrawControl(DrawEventArgs args)
{
OnDrawControl(args);
}
protected virtual void OnDrawControl(DrawEventArgs args)
{
if (DrawControl != null)
DrawControl(this, args);
}
[Category("Drag Drop")]
public event EventHandler<DropNodeValidatingEventArgs> DropNodeValidating;
protected virtual void OnDropNodeValidating(Point point, ref TreeNodeAdv node)
{
if (DropNodeValidating != null)
{
DropNodeValidatingEventArgs args = new DropNodeValidatingEventArgs(point, node);
DropNodeValidating(this, args);
node = args.Node;
}
}
#endregion
public TreeViewAdv()
{
InitializeComponent();
SetStyle(ControlStyles.AllPaintingInWmPaint
| ControlStyles.UserPaint
| ControlStyles.OptimizedDoubleBuffer
| ControlStyles.ResizeRedraw
| ControlStyles.Selectable
, true);
if (Application.RenderWithVisualStyles)
_columnHeaderHeight = 20;
else
_columnHeaderHeight = 17;
//BorderStyle = BorderStyle.Fixed3D;
_hScrollBar.Height = SystemInformation.HorizontalScrollBarHeight;
_vScrollBar.Width = SystemInformation.VerticalScrollBarWidth;
_rowLayout = new FixedRowHeightLayout(this, RowHeight);
_rowMap = new List<TreeNodeAdv>();
_selection = new List<TreeNodeAdv>();
_readonlySelection = new ReadOnlyCollection<TreeNodeAdv>(_selection);
_columns = new TreeColumnCollection(this);
_toolTip = new ToolTip();
_measureContext = new DrawContext();
_measureContext.Font = Font;
_measureContext.Graphics = Graphics.FromImage(new Bitmap(1, 1));
Input = new NormalInputState(this);
_search = new IncrementalSearch(this);
CreateNodes();
CreatePens();
ArrangeControls();
_plusMinus = new NodePlusMinus();
_controls = new NodeControlsCollection(this);
Font = _font;
ExpandingIcon.IconChanged += ExpandingIconChanged;
}
void ExpandingIconChanged(object sender, EventArgs e)
{
if (IsHandleCreated && !IsDisposed)
BeginInvoke(new MethodInvoker(DrawIcons));
}
private void DrawIcons()
{
using (Graphics gr = Graphics.FromHwnd(this.Handle))
{
//Apply the same Graphics Transform logic as used in OnPaint.
int y = 0;
if (UseColumns)
{
y += ColumnHeaderHeight;
if (Columns.Count == 0)
return;
}
int firstRowY = _rowLayout.GetRowBounds(FirstVisibleRow).Y;
y -= firstRowY;
gr.ResetTransform();
gr.TranslateTransform(-OffsetX, y);
DrawContext context = new DrawContext();
context.Graphics = gr;
for (int i = 0; i < _expandingNodes.Count; i++)
{
foreach (NodeControlInfo item in GetNodeControls(_expandingNodes[i]))
{
if (item.Control is ExpandingIcon)
{
Rectangle bounds = item.Bounds;
if (item.Node.Parent == null && UseColumns)
bounds.Location = Point.Empty; // display root expanding icon at 0,0
context.Bounds = bounds;
item.Control.Draw(item.Node, context);
}
}
}
}
}
#region Public Methods
public TreePath GetPath(TreeNodeAdv node)
{
if (node == _root)
return TreePath.Empty;
else
{
Stack<object> stack = new Stack<object>();
while (node != _root && node != null)
{
stack.Push(node.Tag);
node = node.Parent;
}
return new TreePath(stack.ToArray());
}
}
public TreeNodeAdv GetNodeAt(Point point)
{
NodeControlInfo info = GetNodeControlInfoAt(point);
return info.Node;
}
public NodeControlInfo GetNodeControlInfoAt(Point point)
{
if (point.X < 0 || point.Y < 0)
return NodeControlInfo.Empty;
int row = _rowLayout.GetRowAt(point);
if (row < RowCount && row >= 0)
return GetNodeControlInfoAt(RowMap[row], point);
else
return NodeControlInfo.Empty;
}
private NodeControlInfo GetNodeControlInfoAt(TreeNodeAdv node, Point point)
{
Rectangle rect = _rowLayout.GetRowBounds(FirstVisibleRow);
point.Y += (rect.Y - ColumnHeaderHeight);
point.X += OffsetX;
foreach (NodeControlInfo info in GetNodeControls(node))
if (info.Bounds.Contains(point))
return info;
if (FullRowSelect)
return new NodeControlInfo(null, Rectangle.Empty, node);
else
return NodeControlInfo.Empty;
}
public void BeginUpdate()
{
_suspendUpdate = true;
SuspendSelectionEvent = true;
}
public void EndUpdate()
{
_suspendUpdate = false;
if (_needFullUpdate)
FullUpdate();
else
UpdateView();
SuspendSelectionEvent = false;
}
public void ExpandAll()
{
_root.ExpandAll();
}
public void CollapseAll()
{
_root.CollapseAll();
}
/// <summary>
/// Expand all parent nodes, andd scroll to the specified node
/// </summary>
public void EnsureVisible(TreeNodeAdv node)
{
if (node == null)
throw new ArgumentNullException("node");
if (!IsMyNode(node))
throw new ArgumentException();
TreeNodeAdv parent = node.Parent;
while (parent != _root)
{
parent.IsExpanded = true;
parent = parent.Parent;
}
ScrollTo(node);
}
/// <summary>
/// Make node visible, scroll if needed. All parent nodes of the specified node must be expanded
/// </summary>
/// <param name="node"></param>
public void ScrollTo(TreeNodeAdv node)
{
if (node == null)
throw new ArgumentNullException("node");
if (!IsMyNode(node))
throw new ArgumentException();
if (node.Row < 0)
CreateRowMap();
int row = -1;
if (node.Row < FirstVisibleRow)
row = node.Row;
else
{
int pageStart = _rowLayout.GetRowBounds(FirstVisibleRow).Top;
int rowBottom = _rowLayout.GetRowBounds(node.Row).Bottom;
if (rowBottom > pageStart + DisplayRectangle.Height - ColumnHeaderHeight)
row = _rowLayout.GetFirstRow(node.Row);
}
if (row >= _vScrollBar.Minimum && row <= _vScrollBar.Maximum)
_vScrollBar.Value = row;
}
public void ClearSelection()
{
BeginUpdate();
try
{
ClearSelectionInternal();
}
finally
{
EndUpdate();
}
}
internal void ClearSelectionInternal()
{
while (Selection.Count > 0)
{
var t = Selection[0];
t.IsSelected = false;
Selection.Remove(t); //hack
}
}
#endregion
protected override void OnSizeChanged(EventArgs e)
{
ArrangeControls();
SafeUpdateScrollBars();
base.OnSizeChanged(e);
}
private void ArrangeControls()
{
int hBarSize = _hScrollBar.Height;
int vBarSize = _vScrollBar.Width;
Rectangle clientRect = ClientRectangle;
_hScrollBar.SetBounds(clientRect.X, clientRect.Bottom - hBarSize,
clientRect.Width - vBarSize, hBarSize);
_vScrollBar.SetBounds(clientRect.Right - vBarSize, clientRect.Y,
vBarSize, clientRect.Height - hBarSize);
}
private void SafeUpdateScrollBars()
{
if (InvokeRequired)
BeginInvoke(new MethodInvoker(UpdateScrollBars));
else
UpdateScrollBars();
}
private void UpdateScrollBars()
{
UpdateVScrollBar();
UpdateHScrollBar();
UpdateVScrollBar();
UpdateHScrollBar();
_hScrollBar.Width = DisplayRectangle.Width;
_vScrollBar.Height = DisplayRectangle.Height;
}
private void UpdateHScrollBar()
{
_hScrollBar.Maximum = ContentWidth;
_hScrollBar.LargeChange = Math.Max(DisplayRectangle.Width, 0);
_hScrollBar.SmallChange = 5;
_hScrollBar.Visible = _hScrollBar.LargeChange < _hScrollBar.Maximum;
_hScrollBar.Value = Math.Min(_hScrollBar.Value, _hScrollBar.Maximum - _hScrollBar.LargeChange + 1);
}
private void UpdateVScrollBar()
{
_vScrollBar.Maximum = Math.Max(RowCount - 1, 0);
_vScrollBar.LargeChange = _rowLayout.PageRowCount;
_vScrollBar.Visible = (RowCount > 0) && (_vScrollBar.LargeChange <= _vScrollBar.Maximum);
_vScrollBar.Value = Math.Min(_vScrollBar.Value, _vScrollBar.Maximum - _vScrollBar.LargeChange + 1);
}
protected override CreateParams CreateParams
{
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
get
{
CreateParams res = base.CreateParams;
switch (BorderStyle)
{
case BorderStyle.FixedSingle:
res.Style |= 0x800000;
break;
case BorderStyle.Fixed3D:
res.ExStyle |= 0x200;
break;
}
return res;
}
}
protected override void OnGotFocus(EventArgs e)
{
UpdateView();
ChangeInput();
base.OnGotFocus(e);
}
protected override void OnFontChanged(EventArgs e)
{
base.OnFontChanged(e);
_measureContext.Font = Font;
FullUpdate();
}
internal IEnumerable<NodeControlInfo> GetNodeControls(TreeNodeAdv node)
{
if (node == null)
yield break;
Rectangle rowRect = _rowLayout.GetRowBounds(node.Row);
foreach (NodeControlInfo n in GetNodeControls(node, rowRect))
yield return n;
}
internal IEnumerable<NodeControlInfo> GetNodeControls(TreeNodeAdv node, Rectangle rowRect)
{
if (node == null)
yield break;
int y = rowRect.Y;
int x = (node.Level - 1) * _indent + LeftMargin;
int width = 0;
if (node.Row == 0 && ShiftFirstNode)
x -= _indent;
Rectangle rect = Rectangle.Empty;
if (ShowPlusMinus)
{
width = _plusMinus.GetActualSize(node, _measureContext).Width;
rect = new Rectangle(x, y, width, rowRect.Height);
if (UseColumns && Columns.Count > 0 && Columns[0].Width < rect.Right)
rect.Width = Columns[0].Width - x;
yield return new NodeControlInfo(_plusMinus, rect, node);
x += width;
}
if (!UseColumns)
{
foreach (NodeControl c in NodeControls)
{
Size s = c.GetActualSize(node, _measureContext);
if (!s.IsEmpty)
{
width = s.Width;
rect = new Rectangle(x, y, width, rowRect.Height);
x += rect.Width;
yield return new NodeControlInfo(c, rect, node);
}
}
}
else
{
int right = 0;
foreach (TreeColumn col in Columns)
{
if (col.IsVisible && col.Width > 0)
{
right += col.Width;
for (int i = 0; i < NodeControls.Count; i++)
{
NodeControl nc = NodeControls[i];
if (nc.ParentColumn == col)
{
Size s = nc.GetActualSize(node, _measureContext);
if (!s.IsEmpty)
{
bool isLastControl = true;
for (int k = i + 1; k < NodeControls.Count; k++)
if (NodeControls[k].ParentColumn == col)
{
isLastControl = false;
break;
}
width = right - x;
if (!isLastControl)
width = s.Width;
int maxWidth = Math.Max(0, right - x);
rect = new Rectangle(x, y, Math.Min(maxWidth, width), rowRect.Height);
x += width;
yield return new NodeControlInfo(nc, rect, node);
}
}
}
x = right;
}
}
}
}
internal static double Dist(Point p1, Point p2)
{
return Math.Sqrt(Math.Pow(p1.X - p2.X, 2) + Math.Pow(p1.Y - p2.Y, 2));
}
public void FullUpdate()
{
HideEditor();
if (InvokeRequired)
BeginInvoke(new MethodInvoker(UnsafeFullUpdate));
else
UnsafeFullUpdate();
}
private void UnsafeFullUpdate()
{
_rowLayout.ClearCache();
CreateRowMap();
SafeUpdateScrollBars();
UpdateView();
_needFullUpdate = false;
}
internal void UpdateView()
{
if (!_suspendUpdate)
Invalidate(false);
}
internal void UpdateHeaders()
{
Invalidate(new Rectangle(0, 0, Width, ColumnHeaderHeight));
}
internal void UpdateColumns()
{
FullUpdate();
}
private void CreateNodes()
{
Selection.Clear();
SelectionStart = null;
_root = new TreeNodeAdv(this, null);
_root.IsExpanded = true;
if (_root.Nodes.Count > 0)
CurrentNode = _root.Nodes[0];
else
CurrentNode = null;
}
internal void ReadChilds(TreeNodeAdv parentNode)
{
ReadChilds(parentNode, false);
}
internal void ReadChilds(TreeNodeAdv parentNode, bool performFullUpdate)
{
if (!parentNode.IsLeaf)
{
parentNode.IsExpandedOnce = true;
parentNode.Nodes.Clear();
if (Model != null)
{
IEnumerable items = Model.GetChildren(GetPath(parentNode));
if (items != null)
foreach (object obj in items)
{
AddNewNode(parentNode, obj, -1);
if (performFullUpdate)
FullUpdate();
}
}
if (parentNode.AutoExpandOnStructureChanged)
parentNode.ExpandAll();
}
}
private void AddNewNode(TreeNodeAdv parent, object tag, int index)
{
TreeNodeAdv node = new TreeNodeAdv(this, tag);
AddNode(parent, index, node);
}
private void AddNode(TreeNodeAdv parent, int index, TreeNodeAdv node)
{
if (index >= 0 && index < parent.Nodes.Count)
parent.Nodes.Insert(index, node);
else
parent.Nodes.Add(node);
node.IsLeaf = Model.IsLeaf(GetPath(node));
if (node.IsLeaf)
node.Nodes.Clear();
if (!LoadOnDemand || node.IsExpandedOnce)
ReadChilds(node);
}
private struct ExpandArgs
{
public TreeNodeAdv Node;
public bool Value;
public bool IgnoreChildren;
}
public void AbortBackgroundExpandingThreads()
{
_threadPool.CancelAll(true);
for (int i = 0; i < _expandingNodes.Count; i++)
_expandingNodes[i].IsExpandingNow = false;
_expandingNodes.Clear();
Invalidate();
}
internal void SetIsExpanded(TreeNodeAdv node, bool value, bool ignoreChildren)
{
ExpandArgs eargs = new ExpandArgs();
eargs.Node = node;
eargs.Value = value;
eargs.IgnoreChildren = ignoreChildren;
if (AsyncExpanding && LoadOnDemand && !_threadPool.IsMyThread(Thread.CurrentThread))
{
WaitCallback wc = delegate(object argument) { SetIsExpanded((ExpandArgs)argument); };
_threadPool.QueueUserWorkItem(wc, eargs);
}
else
SetIsExpanded(eargs);
}
private void SetIsExpanded(ExpandArgs eargs)
{
bool update = !eargs.IgnoreChildren && !AsyncExpanding;
if (update)
BeginUpdate();
try
{
if (IsMyNode(eargs.Node) && eargs.Node.IsExpanded != eargs.Value)
SetIsExpanded(eargs.Node, eargs.Value);
if (!eargs.IgnoreChildren)
SetIsExpandedRecursive(eargs.Node, eargs.Value);
}
finally
{
if (update)
EndUpdate();
}
}
internal void SetIsExpanded(TreeNodeAdv node, bool value)
{
if (Root == node && !value)
return; //Can't collapse root node
if (value)
{
OnExpanding(node);
node.OnExpanding();
}
else
{
OnCollapsing(node);
node.OnCollapsing();
}
if (value && !node.IsExpandedOnce)
{
if (AsyncExpanding && LoadOnDemand)
{
AddExpandingNode(node);
node.AssignIsExpanded(true);
Invalidate();
}
ReadChilds(node, AsyncExpanding);
RemoveExpandingNode(node);
}
node.AssignIsExpanded(value);
SmartFullUpdate();
if (value)
{
OnExpanded(node);
node.OnExpanded();
}
else
{
OnCollapsed(node);
node.OnCollapsed();
}
}
private void RemoveExpandingNode(TreeNodeAdv node)
{
node.IsExpandingNow = false;
_expandingNodes.Remove(node);
if (_expandingNodes.Count <= 0)
ExpandingIcon.Stop();
}
private void AddExpandingNode(TreeNodeAdv node)
{
node.IsExpandingNow = true;
_expandingNodes.Add(node);
ExpandingIcon.Start();
}
internal void SetIsExpandedRecursive(TreeNodeAdv root, bool value)
{
for (int i = 0; i < root.Nodes.Count; i++)
{
TreeNodeAdv node = root.Nodes[i];
node.IsExpanded = value;
SetIsExpandedRecursive(node, value);
}
}
private void CreateRowMap()
{
RowMap.Clear();
int row = 0;
_contentWidth = 0;
foreach (TreeNodeAdv node in VisibleNodes)
{
node.Row = row;
RowMap.Add(node);
if (!UseColumns)
{
_contentWidth = Math.Max(_contentWidth, GetNodeWidth(node));
}
row++;
}
if (UseColumns)
{
_contentWidth = 0;
foreach (TreeColumn col in _columns)
if (col.IsVisible)
_contentWidth += col.Width;
}
}
private int GetNodeWidth(TreeNodeAdv node)
{
if (node.RightBounds == null)
{
Rectangle res = GetNodeBounds(GetNodeControls(node, Rectangle.Empty));
node.RightBounds = res.Right;
}
return node.RightBounds.Value;
}
internal Rectangle GetNodeBounds(TreeNodeAdv node)
{
return GetNodeBounds(GetNodeControls(node));
}
private Rectangle GetNodeBounds(IEnumerable<NodeControlInfo> nodeControls)
{
Rectangle res = Rectangle.Empty;
foreach (NodeControlInfo info in nodeControls)
{
if (res == Rectangle.Empty)
res = info.Bounds;
else
res = Rectangle.Union(res, info.Bounds);
}
return res;
}
private void _vScrollBar_ValueChanged(object sender, EventArgs e)
{
FirstVisibleRow = _vScrollBar.Value;
}
private void _hScrollBar_ValueChanged(object sender, EventArgs e)
{
OffsetX = _hScrollBar.Value;
}
private void _vScrollBar_Scroll(object sender, ScrollEventArgs e)
{
OnScroll(e);
}
private void _hScrollBar_Scroll(object sender, ScrollEventArgs e)
{
OnScroll(e);
}
internal void SmartFullUpdate()
{
if (_suspendUpdate)
_needFullUpdate = true;
else
FullUpdate();
}
internal bool IsMyNode(TreeNodeAdv node)
{
if (node == null)
return false;
if (node.Tree != this)
return false;
while (node.Parent != null)
node = node.Parent;
return node == _root;
}
internal void UpdateSelection()
{
bool flag = false;
if (!IsMyNode(CurrentNode))
CurrentNode = null;
if (!IsMyNode(_selectionStart))
_selectionStart = null;
for (int i = Selection.Count - 1; i >= 0; i--)
if (!IsMyNode(Selection[i]))
{
flag = true;
Selection.RemoveAt(i);
}
if (flag)
OnSelectionChanged();
}
internal void ChangeColumnWidth(TreeColumn column)
{
if (!(_input is ResizeColumnState))
{
FullUpdate();
OnColumnWidthChanged(column);
}
}
public TreeNodeAdv FindNode(TreePath path)
{
return FindNode(path, false);
}
public TreeNodeAdv FindNode(TreePath path, bool readChilds)
{
if (path.IsEmpty())
return _root;
else
return FindNode(_root, path, 0, readChilds);
}
private TreeNodeAdv FindNode(TreeNodeAdv root, TreePath path, int level, bool readChilds)
{
if (!root.IsExpandedOnce && readChilds)
ReadChilds(root);
for (int i = 0; i < root.Nodes.Count; i++)
{
TreeNodeAdv node = root.Nodes[i];
if (node.Tag == path.FullPath[level])
{
if (level == path.FullPath.Length - 1)
return node;
else
return FindNode(node, path, level + 1, readChilds);
}
}
return null;
}
public TreeNodeAdv FindNodeByTag(object tag)
{
return FindNodeByTag(_root, tag);
}
private TreeNodeAdv FindNodeByTag(TreeNodeAdv root, object tag)
{
foreach (TreeNodeAdv node in root.Nodes)
{
if (node.Tag == tag)
return node;
TreeNodeAdv res = FindNodeByTag(node, tag);
if (res != null)
return res;
}
return null;
}
public void SelectAllNodes()
{
SuspendSelectionEvent = true;
try
{
if (SelectionMode == TreeSelectionMode.MultiSameParent)
{
if (CurrentNode != null)
{
foreach (TreeNodeAdv n in CurrentNode.Parent.Nodes)
n.IsSelected = true;
}
}
else if (SelectionMode == TreeSelectionMode.Multi)
{
SelectNodes(Root.Nodes);
}
}
finally
{
SuspendSelectionEvent = false;
}
}
private void SelectNodes(Collection<TreeNodeAdv> nodes)
{
foreach (TreeNodeAdv n in nodes)
{
n.IsSelected = true;
if (n.IsExpanded)
SelectNodes(n.Nodes);
}
}
#region ModelEvents
private void BindModelEvents()
{
_model.NodesChanged += new EventHandler<TreeModelEventArgs>(_model_NodesChanged);
_model.NodesInserted += new EventHandler<TreeModelEventArgs>(_model_NodesInserted);
_model.NodesRemoved += new EventHandler<TreeModelEventArgs>(_model_NodesRemoved);
_model.StructureChanged += new EventHandler<TreePathEventArgs>(_model_StructureChanged);
}
private void UnbindModelEvents()
{
_model.NodesChanged -= new EventHandler<TreeModelEventArgs>(_model_NodesChanged);
_model.NodesInserted -= new EventHandler<TreeModelEventArgs>(_model_NodesInserted);
_model.NodesRemoved -= new EventHandler<TreeModelEventArgs>(_model_NodesRemoved);
_model.StructureChanged -= new EventHandler<TreePathEventArgs>(_model_StructureChanged);
}
private void _model_StructureChanged(object sender, TreePathEventArgs e)
{
if (e.Path == null)
throw new ArgumentNullException();
TreeNodeAdv node = FindNode(e.Path);
if (node != null)
{
if (node != Root)
node.IsLeaf = Model.IsLeaf(GetPath(node));
var list = new Dictionary<object, object>();
SaveExpandedNodes(node, list);
ReadChilds(node);
RestoreExpandedNodes(node, list);
UpdateSelection();
SmartFullUpdate();
}
//else
// throw new ArgumentException("Path not found");
}
private void RestoreExpandedNodes(TreeNodeAdv node, Dictionary<object, object> list)
{
if (node.Tag != null && list.ContainsKey(node.Tag))
{
node.IsExpanded = true;
foreach (var child in node.Children)
RestoreExpandedNodes(child, list);
}
}
private void SaveExpandedNodes(TreeNodeAdv node, Dictionary<object, object> list)
{
if (node.IsExpanded && node.Tag != null)
{
list.Add(node.Tag, null);
foreach (var child in node.Children)
SaveExpandedNodes(child, list);
}
}
private void _model_NodesRemoved(object sender, TreeModelEventArgs e)
{
TreeNodeAdv parent = FindNode(e.Path);
if (parent != null)
{
if (e.Indices != null)
{
List<int> list = new List<int>(e.Indices);
list.Sort();
for (int n = list.Count - 1; n >= 0; n--)
{
int index = list[n];
if (index >= 0 && index <= parent.Nodes.Count)
parent.Nodes.RemoveAt(index);
else
throw new ArgumentOutOfRangeException("Index out of range");
}
}
else
{
for (int i = parent.Nodes.Count - 1; i >= 0; i--)
{
for (int n = 0; n < e.Children.Length; n++)
if (parent.Nodes[i].Tag == e.Children[n])
{
parent.Nodes.RemoveAt(i);
break;
}
}
}
}
UpdateSelection();
SmartFullUpdate();
}
private void _model_NodesInserted(object sender, TreeModelEventArgs e)
{
if (e.Indices == null)
throw new ArgumentNullException("Indices");
TreeNodeAdv parent = FindNode(e.Path);
if (parent != null)
{
for (int i = 0; i < e.Children.Length; i++)
AddNewNode(parent, e.Children[i], e.Indices[i]);
}
SmartFullUpdate();
}
private void _model_NodesChanged(object sender, TreeModelEventArgs e)
{
TreeNodeAdv parent = FindNode(e.Path);
if (parent != null && parent.IsVisible && parent.IsExpanded)
{
if (InvokeRequired)
BeginInvoke(new UpdateContentWidthDelegate(ClearNodesSize), e, parent);
else
ClearNodesSize(e, parent);
SmartFullUpdate();
}
}
private delegate void UpdateContentWidthDelegate(TreeModelEventArgs e, TreeNodeAdv parent);
private void ClearNodesSize(TreeModelEventArgs e, TreeNodeAdv parent)
{
if (e.Indices != null)
{
foreach (int index in e.Indices)
{
if (index >= 0 && index < parent.Nodes.Count)
{
TreeNodeAdv node = parent.Nodes[index];
node.Height = node.RightBounds = null;
}
else
throw new ArgumentOutOfRangeException("Index out of range");
}
}
else
{
foreach (TreeNodeAdv node in parent.Nodes)
{
foreach (object obj in e.Children)
if (node.Tag == obj)
{
node.Height = node.RightBounds = null;
}
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using $safeprojectname$.Areas.HelpPage.Models;
namespace $safeprojectname$.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 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 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)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(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}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Compute
{
using System;
using System.Collections.Generic;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Resource;
using NUnit.Framework;
/// <summary>
/// Test for task and job adapter.
/// </summary>
public class FailoverTaskSelfTest : AbstractTaskTest
{
/** */
static volatile string _gridName;
/** */
static volatile int _cnt;
/// <summary>
/// Constructor.
/// </summary>
public FailoverTaskSelfTest() : base(false) { }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="fork">Fork flag.</param>
protected FailoverTaskSelfTest(bool fork) : base(fork) { }
/// <summary>
/// Test for GridComputeJobFailoverException.
/// </summary>
[Test]
public void TestClosureFailoverException()
{
for (int i = 0; i < 20; i++)
{
int res = Grid1.GetCompute().Call(new TestClosure());
Assert.AreEqual(2, res);
Cleanup();
}
}
/// <summary>
/// Test for GridComputeJobFailoverException with serializable job.
/// </summary>
[Test]
public void TestTaskAdapterFailoverExceptionSerializable()
{
TestTaskAdapterFailoverException(true);
}
/// <summary>
/// Test for GridComputeJobFailoverException with binary job.
/// </summary>
[Test]
public void TestTaskAdapterFailoverExceptionBinarizable()
{
TestTaskAdapterFailoverException(false);
}
/// <summary>
/// Test for GridComputeJobFailoverException.
/// </summary>
private void TestTaskAdapterFailoverException(bool serializable)
{
int res = Grid1.GetCompute().Execute(new TestTask(),
new Tuple<bool, bool>(serializable, true));
Assert.AreEqual(2, res);
Cleanup();
res = Grid1.GetCompute().Execute(new TestTask(),
new Tuple<bool, bool>(serializable, false));
Assert.AreEqual(2, res);
}
/// <summary>
/// Cleanup.
/// </summary>
[TearDown]
public void Cleanup()
{
_cnt = 0;
_gridName = null;
}
/** <inheritDoc /> */
override protected void GetBinaryTypeConfigurations(ICollection<BinaryTypeConfiguration> portTypeCfgs)
{
portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(TestBinarizableJob)));
}
/// <summary>
/// Test task.
/// </summary>
public class TestTask : ComputeTaskAdapter<Tuple<bool, bool>, int, int>
{
/** <inheritDoc /> */
override public IDictionary<IComputeJob<int>, IClusterNode> Map(IList<IClusterNode> subgrid, Tuple<bool, bool> arg)
{
Assert.AreEqual(3, subgrid.Count);
Tuple<bool, bool> t = arg;
bool serializable = t.Item1;
bool local = t.Item2;
IDictionary<IComputeJob<int>, IClusterNode> jobs = new Dictionary<IComputeJob<int>, IClusterNode>();
IComputeJob<int> job;
if (serializable)
job = new TestSerializableJob();
else
job = new TestBinarizableJob();
foreach (IClusterNode node in subgrid) {
bool add = local ? node.IsLocal : !node.IsLocal;
if (add)
{
jobs.Add(job, node);
break;
}
}
Assert.AreEqual(1, jobs.Count);
return jobs;
}
/** <inheritDoc /> */
override public int Reduce(IList<IComputeJobResult<int>> results)
{
Assert.AreEqual(1, results.Count);
return results[0].Data;
}
}
/// <summary>
///
/// </summary>
[Serializable]
class TestClosure : IComputeFunc<int>
{
[InstanceResource]
private readonly IIgnite _grid = null;
/** <inheritDoc /> */
public int Invoke()
{
return FailoverJob(_grid);
}
}
/// <summary>
///
/// </summary>
[Serializable]
class TestSerializableJob : IComputeJob<int>
{
[InstanceResource]
private readonly IIgnite _grid = null;
/** <inheritDoc /> */
public int Execute()
{
return FailoverJob(_grid);
}
/** <inheritDoc /> */
public void Cancel()
{
// No-op.
}
}
/// <summary>
///
/// </summary>
class TestBinarizableJob : IComputeJob<int>
{
[InstanceResource]
private readonly IIgnite _grid = null;
/** <inheritDoc /> */
public int Execute()
{
return FailoverJob(_grid);
}
public void Cancel()
{
// No-op.
}
}
/// <summary>
/// Throws GridComputeJobFailoverException on first call.
/// </summary>
private static int FailoverJob(IIgnite grid)
{
Assert.NotNull(grid);
_cnt++;
if (_gridName == null)
{
_gridName = grid.Name;
throw new ComputeJobFailoverException("Test error.");
}
Assert.AreNotEqual(_gridName, grid.Name);
return _cnt;
}
}
}
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of halcyon nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications.Capabilities;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.Framework.Scenes
{
/// <summary>
/// Tracks the presences an avatar has on our known neighbor regions
/// </summary>
public class AvatarRemotePresences
{
private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Collection of the currently established remote presences for this user
/// </summary>
private Dictionary<ulong, AvatarRemotePresence> _remotePresences = new Dictionary<ulong, AvatarRemotePresence>();
/// <summary>
/// The current scene we're managing presences for this user on
/// </summary>
private Scene _scene;
/// <summary>
/// The local presence we're managing
/// </summary>
private ScenePresence _sp;
/// <summary>
/// The last number of regions we were able to see into given the user's draw distance
/// </summary>
private uint _lastDrawDistanceFactor;
/// <summary>
/// Semaphore held during large ops to ensure only one major change happens at a time
/// </summary>
private SemaphoreSlim _operationSemaphore = new SemaphoreSlim(1, 1);
public AvatarRemotePresences(Scene currentRegion, ScenePresence sp)
{
_scene = currentRegion;
_sp = sp;
_lastDrawDistanceFactor = Util.GetRegionUnitsFromDD((uint)sp.DrawDistance);
_scene.EventManager.OnMakeRootAgent += EventManager_OnMakeRootAgent;
_scene.EventManager.OnMakeChildAgent += EventManager_OnMakeChildAgent;
}
/// <summary>
/// Called when a root SP is being constructed and we need to copy presences
/// from a previous region
/// </summary>
/// <param name="currentPresences"></param>
public void SetInitialPresences(IEnumerable<RemotePresenceInfo> currentPresences)
{
if (_sp.IsBot) return;
foreach (var pres in currentPresences)
{
//don't include our handle in the remote presences. this may be coming
//from a neighbor region which had us as a remote pres
if (pres.RegionInfo.RegionHandle != _scene.RegionInfo.RegionHandle)
{
_remotePresences[pres.RegionInfo.RegionHandle] =
new AvatarRemotePresence
{
PresenceInfo = pres,
IsFarPresence = false,
State = RemotePresenceState.Established
};
}
}
}
/// <summary>
/// Called when this presence is being changed to a root agent
/// </summary>
/// <param name="presence"></param>
void EventManager_OnMakeRootAgent(ScenePresence presence)
{
if (presence.IsBot) return;
if (presence == _sp)
{
//subscribe to changes in the surrounding region config
_scene.SurroundingRegions.OnNeighborStateChange += SurroundingRegions_OnNeighborStateChange;
//set up our initial connections to neighbors
//let the task run async in the background
const int CROSSING_RESYNC_DELAY = 500;
this.CalculateAndResyncNeighbors((uint)presence.DrawDistance, CROSSING_RESYNC_DELAY);
}
}
/// <summary>
/// Called when this presence is leaving this region
/// </summary>
/// <param name="presence"></param>
void EventManager_OnMakeChildAgent(ScenePresence presence)
{
if (presence.IsBot) return;
//is it our presence that has been made into a child?
if (presence == _sp)
{
StopManagingPresences();
}
}
/// <summary>
/// Unsubscribe to region changes and clear out presences, it is no longer up to us to manage this data
/// </summary>
private void StopManagingPresences()
{
_scene.SurroundingRegions.OnNeighborStateChange -= SurroundingRegions_OnNeighborStateChange;
lock (_remotePresences)
{
_remotePresences.Clear();
}
}
/// <summary>
/// Called by our SP when it is closing
/// </summary>
internal void OnScenePresenceClosed()
{
if (_sp.IsBot) return;
StopManagingPresences();
_sp = null; // release the SP reference
_scene.EventManager.OnMakeRootAgent -= EventManager_OnMakeRootAgent;
_scene.EventManager.OnMakeChildAgent -= EventManager_OnMakeChildAgent;
}
/// <summary>
/// Called by the surrounding region manager when there is a region state change
/// </summary>
/// <param name="neighbor"></param>
/// <param name="changeType"></param>
void SurroundingRegions_OnNeighborStateChange(SimpleRegionInfo neighbor, NeighborStateChangeType changeType)
{
switch (changeType)
{
case NeighborStateChangeType.NeighborUp:
this.HandleNeighborUp(neighbor);
break;
case NeighborStateChangeType.NeighborDown:
this.HandleNeighborDown(neighbor);
break;
}
}
/// <summary>
/// Called when a neighbor has declared that it is down or a ping timed out. We should tell the client
/// to remove these regions from its view and we remove the region presence from our collection
/// </summary>
/// <param name="neighbor"></param>
private async Task HandleNeighborDown(SimpleRegionInfo neighbor)
{
// on any neighbor change, we need to recalculate all neighbors because
// visibility rules may have resulted in more than one new neighbor.
await CalculateAndResyncNeighbors((uint)_sp.DrawDistance, 0);
}
/// <summary>
/// Drops the given presence taking the operation semaphore
/// </summary>
/// <param name="neighbor">The presence to drop</param>
/// <param name="onlyIfFar">Only drop if the presence is a far presence</param>
public async Task DropRemotePresenceLocked(SimpleRegionInfo neighbor, bool onlyIfFar)
{
try
{
await _operationSemaphore.WaitAsync();
await DropRemotePresence(neighbor, onlyIfFar);
}
finally
{
_operationSemaphore.Release();
}
}
/// <summary>
/// Drops the given presence
/// </summary>
/// <param name="neighbor">The presence to drop</param>
/// <param name="onlyIfFar">Only drop if the presence is a far presence</param>
private async Task DropRemotePresence(SimpleRegionInfo neighbor, bool onlyIfFar)
{
AvatarRemotePresence foundPresence = null;
TryGetRemotePresenceLocked(neighbor.RegionHandle, (AvatarRemotePresence presence) =>
{
foundPresence = presence;
if (presence != null)
{
if (onlyIfFar && !presence.IsFarPresence)
{
return;
}
//You can not send a disablesimulator for the remote region
//the viewer processes all disablesimulator messages coming from this
//region as a disablesimulator message FOR this region
//therefore, we remove the neighbor from our known regions list
//and ask the sim on the other end to tear down the connection
_remotePresences.Remove(neighbor.RegionHandle);
}
});
if (foundPresence != null)
{
//send a close to the neighbor
await _scene.InterregionComms.SendCloseAgentAsync(neighbor, _sp.UUID);
}
}
private async Task HandleNeighborUp(SimpleRegionInfo neighbor)
{
// on any neighbor change, we need to recalculate all neighbors because
// visibility rules may have resulted in more than one new neighbor.
await CalculateAndResyncNeighbors((uint)_sp.DrawDistance, 0);
}
/// <summary>
/// Does this user have an established presence on the given region?
/// </summary>
/// <param name="regionHandle"></param>
/// <returns></returns>
public bool HasPresenceOnRegion(ulong regionHandle)
{
bool hasPresence = false;
TryGetRemotePresenceLocked(regionHandle, (AvatarRemotePresence presence) =>
{
if (presence != null)
{
hasPresence = (presence.State == RemotePresenceState.Established);
}
});
return hasPresence;
}
public void TryGetRemotePresenceLocked(ulong regionHandle, Action<AvatarRemotePresence> callback)
{
lock (_remotePresences)
{
AvatarRemotePresence presence;
_remotePresences.TryGetValue(regionHandle, out presence);
callback(presence);
}
}
/// <summary>
/// Attempts to establish a presence on the given region. Does this while waiting for other major tasks to complete
/// </summary>
/// <param name="region">The region we want to establish a child presence on</param>
/// <param name="forceReestablish">Whether to force a reestablishment even if we already think we have a remote presence</param>
/// <param name="isFarPresence">Is this presence intentionally far away? Eg. The beginning of a remote teleport</param>
/// <returns></returns>
public async Task<Tuple<EstablishPresenceResult, string>> EstablishPresenceOnRegionLocked(SimpleRegionInfo region, bool forceReestablish, bool isFarPresence)
{
try
{
await _operationSemaphore.WaitAsync();
return await this.EstablishPresenceOnRegion(region, forceReestablish, isFarPresence);
}
finally
{
_operationSemaphore.Release();
}
}
/// <summary>
/// Attempts to establish a presence on the given region
/// </summary>
/// <param name="region">The region we want to establish a child presence on</param>
/// <param name="forceReestablish">Whether to force a reestablishment even if we already think we have a remote presence</param>
/// <param name="isFarPresence">Is this presence intentionally far away? Eg. The beginning of a remote teleport</param>
/// <returns></returns>
private async Task<Tuple<EstablishPresenceResult, string>> EstablishPresenceOnRegion(SimpleRegionInfo region, bool forceReestablish, bool isFarPresence)
{
Task<Tuple<EstablishPresenceResult, string>> establishTask = null;
bool presenceExisted = false;
//check if we already have or are waiting on an establish
TryGetRemotePresenceLocked(region.RegionHandle, (AvatarRemotePresence presence) =>
{
if (presence != null && !forceReestablish)
{
//we have a presence
//if it is established just return
if (presence.State == RemotePresenceState.Established)
{
presenceExisted = true;
}
else
{
//if not, we can await the existing callback
establishTask = presence.EstablishTask;
}
}
else
{
//we have no presence and we're not waiting for a callback
//begin an async establish and await a callback
presence = new AvatarRemotePresence
{
PresenceInfo = new RemotePresenceInfo { RegionInfo = region, CapsPath = CapsUtil.GetRandomCapsObjectPath() },
IsFarPresence = isFarPresence,
State = RemotePresenceState.Establishing
};
if (_remotePresences.ContainsKey(region.RegionHandle))
_remotePresences.Remove(region.RegionHandle);
_remotePresences.Add(region.RegionHandle, presence);
establishTask = DoEstablishPresenceOnRegion(region, presence);
presence.EstablishTask = establishTask;
}
});
//nothing to do, we're already established
if (presenceExisted) return Tuple.Create(EstablishPresenceResult.Success, String.Empty);
return await establishTask;
}
private async Task<Tuple<EstablishPresenceResult, string>> DoEstablishPresenceOnRegion(SimpleRegionInfo region, AvatarRemotePresence initPresence)
{
Tuple<EstablishPresenceResult, string> establishResult;
try
{
establishResult = await this.LaunchNewEstablishChildTask(initPresence, region);
}
catch (Exception e)
{
establishResult = new Tuple<EstablishPresenceResult, string>(EstablishPresenceResult.ErrorInformingRegion, e.Message);
}
bool failure = false;
TryGetRemotePresenceLocked(region.RegionHandle, (AvatarRemotePresence presence) =>
{
//success, change the status of the task
if (presence != null)
{
if (establishResult.Item1 == EstablishPresenceResult.Success)
{
presence.State = RemotePresenceState.ViewerWait;
}
else
{
//failure contacting other region
_remotePresences.Remove(region.RegionHandle);
failure = true;
}
}
else
{
string context = (_sp == null) ? String.Empty : " for "+_sp.Name;
failure = true;
//hmm, someone stole this presence from us
_log.ErrorFormat("[REMOTEPRESENCE]: Unable to update child presence established to {0}{1}. Child presence missing.", establishResult, context);
establishResult = Tuple.Create(EstablishPresenceResult.ConnectionAborted, "Connection was aborted");
}
});
if (failure)
{
return establishResult;
}
//now we need to call out to the remote region to wait for the SP to be set up
bool waitSuccess = await WaitForScenePresenceEstablished(region);
Tuple<EstablishPresenceResult, string> result = null;
TryGetRemotePresenceLocked(region.RegionHandle, (AvatarRemotePresence presence) =>
{
//success, change the status of the task
if (presence != null)
{
if (waitSuccess)
{
presence.State = RemotePresenceState.Established;
result = Tuple.Create(EstablishPresenceResult.Success, String.Empty);
}
else
{
//failure waiting for SP
_remotePresences.Remove(region.RegionHandle);
result = Tuple.Create(EstablishPresenceResult.ClientWaitTimeout, "Destination region never received a connection from the viewer");
}
}
else
{
//hmm, someone stole this presence from us
_log.ErrorFormat("[REMOTEPRESENCE]: Unable to update child presence established to {0} for {1}. Child presence missing.", establishResult, _sp.Name);
result = Tuple.Create(EstablishPresenceResult.ConnectionAborted, "Connection was aborted");
}
});
return result;
}
private async Task<bool> WaitForScenePresenceEstablished(SimpleRegionInfo region)
{
//this is the HTTP timeout, however the actual wait timeout on the receiving side is 10 seconds
//so that timeout should be triggered first
const int HTTP_SP_WAIT_TIMEOUT = 15000;
var req = (HttpWebRequest)HttpWebRequest.Create(region.InsecurePublicHTTPServerURI + String.Format("/agent2/{0}/{1}", _sp.UUID, region.RegionHandle));
req.Headers["authorization"] = Util.GenerateHttpAuthorization(_scene.GridSendKey);
req.Timeout = HTTP_SP_WAIT_TIMEOUT;
req.ReadWriteTimeout = HTTP_SP_WAIT_TIMEOUT;
req.Method = "GET";
try
{
using (WebResponse response = await req.GetResponseAsync(HTTP_SP_WAIT_TIMEOUT))
{
//we do nothing besides dispose on success. a 200 response means all is well
}
return true;
}
catch (Exception e)
{
_log.ErrorFormat("[REMOTEPRESENCE]: Waiting for viewer connection from {0} to {1} failed: {2}", _sp.Name, region.RegionHandle, e);
return false;
}
}
private Task<Tuple<EstablishPresenceResult, string>> LaunchNewEstablishChildTask(AvatarRemotePresence presence, SimpleRegionInfo region)
{
AgentCircuitData agent = _sp.ControllingClient.RequestClientInfo();
agent.BaseFolder = UUID.Zero;
agent.InventoryFolder = UUID.Zero;
agent.startpos = Scene.DEFAULT_CHILD_AGENT_POS;
agent.child = true;
agent.CapsPath = presence.PresenceInfo.CapsPath;
return _scene.SceneGridService.EstablishChildConnectionToRegionAsync(_sp, agent, region);
}
/// <summary>
/// The user's draw distance has changed, we may need to drop or add some regions
/// </summary>
/// <param name="newDrawDistance"></param>
public async Task HandleDrawDistanceChanged(uint newDrawDistance)
{
if (_sp.IsBot) return;
uint factor = Util.GetRegionUnitsFromDD(newDrawDistance);
if (_lastDrawDistanceFactor == factor)
{
//nothing to do
return;
}
_lastDrawDistanceFactor = factor;
await CalculateAndResyncNeighbors(newDrawDistance, 0);
}
/// <summary>
/// Resyncs the user with our view of the neighbors
/// </summary>
/// <param name="newDrawDistance">The new DD for the user</param>
/// <param name="resyncDelay">Delay before executing the resync. We delay on a region crossing because the viewer locks up sometimes when freeing memory</param>
/// <returns></returns>
private async Task CalculateAndResyncNeighbors(uint newDrawDistance, int resyncDelay)
{
uint xmin, xmax, ymin, ymax;
Util.GetDrawDistanceBasedRegionRectangle((uint)newDrawDistance, _scene.RegionInfo.RegionLocX,
_scene.RegionInfo.RegionLocY, out xmin, out xmax, out ymin, out ymax);
//get our current neighbor list
List<SimpleRegionInfo> knownNeighborsList = _scene.SurroundingRegions.GetKnownNeighborsWithinClientDD(newDrawDistance);
Dictionary<ulong, SimpleRegionInfo> knownNeighborsDict = new Dictionary<ulong, SimpleRegionInfo>();
foreach (var neighbor in knownNeighborsList)
{
knownNeighborsDict.Add(neighbor.RegionHandle, neighbor);
}
HashSet<ulong> knownNeighbors = new HashSet<ulong>(knownNeighborsList.Select(x => x.RegionHandle));
List<ulong> deadRegions;
List<ulong> newRegions;
lock (_remotePresences)
{
//check the list of what we have vs what we should have
HashSet<ulong> usersRegions = new HashSet<ulong>();
//add all regions from the presence
foreach (var presence in _remotePresences.Values)
{
knownNeighborsDict[presence.PresenceInfo.RegionInfo.RegionHandle] = presence.PresenceInfo.RegionInfo;
//dont put far regions into this update, they shouldnt be dropped by DD changes
if (!presence.IsFarPresence)
{
usersRegions.Add(presence.PresenceInfo.RegionInfo.RegionHandle);
}
}
// regions that we have but that we shouldnt have anymore
deadRegions = new List<ulong>(usersRegions.Except(knownNeighbors));
// regions that we don't have that we need to add
newRegions = new List<ulong>(knownNeighbors.Except(usersRegions));
}
try
{
await _operationSemaphore.WaitAsync();
if (resyncDelay > 0) await Task.Delay(resyncDelay);
await this.ResyncRegions(knownNeighborsDict, deadRegions, newRegions);
}
finally
{
_operationSemaphore.Release();
}
}
/// <summary>
/// Resynchronizes our remote presences with the given lists
/// </summary>
/// <param name="knownNeighborsDict">All known regions from both lists</param>
/// <param name="deadRegions">Regions that we should not longer have presences on</param>
/// <param name="newRegions">Regions that we should have presences on but do not</param>
/// <returns></returns>
private async Task ResyncRegions(Dictionary<ulong, SimpleRegionInfo> knownNeighborsDict, List<ulong> deadRegions, List<ulong> newRegions)
{
List<Task<Tuple<EstablishPresenceResult, string>>> connectionTasks = new List<Task<Tuple<EstablishPresenceResult, string>>>(newRegions.Count);
List<Task> disconnectTasks = new List<Task>();
foreach (var region in deadRegions)
{
disconnectTasks.Add(this.DropRemotePresence(knownNeighborsDict[region], false));
}
foreach (var region in newRegions)
{
connectionTasks.Add(this.EstablishPresenceOnRegion(knownNeighborsDict[region], false, false));
}
await Task.WhenAll(connectionTasks);
await Task.WhenAll(disconnectTasks);
if (connectionTasks.Count > 0)
if (_sp != null)
_sp.SendChildAgentUpdate(); // send the other regions the intial avatar info (pos, draw distance) for culling
}
/// <summary>
/// Returns all remote presences we know about, including presences still establishing
/// </summary>
/// <returns></returns>
public List<AvatarRemotePresence> GetRemotePresenceList()
{
lock (_remotePresences)
{
return new List<AvatarRemotePresence>(_remotePresences.Values);
}
}
/// <summary>
/// Returns only established presences
/// </summary>
/// <returns></returns>
public List<AvatarRemotePresence> GetEstablishedRemotePresenceList()
{
List<AvatarRemotePresence> ret = new List<AvatarRemotePresence>();
lock (_remotePresences)
{
foreach (var pres in _remotePresences.Values)
{
if (pres.State == RemotePresenceState.Established)
{
ret.Add(pres);
}
}
}
return ret;
}
/// <summary>
/// Returns whether or not there are any connections currently being established
/// </summary>
/// <returns></returns>
public bool HasConnectionsEstablishing()
{
if (_operationSemaphore.CurrentCount == 0) return true;
lock (_remotePresences)
{
foreach (AvatarRemotePresence pres in _remotePresences.Values)
{
if (pres.State != RemotePresenceState.Established)
{
return true;
}
}
}
return false;
}
public bool HasEstablishedConnection(SimpleRegionInfo region)
{
AvatarRemotePresence pres;
lock (_remotePresences)
{
if (_remotePresences.TryGetValue(region.RegionHandle, out pres))
{
return (pres.State == RemotePresenceState.Established);
}
}
return false;
}
/// <summary>
/// Requests that all remote regions we have children on terminate the child agents
/// </summary>
internal void TerminateAllNeighbors()
{
if (_sp.IsBot) return;
List<AvatarRemotePresence> remotes = this.GetRemotePresenceList();
foreach (var remote in remotes)
{
if (!remote.IsFarPresence)
{
_scene.InterregionComms.SendCloseAgent(remote.PresenceInfo.RegionInfo.RegionHandle, _sp.UUID);
}
}
}
/// <summary>
/// Returns the number of remote presences we have on other regions
/// </summary>
/// <returns></returns>
public int GetRemotePresenceCount()
{
lock (_remotePresences)
{
return _remotePresences.Count;
}
}
}
}
| |
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
namespace Destructible2D
{
[CanEditMultipleObjects]
[CustomEditor(typeof(D2dGui))]
public class D2dGui_Editor : D2dEditor<D2dGui>
{
protected override void OnInspector()
{
DrawDefault("Header");
DrawDefault("Footer");
}
}
}
#endif
namespace Destructible2D
{
// This component shows a simple GUI with FPS
[ExecuteInEditMode]
[DisallowMultipleComponent]
[AddComponentMenu(D2dHelper.ComponentMenuPrefix + "GUI")]
public class D2dGui : MonoBehaviour
{
[Tooltip("The text that appears at the top of the screen")]
[Multiline]
public string Header;
[Tooltip("The text that appears at the bottom of the screen")]
[Multiline]
public string Footer;
// Elapsed seconds from last second
private float counter;
// Elapsed frames from last second
private int frames;
// Previous fps
private float fps;
// Cached GUI styles
private static GUIStyle whiteStyle;
private static GUIStyle blackStyle;
protected virtual void Update()
{
counter += Time.deltaTime;
frames += 1;
if (counter >= 1.0f)
{
fps = (float)frames / counter;
counter = 0.0f;
frames = 0;
}
}
protected virtual void OnGUI()
{
var r1 = new Rect(5, 50 + 55 * 0, 100, 50);
var r2 = new Rect(5, 50 + 55 * 1, 100, 50);
var r3 = new Rect(5, 50 + 55 * 2, 100, 50);
if (GUI.Button(r1, "Reload") == true)
{
LoadLevel(GetCurrentLevel());
}
if (GUI.Button(r2, "Prev") == true)
{
var index = GetCurrentLevel() - 1;
if (index < 0)
{
index = GetLevelCount() - 1;
}
LoadLevel(index);
}
if (GUI.Button(r3, "Next") == true)
{
var index = GetCurrentLevel() + 1;
if (index >= GetLevelCount())
{
index = 0;
}
LoadLevel(index);
}
// Draw FPS?
if (fps > 0.0f)
{
DrawText("FPS: " + fps.ToString("0"), TextAnchor.UpperLeft);
}
// Draw header?
if (string.IsNullOrEmpty(Header) == false)
{
DrawText(Header, TextAnchor.UpperCenter, 150);
}
// Draw footer?
if (string.IsNullOrEmpty(Footer) == false)
{
DrawText(Footer, TextAnchor.LowerCenter, 150);
}
}
#if UNITY_4 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2
private static int GetCurrentLevel()
{
return Application.loadedLevel;
}
private static int GetLevelCount()
{
return Application.levelCount;
}
private static void LoadLevel(int index)
{
Application.LoadLevel(index);
}
#else
private static int GetCurrentLevel()
{
return UnityEngine.SceneManagement.SceneManager.GetActiveScene().buildIndex;
}
private static int GetLevelCount()
{
return UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings;
}
private static void LoadLevel(int index)
{
UnityEngine.SceneManagement.SceneManager.LoadScene(index);
}
#endif
private static void DrawText(string text, TextAnchor anchor, int offsetX = 15, int offsetY = 15)
{
if (string.IsNullOrEmpty(text) == false)
{
if (whiteStyle == null || blackStyle == null)
{
whiteStyle = new GUIStyle();
whiteStyle.fontSize = 20;
whiteStyle.fontStyle = FontStyle.Bold;
whiteStyle.wordWrap = true;
whiteStyle.normal = new GUIStyleState();
whiteStyle.normal.textColor = Color.white;
blackStyle = new GUIStyle();
blackStyle.fontSize = 20;
blackStyle.fontStyle = FontStyle.Bold;
blackStyle.wordWrap = true;
blackStyle.normal = new GUIStyleState();
blackStyle.normal.textColor = Color.black;
}
whiteStyle.alignment = anchor;
blackStyle.alignment = anchor;
var sw = (float)Screen.width;
var sh = (float)Screen.height;
var rect = new Rect(0, 0, sw, sh);
rect.xMin += offsetX;
rect.xMax -= offsetX;
rect.yMin += offsetY;
rect.yMax -= offsetY;
rect.x += 1;
GUI.Label(rect, text, blackStyle);
rect.x -= 2;
GUI.Label(rect, text, blackStyle);
rect.x += 1;
rect.y += 1;
GUI.Label(rect, text, blackStyle);
rect.y -= 2;
GUI.Label(rect, text, blackStyle);
rect.y += 1;
GUI.Label(rect, text, whiteStyle);
}
}
}
}
| |
/*
* Copyright 2012-2021 The Pkcs11Interop Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using System;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.LowLevelAPI40;
using NUnit.Framework;
using NativeULong = System.UInt32;
// Note: Code in this file is generated automatically.
namespace Net.Pkcs11Interop.Tests.LowLevelAPI40
{
/// <summary>
/// C_CreateObject, C_DestroyObject, C_CopyObject and C_GetObjectSize tests.
/// </summary>
[TestFixture()]
public class _16_CreateCopyDestroyObjectTest
{
/// <summary>
/// C_CreateObject and C_DestroyObject test.
/// </summary>
[Test()]
public void _01_CreateDestroyObjectTest()
{
Helpers.CheckPlatform();
CKR rv = CKR.CKR_OK;
using (Pkcs11Library pkcs11Library = new Pkcs11Library(Settings.Pkcs11LibraryPath))
{
rv = pkcs11Library.C_Initialize(Settings.InitArgs40);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
NativeULong slotId = Helpers.GetUsableSlot(pkcs11Library);
NativeULong session = CK.CK_INVALID_HANDLE;
rv = pkcs11Library.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as normal user
rv = pkcs11Library.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt32FromInt32(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare attribute template of new data object
CK_ATTRIBUTE[] template = new CK_ATTRIBUTE[5];
template[0] = CkaUtils.CreateAttribute(CKA.CKA_CLASS, CKO.CKO_DATA);
template[1] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true);
template[2] = CkaUtils.CreateAttribute(CKA.CKA_APPLICATION, Settings.ApplicationName);
template[3] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName);
template[4] = CkaUtils.CreateAttribute(CKA.CKA_VALUE, "Data object content");
// Create object
NativeULong objectId = CK.CK_INVALID_HANDLE;
rv = pkcs11Library.C_CreateObject(session, template, ConvertUtils.UInt32FromInt32(template.Length), ref objectId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// In LowLevelAPI we have to free unmanaged memory taken by attributes
for (int i = 0; i < template.Length; i++)
{
UnmanagedMemory.Free(ref template[i].value);
template[i].valueLen = 0;
}
// Do something interesting with new object
// Destroy object
rv = pkcs11Library.C_DestroyObject(session, objectId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
/// <summary>
/// C_CopyObject test.
/// </summary>
[Test()]
public void _02_CopyObjectTest()
{
Helpers.CheckPlatform();
CKR rv = CKR.CKR_OK;
using (Pkcs11Library pkcs11Library = new Pkcs11Library(Settings.Pkcs11LibraryPath))
{
rv = pkcs11Library.C_Initialize(Settings.InitArgs40);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
NativeULong slotId = Helpers.GetUsableSlot(pkcs11Library);
NativeULong session = CK.CK_INVALID_HANDLE;
rv = pkcs11Library.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as normal user
rv = pkcs11Library.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt32FromInt32(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Create object that can be copied
NativeULong objectId = CK.CK_INVALID_HANDLE;
rv = Helpers.CreateDataObject(pkcs11Library, session, ref objectId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Copy object
NativeULong copiedObjectId = CK.CK_INVALID_HANDLE;
rv = pkcs11Library.C_CopyObject(session, objectId, null, 0, ref copiedObjectId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Do something interesting with new object
rv = pkcs11Library.C_DestroyObject(session, copiedObjectId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_DestroyObject(session, objectId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
/// <summary>
/// C_GetObjectSize test.
/// </summary>
[Test()]
public void _03_GetObjectSizeTest()
{
Helpers.CheckPlatform();
CKR rv = CKR.CKR_OK;
using (Pkcs11Library pkcs11Library = new Pkcs11Library(Settings.Pkcs11LibraryPath))
{
rv = pkcs11Library.C_Initialize(Settings.InitArgs40);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
NativeULong slotId = Helpers.GetUsableSlot(pkcs11Library);
NativeULong session = CK.CK_INVALID_HANDLE;
rv = pkcs11Library.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as normal user
rv = pkcs11Library.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt32FromInt32(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Create object
NativeULong objectId = CK.CK_INVALID_HANDLE;
rv = Helpers.CreateDataObject(pkcs11Library, session, ref objectId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Determine object size
NativeULong objectSize = 0;
rv = pkcs11Library.C_GetObjectSize(session, objectId, ref objectSize);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(objectSize > 0);
rv = pkcs11Library.C_DestroyObject(session, objectId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.IO;
using System.Windows.Forms;
using Vlc.DotNet.Core;
using Vlc.DotNet.Core.Interops.Signatures;
using Vlc.DotNet.Forms.TypeEditors;
namespace Vlc.DotNet.Forms
{
public partial class VlcControl : Control, ISupportInitialize
{
private VlcMediaPlayer myVlcMediaPlayer;
/// <summary>
/// Gets the media player.
/// It can be useful in order to achieve lower-level operations that are not available in the control.
/// </summary>
public VlcMediaPlayer VlcMediaPlayer => this.myVlcMediaPlayer;
#region VlcControl Init
public VlcControl()
{
InitializeComponent();
}
private void InitializeComponent()
{
// Init Component behaviour
BackColor = System.Drawing.Color.Black;
}
private string[] _vlcMediaPlayerOptions = null;
[Category("Media Player")]
public string[] VlcMediaplayerOptions
{
get { return this._vlcMediaPlayerOptions; }
set
{
if (!(myVlcMediaPlayer is null))
{
throw new InvalidOperationException("Cannot modify VlcMediaplayerOptions if Media player has already been initialized. Modify VlcMediaplayerOptions before calling EndInit.");
}
this._vlcMediaPlayerOptions = value;
}
}
private DirectoryInfo _vlcLibDirectory = null;
[Category("Media Player")]
[Editor(typeof(DirectoryEditor), typeof(UITypeEditor))]
public DirectoryInfo VlcLibDirectory {
get { return this._vlcLibDirectory; }
set
{
if (!(myVlcMediaPlayer is null))
{
throw new InvalidOperationException("Cannot modify VlcLibDirectory if Media player has already been initialized. Modify VlcLibDirectory before calling EndInit.");
}
this._vlcLibDirectory = value;
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
public bool IsPlaying
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.IsPlaying();
}
else
{
return false;
}
}
}
public void BeginInit()
{
// not used yet
}
public void EndInit()
{
if (IsInDesignMode || myVlcMediaPlayer != null)
return;
if (_vlcLibDirectory == null && (_vlcLibDirectory = OnVlcLibDirectoryNeeded()) == null)
{
throw new Exception("'VlcLibDirectory' must be set.");
}
if (VlcMediaplayerOptions == null)
{
myVlcMediaPlayer = new VlcMediaPlayer(VlcLibDirectory);
}
else
{
myVlcMediaPlayer = new VlcMediaPlayer(VlcLibDirectory, VlcMediaplayerOptions);
}
if (this.log != null)
{
this.RegisterLogging();
}
myVlcMediaPlayer.VideoHostControlHandle = Handle;
RegisterEvents();
}
private bool loggingRegistered = false;
/// <summary>
/// Connects (only the first time) the events from <see cref="myVlcMediaPlayer"/> to the event handlers registered on this instance
/// </summary>
private void RegisterLogging()
{
if (this.loggingRegistered)
return;
this.myVlcMediaPlayer.Log += this.OnLogInternal;
this.loggingRegistered = true;
}
// work around https://stackoverflow.com/questions/34664/designmode-with-nested-controls/2693338#2693338
private bool IsInDesignMode
{
get
{
if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)
return true;
Control ctrl = this;
while (ctrl != null)
{
if ((ctrl.Site != null) && ctrl.Site.DesignMode)
return true;
ctrl = ctrl.Parent;
}
return false;
}
}
public event EventHandler<VlcLibDirectoryNeededEventArgs> VlcLibDirectoryNeeded;
bool disposed = false;
protected override void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
if (myVlcMediaPlayer != null)
{
UnregisterEvents();
myVlcMediaPlayer.Dispose();
}
myVlcMediaPlayer = null;
}
disposed = true;
}
base.Dispose(disposing);
}
public DirectoryInfo OnVlcLibDirectoryNeeded()
{
var del = VlcLibDirectoryNeeded;
if (del != null)
{
var args = new VlcLibDirectoryNeededEventArgs();
del(this, args);
return args.VlcLibDirectory;
}
return null;
}
#endregion
#region VlcControl Functions & Properties
public void Play()
{
myVlcMediaPlayer?.Play();
}
public void Play(FileInfo file, params string[] options)
{
myVlcMediaPlayer?.Play(file, options);
}
public void Play(Uri uri, params string[] options)
{
myVlcMediaPlayer?.Play(uri, options);
}
public void Play(string mrl, params string[] options)
{
myVlcMediaPlayer?.Play(mrl, options);
}
public void Play(Stream stream, params string[] options)
{
myVlcMediaPlayer?.Play(stream, options);
}
/// <summary>
/// Toggle pause (no effect if there is no media)
/// </summary>
public void Pause()
{
myVlcMediaPlayer?.Pause();
}
/// <summary>
/// Pause or resume (no effect if there is no media)
/// </summary>
/// <param name="doPause">If set to <c>true</c>, pauses the media, resumes if <c>false</c></param>
public void SetPause(bool doPause)
{
myVlcMediaPlayer?.SetPause(doPause);
}
public void Stop()
{
//EndInit();
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.Stop();
}
}
public VlcMedia GetCurrentMedia()
{
//EndInit();
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.GetMedia();
}
else
{
return null;
}
}
/// <summary>
/// Takes a snapshot of the currently playing video and saves it to the given file
/// </summary>
/// <param name="fileName">The name of the file to be written</param>
public bool TakeSnapshot(string fileName)
{
return this.TakeSnapshot(fileName, 0, 0);
}
/// <summary>
/// Takes a snapshot of the currently playing video and saves it to the given file
/// </summary>
/// <remarks>If width AND height is 0, original size is used. If width XOR height is 0, original aspect-ratio is preserved.</remarks>
/// <param name="fileName">The name of the file to be written</param>
/// <param name="width">The width of the snapshot (0 means auto)</param>
/// <param name="height">The height of the snapshot (0 means auto)</param>
public bool TakeSnapshot(string fileName, uint width, uint height)
{
return this.TakeSnapshot(new FileInfo(fileName), width, height);
}
/// <summary>
/// Takes a snapshot of the currently playing video and saves it to the given file
/// </summary>
/// <param name="file">The file to be written</param>
public bool TakeSnapshot(FileInfo file)
{
return this.TakeSnapshot(file, 0, 0);
}
/// <summary>
/// Takes a snapshot of the currently playing video and saves it to the given file
/// </summary>
/// <remarks>If width AND height is 0, original size is used. If width XOR height is 0, original aspect-ratio is preserved.</remarks>
/// <param name="file">The file to be written</param>
/// <param name="width">The width of the snapshot (0 means auto)</param>
/// <param name="height">The height of the snapshot (0 means auto)</param>
public bool TakeSnapshot(FileInfo file, uint width, uint height)
{
return this.myVlcMediaPlayer.TakeSnapshot(file, width, height);
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
public float Position
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Position;
}
else
{
return -1;
}
}
set
{
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.Position = value;
}
}
}
[Browsable(false)]
public IChapterManagement Chapter
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Chapters;
}
else
{
return null;
}
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
public float Rate
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Rate;
}
else
{
return -1;
}
}
set
{
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.Rate = value;
}
}
}
[Browsable(false)]
public MediaStates State
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.State;
}
else
{
return MediaStates.NothingSpecial;
}
}
}
[Browsable(false)]
public ISubTitlesManagement SubTitles
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.SubTitles;
}
else
{
return null;
}
}
}
[Browsable(false)]
public IVideoManagement Video
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Video;
}
else
{
return null;
}
}
}
[Browsable(false)]
public IAudioManagement Audio
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Audio;
}
else
{
return null;
}
}
}
[Browsable(false)]
public long Length
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Length;
}
else
{
return -1;
}
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
public long Time
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Time;
}
else
{
return -1;
}
}
set
{
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.Time = value;
}
}
}
[Browsable(false)]
public int Spu
{
get
{
if (myVlcMediaPlayer != null)
{
return myVlcMediaPlayer.Spu;
}
return -1;
}
set
{
if (myVlcMediaPlayer != null)
{
myVlcMediaPlayer.Spu = value;
}
}
}
public void SetMedia(FileInfo file, params string[] options)
{
//EndInit();
myVlcMediaPlayer.SetMedia(file, options);
}
public void SetMedia(Uri file, params string[] options)
{
//EndInit();
myVlcMediaPlayer.SetMedia(file, options);
}
public void SetMedia(string mrl, params string[] options)
{
//EndInit();
myVlcMediaPlayer.SetMedia(mrl, options);
}
public void SetMedia(Stream stream, params string[] options)
{
//EndInit();
myVlcMediaPlayer.SetMedia(stream, options);
}
public void ResetMedia()
{
myVlcMediaPlayer.ResetMedia();
}
#endregion
}
}
| |
using NAME.Core.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
//Based on the project in https://github.com/samus/mongodb-csharp under the Apache-2.0 license
namespace NAME.MongoDb
{
/// <summary>
/// Provides a mechanism to read a Mongo connection string.
/// </summary>
internal class MongoConnectionStringBuilder
{
/// <summary>
/// The Default database.
/// </summary>
public const string DefaultDatabase = "admin";
private static readonly Regex ServerRegex = new Regex(@"^\s*([^:]+)(?::(\d+))?\s*$");
private static readonly Regex UriRegex = new Regex(@"^mongodb://(?:[^:]*:[^@]*@)?([^/]*)(?:/([^?]*))?(?:\?.*)?$");
private readonly List<MongoServerEndPoint> servers = new List<MongoServerEndPoint>();
/// <summary>
/// Initializes a new instance of the
/// <see cref = "MongoConnectionStringBuilder" />
/// class. Uses the default server connection when
/// no server is added.
/// </summary>
public MongoConnectionStringBuilder()
{
this.Database = DefaultDatabase;
}
/// <summary>
/// Initializes a new instance of the
/// <see cref = "MongoConnectionStringBuilder" />
/// class. Uses the default server connection when
/// no server is added.
/// </summary>
/// <param name = "connectionString">The connection string.</param>
public MongoConnectionStringBuilder(string connectionString)
: this()
{
if (!string.IsNullOrEmpty(connectionString))
{
if (connectionString.StartsWith("mongodb://"))
this.ParseUri(connectionString);
else
throw new NAMEException("The connection string must start with mongodb://", NAMEStatusLevel.Warn);
}
}
/// <summary>
/// Gets the servers.
/// </summary>
/// <value>The servers.</value>
public MongoServerEndPoint[] Servers
{
get
{
return this.servers.Count == 0 ? new[] { MongoServerEndPoint.Default } : this.servers.ToArray();
}
}
/// <summary>
/// Gets or sets the database.
/// </summary>
/// <remarks>
/// Is only used when passing directly constructing MongoDatabase instance.
/// </remarks>
/// <value>The database.</value>
public string Database { get; set; }
/// <summary>
/// Parses the URI.
/// </summary>
/// <param name = "connectionString">The connection string.</param>
private void ParseUri(string connectionString)
{
if (connectionString == null)
throw new ArgumentNullException(nameof(connectionString));
var uriMatch = UriRegex.Match(connectionString);
if (!uriMatch.Success)
throw new FormatException(string.Format("Invalid connection string: {0}", connectionString));
var servers = uriMatch.Groups[1].Value;
if (!string.IsNullOrEmpty(servers))
this.ParseServers(servers);
var database = uriMatch.Groups[2].Value;
if (!string.IsNullOrEmpty(database))
this.Database = database;
}
/// <summary>
/// Parses the servers.
/// </summary>
/// <param name = "value">The value.</param>
private void ParseServers(string value)
{
var servers = value.Split(',');
foreach (var serverMatch in servers.Select(server => ServerRegex.Match(server)))
{
if (!serverMatch.Success)
throw new FormatException(string.Format("Invalid server in connection string: {0}", serverMatch.Value));
var serverHost = serverMatch.Groups[1].Value;
if (int.TryParse(serverMatch.Groups[2].Value, out int port))
this.AddServer(serverHost, port);
else
this.AddServer(serverHost);
}
}
/// <summary>
/// Adds the server.
/// </summary>
/// <param name = "endPoint">The end point.</param>
public void AddServer(MongoServerEndPoint endPoint)
{
if (endPoint == null)
throw new ArgumentNullException("endPoint");
this.servers.Add(endPoint);
}
/// <summary>
/// Clears the servers.
/// </summary>
public void ClearServers()
{
this.servers.Clear();
}
/// <summary>
/// Adds the server with the given host and default port.
/// </summary>
/// <param name = "host">The host.</param>
public void AddServer(string host)
{
this.AddServer(new MongoServerEndPoint(host));
}
/// <summary>
/// Adds the server with the given host and port.
/// </summary>
/// <param name = "host">The host.</param>
/// <param name = "port">The port.</param>
public void AddServer(string host, int port)
{
this.AddServer(new MongoServerEndPoint(host, port));
}
/// <summary>
/// Returns a
/// <see cref = "string" />
/// that represents this instance.
/// </summary>
/// <returns>A
/// <see cref = "string" />
/// that represents this instance.</returns>
public override string ToString()
{
var builder = new StringBuilder();
if (this.servers.Count > 0)
{
builder.Append("Server=");
foreach (var server in this.servers)
{
builder.Append(server.Host);
if (server.Port != MongoServerEndPoint.DefaultPort)
builder.AppendFormat(":{0}", server.Port);
builder.Append(',');
}
// remove last ,
builder.Remove(builder.Length - 1, 1);
builder.Append(';');
}
// remove last ;
if (builder.Length > 0)
builder.Remove(builder.Length - 1, 1);
return builder.ToString();
}
}
}
| |
using System;
using System.Text;
using System.Globalization;
using TestLibrary;
public class StringCompare
{
public static string[] InterestingStrings = new string[] { null, "", "a", "1", "-", "A", "!", "abc", "aBc", "a\u0400Bc", "I", "i", "\u0130", "\u0131", "A", "\uFF21", "\uFE57"};
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Compare interesting strings ordinally");
try
{
foreach (string s in InterestingStrings)
{
foreach (string r in InterestingStrings)
{
retVal &= TestStrings(s, r);
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Compare many characters");
try
{
for (int i = 0; i < 40; i++) // Ok, 40 isn't that many... but this takes way too long
{
char c = Generator.GetChar(-55);
if (string.Compare(new string(new char[] { c }), new string(new char[] { c }), StringComparison.Ordinal) != 0)
{
TestLibrary.TestFramework.LogError("002.1", "Character " + i.ToString() + " is not equal to itself ordinally!");
retVal = false;
}
for (int j = 0; j < (int)c; j++)
{
int compareResult = string.Compare(new string(new char[] { c }), new string(new char[] { (char)j }), StringComparison.Ordinal);
if (compareResult != 0) compareResult = compareResult / Math.Abs(compareResult);
if (compareResult != 1)
{
TestLibrary.TestFramework.LogError("002.2", "Character " + ((int)c).ToString() + " is not greater than character " + j.ToString() + ", Compare result: " + compareResult.ToString());
retVal = false;
}
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.4", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Compare many strings");
try
{
for (int i = 0; i < 1000; i++)
{
string str1 = Generator.GetString(-55, false, 5, 20);
string str2 = Generator.GetString(-55, false, 5, 20);
if (string.Compare(str1, str1, StringComparison.Ordinal) != 0)
{
TestLibrary.TestFramework.LogError("003.1", "Comparison not as expected! Actual result: " + string.Compare(str1, str1, StringComparison.Ordinal).ToString() + ", Expected result: 0");
TestLibrary.TestFramework.LogInformation("String 1: <" + str1 + "> : " + BytesFromString(str1) + "\nString 2: <" + str1 + "> : " + BytesFromString(str1));
retVal = false;
}
if (string.Compare(str2, str2, StringComparison.Ordinal) != 0)
{
TestLibrary.TestFramework.LogError("003.2", "Comparison not as expected! Actual result: " + string.Compare(str2, str2, StringComparison.Ordinal).ToString() + ", Expected result: 0");
TestLibrary.TestFramework.LogInformation("String 1: <" + str2 + "> : " + BytesFromString(str2) + "\nString 2: <" + str2 + "> : " + BytesFromString(str2));
retVal = false;
}
TestStrings(str1, str2);
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.4", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Specific regression cases");
try
{
CultureInfo oldCi = Utilities.CurrentCulture;
Utilities.CurrentCulture = new CultureInfo("hu-HU");
retVal &= TestStrings("dzsdzs", "ddzs");
Utilities.CurrentCulture = oldCi;
retVal &= TestStrings("\u00C0nimal", "A\u0300nimal");
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public static int Main()
{
StringCompare test = new StringCompare();
TestLibrary.TestFramework.BeginTestCase("StringCompare");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
private bool TestStrings(string str1, string str2)
{
bool retVal = true;
int expectValue = PredictValue(str1, str2);
int actualValue = String.Compare(str1, str2, StringComparison.Ordinal);
if (expectValue != 0) expectValue = expectValue / Math.Abs(expectValue);
if (actualValue != 0) actualValue = actualValue / Math.Abs(actualValue);
if (actualValue != expectValue)
{
TestLibrary.TestFramework.LogError("001.1", "Comparison not as expected! Actual result: " + actualValue + ", Expected result: " + expectValue);
TestLibrary.TestFramework.LogInformation("String 1: <" + str1 + "> : " + BytesFromString(str1) + "\nString 2: <" + str2 + "> : " + BytesFromString(str2));
retVal = false;
}
return retVal;
}
int PredictValue(string str1, string str2)
{
if (str1 == null)
{
if (str2 == null) return 0;
else return -1;
}
if (str2 == null) return 1;
for (int i = 0; i < str1.Length; i++)
{
if (i >= str2.Length) return 1;
if ((int)str1[i] > (int)str2[i]) return 1;
if ((int)str1[i] < (int)str2[i]) return -1;
}
if (str2.Length > str1.Length) return -1;
return 0;
}
private static string BytesFromString(string str)
{
if (str == null) return string.Empty;
StringBuilder output = new StringBuilder();
for (int i = 0; i < str.Length; i++)
{
output.Append(Utilities.ByteArrayToString(BitConverter.GetBytes(str[i])));
if (i != (str.Length - 1)) output.Append(", ");
}
return output.ToString();
}
}
| |
//
// LabelBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using Xwt.Drawing;
using Xwt.CairoBackend;
using System.Runtime.InteropServices;
using System.Linq;
using System.Collections.Generic;
namespace Xwt.GtkBackend
{
public partial class LabelBackend: WidgetBackend, ILabelBackend
{
Color? textColor;
List<LabelLink> links;
TextIndexer indexer;
public LabelBackend ()
{
Widget = new Gtk.Label ();
Label.Show ();
Label.Xalign = 0;
Label.Yalign = 0.5f;
}
new ILabelEventSink EventSink {
get { return (ILabelEventSink)base.EventSink; }
}
protected Gtk.Label Label {
get {
if (Widget is Gtk.Label)
return (Gtk.Label) Widget;
else
return (Gtk.Label) ((Gtk.EventBox)base.Widget).Child;
}
}
bool linkEventEnabled;
void EnableLinkEvents ()
{
if (!linkEventEnabled) {
linkEventEnabled = true;
AllocEventBox ();
EventsRootWidget.AddEvents ((int)Gdk.EventMask.PointerMotionMask);
EventsRootWidget.MotionNotifyEvent += HandleMotionNotifyEvent;
EventsRootWidget.AddEvents ((int)Gdk.EventMask.ButtonReleaseMask);
EventsRootWidget.ButtonReleaseEvent += HandleButtonReleaseEvent;
EventsRootWidget.AddEvents ((int)Gdk.EventMask.LeaveNotifyMask);
EventsRootWidget.LeaveNotifyEvent += HandleLeaveNotifyEvent;
}
}
bool mouseInLink;
CursorType normalCursor;
void HandleMotionNotifyEvent (object o, Gtk.MotionNotifyEventArgs args)
{
var li = FindLink (args.Event.X, args.Event.Y);
if (li != null) {
if (!mouseInLink) {
mouseInLink = true;
normalCursor = CurrentCursor;
SetCursor (CursorType.Hand);
}
} else {
if (mouseInLink) {
mouseInLink = false;
SetCursor (normalCursor ?? CursorType.Arrow);
}
}
}
void HandleButtonReleaseEvent (object o, Gtk.ButtonReleaseEventArgs args)
{
var li = FindLink (args.Event.X, args.Event.Y);
if (li != null) {
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnLinkClicked (li.Target);
});
args.RetVal = true;
};
}
void HandleLeaveNotifyEvent (object o, Gtk.LeaveNotifyEventArgs args)
{
if (mouseInLink) {
mouseInLink = false;
SetCursor (normalCursor ?? CursorType.Arrow);
}
}
LabelLink FindLink (double px, double py)
{
if (links == null)
return null;
var alloc = Label.Allocation;
int offsetX, offsetY;
Label.GetLayoutOffsets (out offsetX, out offsetY);
var x = (px - offsetX + alloc.X) * Pango.Scale.PangoScale;
var y = (py - offsetY + alloc.Y) * Pango.Scale.PangoScale;
int byteIndex, trailing;
if (!Label.Layout.XyToIndex ((int)x, (int)y, out byteIndex, out trailing))
return null;
foreach (var li in links)
if (byteIndex >= li.StartIndex && byteIndex <= li.EndIndex)
return li;
return null;
}
public virtual string Text {
get { return Label.Text; }
set {
links = null;
indexer = null;
Label.Text = value;
}
}
public void SetFormattedText (FormattedText text)
{
Label.Text = text.Text;
var list = new FastPangoAttrList ();
indexer = new TextIndexer (text.Text);
list.AddAttributes (indexer, text.Attributes);
gtk_label_set_attributes (Label.Handle, list.Handle);
if (links != null)
links.Clear ();
foreach (var attr in text.Attributes.OfType<LinkTextAttribute> ()) {
LabelLink ll = new LabelLink () {
StartIndex = indexer.IndexToByteIndex (attr.StartIndex),
EndIndex = indexer.IndexToByteIndex (attr.StartIndex + attr.Count),
Target = attr.Target
};
if (links == null) {
links = new List<LabelLink> ();
EnableLinkEvents ();
}
links.Add (ll);
}
if (links == null || links.Count == 0) {
links = null;
indexer = null;
}
}
[DllImport (GtkInterop.LIBGTK, CallingConvention=CallingConvention.Cdecl)]
static extern void gtk_label_set_attributes (IntPtr label, IntPtr attrList);
public Xwt.Drawing.Color TextColor {
get {
return textColor.HasValue ? textColor.Value : Widget.Style.Foreground (Gtk.StateType.Normal).ToXwtValue ();
}
set {
var color = value.ToGtkValue ();
var attr = new Pango.AttrForeground (color.Red, color.Green, color.Blue);
var attrs = new Pango.AttrList ();
attrs.Insert (attr);
Label.Attributes = attrs;
textColor = value;
Label.QueueDraw ();
}
}
Alignment alignment;
public Alignment TextAlignment {
get {
return alignment;
}
set {
alignment = value;
SetAlignment ();
}
}
protected void SetAlignment ()
{
switch (alignment) {
case Alignment.Start:
Label.Justify = Gtk.Justification.Left;
break;
case Alignment.End:
Label.Justify = Gtk.Justification.Right;
break;
case Alignment.Center:
Label.Justify = Gtk.Justification.Center;
break;
}
SetAlignmentGtk ();
}
public EllipsizeMode Ellipsize {
get {
return Label.Ellipsize.ToXwtValue ();
}
set {
Label.Ellipsize = value.ToGtkValue ();
}
}
public WrapMode Wrap {
get {
if (!Label.LineWrap)
return WrapMode.None;
else {
switch (Label.LineWrapMode) {
case Pango.WrapMode.Char:
return WrapMode.Character;
case Pango.WrapMode.Word:
return WrapMode.Word;
case Pango.WrapMode.WordChar:
return WrapMode.WordAndCharacter;
default:
return WrapMode.None;
}
}
}
set {
ToggleSizeCheckEventsForWrap (value);
if (value == WrapMode.None){
if (Label.LineWrap) {
Label.LineWrap = false;
}
} else {
if (!Label.LineWrap) {
Label.LineWrap = true;
}
switch (value) {
case WrapMode.Character:
Label.LineWrapMode = Pango.WrapMode.Char;
break;
case WrapMode.Word:
Label.LineWrapMode = Pango.WrapMode.Word;
break;
case WrapMode.WordAndCharacter:
Label.LineWrapMode = Pango.WrapMode.WordChar;
break;
}
}
SetAlignment ();
}
}
}
class LabelLink
{
public int StartIndex;
public int EndIndex;
public Uri Target;
}
}
| |
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 BugLogger.WebAPI.Areas.HelpPage.ModelDescriptions;
using BugLogger.WebAPI.Areas.HelpPage.Models;
namespace BugLogger.WebAPI.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// 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 Microsoft.Azure.Management.Sql
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ElasticPoolDatabaseActivitiesOperations operations.
/// </summary>
internal partial class ElasticPoolDatabaseActivitiesOperations : IServiceOperations<SqlManagementClient>, IElasticPoolDatabaseActivitiesOperations
{
/// <summary>
/// Initializes a new instance of the ElasticPoolDatabaseActivitiesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ElasticPoolDatabaseActivitiesOperations(SqlManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the SqlManagementClient
/// </summary>
public SqlManagementClient Client { get; private set; }
/// <summary>
/// Returns activity on databases inside of an elastic pool.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='elasticPoolName'>
/// The name of the elastic pool.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<ElasticPoolDatabaseActivity>>> ListByElasticPoolWithHttpMessagesAsync(string resourceGroupName, string serverName, string elasticPoolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (elasticPoolName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "elasticPoolName");
}
string apiVersion = "2014-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("elasticPoolName", elasticPoolName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByElasticPool", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/elasticPools/{elasticPoolName}/elasticPoolDatabaseActivity").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{elasticPoolName}", System.Uri.EscapeDataString(elasticPoolName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<ElasticPoolDatabaseActivity>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ElasticPoolDatabaseActivity>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
#if UNITY_2017_1_OR_NEWER
using UnityEditor.Experimental.AssetImporters;
using UnityEditor;
using System.IO;
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
using System;
using Object = UnityEngine.Object;
using System.Collections;
using UnityGLTF.Loader;
using GLTF.Schema;
using GLTF;
using System.Threading.Tasks;
namespace UnityGLTF
{
[ScriptedImporter(1, new[] { "glb" })]
public class GLTFImporter : ScriptedImporter
{
[SerializeField] private bool _removeEmptyRootObjects = true;
[SerializeField] private float _scaleFactor = 1.0f;
[SerializeField] private int _maximumLod = 300;
[SerializeField] private bool _readWriteEnabled = true;
[SerializeField] private bool _generateColliders = false;
[SerializeField] private bool _swapUvs = false;
[SerializeField] private GLTFImporterNormals _importNormals = GLTFImporterNormals.Import;
[SerializeField] private bool _importMaterials = true;
[SerializeField] private bool _useJpgTextures = false;
public override void OnImportAsset(AssetImportContext ctx)
{
string sceneName = null;
GameObject gltfScene = null;
UnityEngine.Mesh[] meshes = null;
try
{
sceneName = Path.GetFileNameWithoutExtension(ctx.assetPath);
gltfScene = CreateGLTFScene(ctx.assetPath);
// Remove empty roots
if (_removeEmptyRootObjects)
{
var t = gltfScene.transform;
while (
gltfScene.transform.childCount == 1 &&
gltfScene.GetComponents<Component>().Length == 1)
{
var parent = gltfScene;
gltfScene = gltfScene.transform.GetChild(0).gameObject;
t = gltfScene.transform;
t.parent = null; // To keep transform information in the new parent
Object.DestroyImmediate(parent); // Get rid of the parent
}
}
// Ensure there are no hide flags present (will cause problems when saving)
gltfScene.hideFlags &= ~(HideFlags.HideAndDontSave);
foreach (Transform child in gltfScene.transform)
{
child.gameObject.hideFlags &= ~(HideFlags.HideAndDontSave);
}
// Zero position
gltfScene.transform.position = Vector3.zero;
// Get meshes
var meshNames = new List<string>();
var meshHash = new HashSet<UnityEngine.Mesh>();
var meshFilters = gltfScene.GetComponentsInChildren<MeshFilter>();
var vertexBuffer = new List<Vector3>();
meshes = meshFilters.Select(mf =>
{
var mesh = mf.sharedMesh;
vertexBuffer.Clear();
mesh.GetVertices(vertexBuffer);
for (var i = 0; i < vertexBuffer.Count; ++i)
{
vertexBuffer[i] *= _scaleFactor;
}
mesh.SetVertices(vertexBuffer);
if (_swapUvs)
{
var uv = mesh.uv;
var uv2 = mesh.uv2;
mesh.uv = uv2;
mesh.uv2 = uv2;
}
if (_importNormals == GLTFImporterNormals.None)
{
mesh.normals = new Vector3[0];
}
if (_importNormals == GLTFImporterNormals.Calculate)
{
mesh.RecalculateNormals();
}
mesh.UploadMeshData(!_readWriteEnabled);
if (_generateColliders)
{
var collider = mf.gameObject.AddComponent<MeshCollider>();
collider.sharedMesh = mesh;
}
if (meshHash.Add(mesh))
{
var meshName = string.IsNullOrEmpty(mesh.name) ? mf.gameObject.name : mesh.name;
mesh.name = ObjectNames.GetUniqueName(meshNames.ToArray(), meshName);
meshNames.Add(mesh.name);
}
return mesh;
}).ToArray();
var renderers = gltfScene.GetComponentsInChildren<Renderer>();
if (_importMaterials)
{
// Get materials
var materialNames = new List<string>();
var materialHash = new HashSet<UnityEngine.Material>();
var materials = renderers.SelectMany(r =>
{
return r.sharedMaterials.Select(mat =>
{
if (materialHash.Add(mat))
{
var matName = string.IsNullOrEmpty(mat.name) ? mat.shader.name : mat.name;
if (matName == mat.shader.name)
{
matName = matName.Substring(Mathf.Min(matName.LastIndexOf("/") + 1, matName.Length - 1));
}
// Ensure name is unique
matName = string.Format("{0} {1}", sceneName, ObjectNames.NicifyVariableName(matName));
matName = ObjectNames.GetUniqueName(materialNames.ToArray(), matName);
mat.name = matName;
materialNames.Add(matName);
}
return mat;
});
}).ToArray();
// Get textures
var textureNames = new List<string>();
var textureHash = new HashSet<Texture2D>();
var texMaterialMap = new Dictionary<Texture2D, List<TexMaterialMap>>();
var textures = materials.SelectMany(mat =>
{
var shader = mat.shader;
if (!shader) return Enumerable.Empty<Texture2D>();
var matTextures = new List<Texture2D>();
for (var i = 0; i < ShaderUtil.GetPropertyCount(shader); ++i)
{
if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.TexEnv)
{
var propertyName = ShaderUtil.GetPropertyName(shader, i);
var tex = mat.GetTexture(propertyName) as Texture2D;
if (tex)
{
if (textureHash.Add(tex))
{
var texName = tex.name;
if (string.IsNullOrEmpty(texName))
{
if (propertyName.StartsWith("_")) texName = propertyName.Substring(Mathf.Min(1, propertyName.Length - 1));
}
// Ensure name is unique
texName = string.Format("{0} {1}", sceneName, ObjectNames.NicifyVariableName(texName));
texName = ObjectNames.GetUniqueName(textureNames.ToArray(), texName);
tex.name = texName;
textureNames.Add(texName);
matTextures.Add(tex);
}
List<TexMaterialMap> materialMaps;
if (!texMaterialMap.TryGetValue(tex, out materialMaps))
{
materialMaps = new List<TexMaterialMap>();
texMaterialMap.Add(tex, materialMaps);
}
materialMaps.Add(new TexMaterialMap(mat, propertyName, propertyName == "_BumpMap"));
}
}
}
return matTextures;
}).ToArray();
var folderName = Path.GetDirectoryName(ctx.assetPath);
// Save textures as separate assets and rewrite refs
// TODO: Support for other texture types
if (textures.Length > 0)
{
var texturesRoot = string.Concat(folderName, "/", "Textures/");
Directory.CreateDirectory(texturesRoot);
foreach (var tex in textures)
{
var ext = _useJpgTextures ? ".jpg" : ".png";
var texPath = string.Concat(texturesRoot, tex.name, ext);
File.WriteAllBytes(texPath, _useJpgTextures ? tex.EncodeToJPG() : tex.EncodeToPNG());
AssetDatabase.ImportAsset(texPath);
}
}
// Save materials as separate assets and rewrite refs
if (materials.Length > 0)
{
var materialRoot = string.Concat(folderName, "/", "Materials/");
Directory.CreateDirectory(materialRoot);
foreach (var mat in materials)
{
var materialPath = string.Concat(materialRoot, mat.name, ".mat");
var newMat = mat;
CopyOrNew(mat, materialPath, m =>
{
// Fix references
newMat = m;
foreach (var r in renderers)
{
var sharedMaterials = r.sharedMaterials;
for (var i = 0; i < sharedMaterials.Length; ++i)
{
var sharedMaterial = sharedMaterials[i];
if (sharedMaterial.name == mat.name) sharedMaterials[i] = m;
}
sharedMaterials = sharedMaterials.Where(sm => sm).ToArray();
r.sharedMaterials = sharedMaterials;
}
});
// Fix textures
// HACK: This needs to be a delayed call.
// Unity needs a frame to kick off the texture import so we can rewrite the ref
if (textures.Length > 0)
{
EditorApplication.delayCall += () =>
{
for (var i = 0; i < textures.Length; ++i)
{
var tex = textures[i];
var texturesRoot = string.Concat(folderName, "/", "Textures/");
var ext = _useJpgTextures ? ".jpg" : ".png";
var texPath = string.Concat(texturesRoot, tex.name, ext);
// Grab new imported texture
var materialMaps = texMaterialMap[tex];
var importer = (TextureImporter)TextureImporter.GetAtPath(texPath);
var importedTex = AssetDatabase.LoadAssetAtPath<Texture2D>(texPath);
if (importer != null)
{
var isNormalMap = false;
foreach (var materialMap in materialMaps)
{
if (materialMap.Material == mat)
{
isNormalMap |= materialMap.IsNormalMap;
newMat.SetTexture(materialMap.Property, importedTex);
}
};
if (isNormalMap)
{
// Try to auto-detect normal maps
importer.textureType = TextureImporterType.NormalMap;
}
else if (importer.textureType == TextureImporterType.Sprite)
{
// Force disable sprite mode, even for 2D projects
importer.textureType = TextureImporterType.Default;
}
importer.SaveAndReimport();
}
else
{
Debug.LogWarning(string.Format("GLTFImporter: Unable to import texture at path: {0}", texPath));
}
}
};
}
}
}
}
else
{
var temp = GameObject.CreatePrimitive(PrimitiveType.Plane);
temp.SetActive(false);
var defaultMat = new[] { temp.GetComponent<Renderer>().sharedMaterial };
DestroyImmediate(temp);
foreach (var rend in renderers)
{
rend.sharedMaterials = defaultMat;
}
}
}
catch
{
if (gltfScene) DestroyImmediate(gltfScene);
throw;
}
#if UNITY_2017_3_OR_NEWER
// Set main asset
ctx.AddObjectToAsset("main asset", gltfScene);
// Add meshes
foreach (var mesh in meshes)
{
ctx.AddObjectToAsset("mesh " + mesh.name, mesh);
}
ctx.SetMainObject(gltfScene);
#else
// Set main asset
ctx.SetMainAsset("main asset", gltfScene);
// Add meshes
foreach (var mesh in meshes)
{
ctx.AddSubAsset("mesh " + mesh.name, mesh);
}
#endif
}
private GameObject CreateGLTFScene(string projectFilePath)
{
ILoader fileLoader = new FileLoader(Path.GetDirectoryName(projectFilePath));
using (var stream = File.OpenRead(projectFilePath))
{
GLTFRoot gLTFRoot;
GLTFParser.ParseJson(stream, out gLTFRoot);
var loader = new GLTFSceneImporter(gLTFRoot, fileLoader, null, stream);
loader.MaximumLod = _maximumLod;
loader.IsMultithreaded = true;
loader.LoadSceneAsync().Wait();
return loader.LastLoadedScene;
}
}
private void CopyOrNew<T>(T asset, string assetPath, Action<T> replaceReferences) where T : Object
{
var existingAsset = AssetDatabase.LoadAssetAtPath<T>(assetPath);
if (existingAsset)
{
EditorUtility.CopySerialized(asset, existingAsset);
replaceReferences(existingAsset);
return;
}
AssetDatabase.CreateAsset(asset, assetPath);
}
private class TexMaterialMap
{
public UnityEngine.Material Material { get; set; }
public string Property { get; set; }
public bool IsNormalMap { get; set; }
public TexMaterialMap(UnityEngine.Material material, string property, bool isNormalMap)
{
Material = material;
Property = property;
IsNormalMap = isNormalMap;
}
}
}
}
#endif
| |
// 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.Azure.AcceptanceTestsHeadExceptions
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
/// <summary>
/// HeadExceptionOperations operations.
/// </summary>
internal partial class HeadExceptionOperations : Microsoft.Rest.IServiceOperations<AutoRestHeadExceptionTestService>, IHeadExceptionOperations
{
/// <summary>
/// Initializes a new instance of the HeadExceptionOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal HeadExceptionOperations(AutoRestHeadExceptionTestService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestHeadExceptionTestService
/// </summary>
public AutoRestHeadExceptionTestService Client { get; private set; }
/// <summary>
/// Return 200 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// 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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> Head200WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Head200", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/200").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("HEAD");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 204 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// 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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> Head204WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Head204", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/204").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("HEAD");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 404 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// 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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> Head404WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Head404", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/404").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("HEAD");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.