context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
* 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.Data;
using System.Reflection;
using log4net;
using System.Data.SqlClient;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using System.Text;
namespace OpenSim.Data.MSSQL
{
public class MSSQLGenericTableHandler<T> where T : class, new()
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected string m_ConnectionString;
protected MSSQLManager m_database; //used for parameter type translation
protected Dictionary<string, FieldInfo> m_Fields =
new Dictionary<string, FieldInfo>();
protected List<string> m_ColumnNames = null;
protected string m_Realm;
protected FieldInfo m_DataField = null;
public MSSQLGenericTableHandler(string connectionString,
string realm, string storeName)
{
m_Realm = realm;
if (storeName != String.Empty)
{
Assembly assem = GetType().Assembly;
m_ConnectionString = connectionString;
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
{
conn.Open();
Migration m = new Migration(conn, assem, storeName);
m.Update();
}
}
m_database = new MSSQLManager(m_ConnectionString);
Type t = typeof(T);
FieldInfo[] fields = t.GetFields(BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
if (fields.Length == 0)
return;
foreach (FieldInfo f in fields)
{
if (f.Name != "Data")
m_Fields[f.Name] = f;
else
m_DataField = f;
}
}
private void CheckColumnNames(SqlDataReader reader)
{
if (m_ColumnNames != null)
return;
m_ColumnNames = new List<string>();
DataTable schemaTable = reader.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
{
if (row["ColumnName"] != null &&
(!m_Fields.ContainsKey(row["ColumnName"].ToString())))
m_ColumnNames.Add(row["ColumnName"].ToString());
}
}
private List<string> GetConstraints()
{
List<string> constraints = new List<string>();
string query = string.Format(@"SELECT
COL_NAME(ic.object_id,ic.column_id) AS column_name
FROM sys.indexes AS i
INNER JOIN sys.index_columns AS ic
ON i.object_id = ic.object_id AND i.index_id = ic.index_id
WHERE i.is_primary_key = 1
AND i.object_id = OBJECT_ID('{0}');", m_Realm);
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
// query produces 0 to many rows of single column, so always add the first item in each row
constraints.Add((string)rdr[0]);
}
}
return constraints;
}
}
public virtual T[] Get(string field, string key)
{
return Get(new string[] { field }, new string[] { key });
}
public virtual T[] Get(string[] fields, string[] keys)
{
if (fields.Length != keys.Length)
return new T[0];
List<string> terms = new List<string>();
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
for (int i = 0; i < fields.Length; i++)
{
cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i]));
terms.Add("[" + fields[i] + "] = @" + fields[i]);
}
string where = String.Join(" AND ", terms.ToArray());
string query = String.Format("SELECT * FROM {0} WHERE {1}",
m_Realm, where);
cmd.Connection = conn;
cmd.CommandText = query;
conn.Open();
return DoQuery(cmd);
}
}
protected T[] DoQuery(SqlCommand cmd)
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader == null)
return new T[0];
CheckColumnNames(reader);
List<T> result = new List<T>();
while (reader.Read())
{
T row = new T();
foreach (string name in m_Fields.Keys)
{
if (m_Fields[name].GetValue(row) is bool)
{
int v = Convert.ToInt32(reader[name]);
m_Fields[name].SetValue(row, v != 0 ? true : false);
}
else if (m_Fields[name].GetValue(row) is UUID)
{
UUID uuid = UUID.Zero;
UUID.TryParse(reader[name].ToString(), out uuid);
m_Fields[name].SetValue(row, uuid);
}
else if (m_Fields[name].GetValue(row) is int)
{
int v = Convert.ToInt32(reader[name]);
m_Fields[name].SetValue(row, v);
}
else
{
m_Fields[name].SetValue(row, reader[name]);
}
}
if (m_DataField != null)
{
Dictionary<string, string> data =
new Dictionary<string, string>();
foreach (string col in m_ColumnNames)
{
data[col] = reader[col].ToString();
if (data[col] == null)
data[col] = String.Empty;
}
m_DataField.SetValue(row, data);
}
result.Add(row);
}
return result.ToArray();
}
}
public virtual T[] Get(string where)
{
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
string query = String.Format("SELECT * FROM {0} WHERE {1}",
m_Realm, where);
cmd.Connection = conn;
cmd.CommandText = query;
//m_log.WarnFormat("[MSSQLGenericTable]: SELECT {0} WHERE {1}", m_Realm, where);
conn.Open();
return DoQuery(cmd);
}
}
public virtual bool Store(T row)
{
List<string> constraintFields = GetConstraints();
List<KeyValuePair<string, string>> constraints = new List<KeyValuePair<string, string>>();
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
StringBuilder query = new StringBuilder();
List<String> names = new List<String>();
List<String> values = new List<String>();
foreach (FieldInfo fi in m_Fields.Values)
{
names.Add(fi.Name);
values.Add("@" + fi.Name);
if (constraintFields.Count > 0 && constraintFields.Contains(fi.Name))
{
constraints.Add(new KeyValuePair<string, string>(fi.Name, fi.GetValue(row).ToString()));
}
cmd.Parameters.Add(m_database.CreateParameter(fi.Name, fi.GetValue(row).ToString()));
}
if (m_DataField != null)
{
Dictionary<string, string> data =
(Dictionary<string, string>)m_DataField.GetValue(row);
foreach (KeyValuePair<string, string> kvp in data)
{
if (constraintFields.Count > 0 && constraintFields.Contains(kvp.Key))
{
constraints.Add(new KeyValuePair<string, string>(kvp.Key, kvp.Key));
}
names.Add(kvp.Key);
values.Add("@" + kvp.Key);
cmd.Parameters.Add(m_database.CreateParameter("@" + kvp.Key, kvp.Value));
}
}
query.AppendFormat("UPDATE {0} SET ", m_Realm);
int i = 0;
for (i = 0; i < names.Count - 1; i++)
{
query.AppendFormat("[{0}] = {1}, ", names[i], values[i]);
}
query.AppendFormat("[{0}] = {1} ", names[i], values[i]);
if (constraints.Count > 0)
{
List<string> terms = new List<string>();
for (int j = 0; j < constraints.Count; j++)
{
terms.Add(" [" + constraints[j].Key + "] = @" + constraints[j].Key);
}
string where = String.Join(" AND ", terms.ToArray());
query.AppendFormat(" WHERE {0} ", where);
}
cmd.Connection = conn;
cmd.CommandText = query.ToString();
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
//m_log.WarnFormat("[MSSQLGenericTable]: Updating {0}", m_Realm);
return true;
}
else
{
// assume record has not yet been inserted
query = new StringBuilder();
query.AppendFormat("INSERT INTO {0} ([", m_Realm);
query.Append(String.Join("],[", names.ToArray()));
query.Append("]) values (" + String.Join(",", values.ToArray()) + ")");
cmd.Connection = conn;
cmd.CommandText = query.ToString();
//m_log.WarnFormat("[MSSQLGenericTable]: Inserting into {0}", m_Realm);
if (conn.State != ConnectionState.Open)
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
return true;
}
return false;
}
}
public virtual bool Delete(string field, string val)
{
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
string deleteCommand = String.Format("DELETE FROM {0} WHERE [{1}] = @{1}", m_Realm, field);
cmd.CommandText = deleteCommand;
cmd.Parameters.Add(m_database.CreateParameter(field, val));
cmd.Connection = conn;
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
//m_log.Warn("[MSSQLGenericTable]: " + deleteCommand);
return true;
}
return false;
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
function StartLevel( %mission )
{
if( %mission $= "" )
{
%id = CL_levelList.getSelectedId();
%mission = getField(CL_levelList.getRowTextById(%id), 1);
}
if ($pref::HostMultiPlayer)
%serverType = "MultiPlayer";
else
%serverType = "SinglePlayer";
// Show the loading screen immediately.
if ( isObject( LoadingGui ) )
{
Canvas.setContent("LoadingGui");
LoadingProgress.setValue(1);
LoadingProgressTxt.setValue("LOADING MISSION FILE");
Canvas.repaint();
}
createAndConnectToLocalServer( %serverType, %mission );
}
//----------------------------------------
function ChooseLevelDlg::onWake( %this )
{
CL_levelList.clear();
ChooseLevelWindow->SmallPreviews.clear();
%i = 0;
for(%file = findFirstFile($Server::MissionFileSpec); %file !$= ""; %file = findNextFile($Server::MissionFileSpec))
{
// Skip our new level/mission if we arent choosing a level
// to launch in the editor.
if ( !%this.launchInEditor )
{
if (strstr(%file, "newMission.mis") > -1)
continue;
if (strstr(%file, "newLevel.mis") > -1)
continue;
}
%this.addMissionFile( %file );
}
// Also add the new level mission as defined in the world editor settings
// if we are choosing a level to launch in the editor.
if ( %this.launchInEditor )
{
%file = EditorSettings.value( "WorldEditor/newLevelFile" );
if ( %file !$= "" )
%this.addMissionFile( %file );
}
// Sort our list
CL_levelList.sort(0);
// Set the first row as the selected row
CL_levelList.setSelectedRow(0);
for (%i = 0; %i < CL_levelList.rowCount(); %i++)
{
%preview = new GuiBitmapButtonCtrl() {
internalName = "SmallPreview" @ %i;
Extent = "108 81";
bitmap = "core/art/gui/images/no-preview";
command = "ChooseLevelWindow.previewSelected(ChooseLevelWindow->SmallPreviews->SmallPreview" @ %i @ ");";
};
ChooseLevelWindow->SmallPreviews.add(%preview);
// Set this small preview visible
if (%i >= 5)
%preview.setVisible(false);
// Set the level index
%preview.levelIndex = %i;
// Get the name
%name = getField(CL_levelList.getRowText(%i), 0);
%preview.levelName = %name;
%file = getField(CL_levelList.getRowText(%i), 1);
// Find the preview image
%levelPreview = filePath(%file) @ "/" @ fileBase(%file) @ "_preview";
// Test against all of the different image formats
// This should probably be moved into an engine function
if (isFile(%levelPreview @ ".png") ||
isFile(%levelPreview @ ".jpg") ||
isFile(%levelPreview @ ".bmp") ||
isFile(%levelPreview @ ".gif") ||
isFile(%levelPreview @ ".jng") ||
isFile(%levelPreview @ ".mng") ||
isFile(%levelPreview @ ".tga"))
{
%preview.setBitmap(%levelPreview);
}
// Get the description
%desc = getField(CL_levelList.getRowText(%i), 2);
%preview.levelDesc = %desc;
}
ChooseLevelWindow->SmallPreviews.firstVisible = -1;
ChooseLevelWindow->SmallPreviews.lastVisible = -1;
if (ChooseLevelWindow->SmallPreviews.getCount() > 0)
{
ChooseLevelWindow->SmallPreviews.firstVisible = 0;
if (ChooseLevelWindow->SmallPreviews.getCount() < 6)
ChooseLevelWindow->SmallPreviews.lastVisible = ChooseLevelWindow->SmallPreviews.getCount() - 1;
else
ChooseLevelWindow->SmallPreviews.lastVisible = 4;
}
if (ChooseLevelWindow->SmallPreviews.getCount() > 0)
ChooseLevelWindow.previewSelected(ChooseLevelWindow->SmallPreviews.getObject(0));
// If we have 5 or less previews then hide our next/previous buttons
// and resize to fill their positions
if (ChooseLevelWindow->SmallPreviews.getCount() < 6)
{
ChooseLevelWindow->PreviousSmallPreviews.setVisible(false);
ChooseLevelWindow->NextSmallPreviews.setVisible(false);
%previewPos = ChooseLevelWindow->SmallPreviews.getPosition();
%previousPos = ChooseLevelWindow->PreviousSmallPreviews.getPosition();
%previewPosX = getWord(%previousPos, 0);
%previewPosY = getWord(%previewPos, 1);
ChooseLevelWindow->SmallPreviews.setPosition(%previewPosX, %previewPosY);
ChooseLevelWindow->SmallPreviews.colSpacing = 10;//((getWord(NextSmallPreviews.getPosition(), 0)+11)-getWord(PreviousSmallPreviews.getPosition(), 0))/4;
ChooseLevelWindow->SmallPreviews.refresh();
}
if (ChooseLevelWindow->SmallPreviews.getCount() <= 1)
{
// Hide the small previews
ChooseLevelWindow->SmallPreviews.setVisible(false);
// Shrink the ChooseLevelWindow so that we don't have a large blank space
%extentX = getWord(ChooseLevelWindow.getExtent(), 0);
%extentY = getWord(ChooseLevelWindow->SmallPreviews.getPosition(), 1);
ChooseLevelWIndow.setExtent(%extentX, %extentY);
}
else
{
// Make sure the small previews are visible
ChooseLevelWindow->SmallPreviews.setVisible(true);
%extentX = getWord(ChooseLevelWindow.getExtent(), 0);
%extentY = getWord(ChooseLevelWindow->SmallPreviews.getPosition(), 1);
%extentY = %extentY + getWord(ChooseLevelWindow->SmallPreviews.getExtent(), 1);
%extentY = %extentY + 9;
ChooseLevelWIndow.setExtent(%extentX, %extentY);
}
}
function ChooseLevelDlg::addMissionFile( %this, %file )
{
%levelName = fileBase(%file);
%levelDesc = "A Torque level";
%LevelInfoObject = getLevelInfo(%file);
if (%LevelInfoObject != 0)
{
if(%LevelInfoObject.levelName !$= "")
%levelName = %LevelInfoObject.levelName;
else if(%LevelInfoObject.name !$= "")
%levelName = %LevelInfoObject.name;
if (%LevelInfoObject.desc0 !$= "")
%levelDesc = %LevelInfoObject.desc0;
%LevelInfoObject.delete();
}
CL_levelList.addRow( CL_levelList.rowCount(), %levelName TAB %file TAB %levelDesc );
}
function ChooseLevelDlg::onSleep( %this )
{
// This is set from the outside, only stays true for a single wake/sleep
// cycle.
%this.launchInEditor = false;
}
function ChooseLevelWindow::previewSelected(%this, %preview)
{
// Set the selected level
if (isObject(%preview) && %preview.levelIndex !$= "")
CL_levelList.setSelectedRow(%preview.levelIndex);
else
CL_levelList.setSelectedRow(-1);
// Set the large preview image
if (isObject(%preview) && %preview.bitmap !$= "")
%this->CurrentPreview.setBitmap(%preview.bitmap);
else
%this->CurrentPreview.setBitmap("core/art/gui/images/no-preview");
// Set the current level name
if (isObject(%preview) && %preview.levelName !$= "")
%this->LevelName.setText(%preview.levelName);
else
%this->LevelName.setText("Level");
// Set the current level description
if (isObject(%preview) && %preview.levelDesc !$= "")
%this->LevelDescription.setText(%preview.levelDesc);
else
%this->LevelDescription.setText("A Torque Level");
}
function ChooseLevelWindow::previousPreviews(%this)
{
%prevHiddenIdx = %this->SmallPreviews.firstVisible - 1;
if (%prevHiddenIdx < 0)
return;
%lastVisibleIdx = %this->SmallPreviews.lastVisible;
if (%lastVisibleIdx >= %this->SmallPreviews.getCount())
return;
%prevHiddenObj = %this->SmallPreviews.getObject(%prevHiddenIdx);
%lastVisibleObj = %this->SmallPreviews.getObject(%lastVisibleIdx);
if (isObject(%prevHiddenObj) && isObject(%lastVisibleObj))
{
%this->SmallPreviews.firstVisible--;
%this->SmallPreviews.lastVisible--;
%prevHiddenObj.setVisible(true);
%lastVisibleObj.setVisible(false);
}
}
function ChooseLevelWindow::nextPreviews(%this)
{
%firstVisibleIdx = %this->SmallPreviews.firstVisible;
if (%firstVisibleIdx < 0)
return;
%firstHiddenIdx = %this->SmallPreviews.lastVisible + 1;
if (%firstHiddenIdx >= %this->SmallPreviews.getCount())
return;
%firstVisibleObj = %this->SmallPreviews.getObject(%firstVisibleIdx);
%firstHiddenObj = %this->SmallPreviews.getObject(%firstHiddenIdx);
if (isObject(%firstVisibleObj) && isObject(%firstHiddenObj))
{
%this->SmallPreviews.firstVisible++;
%this->SmallPreviews.lastVisible++;
%firstVisibleObj.setVisible(false);
%firstHiddenObj.setVisible(true);
}
}
//----------------------------------------
function getLevelInfo( %missionFile )
{
%file = new FileObject();
%LevelInfoObject = "";
if ( %file.openForRead( %missionFile ) ) {
%inInfoBlock = false;
while ( !%file.isEOF() ) {
%line = %file.readLine();
%line = trim( %line );
if( %line $= "new ScriptObject(LevelInfo) {" )
%inInfoBlock = true;
else if( %line $= "new LevelInfo(theLevelInfo) {" )
%inInfoBlock = true;
else if( %inInfoBlock && %line $= "};" ) {
%inInfoBlock = false;
%LevelInfoObject = %LevelInfoObject @ %line;
break;
}
if( %inInfoBlock )
%LevelInfoObject = %LevelInfoObject @ %line @ " ";
}
%file.close();
}
%file.delete();
if( %LevelInfoObject !$= "" )
{
%LevelInfoObject = "%LevelInfoObject = " @ %LevelInfoObject;
eval( %LevelInfoObject );
return %LevelInfoObject;
}
// Didn't find our LevelInfo
return 0;
}
| |
// 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.Text;
using System.Collections.Generic;
using System.Text.JsonLab.Tests.Resources;
using Xunit;
namespace System.Text.JsonLab.Tests
{
public class JsonParserTests
{
[Fact]
public void ParseBasicJson()
{
var json = ReadJson(TestJson.ParseJson);
var person = json[0];
var age = (double)person[Encoding.UTF8.GetBytes("age")];
var first = (string)person[Encoding.UTF8.GetBytes("first")];
var last = (string)person[Encoding.UTF8.GetBytes("last")];
var phoneNums = person[Encoding.UTF8.GetBytes("phoneNumbers")];
var phoneNum1 = (string)phoneNums[0];
var phoneNum2 = (string)phoneNums[1];
var address = person[Encoding.UTF8.GetBytes("address")];
var street = (string)address[Encoding.UTF8.GetBytes("street")];
var city = (string)address[Encoding.UTF8.GetBytes("city")];
var zipCode = (double)address[Encoding.UTF8.GetBytes("zip")];
// Exceptional use case
//var a = json[1]; // IndexOutOfRangeException
//var b = json["age"]; // NullReferenceException
//var c = person[0]; // NullReferenceException
//var d = address["cit"]; // KeyNotFoundException
//var e = address[0]; // NullReferenceException
//var f = (double)address["city"]; // InvalidCastException
//var g = (bool)address["city"]; // InvalidCastException
//var h = (string)address["zip"]; // InvalidCastException
//var i = (string)person["phoneNumbers"]; // NullReferenceException
//var j = (string)person; // NullReferenceException
Assert.Equal(age, 30);
Assert.Equal(first, "John");
Assert.Equal(last, "Smith");
Assert.Equal(phoneNum1, "425-000-1212");
Assert.Equal(phoneNum2, "425-000-1213");
Assert.Equal(street, "1 Microsoft Way");
Assert.Equal(city, "Redmond");
Assert.Equal(zipCode, 98052);
}
[Fact]
public void ReadBasicJson()
{
var testJson = CreateJson();
Assert.Equal(testJson.ToString(), TestJson.ExpectedCreateJson);
var readJson = ReadJson(TestJson.BasicJson);
var json = readJson.ToString();
Assert.Equal(json, TestJson.ExpectedBasicJson);
}
[Fact]
public void ReadBasicJsonWithLongInt()
{
var readJson = ReadJson(TestJson.BasicJsonWithLargeNum);
var json = readJson.ToString();
Assert.Equal(json, TestJson.ExpectedBasicJsonWithLargeNum);
}
[Fact]
public void ReadFullJsonSchema()
{
var readJson = ReadJson(TestJson.FullJsonSchema1);
var json = readJson.ToString();
Assert.Equal(json, TestJson.ExpectedFullJsonSchema1);
}
[Fact]
public void ReadFullJsonSchemaAndGetValue()
{
var readJson = ReadJson(TestJson.FullJsonSchema2);
var json = readJson.ToString();
Assert.Equal(json, TestJson.ExpectedFullJsonSchema2);
Assert.Equal(readJson.GetValueFromPropertyName("long")[0].NumberValue, 9.2233720368547758E+18);
var emptyObject = readJson.GetValueFromPropertyName("emptyObject");
Assert.Equal(emptyObject[0].ObjectValue.Pairs.Count, 0);
var arrayString = readJson.GetValueFromPropertyName("arrayString");
Assert.Equal(arrayString[0].ArrayValue.Values.Count, 2);
Assert.Equal(readJson.GetValueFromPropertyName("firstName").Count, 4);
Assert.Equal(readJson.GetValueFromPropertyName("propertyDNE").Count, 0);
}
[Fact(Skip = "This test is injecting invalid characters into the stream and needs to be re-visited")]
public void ReadJsonSpecialStrings()
{
var readJson = ReadJson(TestJson.JsonWithSpecialStrings);
var json = readJson.ToString();
Assert.Equal(json, TestJson.ExpectedJsonWithSpecialStrings);
}
[Fact(Skip = "The current primitive parsers do not support E-notation for numbers.")]
public void ReadJsonSpecialNumbers()
{
var readJson = ReadJson(TestJson.JsonWithSpecialNumFormat);
var json = readJson.ToString();
Assert.Equal(json, TestJson.ExpectedJsonWithSpecialNumFormat);
}
[Fact]
public void ReadProjectLockJson()
{
var readJson = ReadJson(TestJson.ProjectLockJson);
var json = readJson.ToString();
Assert.Equal(json, TestJson.ExpectedProjectLockJson);
}
[Fact]
public void ReadHeavyNestedJson()
{
var readJson = ReadJson(TestJson.HeavyNestedJson);
var json = readJson.ToString();
Assert.Equal(json, TestJson.ExpectedHeavyNestedJson);
}
[Fact]
public void ReadHeavyNestedJsonWithArray()
{
var readJson = ReadJson(TestJson.HeavyNestedJsonWithArray);
var json = readJson.ToString();
Assert.Equal(json, TestJson.ExpectedHeavyNestedJsonWithArray);
}
[Fact]
public void ReadLargeJson()
{
var readJson = ReadJson(TestJson.LargeJson);
var json = readJson.ToString();
Assert.Equal(json, TestJson.ExpectedLargeJson);
}
private static TestDom CreateJson()
{
var valueAge = new Value
{
Type = Value.ValueType.Number,
NumberValue = 30
};
var pairAge = new Pair
{
Name = Encoding.UTF8.GetBytes("age"),
Value = valueAge
};
var valueFirst = new Value
{
Type = Value.ValueType.String,
StringValue = Encoding.UTF8.GetBytes("John")
};
var pairFirst = new Pair
{
Name = Encoding.UTF8.GetBytes("first"),
Value = valueFirst
};
var valueLast = new Value
{
Type = Value.ValueType.String,
StringValue = Encoding.UTF8.GetBytes("Smith")
};
var pairLast = new Pair
{
Name = Encoding.UTF8.GetBytes("last"),
Value = valueLast
};
var value1 = new Value
{
Type = Value.ValueType.String,
StringValue = Encoding.UTF8.GetBytes("425-000-1212")
};
var value2 = new Value
{
Type = Value.ValueType.String,
StringValue = Encoding.UTF8.GetBytes("425-000-1213")
};
var values = new List<Value> { value1, value2 };
var arrInner = new Array { Values = values };
var valuePhone = new Value
{
Type = Value.ValueType.Array,
ArrayValue = arrInner
};
var pairPhone = new Pair
{
Name = Encoding.UTF8.GetBytes("phoneNumbers"),
Value = valuePhone
};
var valueStreet = new Value
{
Type = Value.ValueType.String,
StringValue = Encoding.UTF8.GetBytes("1 Microsoft Way")
};
var pairStreet = new Pair
{
Name = Encoding.UTF8.GetBytes("street"),
Value = valueStreet
};
var valueCity = new Value
{
Type = Value.ValueType.String,
StringValue = Encoding.UTF8.GetBytes("Redmond")
};
var pairCity = new Pair
{
Name = Encoding.UTF8.GetBytes("city"),
Value = valueCity
};
var valueZip = new Value
{
Type = Value.ValueType.Number,
NumberValue = 98052
};
var pairZip = new Pair
{
Name = Encoding.UTF8.GetBytes("zip"),
Value = valueZip
};
var pairsInner = new List<Pair> { pairStreet, pairCity, pairZip };
var objInner = new Object { Pairs = pairsInner };
var valueAddress = new Value
{
Type = Value.ValueType.Object,
ObjectValue = objInner
};
var pairAddress = new Pair
{
Name = Encoding.UTF8.GetBytes("address"),
Value = valueAddress
};
var pairs = new List<Pair> { pairAge, pairFirst, pairLast, pairPhone, pairAddress };
var obj = new Object { Pairs = pairs };
var json = new TestDom { Object = obj };
return json;
}
private static TestDom ReadJson(string jsonString)
{
var json = new TestDom();
if (string.IsNullOrEmpty(jsonString))
{
return json;
}
var jsonReader = new Utf8JsonReader(Encoding.UTF8.GetBytes(jsonString));
jsonReader.Read();
switch (jsonReader.TokenType)
{
case JsonTokenType.StartArray:
json.Array = ReadArray(ref jsonReader);
break;
case JsonTokenType.StartObject:
json.Object = ReadObject(ref jsonReader);
break;
default:
Assert.True(false, "The test JSON does not start with an array or object token");
break;
}
return json;
}
private static Value GetValue(ref Utf8JsonReader jsonReader)
{
var value = new Value { Type = MapValueType(jsonReader.ValueType) };
switch (value.Type)
{
case Value.ValueType.String:
value.StringValue = ReadUtf8String(ref jsonReader);
break;
case Value.ValueType.Number:
CustomParser.TryParseDecimal(jsonReader.Value, out decimal num, out int consumed);
value.NumberValue = Convert.ToDouble(num);
break;
case Value.ValueType.True:
break;
case Value.ValueType.False:
break;
case Value.ValueType.Null:
break;
case Value.ValueType.Object:
value.ObjectValue = ReadObject(ref jsonReader);
break;
case Value.ValueType.Array:
value.ArrayValue = ReadArray(ref jsonReader);
break;
default:
throw new ArgumentOutOfRangeException();
}
return value;
}
private static Value.ValueType MapValueType(JsonValueType type)
{
switch (type)
{
case JsonValueType.False:
return Value.ValueType.False;
case JsonValueType.True:
return Value.ValueType.True;
case JsonValueType.Null:
return Value.ValueType.Null;
case JsonValueType.Number:
return Value.ValueType.Number;
case JsonValueType.String:
return Value.ValueType.String;
case JsonValueType.Array:
return Value.ValueType.Array;
case JsonValueType.Object:
return Value.ValueType.Object;
default:
throw new ArgumentException();
}
}
private static Object ReadObject(ref Utf8JsonReader jsonReader)
{
// NOTE: We should be sitting on a StartObject token.
Assert.Equal(JsonTokenType.StartObject, jsonReader.TokenType);
var jsonObject = new Object();
List<Pair> jsonPairs = new List<Pair>();
while (jsonReader.Read())
{
switch (jsonReader.TokenType)
{
case JsonTokenType.EndObject:
jsonObject.Pairs = jsonPairs;
return jsonObject;
case JsonTokenType.PropertyName:
ReadOnlyMemory<byte> name = ReadUtf8String(ref jsonReader);
jsonReader.Read(); // Move to value token
var pair = new Pair
{
Name = name,
Value = GetValue(ref jsonReader)
};
if (jsonPairs != null) jsonPairs.Add(pair);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
throw new FormatException("Json object was started but never ended.");
}
private static Array ReadArray(ref Utf8JsonReader jsonReader)
{
// NOTE: We should be sitting on a StartArray token.
Assert.Equal(JsonTokenType.StartArray, jsonReader.TokenType);
Array jsonArray = new Array();
List<Value> jsonValues = new List<Value>();
while (jsonReader.Read())
{
switch (jsonReader.TokenType)
{
case JsonTokenType.EndArray:
jsonArray.Values = jsonValues;
return jsonArray;
case JsonTokenType.StartArray:
case JsonTokenType.StartObject:
case JsonTokenType.Value:
jsonValues.Add(GetValue(ref jsonReader));
break;
default:
throw new ArgumentOutOfRangeException();
}
}
throw new FormatException("Json array was started but never ended.");
}
private static byte[] ReadUtf8String(ref Utf8JsonReader jsonReader)
{
return jsonReader.Value.ToArray();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.IO;
using System.Collections;
using System.Text;
using System.Diagnostics;
using System.Globalization;
namespace System.Xml
{
// Represents a single node in the document.
[DebuggerDisplay("{debuggerDisplayProxy}")]
public abstract class XmlNode : IEnumerable
{
internal XmlNode parentNode; //this pointer is reused to save the userdata information, need to prevent internal user access the pointer directly.
internal XmlNode()
{
}
internal XmlNode(XmlDocument doc)
{
if (doc == null)
throw new ArgumentException(SR.Xdom_Node_Null_Doc);
this.parentNode = doc;
}
// Gets the name of the node.
public abstract string Name
{
get;
}
// Gets or sets the value of the node.
public virtual string Value
{
get { return null; }
set { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, SR.Xdom_Node_SetVal, NodeType.ToString())); }
}
// Gets the type of the current node.
public abstract XmlNodeType NodeType
{
get;
}
// Gets the parent of this node (for nodes that can have parents).
public virtual XmlNode ParentNode
{
get
{
Debug.Assert(parentNode != null);
if (parentNode.NodeType != XmlNodeType.Document)
{
return parentNode;
}
// Linear lookup through the children of the document
XmlLinkedNode firstChild = parentNode.FirstChild as XmlLinkedNode;
if (firstChild != null)
{
XmlLinkedNode node = firstChild;
do
{
if (node == this)
{
return parentNode;
}
node = node.next;
}
while (node != null
&& node != firstChild);
}
return null;
}
}
// Gets all children of this node.
public virtual XmlNodeList ChildNodes
{
get { return new XmlChildNodes(this); }
}
// Gets the node immediately preceding this node.
public virtual XmlNode PreviousSibling
{
get { return null; }
}
// Gets the node immediately following this node.
public virtual XmlNode NextSibling
{
get { return null; }
}
// Gets a XmlAttributeCollection containing the attributes
// of this node.
public virtual XmlAttributeCollection Attributes
{
get { return null; }
}
// Gets the XmlDocument that contains this node.
public virtual XmlDocument OwnerDocument
{
get
{
Debug.Assert(parentNode != null);
if (parentNode.NodeType == XmlNodeType.Document)
return (XmlDocument)parentNode;
return parentNode.OwnerDocument;
}
}
// Gets the first child of this node.
public virtual XmlNode FirstChild
{
get
{
XmlLinkedNode linkedNode = LastNode;
if (linkedNode != null)
return linkedNode.next;
return null;
}
}
// Gets the last child of this node.
public virtual XmlNode LastChild
{
get { return LastNode; }
}
internal virtual bool IsContainer
{
get { return false; }
}
internal virtual XmlLinkedNode LastNode
{
get { return null; }
set { }
}
internal bool AncestorNode(XmlNode node)
{
XmlNode n = this.ParentNode;
while (n != null && n != this)
{
if (n == node)
return true;
n = n.ParentNode;
}
return false;
}
//trace to the top to find out its parent node.
internal bool IsConnected()
{
XmlNode parent = ParentNode;
while (parent != null && !(parent.NodeType == XmlNodeType.Document))
parent = parent.ParentNode;
return parent != null;
}
// Inserts the specified node immediately before the specified reference node.
public virtual XmlNode InsertBefore(XmlNode newChild, XmlNode refChild)
{
if (this == newChild || AncestorNode(newChild))
throw new ArgumentException(SR.Xdom_Node_Insert_Child);
if (refChild == null)
return AppendChild(newChild);
if (!IsContainer)
throw new InvalidOperationException(SR.Xdom_Node_Insert_Contain);
if (refChild.ParentNode != this)
throw new ArgumentException(SR.Xdom_Node_Insert_Path);
if (newChild == refChild)
return newChild;
XmlDocument childDoc = newChild.OwnerDocument;
XmlDocument thisDoc = OwnerDocument;
if (childDoc != null && childDoc != thisDoc && childDoc != this)
throw new ArgumentException(SR.Xdom_Node_Insert_Context);
if (!CanInsertBefore(newChild, refChild))
throw new InvalidOperationException(SR.Xdom_Node_Insert_Location);
if (newChild.ParentNode != null)
newChild.ParentNode.RemoveChild(newChild);
// special case for doc-fragment.
if (newChild.NodeType == XmlNodeType.DocumentFragment)
{
XmlNode first = newChild.FirstChild;
XmlNode node = first;
if (node != null)
{
newChild.RemoveChild(node);
InsertBefore(node, refChild);
// insert the rest of the children after this one.
InsertAfter(newChild, node);
}
return first;
}
if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType))
throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict);
XmlLinkedNode newNode = (XmlLinkedNode)newChild;
XmlLinkedNode refNode = (XmlLinkedNode)refChild;
string newChildValue = newChild.Value;
XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert);
if (args != null)
BeforeEvent(args);
if (refNode == FirstChild)
{
newNode.next = refNode;
LastNode.next = newNode;
newNode.SetParent(this);
if (newNode.IsText)
{
if (refNode.IsText)
{
NestTextNodes(newNode, refNode);
}
}
}
else
{
XmlLinkedNode prevNode = (XmlLinkedNode)refNode.PreviousSibling;
newNode.next = refNode;
prevNode.next = newNode;
newNode.SetParent(this);
if (prevNode.IsText)
{
if (newNode.IsText)
{
NestTextNodes(prevNode, newNode);
if (refNode.IsText)
{
NestTextNodes(newNode, refNode);
}
}
else
{
if (refNode.IsText)
{
UnnestTextNodes(prevNode, refNode);
}
}
}
else
{
if (newNode.IsText)
{
if (refNode.IsText)
{
NestTextNodes(newNode, refNode);
}
}
}
}
if (args != null)
AfterEvent(args);
return newNode;
}
// Inserts the specified node immediately after the specified reference node.
public virtual XmlNode InsertAfter(XmlNode newChild, XmlNode refChild)
{
if (this == newChild || AncestorNode(newChild))
throw new ArgumentException(SR.Xdom_Node_Insert_Child);
if (refChild == null)
return PrependChild(newChild);
if (!IsContainer)
throw new InvalidOperationException(SR.Xdom_Node_Insert_Contain);
if (refChild.ParentNode != this)
throw new ArgumentException(SR.Xdom_Node_Insert_Path);
if (newChild == refChild)
return newChild;
XmlDocument childDoc = newChild.OwnerDocument;
XmlDocument thisDoc = OwnerDocument;
if (childDoc != null && childDoc != thisDoc && childDoc != this)
throw new ArgumentException(SR.Xdom_Node_Insert_Context);
if (!CanInsertAfter(newChild, refChild))
throw new InvalidOperationException(SR.Xdom_Node_Insert_Location);
if (newChild.ParentNode != null)
newChild.ParentNode.RemoveChild(newChild);
// special case for doc-fragment.
if (newChild.NodeType == XmlNodeType.DocumentFragment)
{
XmlNode last = refChild;
XmlNode first = newChild.FirstChild;
XmlNode node = first;
while (node != null)
{
XmlNode next = node.NextSibling;
newChild.RemoveChild(node);
InsertAfter(node, last);
last = node;
node = next;
}
return first;
}
if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType))
throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict);
XmlLinkedNode newNode = (XmlLinkedNode)newChild;
XmlLinkedNode refNode = (XmlLinkedNode)refChild;
string newChildValue = newChild.Value;
XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert);
if (args != null)
BeforeEvent(args);
if (refNode == LastNode)
{
newNode.next = refNode.next;
refNode.next = newNode;
LastNode = newNode;
newNode.SetParent(this);
if (refNode.IsText)
{
if (newNode.IsText)
{
NestTextNodes(refNode, newNode);
}
}
}
else
{
XmlLinkedNode nextNode = refNode.next;
newNode.next = nextNode;
refNode.next = newNode;
newNode.SetParent(this);
if (refNode.IsText)
{
if (newNode.IsText)
{
NestTextNodes(refNode, newNode);
if (nextNode.IsText)
{
NestTextNodes(newNode, nextNode);
}
}
else
{
if (nextNode.IsText)
{
UnnestTextNodes(refNode, nextNode);
}
}
}
else
{
if (newNode.IsText)
{
if (nextNode.IsText)
{
NestTextNodes(newNode, nextNode);
}
}
}
}
if (args != null)
AfterEvent(args);
return newNode;
}
// Replaces the child node oldChild with newChild node.
public virtual XmlNode ReplaceChild(XmlNode newChild, XmlNode oldChild)
{
XmlNode nextNode = oldChild.NextSibling;
RemoveChild(oldChild);
XmlNode node = InsertBefore(newChild, nextNode);
return oldChild;
}
// Removes specified child node.
public virtual XmlNode RemoveChild(XmlNode oldChild)
{
if (!IsContainer)
throw new InvalidOperationException(SR.Xdom_Node_Remove_Contain);
if (oldChild.ParentNode != this)
throw new ArgumentException(SR.Xdom_Node_Remove_Child);
XmlLinkedNode oldNode = (XmlLinkedNode)oldChild;
string oldNodeValue = oldNode.Value;
XmlNodeChangedEventArgs args = GetEventArgs(oldNode, this, null, oldNodeValue, oldNodeValue, XmlNodeChangedAction.Remove);
if (args != null)
BeforeEvent(args);
XmlLinkedNode lastNode = LastNode;
if (oldNode == FirstChild)
{
if (oldNode == lastNode)
{
LastNode = null;
oldNode.next = null;
oldNode.SetParent(null);
}
else
{
XmlLinkedNode nextNode = oldNode.next;
if (nextNode.IsText)
{
if (oldNode.IsText)
{
UnnestTextNodes(oldNode, nextNode);
}
}
lastNode.next = nextNode;
oldNode.next = null;
oldNode.SetParent(null);
}
}
else
{
if (oldNode == lastNode)
{
XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling;
prevNode.next = oldNode.next;
LastNode = prevNode;
oldNode.next = null;
oldNode.SetParent(null);
}
else
{
XmlLinkedNode prevNode = (XmlLinkedNode)oldNode.PreviousSibling;
XmlLinkedNode nextNode = oldNode.next;
if (nextNode.IsText)
{
if (prevNode.IsText)
{
NestTextNodes(prevNode, nextNode);
}
else
{
if (oldNode.IsText)
{
UnnestTextNodes(oldNode, nextNode);
}
}
}
prevNode.next = nextNode;
oldNode.next = null;
oldNode.SetParent(null);
}
}
if (args != null)
AfterEvent(args);
return oldChild;
}
// Adds the specified node to the beginning of the list of children of this node.
public virtual XmlNode PrependChild(XmlNode newChild)
{
return InsertBefore(newChild, FirstChild);
}
// Adds the specified node to the end of the list of children of this node.
public virtual XmlNode AppendChild(XmlNode newChild)
{
XmlDocument thisDoc = OwnerDocument;
if (thisDoc == null)
{
thisDoc = this as XmlDocument;
}
if (!IsContainer)
throw new InvalidOperationException(SR.Xdom_Node_Insert_Contain);
if (this == newChild || AncestorNode(newChild))
throw new ArgumentException(SR.Xdom_Node_Insert_Child);
if (newChild.ParentNode != null)
newChild.ParentNode.RemoveChild(newChild);
XmlDocument childDoc = newChild.OwnerDocument;
if (childDoc != null && childDoc != thisDoc && childDoc != this)
throw new ArgumentException(SR.Xdom_Node_Insert_Context);
// special case for doc-fragment.
if (newChild.NodeType == XmlNodeType.DocumentFragment)
{
XmlNode first = newChild.FirstChild;
XmlNode node = first;
while (node != null)
{
XmlNode next = node.NextSibling;
newChild.RemoveChild(node);
AppendChild(node);
node = next;
}
return first;
}
if (!(newChild is XmlLinkedNode) || !IsValidChildType(newChild.NodeType))
throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict);
if (!CanInsertAfter(newChild, LastChild))
throw new InvalidOperationException(SR.Xdom_Node_Insert_Location);
string newChildValue = newChild.Value;
XmlNodeChangedEventArgs args = GetEventArgs(newChild, newChild.ParentNode, this, newChildValue, newChildValue, XmlNodeChangedAction.Insert);
if (args != null)
BeforeEvent(args);
XmlLinkedNode refNode = LastNode;
XmlLinkedNode newNode = (XmlLinkedNode)newChild;
if (refNode == null)
{
newNode.next = newNode;
LastNode = newNode;
newNode.SetParent(this);
}
else
{
newNode.next = refNode.next;
refNode.next = newNode;
LastNode = newNode;
newNode.SetParent(this);
if (refNode.IsText)
{
if (newNode.IsText)
{
NestTextNodes(refNode, newNode);
}
}
}
if (args != null)
AfterEvent(args);
return newNode;
}
//the function is provided only at Load time to speed up Load process
internal virtual XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc)
{
XmlNodeChangedEventArgs args = doc.GetInsertEventArgsForLoad(newChild, this);
if (args != null)
doc.BeforeEvent(args);
XmlLinkedNode refNode = LastNode;
XmlLinkedNode newNode = (XmlLinkedNode)newChild;
if (refNode == null)
{
newNode.next = newNode;
LastNode = newNode;
newNode.SetParentForLoad(this);
}
else
{
newNode.next = refNode.next;
refNode.next = newNode;
LastNode = newNode;
if (refNode.IsText
&& newNode.IsText)
{
NestTextNodes(refNode, newNode);
}
else
{
newNode.SetParentForLoad(this);
}
}
if (args != null)
doc.AfterEvent(args);
return newNode;
}
internal virtual bool IsValidChildType(XmlNodeType type)
{
return false;
}
internal virtual bool CanInsertBefore(XmlNode newChild, XmlNode refChild)
{
return true;
}
internal virtual bool CanInsertAfter(XmlNode newChild, XmlNode refChild)
{
return true;
}
// Gets a value indicating whether this node has any child nodes.
public virtual bool HasChildNodes
{
get { return LastNode != null; }
}
// Creates a duplicate of this node.
public abstract XmlNode CloneNode(bool deep);
internal virtual void CopyChildren(XmlDocument doc, XmlNode container, bool deep)
{
for (XmlNode child = container.FirstChild; child != null; child = child.NextSibling)
{
AppendChildForLoad(child.CloneNode(deep), doc);
}
}
// DOM Level 2
// Puts all XmlText nodes in the full depth of the sub-tree
// underneath this XmlNode into a "normal" form where only
// markup (e.g., tags, comments, processing instructions, CDATA sections,
// and entity references) separates XmlText nodes, that is, there
// are no adjacent XmlText nodes.
public virtual void Normalize()
{
XmlNode firstChildTextLikeNode = null;
StringBuilder sb = StringBuilderCache.Acquire();
for (XmlNode crtChild = this.FirstChild; crtChild != null;)
{
XmlNode nextChild = crtChild.NextSibling;
switch (crtChild.NodeType)
{
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
{
sb.Append(crtChild.Value);
XmlNode winner = NormalizeWinner(firstChildTextLikeNode, crtChild);
if (winner == firstChildTextLikeNode)
{
this.RemoveChild(crtChild);
}
else
{
if (firstChildTextLikeNode != null)
this.RemoveChild(firstChildTextLikeNode);
firstChildTextLikeNode = crtChild;
}
break;
}
case XmlNodeType.Element:
{
crtChild.Normalize();
goto default;
}
default:
{
if (firstChildTextLikeNode != null)
{
firstChildTextLikeNode.Value = sb.ToString();
firstChildTextLikeNode = null;
}
sb.Remove(0, sb.Length);
break;
}
}
crtChild = nextChild;
}
if (firstChildTextLikeNode != null && sb.Length > 0)
firstChildTextLikeNode.Value = sb.ToString();
StringBuilderCache.Release(sb);
}
private XmlNode NormalizeWinner(XmlNode firstNode, XmlNode secondNode)
{
//first node has the priority
if (firstNode == null)
return secondNode;
Debug.Assert(firstNode.NodeType == XmlNodeType.Text
|| firstNode.NodeType == XmlNodeType.SignificantWhitespace
|| firstNode.NodeType == XmlNodeType.Whitespace
|| secondNode.NodeType == XmlNodeType.Text
|| secondNode.NodeType == XmlNodeType.SignificantWhitespace
|| secondNode.NodeType == XmlNodeType.Whitespace);
if (firstNode.NodeType == XmlNodeType.Text)
return firstNode;
if (secondNode.NodeType == XmlNodeType.Text)
return secondNode;
if (firstNode.NodeType == XmlNodeType.SignificantWhitespace)
return firstNode;
if (secondNode.NodeType == XmlNodeType.SignificantWhitespace)
return secondNode;
if (firstNode.NodeType == XmlNodeType.Whitespace)
return firstNode;
if (secondNode.NodeType == XmlNodeType.Whitespace)
return secondNode;
Debug.Assert(true, "shouldn't have fall through here.");
return null;
}
// Test if the DOM implementation implements a specific feature.
public virtual bool Supports(string feature, string version)
{
if (String.Equals("XML", feature, StringComparison.OrdinalIgnoreCase))
{
if (version == null || version == "1.0" || version == "2.0")
return true;
}
return false;
}
// Gets the namespace URI of this node.
public virtual string NamespaceURI
{
get { return string.Empty; }
}
// Gets or sets the namespace prefix of this node.
public virtual string Prefix
{
get { return string.Empty; }
set { }
}
// Gets the name of the node without the namespace prefix.
public abstract string LocalName
{
get;
}
// Microsoft extensions
// Gets a value indicating whether the node is read-only.
public virtual bool IsReadOnly
{
get
{
XmlDocument doc = OwnerDocument;
return HasReadOnlyParent(this);
}
}
internal static bool HasReadOnlyParent(XmlNode n)
{
while (n != null)
{
switch (n.NodeType)
{
case XmlNodeType.EntityReference:
case XmlNodeType.Entity:
return true;
case XmlNodeType.Attribute:
n = ((XmlAttribute)n).OwnerElement;
break;
default:
n = n.ParentNode;
break;
}
}
return false;
}
// Provides a simple ForEach-style iteration over the
// collection of nodes in this XmlNamedNodeMap.
IEnumerator IEnumerable.GetEnumerator()
{
return new XmlChildEnumerator(this);
}
public IEnumerator GetEnumerator()
{
return new XmlChildEnumerator(this);
}
private void AppendChildText(StringBuilder builder)
{
for (XmlNode child = FirstChild; child != null; child = child.NextSibling)
{
if (child.FirstChild == null)
{
if (child.NodeType == XmlNodeType.Text || child.NodeType == XmlNodeType.CDATA
|| child.NodeType == XmlNodeType.Whitespace || child.NodeType == XmlNodeType.SignificantWhitespace)
builder.Append(child.InnerText);
}
else
{
child.AppendChildText(builder);
}
}
}
// Gets or sets the concatenated values of the node and
// all its children.
public virtual string InnerText
{
get
{
XmlNode fc = FirstChild;
if (fc == null)
{
return string.Empty;
}
if (fc.NextSibling == null)
{
XmlNodeType nodeType = fc.NodeType;
switch (nodeType)
{
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
return fc.Value;
}
}
StringBuilder builder = StringBuilderCache.Acquire();
AppendChildText(builder);
return StringBuilderCache.GetStringAndRelease(builder);
}
set
{
XmlNode firstChild = FirstChild;
if (firstChild != null //there is one child
&& firstChild.NextSibling == null // and exactly one
&& firstChild.NodeType == XmlNodeType.Text)//which is a text node
{
//this branch is for perf reason and event fired when TextNode.Value is changed
firstChild.Value = value;
}
else
{
RemoveAll();
AppendChild(OwnerDocument.CreateTextNode(value));
}
}
}
// Gets the markup representing this node and all its children.
public virtual string OuterXml
{
get
{
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
XmlDOMTextWriter xw = new XmlDOMTextWriter(sw);
try
{
WriteTo(xw);
}
finally
{
xw.Dispose();
}
return sw.ToString();
}
}
// Gets or sets the markup representing just the children of this node.
public virtual string InnerXml
{
get
{
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
XmlDOMTextWriter xw = new XmlDOMTextWriter(sw);
try
{
WriteContentTo(xw);
}
finally
{
xw.Dispose();
}
return sw.ToString();
}
set
{
throw new InvalidOperationException(SR.Xdom_Set_InnerXml);
}
}
public virtual String BaseURI
{
get
{
XmlNode curNode = this.ParentNode; //save one while loop since if going to here, the nodetype of this node can't be document, entity and entityref
while (curNode != null)
{
XmlNodeType nt = curNode.NodeType;
//EntityReference's children come from the dtd where they are defined.
//we need to investigate the same thing for entity's children if they are defined in an external dtd file.
if (nt == XmlNodeType.EntityReference)
return ((XmlEntityReference)curNode).ChildBaseURI;
if (nt == XmlNodeType.Document
|| nt == XmlNodeType.Entity
|| nt == XmlNodeType.Attribute)
return curNode.BaseURI;
curNode = curNode.ParentNode;
}
return String.Empty;
}
}
// Saves the current node to the specified XmlWriter.
public abstract void WriteTo(XmlWriter w);
// Saves all the children of the node to the specified XmlWriter.
public abstract void WriteContentTo(XmlWriter w);
// Removes all the children and/or attributes
// of the current node.
public virtual void RemoveAll()
{
XmlNode child = FirstChild;
XmlNode sibling = null;
while (child != null)
{
sibling = child.NextSibling;
RemoveChild(child);
child = sibling;
}
}
internal XmlDocument Document
{
get
{
if (NodeType == XmlNodeType.Document)
return (XmlDocument)this;
return OwnerDocument;
}
}
// Looks up the closest xmlns declaration for the given
// prefix that is in scope for the current node and returns
// the namespace URI in the declaration.
public virtual string GetNamespaceOfPrefix(string prefix)
{
string namespaceName = GetNamespaceOfPrefixStrict(prefix);
return namespaceName != null ? namespaceName : string.Empty;
}
internal string GetNamespaceOfPrefixStrict(string prefix)
{
XmlDocument doc = Document;
if (doc != null)
{
prefix = doc.NameTable.Get(prefix);
if (prefix == null)
return null;
XmlNode node = this;
while (node != null)
{
if (node.NodeType == XmlNodeType.Element)
{
XmlElement elem = (XmlElement)node;
if (elem.HasAttributes)
{
XmlAttributeCollection attrs = elem.Attributes;
if (prefix.Length == 0)
{
for (int iAttr = 0; iAttr < attrs.Count; iAttr++)
{
XmlAttribute attr = attrs[iAttr];
if (attr.Prefix.Length == 0)
{
if (Ref.Equal(attr.LocalName, doc.strXmlns))
{
return attr.Value; // found xmlns
}
}
}
}
else
{
for (int iAttr = 0; iAttr < attrs.Count; iAttr++)
{
XmlAttribute attr = attrs[iAttr];
if (Ref.Equal(attr.Prefix, doc.strXmlns))
{
if (Ref.Equal(attr.LocalName, prefix))
{
return attr.Value; // found xmlns:prefix
}
}
else if (Ref.Equal(attr.Prefix, prefix))
{
return attr.NamespaceURI; // found prefix:attr
}
}
}
}
if (Ref.Equal(node.Prefix, prefix))
{
return node.NamespaceURI;
}
node = node.ParentNode;
}
else if (node.NodeType == XmlNodeType.Attribute)
{
node = ((XmlAttribute)node).OwnerElement;
}
else
{
node = node.ParentNode;
}
}
if (Ref.Equal(doc.strXml, prefix))
{ // xmlns:xml
return doc.strReservedXml;
}
else if (Ref.Equal(doc.strXmlns, prefix))
{ // xmlns:xmlns
return doc.strReservedXmlns;
}
}
return null;
}
// Looks up the closest xmlns declaration for the given namespace
// URI that is in scope for the current node and returns
// the prefix defined in that declaration.
public virtual string GetPrefixOfNamespace(string namespaceURI)
{
string prefix = GetPrefixOfNamespaceStrict(namespaceURI);
return prefix != null ? prefix : string.Empty;
}
internal string GetPrefixOfNamespaceStrict(string namespaceURI)
{
XmlDocument doc = Document;
if (doc != null)
{
namespaceURI = doc.NameTable.Add(namespaceURI);
XmlNode node = this;
while (node != null)
{
if (node.NodeType == XmlNodeType.Element)
{
XmlElement elem = (XmlElement)node;
if (elem.HasAttributes)
{
XmlAttributeCollection attrs = elem.Attributes;
for (int iAttr = 0; iAttr < attrs.Count; iAttr++)
{
XmlAttribute attr = attrs[iAttr];
if (attr.Prefix.Length == 0)
{
if (Ref.Equal(attr.LocalName, doc.strXmlns))
{
if (attr.Value == namespaceURI)
{
return string.Empty; // found xmlns="namespaceURI"
}
}
}
else if (Ref.Equal(attr.Prefix, doc.strXmlns))
{
if (attr.Value == namespaceURI)
{
return attr.LocalName; // found xmlns:prefix="namespaceURI"
}
}
else if (Ref.Equal(attr.NamespaceURI, namespaceURI))
{
return attr.Prefix; // found prefix:attr
// with prefix bound to namespaceURI
}
}
}
if (Ref.Equal(node.NamespaceURI, namespaceURI))
{
return node.Prefix;
}
node = node.ParentNode;
}
else if (node.NodeType == XmlNodeType.Attribute)
{
node = ((XmlAttribute)node).OwnerElement;
}
else
{
node = node.ParentNode;
}
}
if (Ref.Equal(doc.strReservedXml, namespaceURI))
{ // xmlns:xml
return doc.strXml;
}
else if (Ref.Equal(doc.strReservedXmlns, namespaceURI))
{ // xmlns:xmlns
return doc.strXmlns;
}
}
return null;
}
// Retrieves the first child element with the specified name.
public virtual XmlElement this[string name]
{
get
{
for (XmlNode n = FirstChild; n != null; n = n.NextSibling)
{
if (n.NodeType == XmlNodeType.Element && n.Name == name)
return (XmlElement)n;
}
return null;
}
}
// Retrieves the first child element with the specified LocalName and
// NamespaceURI.
public virtual XmlElement this[string localname, string ns]
{
get
{
for (XmlNode n = FirstChild; n != null; n = n.NextSibling)
{
if (n.NodeType == XmlNodeType.Element && n.LocalName == localname && n.NamespaceURI == ns)
return (XmlElement)n;
}
return null;
}
}
internal virtual void SetParent(XmlNode node)
{
if (node == null)
{
this.parentNode = OwnerDocument;
}
else
{
this.parentNode = node;
}
}
internal virtual void SetParentForLoad(XmlNode node)
{
this.parentNode = node;
}
internal static void SplitName(string name, out string prefix, out string localName)
{
int colonPos = name.IndexOf(':'); // ordinal compare
if (-1 == colonPos || 0 == colonPos || name.Length - 1 == colonPos)
{
prefix = string.Empty;
localName = name;
}
else
{
prefix = name.Substring(0, colonPos);
localName = name.Substring(colonPos + 1);
}
}
internal virtual XmlNode FindChild(XmlNodeType type)
{
for (XmlNode child = FirstChild; child != null; child = child.NextSibling)
{
if (child.NodeType == type)
{
return child;
}
}
return null;
}
internal virtual XmlNodeChangedEventArgs GetEventArgs(XmlNode node, XmlNode oldParent, XmlNode newParent, string oldValue, string newValue, XmlNodeChangedAction action)
{
XmlDocument doc = OwnerDocument;
if (doc != null)
{
if (!doc.IsLoading)
{
if (((newParent != null && newParent.IsReadOnly) || (oldParent != null && oldParent.IsReadOnly)))
throw new InvalidOperationException(SR.Xdom_Node_Modify_ReadOnly);
}
return doc.GetEventArgs(node, oldParent, newParent, oldValue, newValue, action);
}
return null;
}
internal virtual void BeforeEvent(XmlNodeChangedEventArgs args)
{
if (args != null)
OwnerDocument.BeforeEvent(args);
}
internal virtual void AfterEvent(XmlNodeChangedEventArgs args)
{
if (args != null)
OwnerDocument.AfterEvent(args);
}
internal virtual XmlSpace XmlSpace
{
get
{
XmlNode node = this;
XmlElement elem = null;
do
{
elem = node as XmlElement;
if (elem != null && elem.HasAttribute("xml:space"))
{
switch (XmlConvertEx.TrimString(elem.GetAttribute("xml:space")))
{
case "default":
return XmlSpace.Default;
case "preserve":
return XmlSpace.Preserve;
default:
//should we throw exception if value is otherwise?
break;
}
}
node = node.ParentNode;
}
while (node != null);
return XmlSpace.None;
}
}
internal virtual String XmlLang
{
get
{
XmlNode node = this;
XmlElement elem = null;
do
{
elem = node as XmlElement;
if (elem != null)
{
if (elem.HasAttribute("xml:lang"))
return elem.GetAttribute("xml:lang");
}
node = node.ParentNode;
} while (node != null);
return String.Empty;
}
}
internal virtual string GetXPAttribute(string localName, string namespaceURI)
{
return String.Empty;
}
internal virtual bool IsText
{
get
{
return false;
}
}
public virtual XmlNode PreviousText
{
get
{
return null;
}
}
internal static void NestTextNodes(XmlNode prevNode, XmlNode nextNode)
{
Debug.Assert(prevNode.IsText);
Debug.Assert(nextNode.IsText);
nextNode.parentNode = prevNode;
}
internal static void UnnestTextNodes(XmlNode prevNode, XmlNode nextNode)
{
Debug.Assert(prevNode.IsText);
Debug.Assert(nextNode.IsText);
nextNode.parentNode = prevNode.ParentNode;
}
private object debuggerDisplayProxy { get { return new DebuggerDisplayXmlNodeProxy(this); } }
}
[DebuggerDisplay("{ToString()}")]
internal struct DebuggerDisplayXmlNodeProxy
{
private XmlNode _node;
public DebuggerDisplayXmlNodeProxy(XmlNode node)
{
_node = node;
}
public override string ToString()
{
XmlNodeType nodeType = _node.NodeType;
string result = nodeType.ToString();
switch (nodeType)
{
case XmlNodeType.Element:
case XmlNodeType.EntityReference:
result += ", Name=\"" + _node.Name + "\"";
break;
case XmlNodeType.Attribute:
case XmlNodeType.ProcessingInstruction:
result += ", Name=\"" + _node.Name + "\", Value=\"" + XmlConvertEx.EscapeValueForDebuggerDisplay(_node.Value) + "\"";
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.Comment:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.XmlDeclaration:
result += ", Value=\"" + XmlConvertEx.EscapeValueForDebuggerDisplay(_node.Value) + "\"";
break;
case XmlNodeType.DocumentType:
XmlDocumentType documentType = (XmlDocumentType)_node;
result += ", Name=\"" + documentType.Name + "\", SYSTEM=\"" + documentType.SystemId + "\", PUBLIC=\"" + documentType.PublicId + "\", Value=\"" + XmlConvertEx.EscapeValueForDebuggerDisplay(documentType.InternalSubset) + "\"";
break;
default:
break;
}
return result;
}
}
}
| |
using System;
using Csla;
using ParentLoad.DataAccess;
using ParentLoad.DataAccess.ERCLevel;
namespace ParentLoad.Business.ERCLevel
{
/// <summary>
/// B03_Continent_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="B03_Continent_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="B02_Continent"/> collection.
/// </remarks>
[Serializable]
public partial class B03_Continent_ReChild : BusinessBase<B03_Continent_ReChild>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int continent_ID2 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Continent_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Continent_Child_NameProperty = RegisterProperty<string>(p => p.Continent_Child_Name, "Continent Child Name");
/// <summary>
/// Gets or sets the Continent Child Name.
/// </summary>
/// <value>The Continent Child Name.</value>
public string Continent_Child_Name
{
get { return GetProperty(Continent_Child_NameProperty); }
set { SetProperty(Continent_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="B03_Continent_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="B03_Continent_ReChild"/> object.</returns>
internal static B03_Continent_ReChild NewB03_Continent_ReChild()
{
return DataPortal.CreateChild<B03_Continent_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="B03_Continent_ReChild"/> object from the given B03_Continent_ReChildDto.
/// </summary>
/// <param name="data">The <see cref="B03_Continent_ReChildDto"/>.</param>
/// <returns>A reference to the fetched <see cref="B03_Continent_ReChild"/> object.</returns>
internal static B03_Continent_ReChild GetB03_Continent_ReChild(B03_Continent_ReChildDto data)
{
B03_Continent_ReChild obj = new B03_Continent_ReChild();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(data);
obj.MarkOld();
// check all object rules and property rules
obj.BusinessRules.CheckRules();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="B03_Continent_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public B03_Continent_ReChild()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="B03_Continent_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="B03_Continent_ReChild"/> object from the given <see cref="B03_Continent_ReChildDto"/>.
/// </summary>
/// <param name="data">The B03_Continent_ReChildDto to use.</param>
private void Fetch(B03_Continent_ReChildDto data)
{
// Value properties
LoadProperty(Continent_Child_NameProperty, data.Continent_Child_Name);
// parent properties
continent_ID2 = data.Parent_Continent_ID;
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="B03_Continent_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(B02_Continent parent)
{
var dto = new B03_Continent_ReChildDto();
dto.Parent_Continent_ID = parent.Continent_ID;
dto.Continent_Child_Name = Continent_Child_Name;
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IB03_Continent_ReChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="B03_Continent_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(B02_Continent parent)
{
if (!IsDirty)
return;
var dto = new B03_Continent_ReChildDto();
dto.Parent_Continent_ID = parent.Continent_ID;
dto.Continent_Child_Name = Continent_Child_Name;
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IB03_Continent_ReChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="B03_Continent_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(B02_Continent parent)
{
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IB03_Continent_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Continent_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using Gtk;
using System;
using System.IO;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.CodeDom;
using Mono.Unix;
namespace Stetic {
internal class ProjectBackend : MarshalByRefObject, IProject, IDisposable
{
List<WidgetData> topLevels;
bool modified;
Gtk.Widget selection;
string id;
string fileName;
XmlDocument tempDoc;
bool loading;
IResourceProvider resourceProvider;
// Global action groups of the project
Stetic.Wrapper.ActionGroupCollection actionGroups;
bool ownedGlobalActionGroups = true; // It may be false when reusing groups from another project
Stetic.ProjectIconFactory iconFactory;
Project frontend;
ArrayList widgetLibraries;
ArrayList internalLibs;
ApplicationBackend app;
AssemblyResolver resolver;
string imagesRootPath;
string targetGtkVersion;
// The action collection of the last selected widget
Stetic.Wrapper.ActionGroupCollection oldTopActionCollection;
public event Wrapper.WidgetNameChangedHandler WidgetNameChanged;
public event Wrapper.WidgetEventHandler WidgetAdded;
public event Wrapper.WidgetEventHandler WidgetContentsChanged;
public event ObjectWrapperEventHandler ObjectChanged;
public event EventHandler ComponentTypesChanged;
public event SignalEventHandler SignalAdded;
public event SignalEventHandler SignalRemoved;
public event SignalChangedEventHandler SignalChanged;
public event Wrapper.WidgetEventHandler SelectionChanged;
public event EventHandler ModifiedChanged;
public event EventHandler Changed;
// Fired when the project has been reloaded, due for example to
// a change in the registry
public event EventHandler ProjectReloading;
public event EventHandler ProjectReloaded;
public ProjectBackend (ApplicationBackend app)
{
this.app = app;
topLevels = new List<WidgetData> ();
ActionGroups = new Stetic.Wrapper.ActionGroupCollection ();
Registry.RegistryChanging += OnRegistryChanging;
Registry.RegistryChanged += OnRegistryChanged;
iconFactory = new ProjectIconFactory ();
widgetLibraries = new ArrayList ();
internalLibs = new ArrayList ();
}
public void Dispose ()
{
// First of all, disconnect from the frontend,
// to avoid sending notifications while disposing
frontend = null;
if (oldTopActionCollection != null)
oldTopActionCollection.ActionGroupChanged -= OnComponentTypesChanged;
Registry.RegistryChanging -= OnRegistryChanging;
Registry.RegistryChanged -= OnRegistryChanged;
Close ();
iconFactory = null;
ActionGroups = null;
System.Runtime.Remoting.RemotingServices.Disconnect (this);
}
public override object InitializeLifetimeService ()
{
// Will be disconnected when calling Dispose
return null;
}
public string FileName {
get { return fileName; }
set {
this.fileName = value;
if (fileName != null)
Id = System.IO.Path.GetFileName (fileName);
else
Id = null;
}
}
internal ArrayList WidgetLibraries {
get { return widgetLibraries; }
set { widgetLibraries = value; }
}
internal ArrayList InternalWidgetLibraries {
get { return internalLibs; }
set { internalLibs = value; }
}
public bool IsInternalLibrary (string lib)
{
return internalLibs.Contains (lib);
}
public bool CanGenerateCode {
get {
// It can generate code if all libraries on which depend can generate code
foreach (string s in widgetLibraries) {
WidgetLibrary lib = Registry.GetWidgetLibrary (s);
if (lib != null && !lib.CanGenerateCode)
return false;
}
return true;
}
}
public string TargetGtkVersion {
get { return targetGtkVersion != null ? targetGtkVersion : "2.4"; }
set {
if (TargetGtkVersion == value)
return;
targetGtkVersion = value;
// Update the project
OnRegistryChanging (null, null);
OnRegistryChanged (null, null);
}
}
public string ImagesRootPath {
get {
if (string.IsNullOrEmpty (imagesRootPath)) {
if (string.IsNullOrEmpty (fileName))
return ".";
else
return Path.GetDirectoryName (fileName);
}
else {
if (Path.IsPathRooted (imagesRootPath))
return imagesRootPath;
else if (!string.IsNullOrEmpty (fileName))
return Path.GetFullPath (Path.Combine (Path.GetDirectoryName (fileName), imagesRootPath));
else
return imagesRootPath;
}
}
set { imagesRootPath = value; }
}
public void AddWidgetLibrary (string lib)
{
AddWidgetLibrary (lib, false);
}
public void AddWidgetLibrary (string lib, bool isInternal)
{
if (!widgetLibraries.Contains (lib))
widgetLibraries.Add (lib);
if (isInternal) {
if (!internalLibs.Contains (lib))
internalLibs.Add (lib);
}
else {
internalLibs.Remove (lib);
}
}
public void RemoveWidgetLibrary (string lib)
{
widgetLibraries.Remove (lib);
internalLibs.Remove (lib);
}
public ArrayList GetComponentTypes ()
{
ArrayList list = new ArrayList ();
foreach (WidgetLibrary lib in app.GetProjectLibraries (this)) {
// Don't include in the list widgets which are internal (when the library is
// not internal to the project), widgets not assigned to any category, and deprecated ones.
bool isInternalLib = IsInternalLibrary (lib.Name);
foreach (ClassDescriptor cd in lib.AllClasses) {
if (!cd.Deprecated && cd.Category.Length > 0 && (isInternalLib || !cd.IsInternal) && cd.SupportsGtkVersion (TargetGtkVersion))
list.Add (cd.Name);
}
}
return list;
}
public string[] GetWidgetTypes ()
{
List<string> list = new List<string> ();
foreach (WidgetLibrary lib in app.GetProjectLibraries (this)) {
// Don't include in the list widgets which are internal (when the library is
// not internal to the project) and deprecated ones.
bool isInternalLib = IsInternalLibrary (lib.Name);
foreach (ClassDescriptor cd in lib.AllClasses) {
if (!cd.Deprecated && (isInternalLib || !cd.IsInternal))
list.Add (cd.Name);
}
}
return list.ToArray ();
}
public IResourceProvider ResourceProvider {
get { return resourceProvider; }
set { resourceProvider = value; }
}
public Stetic.Wrapper.ActionGroupCollection ActionGroups {
get { return actionGroups; }
set {
if (actionGroups != null) {
actionGroups.ActionGroupAdded -= OnGroupAdded;
actionGroups.ActionGroupRemoved -= OnGroupRemoved;
actionGroups.ActionGroupChanged -= OnComponentTypesChanged;
}
actionGroups = value;
if (actionGroups != null) {
actionGroups.ActionGroupAdded += OnGroupAdded;
actionGroups.ActionGroupRemoved += OnGroupRemoved;
actionGroups.ActionGroupChanged += OnComponentTypesChanged;
}
ownedGlobalActionGroups = true;
}
}
public void AttachActionGroups (Stetic.Wrapper.ActionGroupCollection groups)
{
ActionGroups = groups;
ownedGlobalActionGroups = false;
}
public Stetic.ProjectIconFactory IconFactory {
get { return iconFactory; }
set { iconFactory = value; }
}
internal void SetFileName (string fileName)
{
this.fileName = fileName;
}
internal void SetFrontend (Project project)
{
frontend = project;
}
public void Close ()
{
fileName = null;
if (actionGroups != null && ownedGlobalActionGroups) {
foreach (Stetic.Wrapper.ActionGroup ag in actionGroups)
ag.Dispose ();
actionGroups.Clear ();
}
foreach (WidgetData wd in topLevels) {
if (wd.Widget != null)
wd.Widget.Destroy ();
}
selection = null;
topLevels.Clear ();
widgetLibraries.Clear ();
iconFactory = new ProjectIconFactory ();
}
public void Load (string fileName)
{
Load (fileName, fileName);
}
public void Load (string xmlFile, string fileName)
{
this.fileName = fileName;
XmlDocument doc = new XmlDocument ();
doc.PreserveWhitespace = true;
doc.Load (xmlFile);
Read (doc);
Id = System.IO.Path.GetFileName (fileName);
}
void Read (XmlDocument doc)
{
loading = true;
string basePath = fileName != null ? Path.GetDirectoryName (fileName) : null;
try {
string fn = fileName;
Close ();
fileName = fn;
XmlNode node = doc.SelectSingleNode ("/stetic-interface");
if (node == null)
throw new ApplicationException (Catalog.GetString ("Not a Stetic file according to node name."));
// Load configuration options
foreach (XmlNode configNode in node.SelectNodes ("configuration/*")) {
XmlElement config = configNode as XmlElement;
if (config == null) continue;
if (config.LocalName == "images-root-path")
imagesRootPath = config.InnerText;
else if (config.LocalName == "target-gtk-version")
targetGtkVersion = config.InnerText;
}
// Load the assembly directories
resolver = new AssemblyResolver (app);
foreach (XmlElement libElem in node.SelectNodes ("import/assembly-directory")) {
string dir = libElem.GetAttribute ("path");
if (dir.Length > 0) {
if (basePath != null && !Path.IsPathRooted (dir)) {
dir = Path.Combine (basePath, dir);
if (Directory.Exists (dir))
dir = Path.GetFullPath (dir);
}
resolver.Directories.Add (dir);
}
}
// Import the referenced libraries
foreach (XmlElement libElem in node.SelectNodes ("import/widget-library")) {
string libname = libElem.GetAttribute ("name");
if (libname.EndsWith (".dll") || libname.EndsWith (".exe")) {
if (basePath != null && !Path.IsPathRooted (libname)) {
libname = Path.Combine (basePath, libname);
if (File.Exists (libname))
libname = Path.GetFullPath (libname);
}
}
widgetLibraries.Add (libname);
if (libElem.GetAttribute ("internal") == "true")
internalLibs.Add (libname);
}
app.LoadLibraries (resolver, widgetLibraries);
ObjectReader reader = new ObjectReader (this, FileFormat.Native);
if (ownedGlobalActionGroups) {
foreach (XmlElement groupElem in node.SelectNodes ("action-group")) {
Wrapper.ActionGroup actionGroup = new Wrapper.ActionGroup ();
actionGroup.Read (reader, groupElem);
actionGroups.Add (actionGroup);
}
}
XmlElement iconsElem = node.SelectSingleNode ("icon-factory") as XmlElement;
if (iconsElem != null)
iconFactory.Read (this, iconsElem);
foreach (XmlElement toplevel in node.SelectNodes ("widget")) {
topLevels.Add (new WidgetData (toplevel.GetAttribute ("id"), toplevel, null));
}
} finally {
loading = false;
}
}
public Gtk.Widget GetWidget (WidgetData data)
{
if (data.Widget == null) {
try {
loading = true;
ObjectReader reader = new ObjectReader (this, FileFormat.Native);
Wrapper.Container wrapper = Stetic.ObjectWrapper.ReadObject (reader, data.XmlData) as Wrapper.Container;
data.Widget = wrapper.Wrapped;
} finally {
loading = false;
}
}
return data.Widget;
}
public void Save (string fileName)
{
this.fileName = fileName;
XmlDocument doc = Write (false);
XmlTextWriter writer = null;
try {
// Write to a temporary file first, just in case something fails
writer = new XmlTextWriter (fileName + "~", System.Text.Encoding.UTF8);
writer.Formatting = Formatting.Indented;
doc.Save (writer);
writer.Close ();
File.Copy (fileName + "~", fileName, true);
File.Delete (fileName + "~");
} finally {
if (writer != null)
writer.Close ();
}
}
XmlDocument Write (bool includeUndoInfo)
{
XmlDocument doc = new XmlDocument ();
doc.PreserveWhitespace = true;
XmlElement toplevel = doc.CreateElement ("stetic-interface");
doc.AppendChild (toplevel);
XmlElement config = doc.CreateElement ("configuration");
if (!string.IsNullOrEmpty (imagesRootPath)) {
XmlElement iroot = doc.CreateElement ("images-root-path");
iroot.InnerText = imagesRootPath;
config.AppendChild (iroot);
}
if (!string.IsNullOrEmpty (targetGtkVersion)) {
XmlElement iroot = doc.CreateElement ("target-gtk-version");
iroot.InnerText = targetGtkVersion;
config.AppendChild (iroot);
}
if (config.ChildNodes.Count > 0)
toplevel.AppendChild (config);
if (widgetLibraries.Count > 0 || (resolver != null && resolver.Directories.Count > 0)) {
XmlElement importElem = doc.CreateElement ("import");
toplevel.AppendChild (importElem);
string basePath = Path.GetDirectoryName (fileName);
if (resolver != null && resolver.Directories.Count > 0) {
foreach (string dir in resolver.Directories) {
XmlElement dirElem = doc.CreateElement ("assembly-directory");
if (basePath != null)
dirElem.SetAttribute ("path", AbsoluteToRelativePath (basePath, dir));
else
dirElem.SetAttribute ("path", dir);
toplevel.AppendChild (dirElem);
}
}
foreach (string wlib in widgetLibraries) {
string libName = wlib;
XmlElement libElem = doc.CreateElement ("widget-library");
if (wlib.EndsWith (".dll") || wlib.EndsWith (".exe")) {
if (basePath != null)
libName = AbsoluteToRelativePath (basePath, wlib);
}
libElem.SetAttribute ("name", libName);
if (IsInternalLibrary (wlib))
libElem.SetAttribute ("internal", "true");
importElem.AppendChild (libElem);
}
}
ObjectWriter writer = new ObjectWriter (doc, FileFormat.Native);
writer.CreateUndoInfo = includeUndoInfo;
if (ownedGlobalActionGroups) {
foreach (Wrapper.ActionGroup agroup in actionGroups) {
XmlElement elem = agroup.Write (writer);
toplevel.AppendChild (elem);
}
}
if (iconFactory.Icons.Count > 0)
toplevel.AppendChild (iconFactory.Write (doc));
foreach (WidgetData data in topLevels) {
if (data.Widget != null) {
Stetic.Wrapper.Container wrapper = Stetic.Wrapper.Container.Lookup (data.Widget);
if (wrapper == null)
continue;
XmlElement elem = wrapper.Write (writer);
if (elem != null)
toplevel.AppendChild (elem);
} else {
toplevel.AppendChild (doc.ImportNode (data.XmlData, true));
}
}
// Remove undo annotations from the xml document
CleanUndoData (doc.DocumentElement);
return doc;
}
public void ImportGlade (string fileName)
{
GladeFiles.Import (this, fileName);
}
public void ExportGlade (string fileName)
{
GladeFiles.Export (this, fileName);
}
public void EditIcons ()
{
using (Stetic.Editor.EditIconFactoryDialog dlg = new Stetic.Editor.EditIconFactoryDialog (null, this, this.IconFactory)) {
dlg.Run ();
}
}
internal WidgetEditSession CreateWidgetDesignerSession (WidgetDesignerFrontend frontend, string windowName, Stetic.ProjectBackend editingBackend, bool autoCommitChanges)
{
return new WidgetEditSession (this, frontend, windowName, editingBackend, autoCommitChanges);
}
internal ActionGroupEditSession CreateGlobalActionGroupDesignerSession (ActionGroupDesignerFrontend frontend, string groupName, bool autoCommitChanges)
{
return new ActionGroupEditSession (frontend, this, null, groupName, autoCommitChanges);
}
internal ActionGroupEditSession CreateLocalActionGroupDesignerSession (ActionGroupDesignerFrontend frontend, string windowName, bool autoCommitChanges)
{
return new ActionGroupEditSession (frontend, this, windowName, null, autoCommitChanges);
}
public Wrapper.Container GetTopLevelWrapper (string name, bool throwIfNotFound)
{
Gtk.Widget w = GetTopLevel (name);
if (w != null) {
Wrapper.Container ww = Wrapper.Container.Lookup (w);
if (ww != null)
return (Wrapper.Container) Component.GetSafeReference (ww);
}
if (throwIfNotFound)
throw new InvalidOperationException ("Component not found: " + name);
return null;
}
public object AddNewWidget (string type, string name)
{
ClassDescriptor cls = Registry.LookupClassByName (type);
Gtk.Widget w = (Gtk.Widget) cls.NewInstance (this);
w.Name = name;
this.AddWidget (w);
return Component.GetSafeReference (ObjectWrapper.Lookup (w));
}
public object AddNewWidgetFromTemplate (string template)
{
XmlDocument doc = new XmlDocument ();
doc.LoadXml (template);
Gtk.Widget widget = Stetic.WidgetUtils.ImportWidget (this, doc.DocumentElement);
AddWidget (widget);
return Component.GetSafeReference (ObjectWrapper.Lookup (widget));
}
public void RemoveWidget (string name)
{
WidgetData data = GetWidgetData (name);
if (data == null)
return;
if (frontend != null)
frontend.NotifyWidgetRemoved (data.Name);
topLevels.Remove (data);
if (data.Widget != null)
data.Widget.Destroy ();
}
public Stetic.Wrapper.ActionGroup AddNewActionGroup (string name)
{
Stetic.Wrapper.ActionGroup group = new Stetic.Wrapper.ActionGroup ();
group.Name = name;
ActionGroups.Add (group);
return group;
}
public Stetic.Wrapper.ActionGroup AddNewActionGroupFromTemplate (string template)
{
XmlDocument doc = new XmlDocument ();
doc.LoadXml (template);
ObjectReader or = new ObjectReader (this, FileFormat.Native);
Stetic.Wrapper.ActionGroup group = new Stetic.Wrapper.ActionGroup ();
group.Read (or, doc.DocumentElement);
ActionGroups.Add (group);
return group;
}
public void RemoveActionGroup (Stetic.Wrapper.ActionGroup group)
{
ActionGroups.Remove (group);
}
public Wrapper.ActionGroup[] GetActionGroups ()
{
// Needed since ActionGroupCollection can't be made serializable
return ActionGroups.ToArray ();
}
public void CopyWidgetToProject (string name, ProjectBackend other, string replacedName)
{
WidgetData wdata = GetWidgetData (name);
if (name == null)
throw new InvalidOperationException ("Component not found: " + name);
XmlElement data;
if (wdata.Widget != null)
data = Stetic.WidgetUtils.ExportWidget (wdata.Widget);
else
data = (XmlElement) wdata.XmlData.Clone ();
// If widget already exist, replace it
wdata = other.GetWidgetData (replacedName);
if (wdata == null) {
wdata = new WidgetData (name, data, null);
other.topLevels.Add (wdata);
} else {
if (wdata.Widget != null) {
// If a widget instance already exist, load the new data on it
Wrapper.Widget sw = Wrapper.Widget.Lookup (wdata.Widget);
sw.Read (new ObjectReader (other, FileFormat.Native), data);
sw.NotifyChanged ();
if (name != replacedName)
other.OnWidgetNameChanged (new Wrapper.WidgetNameChangedArgs (sw, replacedName, name), true);
} else {
wdata.SetXmlData (name, data);
if (name != replacedName)
other.OnWidgetNameChanged (new Wrapper.WidgetNameChangedArgs (null, replacedName, name), true);
}
}
}
void CleanUndoData (XmlElement elem)
{
elem.RemoveAttribute ("undoId");
foreach (XmlNode cn in elem.ChildNodes) {
XmlElement ce = cn as XmlElement;
if (ce != null)
CleanUndoData (ce);
}
}
void OnRegistryChanging (object o, EventArgs args)
{
if (loading) return;
// Store a copy of the current tree. The tree will
// be recreated once the registry change is completed.
tempDoc = Write (true);
Selection = null;
}
void OnRegistryChanged (object o, EventArgs args)
{
if (loading) return;
if (tempDoc != null) {
if (frontend != null)
frontend.NotifyProjectReloading ();
if (ProjectReloading != null)
ProjectReloading (this, EventArgs.Empty);
ProjectIconFactory icf = iconFactory;
Read (tempDoc);
// Reuse the same icon factory, since a registry change has no effect to it
// and it may be inherited from another project
iconFactory = icf;
tempDoc = null;
if (frontend != null)
frontend.NotifyProjectReloaded ();
if (ProjectReloaded != null)
ProjectReloaded (this, EventArgs.Empty);
NotifyComponentTypesChanged ();
}
}
public void Reload ()
{
OnRegistryChanging (null, null);
OnRegistryChanged (null, null);
}
public string Id {
get { return id; }
set { id = value; }
}
public bool Modified {
get { return modified; }
set {
if (modified != value) {
modified = value;
if (frontend != null)
frontend.NotifyModifiedChanged ();
OnModifiedChanged (EventArgs.Empty);
}
}
}
public AssemblyResolver Resolver {
get { return resolver; }
}
public string ImportFile (string filePath)
{
return frontend.ImportFile (filePath);
}
public void AddWindow (Gtk.Window window)
{
AddWindow (window, false);
}
public void AddWindow (Gtk.Window window, bool select)
{
AddWidget (window);
if (select)
Selection = window;
}
public void AddWidget (Gtk.Widget widget)
{
if (!typeof(Gtk.Container).IsInstanceOfType (widget))
throw new System.ArgumentException ("widget", "Only containers can be top level widgets");
topLevels.Add (new WidgetData (null, null, widget));
if (!loading) {
Stetic.Wrapper.Widget ww = Stetic.Wrapper.Widget.Lookup (widget);
if (ww == null)
throw new InvalidOperationException ("Widget not wrapped");
if (frontend != null)
frontend.NotifyWidgetAdded (Component.GetSafeReference (ww), widget.Name, ww.ClassDescriptor.Name);
OnWidgetAdded (new Stetic.Wrapper.WidgetEventArgs (ww));
}
}
void IProject.NotifyObjectChanged (ObjectWrapperEventArgs args)
{
if (loading)
return;
NotifyChanged ();
if (ObjectChanged != null)
ObjectChanged (this, args);
}
void IProject.NotifyNameChanged (Stetic.Wrapper.WidgetNameChangedArgs args)
{
if (loading)
return;
NotifyChanged ();
OnWidgetNameChanged (args, args.WidgetWrapper.IsTopLevel);
}
void IProject.NotifySignalAdded (SignalEventArgs args)
{
if (loading)
return;
if (frontend != null)
frontend.NotifySignalAdded (Component.GetSafeReference (args.Wrapper), null, args.Signal);
OnSignalAdded (args);
}
void IProject.NotifySignalRemoved (SignalEventArgs args)
{
if (loading)
return;
if (frontend != null)
frontend.NotifySignalRemoved (Component.GetSafeReference (args.Wrapper), null, args.Signal);
OnSignalRemoved (args);
}
void IProject.NotifySignalChanged (SignalChangedEventArgs args)
{
if (loading)
return;
OnSignalChanged (args);
}
void IProject.NotifyWidgetContentsChanged (Wrapper.Widget w)
{
if (loading)
return;
if (WidgetContentsChanged != null)
WidgetContentsChanged (this, new Wrapper.WidgetEventArgs (w));
}
void OnWidgetNameChanged (Stetic.Wrapper.WidgetNameChangedArgs args, bool isTopLevel)
{
if (frontend != null)
frontend.NotifyWidgetNameChanged (Component.GetSafeReference (args.WidgetWrapper), args.OldName, args.NewName, isTopLevel);
if (args.WidgetWrapper != null && WidgetNameChanged != null)
WidgetNameChanged (this, args);
}
void OnSignalAdded (object sender, SignalEventArgs args)
{
if (frontend != null)
frontend.NotifySignalAdded (Component.GetSafeReference (args.Wrapper), null, args.Signal);
OnSignalAdded (args);
}
protected virtual void OnSignalAdded (SignalEventArgs args)
{
if (SignalAdded != null)
SignalAdded (this, args);
}
void OnSignalRemoved (object sender, SignalEventArgs args)
{
if (frontend != null)
frontend.NotifySignalRemoved (Component.GetSafeReference (args.Wrapper), null, args.Signal);
OnSignalRemoved (args);
}
protected virtual void OnSignalRemoved (SignalEventArgs args)
{
if (SignalRemoved != null)
SignalRemoved (this, args);
}
void OnSignalChanged (object sender, SignalChangedEventArgs args)
{
OnSignalChanged (args);
}
protected virtual void OnSignalChanged (SignalChangedEventArgs args)
{
if (frontend != null)
frontend.NotifySignalChanged (Component.GetSafeReference (args.Wrapper), null, args.OldSignal, args.Signal);
if (SignalChanged != null)
SignalChanged (this, args);
}
public Gtk.Widget[] Toplevels {
get {
List<Gtk.Widget> list = new List<Gtk.Widget> ();
foreach (WidgetData w in topLevels)
list.Add (GetWidget (w));
return list.ToArray ();
}
}
public Gtk.Widget GetTopLevel (string name)
{
WidgetData w = GetWidgetData (name);
if (w != null)
return GetWidget (w);
else
return null;
}
public WidgetData GetWidgetData (string name)
{
foreach (WidgetData w in topLevels) {
if (w.Name == name)
return w;
}
return null;
}
// IProject
public Gtk.Widget Selection {
get {
return selection;
}
set {
if (selection == value)
return;
Wrapper.ActionGroupCollection newCollection = null;
// FIXME: should there be an IsDestroyed property?
if (selection != null && selection.Handle != IntPtr.Zero) {
Stetic.Wrapper.Container parent = Stetic.Wrapper.Container.LookupParent (selection);
if (parent == null)
parent = Stetic.Wrapper.Container.Lookup (selection);
if (parent != null)
parent.UnSelect (selection);
}
selection = value;
if (selection != null && selection.Handle != IntPtr.Zero) {
Stetic.Wrapper.Container parent = Stetic.Wrapper.Container.LookupParent (selection);
if (parent == null)
parent = Stetic.Wrapper.Container.Lookup (selection);
if (parent != null)
parent.Select (selection);
Wrapper.Widget w = Wrapper.Widget.Lookup (selection);
if (w != null)
newCollection = w.LocalActionGroups;
}
if (SelectionChanged != null)
SelectionChanged (this, new Wrapper.WidgetEventArgs (Wrapper.Widget.Lookup (selection)));
if (oldTopActionCollection != newCollection) {
if (oldTopActionCollection != null)
oldTopActionCollection.ActionGroupChanged -= OnComponentTypesChanged;
if (newCollection != null)
newCollection.ActionGroupChanged += OnComponentTypesChanged;
oldTopActionCollection = newCollection;
OnComponentTypesChanged (null, null);
}
}
}
public void PopupContextMenu (Stetic.Wrapper.Widget wrapper)
{
Gtk.Menu m = new ContextMenu (wrapper);
m.Popup ();
}
public void PopupContextMenu (Placeholder ph)
{
Gtk.Menu m = new ContextMenu (ph);
m.Popup ();
}
internal static string AbsoluteToRelativePath (string baseDirectoryPath, string absPath)
{
if (!Path.IsPathRooted (absPath))
return absPath;
absPath = Path.GetFullPath (absPath);
baseDirectoryPath = Path.GetFullPath (baseDirectoryPath);
char[] separators = { Path.DirectorySeparatorChar, Path.VolumeSeparatorChar, Path.AltDirectorySeparatorChar };
string[] bPath = baseDirectoryPath.Split (separators);
string[] aPath = absPath.Split (separators);
int indx = 0;
for(; indx < Math.Min(bPath.Length, aPath.Length); ++indx) {
if(!bPath[indx].Equals(aPath[indx]))
break;
}
if (indx == 0) {
return absPath;
}
string erg = "";
if(indx == bPath.Length) {
erg += "." + Path.DirectorySeparatorChar;
} else {
for (int i = indx; i < bPath.Length; ++i) {
erg += ".." + Path.DirectorySeparatorChar;
}
}
erg += String.Join(Path.DirectorySeparatorChar.ToString(), aPath, indx, aPath.Length-indx);
return erg;
}
void OnComponentTypesChanged (object s, EventArgs a)
{
if (!loading)
NotifyComponentTypesChanged ();
}
public void NotifyComponentTypesChanged ()
{
if (frontend != null)
frontend.NotifyComponentTypesChanged ();
if (ComponentTypesChanged != null)
ComponentTypesChanged (this, EventArgs.Empty);
}
void OnGroupAdded (object s, Stetic.Wrapper.ActionGroupEventArgs args)
{
args.ActionGroup.SignalAdded += OnSignalAdded;
args.ActionGroup.SignalRemoved += OnSignalRemoved;
args.ActionGroup.SignalChanged += OnSignalChanged;
if (frontend != null)
frontend.NotifyActionGroupAdded (args.ActionGroup.Name);
OnComponentTypesChanged (null, null);
}
void OnGroupRemoved (object s, Stetic.Wrapper.ActionGroupEventArgs args)
{
args.ActionGroup.SignalAdded -= OnSignalAdded;
args.ActionGroup.SignalRemoved -= OnSignalRemoved;
args.ActionGroup.SignalChanged -= OnSignalChanged;
if (frontend != null)
frontend.NotifyActionGroupRemoved (args.ActionGroup.Name);
OnComponentTypesChanged (null, null);
}
void NotifyChanged ()
{
Modified = true;
if (frontend != null)
frontend.NotifyChanged ();
if (Changed != null)
Changed (this, EventArgs.Empty);
}
protected virtual void OnModifiedChanged (EventArgs args)
{
if (ModifiedChanged != null)
ModifiedChanged (this, args);
}
protected virtual void OnWidgetAdded (Stetic.Wrapper.WidgetEventArgs args)
{
NotifyChanged ();
if (WidgetAdded != null)
WidgetAdded (this, args);
}
}
class WidgetData
{
string name;
public WidgetData (string name, XmlElement data, Gtk.Widget widget)
{
SetXmlData (name, data);
Widget = widget;
}
public void SetXmlData (string name, XmlElement data)
{
this.name = name;
XmlData = data;
Widget = null;
}
public XmlElement XmlData;
public Gtk.Widget Widget;
public string Name {
get {
if (Widget != null)
return Widget.Name;
else
return name;
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Communication;
using Apache.Ignite.Core.Communication.Tcp;
using Apache.Ignite.Core.DataStructures.Configuration;
using Apache.Ignite.Core.Discovery;
using Apache.Ignite.Core.Discovery.Tcp;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.SwapSpace;
using Apache.Ignite.Core.Lifecycle;
using Apache.Ignite.Core.Log;
using Apache.Ignite.Core.Plugin;
using Apache.Ignite.Core.SwapSpace;
using Apache.Ignite.Core.Transactions;
using BinaryWriter = Apache.Ignite.Core.Impl.Binary.BinaryWriter;
/// <summary>
/// Grid configuration.
/// </summary>
public class IgniteConfiguration
{
/// <summary>
/// Default initial JVM memory in megabytes.
/// </summary>
public const int DefaultJvmInitMem = -1;
/// <summary>
/// Default maximum JVM memory in megabytes.
/// </summary>
public const int DefaultJvmMaxMem = -1;
/// <summary>
/// Default metrics expire time.
/// </summary>
public static readonly TimeSpan DefaultMetricsExpireTime = TimeSpan.MaxValue;
/// <summary>
/// Default metrics history size.
/// </summary>
public const int DefaultMetricsHistorySize = 10000;
/// <summary>
/// Default metrics log frequency.
/// </summary>
public static readonly TimeSpan DefaultMetricsLogFrequency = TimeSpan.FromMilliseconds(60000);
/// <summary>
/// Default metrics update frequency.
/// </summary>
public static readonly TimeSpan DefaultMetricsUpdateFrequency = TimeSpan.FromMilliseconds(2000);
/// <summary>
/// Default network timeout.
/// </summary>
public static readonly TimeSpan DefaultNetworkTimeout = TimeSpan.FromMilliseconds(5000);
/// <summary>
/// Default network retry delay.
/// </summary>
public static readonly TimeSpan DefaultNetworkSendRetryDelay = TimeSpan.FromMilliseconds(1000);
/// <summary>
/// Default failure detection timeout.
/// </summary>
public static readonly TimeSpan DefaultFailureDetectionTimeout = TimeSpan.FromSeconds(10);
/** */
private TimeSpan? _metricsExpireTime;
/** */
private int? _metricsHistorySize;
/** */
private TimeSpan? _metricsLogFrequency;
/** */
private TimeSpan? _metricsUpdateFrequency;
/** */
private int? _networkSendRetryCount;
/** */
private TimeSpan? _networkSendRetryDelay;
/** */
private TimeSpan? _networkTimeout;
/** */
private bool? _isDaemon;
/** */
private bool? _isLateAffinityAssignment;
/** */
private bool? _clientMode;
/** */
private TimeSpan? _failureDetectionTimeout;
/// <summary>
/// Default network retry count.
/// </summary>
public const int DefaultNetworkSendRetryCount = 3;
/// <summary>
/// Default late affinity assignment mode.
/// </summary>
public const bool DefaultIsLateAffinityAssignment = true;
/// <summary>
/// Initializes a new instance of the <see cref="IgniteConfiguration"/> class.
/// </summary>
public IgniteConfiguration()
{
JvmInitialMemoryMb = DefaultJvmInitMem;
JvmMaxMemoryMb = DefaultJvmMaxMem;
}
/// <summary>
/// Initializes a new instance of the <see cref="IgniteConfiguration"/> class.
/// </summary>
/// <param name="configuration">The configuration to copy.</param>
public IgniteConfiguration(IgniteConfiguration configuration)
{
IgniteArgumentCheck.NotNull(configuration, "configuration");
using (var stream = IgniteManager.Memory.Allocate().GetStream())
{
var marsh = BinaryUtils.Marshaller;
configuration.Write(marsh.StartMarshal(stream));
stream.SynchronizeOutput();
stream.Seek(0, SeekOrigin.Begin);
ReadCore(marsh.StartUnmarshal(stream));
}
CopyLocalProperties(configuration);
}
/// <summary>
/// Initializes a new instance of the <see cref="IgniteConfiguration" /> class from a reader.
/// </summary>
/// <param name="binaryReader">The binary reader.</param>
/// <param name="baseConfig">The base configuration.</param>
internal IgniteConfiguration(IBinaryRawReader binaryReader, IgniteConfiguration baseConfig)
{
Debug.Assert(binaryReader != null);
Debug.Assert(baseConfig != null);
CopyLocalProperties(baseConfig);
Read(binaryReader);
}
/// <summary>
/// Writes this instance to a writer.
/// </summary>
/// <param name="writer">The writer.</param>
internal void Write(BinaryWriter writer)
{
Debug.Assert(writer != null);
// Simple properties
writer.WriteBooleanNullable(_clientMode);
writer.WriteIntArray(IncludedEventTypes == null ? null : IncludedEventTypes.ToArray());
writer.WriteTimeSpanAsLongNullable(_metricsExpireTime);
writer.WriteIntNullable(_metricsHistorySize);
writer.WriteTimeSpanAsLongNullable(_metricsLogFrequency);
writer.WriteTimeSpanAsLongNullable(_metricsUpdateFrequency);
writer.WriteIntNullable(_networkSendRetryCount);
writer.WriteTimeSpanAsLongNullable(_networkSendRetryDelay);
writer.WriteTimeSpanAsLongNullable(_networkTimeout);
writer.WriteString(WorkDirectory);
writer.WriteString(Localhost);
writer.WriteBooleanNullable(_isDaemon);
writer.WriteBooleanNullable(_isLateAffinityAssignment);
writer.WriteTimeSpanAsLongNullable(_failureDetectionTimeout);
// Cache config
var caches = CacheConfiguration;
if (caches == null)
writer.WriteInt(0);
else
{
writer.WriteInt(caches.Count);
foreach (var cache in caches)
cache.Write(writer);
}
// Discovery config
var disco = DiscoverySpi;
if (disco != null)
{
writer.WriteBoolean(true);
var tcpDisco = disco as TcpDiscoverySpi;
if (tcpDisco == null)
throw new InvalidOperationException("Unsupported discovery SPI: " + disco.GetType());
tcpDisco.Write(writer);
}
else
writer.WriteBoolean(false);
// Communication config
var comm = CommunicationSpi;
if (comm != null)
{
writer.WriteBoolean(true);
var tcpComm = comm as TcpCommunicationSpi;
if (tcpComm == null)
throw new InvalidOperationException("Unsupported communication SPI: " + comm.GetType());
tcpComm.Write(writer);
}
else
writer.WriteBoolean(false);
// Binary config
if (BinaryConfiguration != null)
{
writer.WriteBoolean(true);
if (BinaryConfiguration.CompactFooterInternal != null)
{
writer.WriteBoolean(true);
writer.WriteBoolean(BinaryConfiguration.CompactFooter);
}
else
{
writer.WriteBoolean(false);
}
// Send only descriptors with non-null EqualityComparer to preserve old behavior where
// remote nodes can have no BinaryConfiguration.
if (BinaryConfiguration.TypeConfigurations != null &&
BinaryConfiguration.TypeConfigurations.Any(x => x.EqualityComparer != null))
{
// Create a new marshaller to reuse type name resolver mechanism.
var types = new Marshaller(BinaryConfiguration).GetUserTypeDescriptors()
.Where(x => x.EqualityComparer != null).ToList();
writer.WriteInt(types.Count);
foreach (var type in types)
{
writer.WriteString(BinaryUtils.SimpleTypeName(type.TypeName));
writer.WriteBoolean(type.IsEnum);
BinaryEqualityComparerSerializer.Write(writer, type.EqualityComparer);
}
}
else
{
writer.WriteInt(0);
}
}
else
{
writer.WriteBoolean(false);
}
// User attributes
var attrs = UserAttributes;
if (attrs == null)
writer.WriteInt(0);
else
{
writer.WriteInt(attrs.Count);
foreach (var pair in attrs)
{
writer.WriteString(pair.Key);
writer.Write(pair.Value);
}
}
// Atomic
if (AtomicConfiguration != null)
{
writer.WriteBoolean(true);
writer.WriteInt(AtomicConfiguration.AtomicSequenceReserveSize);
writer.WriteInt(AtomicConfiguration.Backups);
writer.WriteInt((int) AtomicConfiguration.CacheMode);
}
else
writer.WriteBoolean(false);
// Tx
if (TransactionConfiguration != null)
{
writer.WriteBoolean(true);
writer.WriteInt(TransactionConfiguration.PessimisticTransactionLogSize);
writer.WriteInt((int) TransactionConfiguration.DefaultTransactionConcurrency);
writer.WriteInt((int) TransactionConfiguration.DefaultTransactionIsolation);
writer.WriteLong((long) TransactionConfiguration.DefaultTimeout.TotalMilliseconds);
writer.WriteInt((int) TransactionConfiguration.PessimisticTransactionLogLinger.TotalMilliseconds);
}
else
writer.WriteBoolean(false);
// Swap space
SwapSpaceSerializer.Write(writer, SwapSpaceSpi);
// Event storage
if (EventStorageSpi == null)
{
writer.WriteByte(0);
}
else if (EventStorageSpi is NoopEventStorageSpi)
{
writer.WriteByte(1);
}
else
{
var memEventStorage = EventStorageSpi as MemoryEventStorageSpi;
if (memEventStorage == null)
{
throw new IgniteException(string.Format(
"Unsupported IgniteConfiguration.EventStorageSpi: '{0}'. " +
"Supported implementations: '{1}', '{2}'.",
EventStorageSpi.GetType(), typeof(NoopEventStorageSpi), typeof(MemoryEventStorageSpi)));
}
writer.WriteByte(2);
memEventStorage.Write(writer);
}
// Plugins (should be last)
if (PluginConfigurations != null)
{
var pos = writer.Stream.Position;
writer.WriteInt(0); // reserve count
var cnt = 0;
foreach (var cfg in PluginConfigurations)
{
if (cfg.PluginConfigurationClosureFactoryId != null)
{
writer.WriteInt(cfg.PluginConfigurationClosureFactoryId.Value);
cfg.WriteBinary(writer);
cnt++;
}
}
writer.Stream.WriteInt(pos, cnt);
}
else
{
writer.WriteInt(0);
}
}
/// <summary>
/// Validates this instance and outputs information to the log, if necessary.
/// </summary>
internal void Validate(ILogger log)
{
Debug.Assert(log != null);
var ccfg = CacheConfiguration;
if (ccfg != null)
{
foreach (var cfg in ccfg)
cfg.Validate(log);
}
}
/// <summary>
/// Reads data from specified reader into current instance.
/// </summary>
/// <param name="r">The binary reader.</param>
private void ReadCore(IBinaryRawReader r)
{
// Simple properties
_clientMode = r.ReadBooleanNullable();
IncludedEventTypes = r.ReadIntArray();
_metricsExpireTime = r.ReadTimeSpanNullable();
_metricsHistorySize = r.ReadIntNullable();
_metricsLogFrequency = r.ReadTimeSpanNullable();
_metricsUpdateFrequency = r.ReadTimeSpanNullable();
_networkSendRetryCount = r.ReadIntNullable();
_networkSendRetryDelay = r.ReadTimeSpanNullable();
_networkTimeout = r.ReadTimeSpanNullable();
WorkDirectory = r.ReadString();
Localhost = r.ReadString();
_isDaemon = r.ReadBooleanNullable();
_isLateAffinityAssignment = r.ReadBooleanNullable();
_failureDetectionTimeout = r.ReadTimeSpanNullable();
// Cache config
var cacheCfgCount = r.ReadInt();
CacheConfiguration = new List<CacheConfiguration>(cacheCfgCount);
for (int i = 0; i < cacheCfgCount; i++)
CacheConfiguration.Add(new CacheConfiguration(r));
// Discovery config
DiscoverySpi = r.ReadBoolean() ? new TcpDiscoverySpi(r) : null;
// Communication config
CommunicationSpi = r.ReadBoolean() ? new TcpCommunicationSpi(r) : null;
// Binary config
if (r.ReadBoolean())
{
BinaryConfiguration = BinaryConfiguration ?? new BinaryConfiguration();
if (r.ReadBoolean())
BinaryConfiguration.CompactFooter = r.ReadBoolean();
var typeCount = r.ReadInt();
if (typeCount > 0)
{
var types = new List<BinaryTypeConfiguration>(typeCount);
for (var i = 0; i < typeCount; i++)
{
types.Add(new BinaryTypeConfiguration
{
TypeName = r.ReadString(),
IsEnum = r.ReadBoolean(),
EqualityComparer = BinaryEqualityComparerSerializer.Read(r)
});
}
BinaryConfiguration.TypeConfigurations = types;
}
}
// User attributes
UserAttributes = Enumerable.Range(0, r.ReadInt())
.ToDictionary(x => r.ReadString(), x => r.ReadObject<object>());
// Atomic
if (r.ReadBoolean())
{
AtomicConfiguration = new AtomicConfiguration
{
AtomicSequenceReserveSize = r.ReadInt(),
Backups = r.ReadInt(),
CacheMode = (CacheMode) r.ReadInt()
};
}
// Tx
if (r.ReadBoolean())
{
TransactionConfiguration = new TransactionConfiguration
{
PessimisticTransactionLogSize = r.ReadInt(),
DefaultTransactionConcurrency = (TransactionConcurrency) r.ReadInt(),
DefaultTransactionIsolation = (TransactionIsolation) r.ReadInt(),
DefaultTimeout = TimeSpan.FromMilliseconds(r.ReadLong()),
PessimisticTransactionLogLinger = TimeSpan.FromMilliseconds(r.ReadInt())
};
}
// Swap
SwapSpaceSpi = SwapSpaceSerializer.Read(r);
// Event storage
switch (r.ReadByte())
{
case 1: EventStorageSpi = new NoopEventStorageSpi();
break;
case 2:
EventStorageSpi = MemoryEventStorageSpi.Read(r);
break;
}
}
/// <summary>
/// Reads data from specified reader into current instance.
/// </summary>
/// <param name="binaryReader">The binary reader.</param>
private void Read(IBinaryRawReader binaryReader)
{
ReadCore(binaryReader);
// Misc
IgniteHome = binaryReader.ReadString();
JvmInitialMemoryMb = (int) (binaryReader.ReadLong()/1024/2014);
JvmMaxMemoryMb = (int) (binaryReader.ReadLong()/1024/2014);
// Local data (not from reader)
JvmDllPath = Process.GetCurrentProcess().Modules.OfType<ProcessModule>()
.Single(x => string.Equals(x.ModuleName, IgniteUtils.FileJvmDll, StringComparison.OrdinalIgnoreCase))
.FileName;
}
/// <summary>
/// Copies the local properties (properties that are not written in Write method).
/// </summary>
private void CopyLocalProperties(IgniteConfiguration cfg)
{
IgniteInstanceName = cfg.IgniteInstanceName;
if (BinaryConfiguration != null && cfg.BinaryConfiguration != null)
{
BinaryConfiguration.MergeTypes(cfg.BinaryConfiguration);
}
else if (cfg.BinaryConfiguration != null)
{
BinaryConfiguration = new BinaryConfiguration(cfg.BinaryConfiguration);
}
JvmClasspath = cfg.JvmClasspath;
JvmOptions = cfg.JvmOptions;
Assemblies = cfg.Assemblies;
SuppressWarnings = cfg.SuppressWarnings;
LifecycleBeans = cfg.LifecycleBeans;
Logger = cfg.Logger;
JvmInitialMemoryMb = cfg.JvmInitialMemoryMb;
JvmMaxMemoryMb = cfg.JvmMaxMemoryMb;
PluginConfigurations = cfg.PluginConfigurations;
}
/// <summary>
/// Gets or sets optional local instance name.
/// <para />
/// This name only works locally and has no effect on topology.
/// <para />
/// This property is used to when there are multiple Ignite nodes in one process to distinguish them.
/// </summary>
public string IgniteInstanceName { get; set; }
/// <summary>
/// Gets or sets optional local instance name.
/// <para />
/// This name only works locally and has no effect on topology.
/// <para />
/// This property is used to when there are multiple Ignite nodes in one process to distinguish them.
/// </summary>
[Obsolete("Use IgniteInstanceName instead.")]
public string GridName
{
get { return IgniteInstanceName; }
set { IgniteInstanceName = value; }
}
/// <summary>
/// Gets or sets the binary configuration.
/// </summary>
/// <value>
/// The binary configuration.
/// </value>
public BinaryConfiguration BinaryConfiguration { get; set; }
/// <summary>
/// Gets or sets the cache configuration.
/// </summary>
/// <value>
/// The cache configuration.
/// </value>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<CacheConfiguration> CacheConfiguration { get; set; }
/// <summary>
/// URL to Spring configuration file.
/// <para />
/// Spring configuration is loaded first, then <see cref="IgniteConfiguration"/> properties are applied.
/// Null property values do not override Spring values.
/// Value-typed properties are tracked internally: if setter was not called, Spring value won't be overwritten.
/// <para />
/// This merging happens on the top level only; e. g. if there are cache configurations defined in Spring
/// and in .NET, .NET caches will overwrite Spring caches.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")]
public string SpringConfigUrl { get; set; }
/// <summary>
/// Path jvm.dll file. If not set, it's location will be determined
/// using JAVA_HOME environment variable.
/// If path is neither set nor determined automatically, an exception
/// will be thrown.
/// </summary>
public string JvmDllPath { get; set; }
/// <summary>
/// Path to Ignite home. If not set environment variable IGNITE_HOME will be used.
/// </summary>
public string IgniteHome { get; set; }
/// <summary>
/// Classpath used by JVM on Ignite start.
/// </summary>
public string JvmClasspath { get; set; }
/// <summary>
/// Collection of options passed to JVM on Ignite start.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<string> JvmOptions { get; set; }
/// <summary>
/// List of additional .Net assemblies to load on Ignite start. Each item can be either
/// fully qualified assembly name, path to assembly to DLL or path to a directory when
/// assemblies reside.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<string> Assemblies { get; set; }
/// <summary>
/// Whether to suppress warnings.
/// </summary>
public bool SuppressWarnings { get; set; }
/// <summary>
/// Lifecycle beans.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<ILifecycleBean> LifecycleBeans { get; set; }
/// <summary>
/// Initial amount of memory in megabytes given to JVM. Maps to -Xms Java option.
/// <code>-1</code> maps to JVM defaults.
/// Defaults to <see cref="DefaultJvmInitMem"/>.
/// </summary>
[DefaultValue(DefaultJvmInitMem)]
public int JvmInitialMemoryMb { get; set; }
/// <summary>
/// Maximum amount of memory in megabytes given to JVM. Maps to -Xmx Java option.
/// <code>-1</code> maps to JVM defaults.
/// Defaults to <see cref="DefaultJvmMaxMem"/>.
/// </summary>
[DefaultValue(DefaultJvmMaxMem)]
public int JvmMaxMemoryMb { get; set; }
/// <summary>
/// Gets or sets the discovery service provider.
/// Null for default discovery.
/// </summary>
public IDiscoverySpi DiscoverySpi { get; set; }
/// <summary>
/// Gets or sets the communication service provider.
/// Null for default communication.
/// </summary>
public ICommunicationSpi CommunicationSpi { get; set; }
/// <summary>
/// Gets or sets a value indicating whether node should start in client mode.
/// Client node cannot hold data in the caches.
/// </summary>
public bool ClientMode
{
get { return _clientMode ?? default(bool); }
set { _clientMode = value; }
}
/// <summary>
/// Gets or sets a set of event types (<see cref="EventType" />) to be recorded by Ignite.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<int> IncludedEventTypes { get; set; }
/// <summary>
/// Gets or sets the time after which a certain metric value is considered expired.
/// </summary>
[DefaultValue(typeof(TimeSpan), "10675199.02:48:05.4775807")]
public TimeSpan MetricsExpireTime
{
get { return _metricsExpireTime ?? DefaultMetricsExpireTime; }
set { _metricsExpireTime = value; }
}
/// <summary>
/// Gets or sets the number of metrics kept in history to compute totals and averages.
/// </summary>
[DefaultValue(DefaultMetricsHistorySize)]
public int MetricsHistorySize
{
get { return _metricsHistorySize ?? DefaultMetricsHistorySize; }
set { _metricsHistorySize = value; }
}
/// <summary>
/// Gets or sets the frequency of metrics log print out.
/// <see cref="TimeSpan.Zero"/> to disable metrics print out.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:01:00")]
public TimeSpan MetricsLogFrequency
{
get { return _metricsLogFrequency ?? DefaultMetricsLogFrequency; }
set { _metricsLogFrequency = value; }
}
/// <summary>
/// Gets or sets the job metrics update frequency.
/// <see cref="TimeSpan.Zero"/> to update metrics on job start/finish.
/// Negative value to never update metrics.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:00:02")]
public TimeSpan MetricsUpdateFrequency
{
get { return _metricsUpdateFrequency ?? DefaultMetricsUpdateFrequency; }
set { _metricsUpdateFrequency = value; }
}
/// <summary>
/// Gets or sets the network send retry count.
/// </summary>
[DefaultValue(DefaultNetworkSendRetryCount)]
public int NetworkSendRetryCount
{
get { return _networkSendRetryCount ?? DefaultNetworkSendRetryCount; }
set { _networkSendRetryCount = value; }
}
/// <summary>
/// Gets or sets the network send retry delay.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:00:01")]
public TimeSpan NetworkSendRetryDelay
{
get { return _networkSendRetryDelay ?? DefaultNetworkSendRetryDelay; }
set { _networkSendRetryDelay = value; }
}
/// <summary>
/// Gets or sets the network timeout.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:00:05")]
public TimeSpan NetworkTimeout
{
get { return _networkTimeout ?? DefaultNetworkTimeout; }
set { _networkTimeout = value; }
}
/// <summary>
/// Gets or sets the work directory.
/// If not provided, a folder under <see cref="IgniteHome"/> will be used.
/// </summary>
public string WorkDirectory { get; set; }
/// <summary>
/// Gets or sets system-wide local address or host for all Ignite components to bind to.
/// If provided it will override all default local bind settings within Ignite.
/// <para />
/// If <c>null</c> then Ignite tries to use local wildcard address.That means that all services
/// will be available on all network interfaces of the host machine.
/// <para />
/// It is strongly recommended to set this parameter for all production environments.
/// </summary>
public string Localhost { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this node should be a daemon node.
/// <para />
/// Daemon nodes are the usual grid nodes that participate in topology but not visible on the main APIs,
/// i.e. they are not part of any cluster groups.
/// <para />
/// Daemon nodes are used primarily for management and monitoring functionality that is built on Ignite
/// and needs to participate in the topology, but also needs to be excluded from the "normal" topology,
/// so that it won't participate in the task execution or in-memory data grid storage.
/// </summary>
public bool IsDaemon
{
get { return _isDaemon ?? default(bool); }
set { _isDaemon = value; }
}
/// <summary>
/// Gets or sets the user attributes for this node.
/// <para />
/// These attributes can be retrieved later via <see cref="IClusterNode.GetAttributes"/>.
/// Environment variables are added to node attributes automatically.
/// NOTE: attribute names starting with "org.apache.ignite" are reserved for internal use.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public IDictionary<string, object> UserAttributes { get; set; }
/// <summary>
/// Gets or sets the atomic data structures configuration.
/// </summary>
public AtomicConfiguration AtomicConfiguration { get; set; }
/// <summary>
/// Gets or sets the transaction configuration.
/// </summary>
public TransactionConfiguration TransactionConfiguration { get; set; }
/// <summary>
/// Gets or sets a value indicating whether late affinity assignment mode should be used.
/// <para />
/// On each topology change, for each started cache, partition-to-node mapping is
/// calculated using AffinityFunction for cache. When late
/// affinity assignment mode is disabled then new affinity mapping is applied immediately.
/// <para />
/// With late affinity assignment mode, if primary node was changed for some partition, but data for this
/// partition is not rebalanced yet on this node, then current primary is not changed and new primary
/// is temporary assigned as backup. This nodes becomes primary only when rebalancing for all assigned primary
/// partitions is finished. This mode can show better performance for cache operations, since when cache
/// primary node executes some operation and data is not rebalanced yet, then it sends additional message
/// to force rebalancing from other nodes.
/// <para />
/// Note, that <see cref="ICacheAffinity"/> interface provides assignment information taking late assignment
/// into account, so while rebalancing for new primary nodes is not finished it can return assignment
/// which differs from assignment calculated by AffinityFunction.
/// <para />
/// This property should have the same value for all nodes in cluster.
/// <para />
/// If not provided, default value is <see cref="DefaultIsLateAffinityAssignment"/>.
/// </summary>
[DefaultValue(DefaultIsLateAffinityAssignment)]
public bool IsLateAffinityAssignment
{
get { return _isLateAffinityAssignment ?? DefaultIsLateAffinityAssignment; }
set { _isLateAffinityAssignment = value; }
}
/// <summary>
/// Serializes this instance to the specified XML writer.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="rootElementName">Name of the root element.</param>
public void ToXml(XmlWriter writer, string rootElementName)
{
IgniteArgumentCheck.NotNull(writer, "writer");
IgniteArgumentCheck.NotNullOrEmpty(rootElementName, "rootElementName");
IgniteConfigurationXmlSerializer.Serialize(this, writer, rootElementName);
}
/// <summary>
/// Serializes this instance to an XML string.
/// </summary>
public string ToXml()
{
var sb = new StringBuilder();
var settings = new XmlWriterSettings
{
Indent = true
};
using (var xmlWriter = XmlWriter.Create(sb, settings))
{
ToXml(xmlWriter, "igniteConfiguration");
}
return sb.ToString();
}
/// <summary>
/// Deserializes IgniteConfiguration from the XML reader.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>Deserialized instance.</returns>
public static IgniteConfiguration FromXml(XmlReader reader)
{
IgniteArgumentCheck.NotNull(reader, "reader");
return IgniteConfigurationXmlSerializer.Deserialize(reader);
}
/// <summary>
/// Deserializes IgniteConfiguration from the XML string.
/// </summary>
/// <param name="xml">Xml string.</param>
/// <returns>Deserialized instance.</returns>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
[SuppressMessage("Microsoft.Usage", "CA2202: Do not call Dispose more than one time on an object")]
public static IgniteConfiguration FromXml(string xml)
{
IgniteArgumentCheck.NotNullOrEmpty(xml, "xml");
using (var stringReader = new StringReader(xml))
using (var xmlReader = XmlReader.Create(stringReader))
{
// Skip XML header.
xmlReader.MoveToContent();
return FromXml(xmlReader);
}
}
/// <summary>
/// Gets or sets the logger.
/// <para />
/// If no logger is set, logging is delegated to Java, which uses the logger defined in Spring XML (if present)
/// or logs to console otherwise.
/// </summary>
public ILogger Logger { get; set; }
/// <summary>
/// Gets or sets the failure detection timeout used by <see cref="TcpDiscoverySpi"/>
/// and <see cref="TcpCommunicationSpi"/>.
/// </summary>
[DefaultValue(typeof(TimeSpan), "00:00:10")]
public TimeSpan FailureDetectionTimeout
{
get { return _failureDetectionTimeout ?? DefaultFailureDetectionTimeout; }
set { _failureDetectionTimeout = value; }
}
/// <summary>
/// Gets or sets the swap space SPI.
/// </summary>
public ISwapSpaceSpi SwapSpaceSpi { get; set; }
/// <summary>
/// Gets or sets the configurations for plugins to be started.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public ICollection<IPluginConfiguration> PluginConfigurations { get; set; }
/// <summary>
/// Gets or sets the event storage interface.
/// <para />
/// Only predefined implementations are supported:
/// <see cref="NoopEventStorageSpi"/>, <see cref="MemoryEventStorageSpi"/>.
/// </summary>
public IEventStorageSpi EventStorageSpi { get; set; }
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoadRO.Business.ERCLevel
{
/// <summary>
/// B02Level1 (read only object).<br/>
/// This is a generated base class of <see cref="B02Level1"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="B03Level11Objects"/> of type <see cref="B03Level11Coll"/> (1:M relation to <see cref="B04Level11"/>)<br/>
/// This class is an item of <see cref="B01Level1Coll"/> collection.
/// </remarks>
[Serializable]
public partial class B02Level1 : ReadOnlyBase<B02Level1>
{
#region ParentList Property
/// <summary>
/// Maintains metadata about <see cref="ParentList"/> property.
/// </summary>
public static readonly PropertyInfo<B01Level1Coll> ParentListProperty = RegisterProperty<B01Level1Coll>(p => p.ParentList);
/// <summary>
/// Provide access to the parent list reference for use in child object code.
/// </summary>
/// <value>The parent list reference.</value>
public B01Level1Coll ParentList
{
get { return ReadProperty(ParentListProperty); }
internal set { LoadProperty(ParentListProperty, value); }
}
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Level_1_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Level_1_IDProperty = RegisterProperty<int>(p => p.Level_1_ID, "Level_1 ID", -1);
/// <summary>
/// Gets the Level_1 ID.
/// </summary>
/// <value>The Level_1 ID.</value>
public int Level_1_ID
{
get { return GetProperty(Level_1_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Level_1_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Level_1_NameProperty = RegisterProperty<string>(p => p.Level_1_Name, "Level_1 Name");
/// <summary>
/// Gets the Level_1 Name.
/// </summary>
/// <value>The Level_1 Name.</value>
public string Level_1_Name
{
get { return GetProperty(Level_1_NameProperty); }
}
/// <summary>
/// Maintains metadata about child <see cref="B03Level11SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<B03Level11Child> B03Level11SingleObjectProperty = RegisterProperty<B03Level11Child>(p => p.B03Level11SingleObject, "B3 Level11 Single Object");
/// <summary>
/// Gets the B03 Level11 Single Object ("parent load" child property).
/// </summary>
/// <value>The B03 Level11 Single Object.</value>
public B03Level11Child B03Level11SingleObject
{
get { return GetProperty(B03Level11SingleObjectProperty); }
private set { LoadProperty(B03Level11SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="B03Level11ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<B03Level11ReChild> B03Level11ASingleObjectProperty = RegisterProperty<B03Level11ReChild>(p => p.B03Level11ASingleObject, "B3 Level11 ASingle Object");
/// <summary>
/// Gets the B03 Level11 ASingle Object ("parent load" child property).
/// </summary>
/// <value>The B03 Level11 ASingle Object.</value>
public B03Level11ReChild B03Level11ASingleObject
{
get { return GetProperty(B03Level11ASingleObjectProperty); }
private set { LoadProperty(B03Level11ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="B03Level11Objects"/> property.
/// </summary>
public static readonly PropertyInfo<B03Level11Coll> B03Level11ObjectsProperty = RegisterProperty<B03Level11Coll>(p => p.B03Level11Objects, "B3 Level11 Objects");
/// <summary>
/// Gets the B03 Level11 Objects ("parent load" child property).
/// </summary>
/// <value>The B03 Level11 Objects.</value>
public B03Level11Coll B03Level11Objects
{
get { return GetProperty(B03Level11ObjectsProperty); }
private set { LoadProperty(B03Level11ObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Loads a <see cref="B02Level1"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="B02Level1"/> object.</returns>
internal static B02Level1 GetB02Level1(SafeDataReader dr)
{
B02Level1 obj = new B02Level1();
obj.Fetch(dr);
obj.LoadProperty(B03Level11ObjectsProperty, new B03Level11Coll());
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="B02Level1"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private B02Level1()
{
// Prevent direct creation
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="B02Level1"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Level_1_IDProperty, dr.GetInt32("Level_1_ID"));
LoadProperty(Level_1_NameProperty, dr.GetString("Level_1_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
internal void FetchChildren(SafeDataReader dr)
{
dr.NextResult();
while (dr.Read())
{
var child = B03Level11Child.GetB03Level11Child(dr);
var obj = ParentList.FindB02Level1ByParentProperties(child.cParentID1);
obj.LoadProperty(B03Level11SingleObjectProperty, child);
}
dr.NextResult();
while (dr.Read())
{
var child = B03Level11ReChild.GetB03Level11ReChild(dr);
var obj = ParentList.FindB02Level1ByParentProperties(child.cParentID2);
obj.LoadProperty(B03Level11ASingleObjectProperty, child);
}
dr.NextResult();
var b03Level11Coll = B03Level11Coll.GetB03Level11Coll(dr);
b03Level11Coll.LoadItems(ParentList);
dr.NextResult();
while (dr.Read())
{
var child = B05Level111ReChild.GetB05Level111ReChild(dr);
var obj = b03Level11Coll.FindB04Level11ByParentProperties(child.cMarentID2);
obj.LoadChild(child);
}
dr.NextResult();
while (dr.Read())
{
var child = B05Level111Child.GetB05Level111Child(dr);
var obj = b03Level11Coll.FindB04Level11ByParentProperties(child.cMarentID1);
obj.LoadChild(child);
}
dr.NextResult();
var b05Level111Coll = B05Level111Coll.GetB05Level111Coll(dr);
b05Level111Coll.LoadItems(b03Level11Coll);
dr.NextResult();
while (dr.Read())
{
var child = B07Level1111Child.GetB07Level1111Child(dr);
var obj = b05Level111Coll.FindB06Level111ByParentProperties(child.cLarentID1);
obj.LoadChild(child);
}
dr.NextResult();
while (dr.Read())
{
var child = B07Level1111ReChild.GetB07Level1111ReChild(dr);
var obj = b05Level111Coll.FindB06Level111ByParentProperties(child.cLarentID2);
obj.LoadChild(child);
}
dr.NextResult();
var b07Level1111Coll = B07Level1111Coll.GetB07Level1111Coll(dr);
b07Level1111Coll.LoadItems(b05Level111Coll);
dr.NextResult();
while (dr.Read())
{
var child = B09Level11111Child.GetB09Level11111Child(dr);
var obj = b07Level1111Coll.FindB08Level1111ByParentProperties(child.cNarentID1);
obj.LoadChild(child);
}
dr.NextResult();
while (dr.Read())
{
var child = B09Level11111ReChild.GetB09Level11111ReChild(dr);
var obj = b07Level1111Coll.FindB08Level1111ByParentProperties(child.cNarentID2);
obj.LoadChild(child);
}
dr.NextResult();
var b09Level11111Coll = B09Level11111Coll.GetB09Level11111Coll(dr);
b09Level11111Coll.LoadItems(b07Level1111Coll);
dr.NextResult();
while (dr.Read())
{
var child = B11Level111111Child.GetB11Level111111Child(dr);
var obj = b09Level11111Coll.FindB10Level11111ByParentProperties(child.cQarentID1);
obj.LoadChild(child);
}
dr.NextResult();
while (dr.Read())
{
var child = B11Level111111ReChild.GetB11Level111111ReChild(dr);
var obj = b09Level11111Coll.FindB10Level11111ByParentProperties(child.cQarentID2);
obj.LoadChild(child);
}
dr.NextResult();
var b11Level111111Coll = B11Level111111Coll.GetB11Level111111Coll(dr);
b11Level111111Coll.LoadItems(b09Level11111Coll);
}
#endregion
#region Pseudo Events
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using Jovian.Tools.Support;
namespace Jovian.Tools.Formating
{
/// <summary>
/// Summary description for BraceBased.
/// </summary>
public class TabBraces : Formatter
{
public string apply(rtfDocument doc)
{
System.IO.StringWriter total = new System.IO.StringWriter();
string line = "";
int tabLevel = 0;
for(int k = 0; k < doc.NumLines(); k++)
{
rtfLine L = doc.lineAt(k);
bool initWS = false;
line = "";
for(int j = 0; j < tabLevel - 1; j++)
{
line += "" + (char)9;
}
for(int j = 0; j < L.Length(); j++)
{
rtfChar C = L.charAt(j);
bool handled = false;
if(Char.IsWhiteSpace(C.v))
{
handled = true;
if(initWS)
{
line += "" + C.v;
}
}
else
{
if(!initWS && tabLevel > 0)
{
if(!(C.v == '}' && C.s == 0))
{
line += "" + (char)9;
}
}
initWS = true;
}
if(!handled)
{
line += C.v;
if(C.s == 0 && C.v == '{')
{
tabLevel++;
}
if(C.s == 0 && C.v == '}')
{
tabLevel--;
}
}
}
total.WriteLine(line.TrimEnd());
}
string Total = total.ToString();
return Total;
}
}
public class ExplodeBraces : Formatter
{
public string apply(rtfDocument doc)
{
System.IO.StringWriter total = new System.IO.StringWriter();
string line = "";
for(int k = 0; k < doc.NumLines(); k++)
{
rtfLine L = doc.lineAt(k);
line = "";
for(int j = 0; j < L.Length(); j++)
{
rtfChar C = L.charAt(j);
if((C.v == '}' || C.v == '{') && C.s == 0)
{
line += total.NewLine + C.v + total.NewLine;
}
else
{
line += C.v;
}
}
line = line.Trim();
total.WriteLine(line.TrimEnd());
}
string Total = total.ToString();
int S = Total.Length;
Total = Total.Replace(total.NewLine + total.NewLine, total.NewLine);
while(Total.Length != S)
{
S = Total.Length;
Total = Total.Replace(total.NewLine + total.NewLine, total.NewLine);
}
return Total;
}
}
public class CollapseBraces : Formatter
{
public string apply(rtfDocument doc)
{
System.IO.StringWriter T = new System.IO.StringWriter();
for(int k = 0; k < doc.NumLines(); k++)
{
rtfLine L = doc.lineAt(k);
if(L.Length() > 0)
{
string str = L.ExtractAll();
if(L.charAt(L.Length() - 1).s == 0)
{
if(k + 1 < doc.NumLines())
{
string nxt = doc.lineAt(k+1).ExtractAll().Trim();
if(nxt.Equals("{"))
{
str += nxt;
k++;
}
else
{
if(str.Trim().Equals("}"))
{
if(nxt.Equals(";") || nxt.Equals(","))
{
str += nxt;
k++;
}
}
}
}
}
T.WriteLine(str);
}
}
return T.ToString();
/*
string x = doc.GetTEXT();
int S = x.Length;
x = x.Replace(((char)9) + "{","{");
while(S != x.Length)
{
S = x.Length;
x = x.Replace(((char)9) + "{","{");
}
x = x.Replace(T.NewLine + "{"," {");
return x;
*/
}
}
public class CollapseExtraNewlines : Formatter
{
#region Formatter Members
public string apply(rtfDocument doc)
{
System.IO.StringWriter total = new System.IO.StringWriter();
string Total = doc.GetTEXT();
int S = Total.Length;
Total = Total.Replace(total.NewLine + total.NewLine, total.NewLine);
while(Total.Length != S)
{
S = Total.Length;
Total = Total.Replace(total.NewLine + total.NewLine, total.NewLine);
}
return Total;
}
#endregion
}
public class ExtractStrings : Formatter
{
#region Formatter Members
public string Strings;
public ExtractStrings()
{
Strings = "";
}
public string apply(rtfDocument doc)
{
System.IO.StringWriter T = new System.IO.StringWriter();
for(int k = 0; k < doc.NumLines(); k++)
{
rtfLine L = doc.lineAt(k);
string txt = "";
for(int j = 0; j < L.Length(); j++)
{
rtfChar C = L.charAt(j);
if(C.s == 3)
{
txt += C.v;
}
else
{
if(txt.Length > 0)
{
if(txt.Length >= 2)
{
txt = txt.Substring(0,txt.Length - 1).Substring(1);
if(txt.Length > 0)
{
T.WriteLine(txt);
}
}
txt = "";
}
}
}
if(txt.Length > 0)
{
T.WriteLine(txt);
txt = "";
}
}
Strings = T.ToString();
return Strings;
}
#endregion
}
public class CollapseExtraSpaces : Formatter
{
#region Formatter Members
public string apply(rtfDocument doc)
{
string Total = doc.GetTEXT();
int S = Total.Length;
Total = Total.Replace(" ", " ");
while(Total.Length != S)
{
S = Total.Length;
Total = Total.Replace(" ", " ");
Total = Total.Replace(" ", " ");
}
return Total;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ExpressiveExpressionTrees.Tests.ExpressionVisitorTest
{
[TestClass]
public class TryCatchVisitorTests
{
[TestMethod]
public void Test001()
{
var e1 = Expression.Default(typeof(int));
var e2 = Expression.Parameter(typeof(Exception));
var e3 = Expression.Constant(10, typeof(int));
var e4 = Expression.Catch(e2, e3);
var e5 = Expression.TryCatch(e1, e4);
var assert = ExpressionVisitorVerifierTool.Test(e5);
assert.WasVisited(e1);
assert.WasProduced(e1);
assert.WasVisited(e2);
assert.WasProduced(e2);
assert.WasVisited(e3);
assert.WasProduced(e3);
assert.WasVisited(e5);
assert.WasProduced(e5);
// fault, finally, and catch block filter
assert.WasVisited(null, 3);
assert.WasProduced(null, 3);
assert.TotalVisits(7);
assert.TotalProduced(7);
var cbResult = (TryExpression)assert.Result;
Assert.AreEqual(cbResult.Handlers[0], e4);
}
[TestMethod]
public void Test002()
{
var e1 = Expression.Constant(10, typeof(int));
var e2 = Expression.Parameter(typeof(Exception));
var e3 = Expression.Constant(11, typeof(int));
var e4 = Expression.Catch(e2, e3);
var e6 = Expression.Parameter(typeof(NullReferenceException));
var e7 = Expression.Constant(13, typeof(int));
var e8 = Expression.Catch(e6, e7);
var e9 = Expression.TryCatch(e1, e4, e8);
var assert = ExpressionVisitorVerifierTool.Test(e9);
assert.WasVisited(e1);
assert.WasProduced(e1);
assert.WasVisited(e2);
assert.WasProduced(e2);
assert.WasVisited(e3);
assert.WasProduced(e3);
assert.WasVisited(e6);
assert.WasProduced(e6);
assert.WasVisited(e7);
assert.WasProduced(e7);
assert.WasVisited(e9);
assert.WasProduced(e9);
// fault, finally, and 2x catch block filter
assert.WasVisited(null, 4);
assert.WasProduced(null, 4);
assert.TotalVisits(10);
assert.TotalProduced(10);
var cbResult = (TryExpression)assert.Result;
Assert.AreEqual(cbResult.Handlers[0], e4);
Assert.AreEqual(cbResult.Handlers[1], e8);
}
[TestMethod]
public void Test003()
{
var e1 = Expression.Constant(10, typeof(int));
var e2 = Expression.Parameter(typeof(Exception));
var e3 = Expression.Constant(11, typeof(int));
var e4 = Expression.Catch(e2, e3);
var e6 = Expression.Parameter(typeof(NullReferenceException));
var e7 = Expression.Constant(13, typeof(int));
var e8 = Expression.Catch(e6, e7);
var e10 = Expression.Parameter(typeof(AggregateException));
var e11 = Expression.Constant(15, typeof(int));
var e12 = Expression.Catch(e10, e11);
var e14 = Expression.TryCatch(e1, e4, e8, e12);
var assert = ExpressionVisitorVerifierTool.Test(e14);
assert.WasVisited(e1);
assert.WasProduced(e1);
assert.WasVisited(e2);
assert.WasProduced(e2);
assert.WasVisited(e3);
assert.WasProduced(e3);
assert.WasVisited(e6);
assert.WasProduced(e6);
assert.WasVisited(e7);
assert.WasProduced(e7);
assert.WasVisited(e10);
assert.WasProduced(e10);
assert.WasVisited(e11);
assert.WasProduced(e11);
assert.WasVisited(e14);
assert.WasProduced(e14);
// fault, finally, and 3x catch block filter
assert.WasVisited(null, 5);
assert.WasProduced(null, 5);
assert.TotalVisits(13);
assert.TotalProduced(13);
var cbResult = (TryExpression)assert.Result;
Assert.AreEqual(cbResult.Handlers[0], e4);
Assert.AreEqual(cbResult.Handlers[1], e8);
Assert.AreEqual(cbResult.Handlers[2], e12);
}
[TestMethod]
public void Test011()
{
var e1 = Expression.Constant(9, typeof(int));
var e2 = Expression.Parameter(typeof(Exception));
var e3 = Expression.Constant(10, typeof(int));
var e4 = Expression.Catch(e2, e3);
var e6 = Expression.Constant(20, typeof(int));
var e5 = Expression.TryCatchFinally(e1, e6, e4);
var assert = ExpressionVisitorVerifierTool.Test(e5);
assert.WasVisited(e1);
assert.WasProduced(e1);
assert.WasVisited(e2);
assert.WasProduced(e2);
assert.WasVisited(e3);
assert.WasProduced(e3);
assert.WasVisited(e6);
assert.WasProduced(e6);
assert.WasVisited(e5);
assert.WasProduced(e5);
// fault and catch block filter
assert.WasVisited(null, 2);
assert.WasProduced(null, 2);
assert.TotalVisits(7);
assert.TotalProduced(7);
}
[TestMethod]
public void Test012()
{
var e1 = Expression.Constant(10, typeof(int));
var e2 = Expression.Parameter(typeof(Exception));
var e3 = Expression.Constant(11, typeof(int));
var e4 = Expression.Catch(e2, e3);
var e6 = Expression.Parameter(typeof(NullReferenceException));
var e7 = Expression.Constant(13, typeof(int));
var e8 = Expression.Catch(e6, e7);
var e11 = Expression.Constant(20, typeof(int));
var e9 = Expression.TryCatchFinally(e1, e11, e4, e8);
var assert = ExpressionVisitorVerifierTool.Test(e9);
assert.WasVisited(e1);
assert.WasProduced(e1);
assert.WasVisited(e2);
assert.WasProduced(e2);
assert.WasVisited(e3);
assert.WasProduced(e3);
assert.WasVisited(e6);
assert.WasProduced(e6);
assert.WasVisited(e7);
assert.WasProduced(e7);
assert.WasVisited(e11);
assert.WasProduced(e11);
assert.WasVisited(e9);
assert.WasProduced(e9);
// fault and 2x catch block filter
assert.WasVisited(null, 3);
assert.WasProduced(null, 3);
assert.TotalVisits(10);
assert.TotalProduced(10);
}
[TestMethod]
public void Test013()
{
var e1 = Expression.Constant(10, typeof(int));
var e2 = Expression.Parameter(typeof(Exception));
var e3 = Expression.Constant(11, typeof(int));
var e4 = Expression.Catch(e2, e3);
var e6 = Expression.Parameter(typeof(NullReferenceException));
var e7 = Expression.Constant(13, typeof(int));
var e8 = Expression.Catch(e6, e7);
var e10 = Expression.Parameter(typeof(AggregateException));
var e11 = Expression.Constant(15, typeof(int));
var e12 = Expression.Catch(e10, e11);
var e13 = Expression.Constant(20, typeof(int));
var e14 = Expression.TryCatchFinally(e1, e13, e4, e8, e12);
var assert = ExpressionVisitorVerifierTool.Test(e14);
assert.WasVisited(e1);
assert.WasProduced(e1);
assert.WasVisited(e2);
assert.WasProduced(e2);
assert.WasVisited(e3);
assert.WasProduced(e3);
assert.WasVisited(e6);
assert.WasProduced(e6);
assert.WasVisited(e7);
assert.WasProduced(e7);
assert.WasVisited(e10);
assert.WasProduced(e10);
assert.WasVisited(e11);
assert.WasProduced(e11);
assert.WasVisited(e13);
assert.WasProduced(e13);
assert.WasVisited(e14);
assert.WasProduced(e14);
// fault and 3x catch block filter
assert.WasVisited(null, 4);
assert.WasProduced(null, 4);
assert.TotalVisits(13);
assert.TotalProduced(13);
}
[TestMethod]
public void Test021()
{
var e1 = Expression.Constant(1, typeof(int));
var e2 = Expression.Constant(2, typeof(int));
var e5 = Expression.TryFinally(e1, e2);
var assert = ExpressionVisitorVerifierTool.Test(e5);
assert.WasVisited(e1);
assert.WasProduced(e1);
assert.WasVisited(e2);
assert.WasProduced(e2);
assert.WasVisited(e5);
assert.WasProduced(e5);
// fault
assert.WasVisited(null, 1);
assert.WasProduced(null, 1);
assert.TotalVisits(4);
assert.TotalProduced(4);
}
[TestMethod]
public void Test022()
{
var e1 = Expression.Constant(1, typeof(int));
var e2 = Expression.Constant(2, typeof(int));
var e5 = Expression.TryFault(e1, e2);
var assert = ExpressionVisitorVerifierTool.Test(e5);
assert.WasVisited(e1);
assert.WasProduced(e1);
assert.WasVisited(e2);
assert.WasProduced(e2);
assert.WasVisited(e5);
assert.WasProduced(e5);
// finally
assert.WasVisited(null, 1);
assert.WasProduced(null, 1);
assert.TotalVisits(4);
assert.TotalProduced(4);
}
[TestMethod]
public void Test031()
{
var e1 = Expression.Default(typeof(int));
var e2 = Expression.Parameter(typeof(Exception));
var e2n = Expression.Parameter(typeof(Exception));
var e3 = Expression.Constant(10, typeof(int));
var e6 = Expression.Constant(true, typeof(bool));
var e4 = Expression.Catch(e2, e3, e6);
var e5 = Expression.TryCatch(e1, e4);
var replacer = new Dictionary<Expression,Expression> {
{ e2, e2n }
};
var assert = ExpressionVisitorVerifierTool.Test(e5, replacer);
assert.WasVisited(e1);
assert.WasProduced(e1);
assert.WasVisited(e2);
assert.WasNotProduced(e2);
assert.WasProduced(e2n);
assert.WasVisited(e3);
assert.WasProduced(e3);
assert.WasVisited(e6);
assert.WasProduced(e6);
assert.WasVisited(e5);
assert.WasNotProduced(e5);
assert.WasProduced(assert.Result);
// fault, finally
assert.WasVisited(null, 2);
assert.WasProduced(null, 2);
assert.TotalVisits(7);
assert.TotalProduced(7);
}
[TestMethod]
public void Test032()
{
var e1 = Expression.Default(typeof(int));
var e2 = Expression.Parameter(typeof(Exception));
var e3 = Expression.Constant(10, typeof(int));
var e3n = Expression.Constant(14, typeof(int));
var e6 = Expression.Constant(true, typeof(bool));
var e4 = Expression.Catch(e2, e3, e6);
var e5 = Expression.TryCatch(e1, e4);
var replacer = new Dictionary<Expression,Expression> {
{ e3, e3n }
};
var assert = ExpressionVisitorVerifierTool.Test(e5, replacer);
assert.WasVisited(e1);
assert.WasProduced(e1);
assert.WasVisited(e2);
assert.WasProduced(e2);
assert.WasVisited(e3);
assert.WasNotProduced(e3);
assert.WasProduced(e3n);
assert.WasVisited(e6);
assert.WasProduced(e6);
assert.WasVisited(e5);
assert.WasNotProduced(e5);
assert.WasProduced(assert.Result);
// fault, finally
assert.WasVisited(null, 2);
assert.WasProduced(null, 2);
assert.TotalVisits(7);
assert.TotalProduced(7);
}
[TestMethod]
public void Test033()
{
var e1 = Expression.Default(typeof(int));
var e2 = Expression.Parameter(typeof(Exception));
var e3 = Expression.Constant(10, typeof(int));
var e6 = Expression.Constant(true, typeof(bool));
var e6n = Expression.Constant(false, typeof(bool));
var e4 = Expression.Catch(e2, e3, e6);
var e5 = Expression.TryCatch(e1, e4);
var replacer = new Dictionary<Expression,Expression> {
{ e6, e6n }
};
var assert = ExpressionVisitorVerifierTool.Test(e5, replacer);
assert.WasVisited(e1);
assert.WasProduced(e1);
assert.WasVisited(e2);
assert.WasProduced(e2);
assert.WasVisited(e3);
assert.WasProduced(e3);
assert.WasVisited(e6);
assert.WasNotProduced(e6);
assert.WasProduced(e6n);
assert.WasVisited(e5);
assert.WasNotProduced(e5);
assert.WasProduced(assert.Result);
// fault, finally
assert.WasVisited(null, 2);
assert.WasProduced(null, 2);
assert.TotalVisits(7);
assert.TotalProduced(7);
}
[TestMethod]
public void Test041()
{
var e1 = Expression.Constant(10, typeof(int));
var e2 = Expression.Parameter(typeof(Exception));
var e3 = Expression.Constant(11, typeof(int));
var e4 = Expression.Catch(e2, e3);
var e4n = Expression.Catch(e2, e3);
var e6 = Expression.Parameter(typeof(NullReferenceException));
var e7 = Expression.Constant(13, typeof(int));
var e8 = Expression.Catch(e6, e7);
var e10 = Expression.Parameter(typeof(AggregateException));
var e11 = Expression.Constant(15, typeof(int));
var e12 = Expression.Catch(e10, e11);
var e14 = Expression.TryCatch(e1, e4, e8, e12);
var assert = ExpressionVisitorVerifierTool.Create();
assert.CatchBlockReplace.Add(e4, e4n);
assert.Execute(e14);
assert.WasVisited(e1);
assert.WasProduced(e1);
assert.WasVisited(e2);
assert.WasProduced(e2);
assert.WasVisited(e3);
assert.WasProduced(e3);
assert.WasVisited(e6);
assert.WasProduced(e6);
assert.WasVisited(e7);
assert.WasProduced(e7);
assert.WasVisited(e10);
assert.WasProduced(e10);
assert.WasVisited(e11);
assert.WasProduced(e11);
assert.WasVisited(e14);
assert.WasNotProduced(e14);
assert.WasProduced(assert.Result);
// fault, finally, and 3x catch block filter
assert.WasVisited(null, 5);
assert.WasProduced(null, 5);
assert.TotalVisits(13);
assert.TotalProduced(13);
var cbResult = (TryExpression)assert.Result;
Assert.AreEqual(cbResult.Handlers[0], e4n);
Assert.AreEqual(cbResult.Handlers[1], e8);
Assert.AreEqual(cbResult.Handlers[2], e12);
}
[TestMethod]
public void Test042()
{
var e1 = Expression.Constant(10, typeof(int));
var e2 = Expression.Parameter(typeof(Exception));
var e3 = Expression.Constant(11, typeof(int));
var e4 = Expression.Catch(e2, e3);
var e6 = Expression.Parameter(typeof(NullReferenceException));
var e7 = Expression.Constant(13, typeof(int));
var e8 = Expression.Catch(e6, e7);
var e8n = Expression.Catch(e6, e7);
var e10 = Expression.Parameter(typeof(AggregateException));
var e11 = Expression.Constant(15, typeof(int));
var e12 = Expression.Catch(e10, e11);
var e14 = Expression.TryCatch(e1, e4, e8, e12);
var assert = ExpressionVisitorVerifierTool.Create();
assert.CatchBlockReplace.Add(e8, e8n);
assert.Execute(e14);
assert.WasVisited(e1);
assert.WasProduced(e1);
assert.WasVisited(e2);
assert.WasProduced(e2);
assert.WasVisited(e3);
assert.WasProduced(e3);
assert.WasVisited(e6);
assert.WasProduced(e6);
assert.WasVisited(e7);
assert.WasProduced(e7);
assert.WasVisited(e10);
assert.WasProduced(e10);
assert.WasVisited(e11);
assert.WasProduced(e11);
assert.WasVisited(e14);
assert.WasNotProduced(e14);
assert.WasProduced(assert.Result);
// fault, finally, and 3x catch block filter
assert.WasVisited(null, 5);
assert.WasProduced(null, 5);
assert.TotalVisits(13);
assert.TotalProduced(13);
var cbResult = (TryExpression)assert.Result;
Assert.AreEqual(cbResult.Handlers[0], e4);
Assert.AreEqual(cbResult.Handlers[1], e8n);
Assert.AreEqual(cbResult.Handlers[2], e12);
}
[TestMethod]
public void Test043()
{
var e1 = Expression.Constant(10, typeof(int));
var e2 = Expression.Parameter(typeof(Exception));
var e3 = Expression.Constant(11, typeof(int));
var e4 = Expression.Catch(e2, e3);
var e6 = Expression.Parameter(typeof(NullReferenceException));
var e7 = Expression.Constant(13, typeof(int));
var e8 = Expression.Catch(e6, e7);
var e10 = Expression.Parameter(typeof(AggregateException));
var e11 = Expression.Constant(15, typeof(int));
var e12 = Expression.Catch(e10, e11);
var e12n = Expression.Catch(e10, e11);
var e14 = Expression.TryCatch(e1, e4, e8, e12);
var assert = ExpressionVisitorVerifierTool.Create();
assert.CatchBlockReplace.Add(e12, e12n);
assert.Execute(e14);
assert.WasVisited(e1);
assert.WasProduced(e1);
assert.WasVisited(e2);
assert.WasProduced(e2);
assert.WasVisited(e3);
assert.WasProduced(e3);
assert.WasVisited(e6);
assert.WasProduced(e6);
assert.WasVisited(e7);
assert.WasProduced(e7);
assert.WasVisited(e10);
assert.WasProduced(e10);
assert.WasVisited(e11);
assert.WasProduced(e11);
assert.WasVisited(e14);
assert.WasNotProduced(e14);
assert.WasProduced(assert.Result);
// fault, finally, and 3x catch block filter
assert.WasVisited(null, 5);
assert.WasProduced(null, 5);
assert.TotalVisits(13);
assert.TotalProduced(13);
var cbResult = (TryExpression)assert.Result;
Assert.AreEqual(cbResult.Handlers[0], e4);
Assert.AreEqual(cbResult.Handlers[1], e8);
Assert.AreEqual(cbResult.Handlers[2], e12n);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
public class RelativisticParent : MonoBehaviour {
//Keep track of our own Mesh Filter
private MeshFilter meshFilter;
//Store this object's velocity here.
public Vector3 viw;
private GameState state;
//When was this object created? use for moving objects
private float startTime = 0;
//When should we die? again, for moving objects
private float deathTime = 0;
// Get the start time of our object, so that we know where not to draw it
public void SetStartTime()
{
startTime = (float) GameObject.FindGameObjectWithTag("Player").GetComponent<GameState>().TotalTimeWorld;
}
//Set the death time, so that we know at what point to destroy the object in the player's view point.
public void SetDeathTime()
{
deathTime = (float)state.TotalTimeWorld;
}
//This is a function that just ensures we're slower than our maximum speed. The VIW that Unity sets SHOULD (it's creator-chosen) be smaller than the maximum speed.
private void checkSpeed()
{
if (viw.magnitude > state.MaxSpeed-.01)
{
viw = viw.normalized * (float)(state.MaxSpeed-.01f);
}
}
// Use this for initialization
void Start()
{
if (GetComponent<ObjectMeshDensity>())
{
GetComponent<ObjectMeshDensity>().enabled = false;
}
int vertCount = 0, triangleCount = 0;
checkSpeed ();
Matrix4x4 worldLocalMatrix = transform.worldToLocalMatrix;
//This code combines the meshes of children of parent objects
//This increases our FPS by a ton
//Get an array of the meshfilters
MeshFilter[] meshFilters = GetComponentsInChildren<MeshFilter>();
//Count submeshes
int[] subMeshCount = new int[meshFilters.Length];
//Get all the meshrenderers
MeshRenderer[] meshRenderers = GetComponentsInChildren<MeshRenderer>();
//Length of our original array
int meshFilterLength = meshFilters.Length;
//And a counter
int subMeshCounts = 0;
//For every meshfilter,
for (int y = 0; y < meshFilterLength; y++)
{
//If it's null, ignore it.
if (meshFilters[y] == null) continue;
if (meshFilters[y].sharedMesh == null) continue;
//else add its vertices to the vertcount
vertCount += meshFilters[y].sharedMesh.vertices.Length;
//Add its triangles to the count
triangleCount += meshFilters[y].sharedMesh.triangles.Length;
//Add the number of submeshes to its spot in the array
subMeshCount[y] = meshFilters[y].mesh.subMeshCount;
//And add up the total number of submeshes
subMeshCounts += meshFilters[y].mesh.subMeshCount;
}
// Get a temporary array of EVERY vertex
Vector3[] tempVerts = new Vector3[vertCount];
//And make a triangle array for every submesh
int[][] tempTriangles = new int[subMeshCounts][];
for (int u = 0; u < subMeshCounts; u++)
{
//Make every array the correct length of triangles
tempTriangles[u] = new int[triangleCount];
}
//Also grab our UV texture coordinates
Vector2[] tempUVs = new Vector2[vertCount];
//And store a number of materials equal to the number of submeshes.
Material[] tempMaterials = new Material[subMeshCounts];
int vertIndex = 0;
Mesh MFs;
int subMeshIndex = 0;
//For all meshfilters
for (int i = 0; i < meshFilterLength; i++)
{
//just doublecheck that the mesh isn't null
MFs = meshFilters[i].sharedMesh;
if (MFs == null) continue;
//Otherwise, for all submeshes in the current mesh
for (int q = 0; q < subMeshCount[i]; q++)
{
//grab its material
tempMaterials[subMeshIndex] = meshRenderers[i].materials[q];
//Grab its triangles
int[] tempSubTriangles = MFs.GetTriangles(q);
//And put them into the submesh's triangle array
for (int k = 0; k < tempSubTriangles.Length; k++)
{
tempTriangles[subMeshIndex][k] = tempSubTriangles[k] + vertIndex;
}
//Increment the submesh index
subMeshIndex++;
}
Matrix4x4 cTrans = worldLocalMatrix * meshFilters[i].transform.localToWorldMatrix;
//For all the vertices in the mesh
for (int v = 0; v < MFs.vertices.Length; v++)
{
//Get the vertex and the UV coordinate
tempVerts[vertIndex] = cTrans.MultiplyPoint3x4(MFs.vertices[v]);
tempUVs[vertIndex] = MFs.uv[v];
vertIndex++;
}
//And delete that gameobject.
meshFilters[i].gameObject.SetActive(false);
}
//Put it all together now.
Mesh myMesh = new Mesh();
//Make the mesh have as many submeshes as you need
myMesh.subMeshCount = subMeshCounts;
//Set its vertices to tempverts
myMesh.vertices = tempVerts;
//start at the first submesh
subMeshIndex = 0;
//For every submesh in each meshfilter
for (int l = 0; l < meshFilterLength; l++)
{
for (int g = 0; g < subMeshCount[l]; g++)
{
//Set a new submesh, using the triangle array and its submesh index (built in unity function)
myMesh.SetTriangles(tempTriangles[subMeshIndex], subMeshIndex);
//increment the submesh index
subMeshIndex++;
}
}
//Just shunt in the UV coordinates, we don't need to change them
myMesh.uv = tempUVs;
//THEN totally replace our object's mesh with this new, combined mesh
GetComponent<MeshFilter>().mesh = myMesh;
GetComponent<MeshRenderer>().enabled = true;
GetComponent<MeshFilter>().mesh.RecalculateNormals();
GetComponent<MeshFilter>().renderer.materials = tempMaterials;
transform.gameObject.SetActive(true);
//End section of combining meshes
state = GameObject.FindGameObjectWithTag("Player").GetComponent<GameState>();
meshFilter = GetComponent<MeshFilter>();
MeshRenderer tempRenderer = GetComponent<MeshRenderer>();
//Then the standard RelativisticObject startup
if (tempRenderer.materials[0].mainTexture != null)
{
//So that we can set unique values to every moving object, we have to instantiate a material
//It's the same as our old one, but now it's not connected to every other object with the same material
Material quickSwapMaterial = Instantiate((tempRenderer as Renderer).materials[0]) as Material;
//Then, set the value that we want
quickSwapMaterial.SetFloat("_viw", 0);
//And stick it back into our renderer. We'll do the SetVector thing every frame.
tempRenderer.materials[0] = quickSwapMaterial;
//set our start time and start position in the shader.
tempRenderer.materials[0].SetFloat("_strtTime", (float)startTime);
tempRenderer.materials[0].SetVector("_strtPos", new Vector4(transform.position.x, transform.position.y, transform.position.z, 0));
}
//This code is a hack to ensure that frustrum culling does not take place
//It changes the render bounds so that everything is contained within them
Transform camTransform = Camera.main.transform;
float distToCenter = (Camera.main.farClipPlane - Camera.main.nearClipPlane) / 2.0f;
Vector3 center = camTransform.position + camTransform.forward * distToCenter;
float extremeBound = 500000.0f;
meshFilter.sharedMesh.bounds = new Bounds(center, Vector3.one * extremeBound);
if (GetComponent<ObjectMeshDensity>())
{
GetComponent<ObjectMeshDensity>().enabled = true;
}
}
// Update is called once per frame
void Update()
{
//Grab our renderer.
MeshRenderer tempRenderer = GetComponent<MeshRenderer>();
if (meshFilter != null && !state.MovementFrozen)
{
//Send our object's v/c (Velocity over the Speed of Light) to the shader
if (tempRenderer != null)
{
Vector3 tempViw = viw / (float)state.SpeedOfLight;
tempRenderer.materials[0].SetVector("_viw", new Vector4(tempViw.x, tempViw.y, tempViw.z, 0));
}
//As long as our object is actually alive, perform these calculations
if (transform!=null && deathTime != 0)
{
//Here I take the angle that the player's velocity vector makes with the z axis
float rotationAroundZ = 57.2957795f * Mathf.Acos(Vector3.Dot(state.rigid.vitesse, Vector3.forward) / state.rigid.vitesse.magnitude);
if (state.rigid.vitesse.sqrMagnitude == 0)
{
rotationAroundZ = 0;
}
//Now we turn that rotation into a quaternion
Quaternion rotateZ = Quaternion.AngleAxis(-rotationAroundZ, Vector3.Cross(state.rigid.vitesse,Vector3.forward));
//******************************************************************
//Place the vertex to be changed in a new Vector3
Vector3 riw = new Vector3(transform.position.x, transform.position.y, transform.position.z);
riw -= state.playerTransform.position;
//And we rotate our point that much to make it as if our magnitude of velocity is in the Z direction
riw = rotateZ * riw;
//Here begins the original code, made by the guys behind the Relativity game
/****************************
* Start Part 6 Bullet 1
*/
//Rotate that velocity!
Vector3 storedViw = rotateZ * viw;
float c = -Vector3.Dot(riw, riw); //first get position squared (position doted with position)
float b = -(2 * Vector3.Dot(riw, storedViw)); //next get position doted with velocity, should be only in the Z direction
float a = (float)state.SpeedOfLightSqrd - Vector3.Dot(storedViw, storedViw);
/****************************
* Start Part 6 Bullet 2
* **************************/
float tisw = (float)(((-b - (Math.Sqrt((b * b) - 4f * a * c))) / (2f * a)));
//If we're past our death time (in the player's view, as seen by tisw)
if (state.TotalTimeWorld + tisw > deathTime)
{
Destroy(this.gameObject);
}
}
//make our rigidbody's velocity viw
if (GetComponent<Rigidbody>()!=null)
{
if (!double.IsNaN((double)state.SqrtOneMinusVSquaredCWDividedByCSquared) && (float)state.SqrtOneMinusVSquaredCWDividedByCSquared != 0)
{
Vector3 tempViw = viw;
//ASK RYAN WHY THESE WERE DIVIDED BY THIS
tempViw.x /= (float)state.SqrtOneMinusVSquaredCWDividedByCSquared;
tempViw.y /= (float)state.SqrtOneMinusVSquaredCWDividedByCSquared;
tempViw.z /= (float)state.SqrtOneMinusVSquaredCWDividedByCSquared;
GetComponent<Rigidbody>().velocity = tempViw;
}
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Composition;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.SolutionCrawler
{
public class WorkCoordinatorTests
{
private const string SolutionCrawler = "SolutionCrawler";
[Fact]
public void RegisterService()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var registrationService = new SolutionCrawlerRegistrationService(
SpecializedCollections.EmptyEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>(),
AggregateAsynchronousOperationListener.EmptyListeners);
// register and unregister workspace to the service
registrationService.Register(workspace);
registrationService.Unregister(workspace);
}
}
[Fact, WorkItem(747226)]
public void SolutionAdded_Simple()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solutionId = SolutionId.CreateNewId();
var projectId = ProjectId.CreateNewId();
var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(),
projects: new[]
{
ProjectInfo.Create(projectId, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp,
documents: new[]
{
DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1")
})
});
var worker = ExecuteOperation(workspace, w => w.OnSolutionAdded(solutionInfo));
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void SolutionAdded_Complex()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
var worker = ExecuteOperation(workspace, w => w.OnSolutionAdded(solution));
Assert.Equal(10, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void Solution_Remove()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var worker = ExecuteOperation(workspace, w => w.OnSolutionRemoved());
Assert.Equal(10, worker.InvalidateDocumentIds.Count);
}
}
[Fact]
public void Solution_Clear()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var worker = ExecuteOperation(workspace, w => w.ClearSolution());
Assert.Equal(10, worker.InvalidateDocumentIds.Count);
}
}
[Fact]
public void Solution_Reload()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var worker = ExecuteOperation(workspace, w => w.OnSolutionReloaded(solution));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void Solution_Change()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solutionInfo = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solutionInfo);
WaitWaiter(workspace.ExportProvider);
var solution = workspace.CurrentSolution;
var documentId = solution.Projects.First().DocumentIds[0];
solution = solution.RemoveDocument(documentId);
var changedSolution = solution.AddProject("P3", "P3", LanguageNames.CSharp).AddDocument("D1", "").Project.Solution;
var worker = ExecuteOperation(workspace, w => w.ChangeSolution(changedSolution));
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void Project_Add()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var projectId = ProjectId.CreateNewId();
var projectInfo = ProjectInfo.Create(
projectId, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp,
documents: new List<DocumentInfo>
{
DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D2")
});
var worker = ExecuteOperation(workspace, w => w.OnProjectAdded(projectInfo));
Assert.Equal(2, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void Project_Remove()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var projectid = workspace.CurrentSolution.ProjectIds[0];
var worker = ExecuteOperation(workspace, w => w.OnProjectRemoved(projectid));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
Assert.Equal(5, worker.InvalidateDocumentIds.Count);
}
}
[Fact]
public void Project_Change()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solutionInfo = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solutionInfo);
WaitWaiter(workspace.ExportProvider);
var project = workspace.CurrentSolution.Projects.First();
var documentId = project.DocumentIds[0];
var solution = workspace.CurrentSolution.RemoveDocument(documentId);
var worker = ExecuteOperation(workspace, w => w.ChangeProject(project.Id, solution));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
Assert.Equal(1, worker.InvalidateDocumentIds.Count);
}
}
[Fact]
public void Project_Reload()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var project = solution.Projects[0];
var worker = ExecuteOperation(workspace, w => w.OnProjectReloaded(project));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void Document_Add()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var project = solution.Projects[0];
var info = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6");
var worker = ExecuteOperation(workspace, w => w.OnDocumentAdded(info));
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
Assert.Equal(6, worker.DocumentIds.Count);
}
}
[Fact]
public void Document_Remove()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var id = workspace.CurrentSolution.Projects.First().DocumentIds[0];
var worker = ExecuteOperation(workspace, w => w.OnDocumentRemoved(id));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
Assert.Equal(4, worker.DocumentIds.Count);
Assert.Equal(1, worker.InvalidateDocumentIds.Count);
}
}
[Fact]
public void Document_Reload()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var id = solution.Projects[0].Documents[0];
var worker = ExecuteOperation(workspace, w => w.OnDocumentReloaded(id));
Assert.Equal(0, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void Document_Reanalyze()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var info = solution.Projects[0].Documents[0];
var worker = new Analyzer();
var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(worker), Metadata.Crawler);
var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider));
service.Register(workspace);
// don't rely on background parser to have tree. explicitly do it here.
TouchEverything(workspace.CurrentSolution);
service.Reanalyze(workspace, worker, projectIds: null, documentIds: SpecializedCollections.SingletonEnumerable<DocumentId>(info.Id));
TouchEverything(workspace.CurrentSolution);
Wait(service, workspace);
service.Unregister(workspace);
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
Assert.Equal(1, worker.DocumentIds.Count);
}
}
[WorkItem(670335)]
public void Document_Change()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var id = workspace.CurrentSolution.Projects.First().DocumentIds[0];
var worker = ExecuteOperation(workspace, w => w.ChangeDocument(id, SourceText.From("//")));
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
}
}
[Fact]
public void Document_AdditionalFileChange()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var project = solution.Projects[0];
var ncfile = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6");
var worker = ExecuteOperation(workspace, w => w.OnAdditionalDocumentAdded(ncfile));
Assert.Equal(5, worker.SyntaxDocumentIds.Count);
Assert.Equal(5, worker.DocumentIds.Count);
worker = ExecuteOperation(workspace, w => w.ChangeAdditionalDocument(ncfile.Id, SourceText.From("//")));
Assert.Equal(5, worker.SyntaxDocumentIds.Count);
Assert.Equal(5, worker.DocumentIds.Count);
worker = ExecuteOperation(workspace, w => w.OnAdditionalDocumentRemoved(ncfile.Id));
Assert.Equal(5, worker.SyntaxDocumentIds.Count);
Assert.Equal(5, worker.DocumentIds.Count);
}
}
[WorkItem(670335)]
public void Document_Cancellation()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var id = workspace.CurrentSolution.Projects.First().DocumentIds[0];
var analyzer = new Analyzer(waitForCancellation: true);
var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler);
var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider));
service.Register(workspace);
workspace.ChangeDocument(id, SourceText.From("//"));
analyzer.RunningEvent.Wait();
workspace.ChangeDocument(id, SourceText.From("// "));
Wait(service, workspace);
service.Unregister(workspace);
Assert.Equal(1, analyzer.SyntaxDocumentIds.Count);
Assert.Equal(5, analyzer.DocumentIds.Count);
}
}
[WorkItem(670335)]
public void Document_Cancellation_MultipleTimes()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var id = workspace.CurrentSolution.Projects.First().DocumentIds[0];
var analyzer = new Analyzer(waitForCancellation: true);
var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler);
var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider));
service.Register(workspace);
workspace.ChangeDocument(id, SourceText.From("//"));
analyzer.RunningEvent.Wait();
analyzer.RunningEvent.Reset();
workspace.ChangeDocument(id, SourceText.From("// "));
analyzer.RunningEvent.Wait();
workspace.ChangeDocument(id, SourceText.From("// "));
Wait(service, workspace);
service.Unregister(workspace);
Assert.Equal(1, analyzer.SyntaxDocumentIds.Count);
Assert.Equal(5, analyzer.DocumentIds.Count);
}
}
[WorkItem(670335)]
public void Document_InvocationReasons()
{
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
var solution = GetInitialSolutionInfo(workspace);
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var id = workspace.CurrentSolution.Projects.First().DocumentIds[0];
var analyzer = new Analyzer(blockedRun: true);
var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler);
var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider));
service.Register(workspace);
// first invocation will block worker
workspace.ChangeDocument(id, SourceText.From("//"));
analyzer.RunningEvent.Wait();
var openReady = new ManualResetEventSlim(initialState: false);
var closeReady = new ManualResetEventSlim(initialState: false);
workspace.DocumentOpened += (o, e) => openReady.Set();
workspace.DocumentClosed += (o, e) => closeReady.Set();
// cause several different request to queue up
workspace.ChangeDocument(id, SourceText.From("// "));
workspace.OpenDocument(id);
workspace.CloseDocument(id);
openReady.Set();
closeReady.Set();
analyzer.BlockEvent.Set();
Wait(service, workspace);
service.Unregister(workspace);
Assert.Equal(1, analyzer.SyntaxDocumentIds.Count);
Assert.Equal(5, analyzer.DocumentIds.Count);
}
}
[Fact]
public void Document_TopLevelType_Whitespace()
{
var code = @"class C { $$ }";
var textToInsert = " ";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_TopLevelType_Character()
{
var code = @"class C { $$ }";
var textToInsert = "int";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_TopLevelType_NewLine()
{
var code = @"class C { $$ }";
var textToInsert = "\r\n";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_TopLevelType_NewLine2()
{
var code = @"class C { $$";
var textToInsert = "\r\n";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_EmptyFile()
{
var code = @"$$";
var textToInsert = "class";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_TopLevel1()
{
var code = @"class C
{
public void Test($$";
var textToInsert = "int";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_TopLevel2()
{
var code = @"class C
{
public void Test(int $$";
var textToInsert = " ";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_TopLevel3()
{
var code = @"class C
{
public void Test(int i,$$";
var textToInsert = "\r\n";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_InteriorNode1()
{
var code = @"class C
{
public void Test()
{$$";
var textToInsert = "\r\n";
InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public void Document_InteriorNode2()
{
var code = @"class C
{
public void Test()
{
$$
}";
var textToInsert = "int";
InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public void Document_InteriorNode_Field()
{
var code = @"class C
{
int i = $$
}";
var textToInsert = "1";
InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public void Document_InteriorNode_Field1()
{
var code = @"class C
{
int i = 1 + $$
}";
var textToInsert = "1";
InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public void Document_InteriorNode_Accessor()
{
var code = @"class C
{
public int A
{
get
{
$$
}
}
}";
var textToInsert = "return";
InsertText(code, textToInsert, expectDocumentAnalysis: false);
}
[Fact]
public void Document_TopLevelWhitespace()
{
var code = @"class C
{
/// $$
public int A()
{
}
}";
var textToInsert = "return";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_TopLevelWhitespace2()
{
var code = @"/// $$
class C
{
public int A()
{
}
}";
var textToInsert = "return";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void Document_InteriorNode_Malformed()
{
var code = @"class C
{
public void Test()
{
$$";
var textToInsert = "int";
InsertText(code, textToInsert, expectDocumentAnalysis: true);
}
[Fact]
public void VBPropertyTest()
{
var markup = @"Class C
Default Public Property G(x As Integer) As Integer
Get
$$
End Get
Set(value As Integer)
End Set
End Property
End Class";
int position;
string code;
MarkupTestFile.GetPosition(markup, out code, out position);
var root = Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseCompilationUnit(code);
var property = root.FindToken(position).Parent.FirstAncestorOrSelf<Microsoft.CodeAnalysis.VisualBasic.Syntax.PropertyBlockSyntax>();
var memberId = (new Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxFactsService()).GetMethodLevelMemberId(root, property);
Assert.Equal(0, memberId);
}
[Fact, WorkItem(739943)]
public void SemanticChange_Propagation()
{
var solution = GetInitialSolutionInfoWithP2P();
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
workspace.OnSolutionAdded(solution);
WaitWaiter(workspace.ExportProvider);
var id = solution.Projects[0].Id;
var info = DocumentInfo.Create(DocumentId.CreateNewId(id), "D6");
var worker = ExecuteOperation(workspace, w => w.OnDocumentAdded(info));
Assert.Equal(1, worker.SyntaxDocumentIds.Count);
Assert.Equal(4, worker.DocumentIds.Count);
#if false
Assert.True(1 == worker.SyntaxDocumentIds.Count,
string.Format("Expected 1 SyntaxDocumentIds, Got {0}\n\n{1}", worker.SyntaxDocumentIds.Count, GetListenerTrace(workspace.ExportProvider)));
Assert.True(4 == worker.DocumentIds.Count,
string.Format("Expected 4 DocumentIds, Got {0}\n\n{1}", worker.DocumentIds.Count, GetListenerTrace(workspace.ExportProvider)));
#endif
}
}
[Fact]
public void ProgressReporterTest()
{
var solution = GetInitialSolutionInfoWithP2P();
using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
{
WaitWaiter(workspace.ExportProvider);
var service = workspace.Services.GetService<ISolutionCrawlerService>();
var reporter = service.GetProgressReporter(workspace);
Assert.False(reporter.InProgress);
// set up events
bool started = false;
reporter.Started += (o, a) => { started = true; };
bool stopped = false;
reporter.Stopped += (o, a) => { stopped = true; };
var registrationService = workspace.Services.GetService<ISolutionCrawlerRegistrationService>();
registrationService.Register(workspace);
// first mutation
workspace.OnSolutionAdded(solution);
Wait((SolutionCrawlerRegistrationService)registrationService, workspace);
Assert.True(started);
Assert.True(stopped);
// reset
started = false;
stopped = false;
// second mutation
workspace.OnDocumentAdded(DocumentInfo.Create(DocumentId.CreateNewId(solution.Projects[0].Id), "D6"));
Wait((SolutionCrawlerRegistrationService)registrationService, workspace);
Assert.True(started);
Assert.True(stopped);
registrationService.Unregister(workspace);
}
}
private void InsertText(string code, string text, bool expectDocumentAnalysis, string language = LanguageNames.CSharp)
{
using (var workspace = TestWorkspaceFactory.CreateWorkspaceFromLines(
SolutionCrawler, language, compilationOptions: null, parseOptions: null, content: new string[] { code }))
{
var analyzer = new Analyzer();
var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler);
var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider));
service.Register(workspace);
var testDocument = workspace.Documents.First();
var insertPosition = testDocument.CursorPosition;
var textBuffer = testDocument.GetTextBuffer();
using (var edit = textBuffer.CreateEdit())
{
edit.Insert(insertPosition.Value, text);
edit.Apply();
}
Wait(service, workspace);
service.Unregister(workspace);
Assert.Equal(1, analyzer.SyntaxDocumentIds.Count);
Assert.Equal(expectDocumentAnalysis ? 1 : 0, analyzer.DocumentIds.Count);
}
}
private Analyzer ExecuteOperation(TestWorkspace workspace, Action<TestWorkspace> operation)
{
var worker = new Analyzer();
var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(worker), Metadata.Crawler);
var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider));
service.Register(workspace);
// don't rely on background parser to have tree. explicitly do it here.
TouchEverything(workspace.CurrentSolution);
operation(workspace);
TouchEverything(workspace.CurrentSolution);
Wait(service, workspace);
service.Unregister(workspace);
return worker;
}
private void TouchEverything(Solution solution)
{
foreach (var project in solution.Projects)
{
foreach (var document in project.Documents)
{
document.GetTextAsync().PumpingWait();
document.GetSyntaxRootAsync().PumpingWait();
document.GetSemanticModelAsync().PumpingWait();
}
}
}
private void Wait(SolutionCrawlerRegistrationService service, TestWorkspace workspace)
{
WaitWaiter(workspace.ExportProvider);
service.WaitUntilCompletion_ForTestingPurposesOnly(workspace);
}
private void WaitWaiter(ExportProvider provider)
{
var workspasceWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as IAsynchronousOperationWaiter;
workspasceWaiter.CreateWaitTask().PumpingWait();
var solutionCrawlerWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as IAsynchronousOperationWaiter;
solutionCrawlerWaiter.CreateWaitTask().PumpingWait();
}
private static SolutionInfo GetInitialSolutionInfoWithP2P()
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
var projectId3 = ProjectId.CreateNewId();
var projectId4 = ProjectId.CreateNewId();
var projectId5 = ProjectId.CreateNewId();
var solution = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(),
projects: new[]
{
ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1") }),
ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2") },
projectReferences: new[] { new ProjectReference(projectId1) }),
ProjectInfo.Create(projectId3, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId3), "D3") },
projectReferences: new[] { new ProjectReference(projectId2) }),
ProjectInfo.Create(projectId4, VersionStamp.Create(), "P4", "P4", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId4), "D4") }),
ProjectInfo.Create(projectId5, VersionStamp.Create(), "P5", "P5", LanguageNames.CSharp,
documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId5), "D5") },
projectReferences: new[] { new ProjectReference(projectId4) }),
});
return solution;
}
private static SolutionInfo GetInitialSolutionInfo(TestWorkspace workspace)
{
var projectId1 = ProjectId.CreateNewId();
var projectId2 = ProjectId.CreateNewId();
return SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(),
projects: new[]
{
ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp,
documents: new[]
{
DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D2"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D3"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D4"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D5")
}),
ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp,
documents: new[]
{
DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D1"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D3"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D4"),
DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D5")
})
});
}
private IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> GetListeners(ExportProvider provider)
{
return provider.GetExports<IAsynchronousOperationListener, FeatureMetadata>();
}
[Export(typeof(IAsynchronousOperationListener))]
[Export(typeof(IAsynchronousOperationWaiter))]
[Feature(FeatureAttribute.SolutionCrawler)]
private class SolutionCrawlerWaiter : AsynchronousOperationListener { }
[Export(typeof(IAsynchronousOperationListener))]
[Export(typeof(IAsynchronousOperationWaiter))]
[Feature(FeatureAttribute.Workspace)]
private class WorkspaceWaiter : AsynchronousOperationListener { }
private class AnalyzerProvider : IIncrementalAnalyzerProvider
{
private readonly Analyzer _analyzer;
public AnalyzerProvider(Analyzer analyzer)
{
_analyzer = analyzer;
}
public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace)
{
return _analyzer;
}
}
internal class Metadata : IncrementalAnalyzerProviderMetadata
{
public Metadata(params string[] workspaceKinds)
: base(new Dictionary<string, object> { { "WorkspaceKinds", workspaceKinds }, { "HighPriorityForActiveFile", false } })
{
}
public static readonly Metadata Crawler = new Metadata(SolutionCrawler);
}
private class Analyzer : IIncrementalAnalyzer
{
private readonly bool _waitForCancellation;
private readonly bool _blockedRun;
public readonly ManualResetEventSlim BlockEvent;
public readonly ManualResetEventSlim RunningEvent;
public readonly HashSet<DocumentId> SyntaxDocumentIds = new HashSet<DocumentId>();
public readonly HashSet<DocumentId> DocumentIds = new HashSet<DocumentId>();
public readonly HashSet<ProjectId> ProjectIds = new HashSet<ProjectId>();
public readonly HashSet<DocumentId> InvalidateDocumentIds = new HashSet<DocumentId>();
public readonly HashSet<ProjectId> InvalidateProjectIds = new HashSet<ProjectId>();
public Analyzer(bool waitForCancellation = false, bool blockedRun = false)
{
_waitForCancellation = waitForCancellation;
_blockedRun = blockedRun;
this.BlockEvent = new ManualResetEventSlim(initialState: false);
this.RunningEvent = new ManualResetEventSlim(initialState: false);
}
public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken)
{
this.ProjectIds.Add(project.Id);
return SpecializedTasks.EmptyTask;
}
public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken)
{
if (bodyOpt == null)
{
this.DocumentIds.Add(document.Id);
}
return SpecializedTasks.EmptyTask;
}
public Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken)
{
this.SyntaxDocumentIds.Add(document.Id);
Process(document.Id, cancellationToken);
return SpecializedTasks.EmptyTask;
}
public void RemoveDocument(DocumentId documentId)
{
InvalidateDocumentIds.Add(documentId);
}
public void RemoveProject(ProjectId projectId)
{
InvalidateProjectIds.Add(projectId);
}
private void Process(DocumentId documentId, CancellationToken cancellationToken)
{
if (_blockedRun && !RunningEvent.IsSet)
{
this.RunningEvent.Set();
// Wait until unblocked
this.BlockEvent.Wait();
}
if (_waitForCancellation && !RunningEvent.IsSet)
{
this.RunningEvent.Set();
cancellationToken.WaitHandle.WaitOne();
cancellationToken.ThrowIfCancellationRequested();
}
}
#region unused
public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task DocumentResetAsync(Document document, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e)
{
return false;
}
#endregion
}
#if false
private string GetListenerTrace(ExportProvider provider)
{
var sb = new StringBuilder();
var workspasceWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as TestAsynchronousOperationListener;
sb.AppendLine("workspace");
sb.AppendLine(workspasceWaiter.Trace());
var solutionCrawlerWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as TestAsynchronousOperationListener;
sb.AppendLine("solutionCrawler");
sb.AppendLine(solutionCrawlerWaiter.Trace());
return sb.ToString();
}
internal abstract partial class TestAsynchronousOperationListener : IAsynchronousOperationListener, IAsynchronousOperationWaiter
{
private readonly object gate = new object();
private readonly HashSet<TaskCompletionSource<bool>> pendingTasks = new HashSet<TaskCompletionSource<bool>>();
private readonly StringBuilder sb = new StringBuilder();
private int counter;
public TestAsynchronousOperationListener()
{
}
public IAsyncToken BeginAsyncOperation(string name, object tag = null)
{
lock (gate)
{
return new AsyncToken(this, name);
}
}
private void Increment(string name)
{
lock (gate)
{
sb.AppendLine("i -> " + name + ":" + counter++);
}
}
private void Decrement(string name)
{
lock (gate)
{
counter--;
if (counter == 0)
{
foreach (var task in pendingTasks)
{
task.SetResult(true);
}
pendingTasks.Clear();
}
sb.AppendLine("d -> " + name + ":" + counter);
}
}
public virtual Task CreateWaitTask()
{
lock (gate)
{
var source = new TaskCompletionSource<bool>();
if (counter == 0)
{
// There is nothing to wait for, so we are immediately done
source.SetResult(true);
}
else
{
pendingTasks.Add(source);
}
return source.Task;
}
}
public bool TrackActiveTokens { get; set; }
public bool HasPendingWork
{
get
{
return counter != 0;
}
}
private class AsyncToken : IAsyncToken
{
private readonly TestAsynchronousOperationListener listener;
private readonly string name;
private bool disposed;
public AsyncToken(TestAsynchronousOperationListener listener, string name)
{
this.listener = listener;
this.name = name;
listener.Increment(name);
}
public void Dispose()
{
lock (listener.gate)
{
if (disposed)
{
throw new InvalidOperationException("Double disposing of an async token");
}
disposed = true;
listener.Decrement(this.name);
}
}
}
public string Trace()
{
return sb.ToString();
}
}
#endif
}
}
| |
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.NHibernateIntegration.Saga
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;
using Logging;
using MassTransit.Saga;
using NHibernate;
using NHibernate.Exceptions;
using Pipeline;
using Util;
public class NHibernateSagaRepository<TSaga> :
ISagaRepository<TSaga>,
IQuerySagaRepository<TSaga>
where TSaga : class, ISaga
{
static readonly ILog _log = Logger.Get<NHibernateSagaRepository<TSaga>>();
readonly ISessionFactory _sessionFactory;
System.Data.IsolationLevel _insertIsolationLevel;
public NHibernateSagaRepository(ISessionFactory sessionFactory)
{
_sessionFactory = sessionFactory;
_insertIsolationLevel = System.Data.IsolationLevel.ReadCommitted;
}
public NHibernateSagaRepository(ISessionFactory sessionFactory, System.Data.IsolationLevel isolationLevel)
{
_sessionFactory = sessionFactory;
_insertIsolationLevel = isolationLevel;
}
public Task<IEnumerable<Guid>> Find(ISagaQuery<TSaga> query)
{
using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew))
using (ISession session = _sessionFactory.OpenSession())
{
IList<Guid> result = session.QueryOver<TSaga>()
.Where(query.FilterExpression)
.Select(x => x.CorrelationId)
.List<Guid>();
scope.Complete();
return Task.FromResult<IEnumerable<Guid>>(result);
}
}
void IProbeSite.Probe(ProbeContext context)
{
ProbeContext scope = context.CreateScope("sagaRepository");
scope.Set(new
{
Persistence = "nhibernate",
Entities = _sessionFactory.GetAllClassMetadata().Select(x => x.Value.EntityName).ToArray()
});
}
async Task ISagaRepository<TSaga>.Send<T>(ConsumeContext<T> context, ISagaPolicy<TSaga, T> policy, IPipe<SagaConsumeContext<TSaga, T>> next)
{
if (!context.CorrelationId.HasValue)
throw new SagaException("The CorrelationId was not specified", typeof(TSaga), typeof(T));
Guid sagaId = context.CorrelationId.Value;
using (ISession session = _sessionFactory.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
bool inserted = false;
TSaga instance;
if (policy.PreInsertInstance(context, out instance))
inserted = PreInsertSagaInstance<T>(session, instance, inserted);
try
{
if (instance == null)
instance = session.Get<TSaga>(sagaId, LockMode.Upgrade);
if (instance == null)
{
var missingSagaPipe = new MissingPipe<T>(session, next);
await policy.Missing(context, missingSagaPipe).ConfigureAwait(false);
}
else
{
if (_log.IsDebugEnabled)
_log.DebugFormat("SAGA:{0}:{1} Used {2}", TypeMetadataCache<TSaga>.ShortName, instance.CorrelationId, TypeMetadataCache<T>.ShortName);
var sagaConsumeContext = new NHibernateSagaConsumeContext<TSaga, T>(session, context, instance);
await policy.Existing(sagaConsumeContext, next).ConfigureAwait(false);
if (inserted && !sagaConsumeContext.IsCompleted)
session.Update(instance);
}
if (transaction.IsActive)
transaction.Commit();
}
catch (Exception)
{
if (transaction.IsActive)
transaction.Rollback();
throw;
}
}
}
public async Task SendQuery<T>(SagaQueryConsumeContext<TSaga, T> context, ISagaPolicy<TSaga, T> policy, IPipe<SagaConsumeContext<TSaga, T>> next)
where T : class
{
using (ISession session = _sessionFactory.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
try
{
IList<TSaga> instances = session.QueryOver<TSaga>()
.Where(context.Query.FilterExpression)
.List<TSaga>();
if (instances.Count == 0)
{
var missingSagaPipe = new MissingPipe<T>(session, next);
await policy.Missing(context, missingSagaPipe).ConfigureAwait(false);
}
else
await Task.WhenAll(instances.Select(instance => SendToInstance(context, policy, instance, next, session))).ConfigureAwait(false);
// TODO partial failure should not affect them all
if (transaction.IsActive)
transaction.Commit();
}
catch (SagaException sex)
{
if (_log.IsErrorEnabled)
_log.Error("Saga Exception Occurred", sex);
}
catch (Exception ex)
{
if (_log.IsErrorEnabled)
_log.Error($"SAGA:{TypeMetadataCache<TSaga>.ShortName} Exception {TypeMetadataCache<T>.ShortName}", ex);
if (transaction.IsActive)
transaction.Rollback();
throw new SagaException(ex.Message, typeof(TSaga), typeof(T), Guid.Empty, ex);
}
}
}
static bool PreInsertSagaInstance<T>(ISession session, TSaga instance, bool inserted)
{
try
{
session.Save(instance);
session.Flush();
inserted = true;
_log.DebugFormat("SAGA:{0}:{1} Insert {2}", TypeMetadataCache<TSaga>.ShortName, instance.CorrelationId,
TypeMetadataCache<T>.ShortName);
}
catch (GenericADOException ex)
{
if (_log.IsDebugEnabled)
{
_log.DebugFormat("SAGA:{0}:{1} Dupe {2} - {3}", TypeMetadataCache<TSaga>.ShortName, instance.CorrelationId,
TypeMetadataCache<T>.ShortName, ex.Message);
}
}
return inserted;
}
async Task SendToInstance<T>(SagaQueryConsumeContext<TSaga, T> context, ISagaPolicy<TSaga, T> policy, TSaga instance,
IPipe<SagaConsumeContext<TSaga, T>> next, ISession session)
where T : class
{
try
{
if (_log.IsDebugEnabled)
_log.DebugFormat("SAGA:{0}:{1} Used {2}", TypeMetadataCache<TSaga>.ShortName, instance.CorrelationId, TypeMetadataCache<T>.ShortName);
var sagaConsumeContext = new NHibernateSagaConsumeContext<TSaga, T>(session, context, instance);
await policy.Existing(sagaConsumeContext, next).ConfigureAwait(false);
}
catch (SagaException)
{
throw;
}
catch (Exception ex)
{
throw new SagaException(ex.Message, typeof(TSaga), typeof(T), instance.CorrelationId, ex);
}
}
/// <summary>
/// Once the message pipe has processed the saga instance, add it to the saga repository
/// </summary>
/// <typeparam name="TMessage"></typeparam>
class MissingPipe<TMessage> :
IPipe<SagaConsumeContext<TSaga, TMessage>>
where TMessage : class
{
readonly IPipe<SagaConsumeContext<TSaga, TMessage>> _next;
readonly ISession _session;
public MissingPipe(ISession session, IPipe<SagaConsumeContext<TSaga, TMessage>> next)
{
_session = session;
_next = next;
}
void IProbeSite.Probe(ProbeContext context)
{
_next.Probe(context);
}
public async Task Send(SagaConsumeContext<TSaga, TMessage> context)
{
if (_log.IsDebugEnabled)
{
_log.DebugFormat("SAGA:{0}:{1} Added {2}", TypeMetadataCache<TSaga>.ShortName, context.Saga.CorrelationId,
TypeMetadataCache<TMessage>.ShortName);
}
SagaConsumeContext<TSaga, TMessage> proxy = new NHibernateSagaConsumeContext<TSaga, TMessage>(_session, context, context.Saga);
await _next.Send(proxy).ConfigureAwait(false);
if (!proxy.IsCompleted)
_session.Save(context.Saga);
}
}
}
}
| |
/**********************************************************************
*
* Update Controls .NET
* Copyright 2010 Michael L Perry
* MIT License
*
* http://updatecontrols.net
* http://www.codeplex.com/updatecontrols/
*
**********************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Assisticant.Fields;
namespace Assisticant
{
/// <summary>
/// A sentry that controls a computed field.
/// <seealso cref="UpdateProcedure"/>
/// <seealso cref="RecycleBin{T}"/>
/// </summary>
/// <threadsafety static="true" instance="true"/>
/// <remarks>
/// <para>
/// A computed field is one whose value is determined by an update
/// procedure. Use a Computed sentry to control such a field.
/// </para><para>
/// Define a field of type Computed in the same class as the computed
/// field, and initialize it with an update procedure, also defined
/// within the class.
/// </para><para>
/// Calculate and set the computed field within
/// the update procedure. No other code should modify the computed
/// field.
/// </para><para>
/// Before each line of code that gets the computed field, call
/// the sentry's <see cref="Computed.OnGet"/>. This will ensure
/// that the field is up-to-date, and will record any dependencies
/// upon the field.
/// </para><para>
/// If the computed field is a collection, consider using a
/// <see cref="RecycleBin{T}"/> to prevent complete destruction and
/// recreation of the contents of the collection.
/// </para>
/// </remarks>
/// <example>A class with a computed field.
/// <code language="C#">
/// public class MyCalculatedObject
/// {
/// private MyDynamicObject _someOtherObject;
/// private string _text;
/// private Computed _depText;
///
/// public MyCalculatedObject( MyDynamicObject someOtherObject )
/// {
/// _someOtherObject = someOtherObject;
/// _depText = new Computed( UpdateText );
/// }
///
/// private void UpdateText()
/// {
/// _text = _someOtherObject.StringProperty;
/// }
///
/// public string Text
/// {
/// get
/// {
/// _depText.OnGet();
/// return _text;
/// }
/// }
/// }
/// </code>
/// <code language="VB">
/// Public Class MyCalculatedObject
/// Private _someOtherObject As MyDynamicObject
/// Private _text As String
/// Private _depText As Computed
/// Public Sub New(ByVal someOtherObject As MyDynamicObject)
/// _someOtherObject = someOtherObject
/// _depText = New Computed(New UpdateProcedure(UpdateText))
/// End Sub
/// Private Sub UpdateText()
/// _text = _someOtherObject.StringProperty
/// End Sub
/// Public ReadOnly Property Text() As String
/// Get
/// _depText.OnGet()
/// Return _text
/// End Get
/// End Property
/// End Class
/// </code>
/// </example>
public partial class Computed : Precedent
{
public static Computed New(Action update) { return DebugMode ? new NamedComputed(update) : new Computed(update); }
public static Computed<T> New<T>(Func<T> update) { return new Computed<T>(update); }
public static NamedComputed New(string name, Action update) { return new NamedComputed(name, update); }
public static Computed<T> New<T>(string name, Func<T> update) { return new Computed<T>(name, update); }
private static ThreadLocal<Computed> _currentUpdate = new ThreadLocal<Computed>();
internal static Computed GetCurrentUpdate()
{
return _currentUpdate.Value;
}
/// <summary>
/// Event fired when the computed becomes out-of-date.
/// <remarks>
/// This event should not call <see cref="OnGet"/>. However, it should
/// set up the conditions for OnGet to be called. For example, it could
/// invalidate a region of the window so that a Paint method later calls
/// OnGet, or it could signal a thread that will call OnGet.
/// </remarks>
/// </summary>
public event Action Invalidated;
protected internal Action _update;
/// <summary>Gets the update method.</summary>
/// <remarks>This property is used by GuiUpdateHelper.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public Action UpdateMethod
{
get { return _update; }
}
private enum StatusType
{
OUT_OF_DATE,
UP_TO_DATE,
UPDATING,
UPDATING_AND_OUT_OF_DATE,
DISPOSED
};
private StatusType _status;
private class PrecedentNode
{
public Precedent Precedent;
public PrecedentNode Next;
}
private PrecedentNode _firstPrecedent = null;
/// <summary>
/// Creates a new computed sentry with a given update procedure.
/// <seealso cref="UpdateProcedure"/>
/// </summary>
/// <param name="update">The procedure that updates the value of the controled field.</param>
/// <remarks>
/// The update parameter is allowed to be null, so that derived classes
/// can initialize properly. Due to a limitation of C#, an Update method
/// defined in a derived class can't be passed to the constructor of the
/// base class. Instead, update must be null and the _update member must
/// be set afterward.
/// </remarks>
public Computed( Action update )
{
_update = update;
_status = StatusType.OUT_OF_DATE;
}
/// <summary>
/// Call this method before reading the value of a controlled field.
/// </summary>
/// <remarks>
/// If the controlled field is out-of-date, this function calls the
/// update procedure to bring it back up-to-date. If another computed
/// is currently updating, that computed depends upon this one; when this
/// computed goes out-of-date again, that one does as well.
/// </remarks>
public void OnGet()
{
// Ensure that the attribute is up-to-date.
if (MakeUpToDate())
{
// Establish dependency between the current update
// and this attribute.
RecordDependent();
}
else
{
// We're still not up-to-date (because of a concurrent change).
// The current update should similarly not be up-to-date.
Computed currentUpdate = _currentUpdate.Value;
if (currentUpdate != null)
currentUpdate.MakeOutOfDate();
}
}
/// <summary>
/// Call this method to tear down dependencies prior to destroying
/// the computed.
/// </summary>
/// <remarks>
/// While it is not absolutely necessary to call this method, doing
/// so can help the garbage collector to reclaim the object. While
/// the computed is up-to-date, all of its precedents maintain
/// pointers. Calling this method destroys those pointers so that
/// the computed can be removed from memory.
/// </remarks>
public void Dispose()
{
MakeOutOfDate();
_status = StatusType.DISPOSED;
}
/// <summary>
/// Read only property that is true when the computed is up-to-date.
/// </summary>
public bool IsUpToDate
{
get
{
lock (this)
{
bool isUpToDate = _status == StatusType.UP_TO_DATE;
return isUpToDate;
}
}
}
/// <summary>
/// Read only property that is true when the computed is not updating.
/// </summary>
public bool IsNotUpdating
{
get
{
lock (this)
{
return
_status != StatusType.UPDATING &&
_status != StatusType.UPDATING_AND_OUT_OF_DATE;
}
}
}
/// <summary>
/// Bring the computed up-to-date, but don't take a dependency on it. This is
/// useful for pre-loading properties of an object as it is created. It avoids
/// the appearance of a list populated with empty objects while properties
/// of that object are loaded.
/// </summary>
public void Touch()
{
MakeUpToDate();
}
internal void MakeOutOfDate()
{
bool wasUpToDate = false;
lock ( this )
{
if ( _status == StatusType.UP_TO_DATE ||
_status == StatusType.UPDATING )
{
wasUpToDate = true;
// Tell all precedents to forget about me.
for (PrecedentNode current = _firstPrecedent; current != null; current = current.Next)
current.Precedent.RemoveDependent(this);
_firstPrecedent = null;
if ( _status == StatusType.UP_TO_DATE )
_status = StatusType.OUT_OF_DATE;
else if ( _status == StatusType.UPDATING )
_status = StatusType.UPDATING_AND_OUT_OF_DATE;
if (Invalidated != null)
Invalidated();
}
}
if (wasUpToDate)
// Make all indirect dependents out-of-date, too.
MakeDependentsOutOfDate();
}
internal bool MakeUpToDate()
{
StatusType formerStatus;
bool isUpToDate = true;
lock ( this )
{
// Get the former status.
formerStatus = _status;
// Reserve the right to update.
if ( _status == StatusType.OUT_OF_DATE )
_status = StatusType.UPDATING;
}
if (formerStatus == StatusType.UPDATING ||
formerStatus == StatusType.UPDATING_AND_OUT_OF_DATE)
{
// Report cycles.
ReportCycles();
//MLP: Don't throw, because this will mask any exception in an update which caused reentrance.
//throw new InvalidOperationException( "Cycle discovered during update." );
}
else if (formerStatus == StatusType.OUT_OF_DATE)
{
// Push myself to the update stack.
Computed stack = _currentUpdate.Value;
_currentUpdate.Value = this;
// Update the attribute.
try
{
_update();
}
finally
{
// Pop myself off the update stack.
Computed that = _currentUpdate.Value;
Debug.Assert(that == this);
_currentUpdate.Value = stack;
lock (this)
{
// Look for changes since the update began.
if (_status == StatusType.UPDATING)
{
_status = StatusType.UP_TO_DATE;
}
else if (_status == StatusType.UPDATING_AND_OUT_OF_DATE)
{
_status = StatusType.OUT_OF_DATE;
isUpToDate = false;
}
else
Debug.Assert(false, "Unexpected state in MakeUpToDate");
}
}
}
return isUpToDate;
}
internal bool AddPrecedent( Precedent precedent )
{
lock ( this )
{
if ( _status == StatusType.UPDATING )
{
_firstPrecedent = new PrecedentNode { Precedent = precedent, Next = _firstPrecedent };
return true;
}
else if ( _status != StatusType.UPDATING_AND_OUT_OF_DATE )
Debug.Assert( false, "Unexpected state in AddPrecedent" );
return false;
}
}
static partial void ReportCycles();
#region Debugger Visualization
/// <summary>Intended for the debugger. Returns a tree of Computeds that
/// use this Computed.</summary>
/// <remarks>UsedBy is defined separately in Observable and Computed so
/// that the user doesn't have to drill down to the final base class,
/// Precedent, in order to view this property.</remarks>
protected DependentVisualizer UsedBy
{
get { return new DependentVisualizer(this); }
}
/// <summary>Intended for the debugger. Returns a tree of Precedents that
/// were accessed when this Computed was last updated.</summary>
protected PrecedentVisualizer Uses
{
get { return new PrecedentVisualizer(this); }
}
/// <summary>Intended for the debugger. Returns a tree of Precedents that
/// were accessed when this Computed was last updated, collapsed so that
/// all precedents that have the same name are shown as a single item.</summary>
protected PrecedentSummarizer UsesSummary
{
get { return new PrecedentSummarizer(this); }
}
/// <summary>Helper class, intended to be viewed in the debugger, that
/// shows a list of Computeds and Observables that are used by this
/// Computed.</summary>
protected class PrecedentVisualizer
{
Computed _self;
public PrecedentVisualizer(Computed self) { _self = self; }
public override string ToString() { return _self.VisualizerName(true); }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public object[] Items
{
get {
var list = new List<object>();
lock (_self)
{
for (PrecedentNode current = _self._firstPrecedent; current != null; current = current.Next)
{
var dep = current.Precedent as Computed;
var ind = current.Precedent as Observable;
if (dep != null)
list.Add(new PrecedentVisualizer(dep));
else
list.Add(new LeafVisualizer(ind));
}
list.Sort((a, b) => a.ToString().CompareTo(b.ToString()));
// Return as array so that the debugger doesn't offer a useless "Raw View"
return list.ToArray();
}
}
}
}
/// <summary>Helper class, used by <see cref="PrecedentVisualizer"/>, whose
/// ToString() method shows [I] plus the "extended name" of an Observable.</summary>
private class LeafVisualizer
{
Observable _self;
public LeafVisualizer(Observable self) { _self = self; }
public override string ToString() { return _self.VisualizerName(true); }
}
/// <summary>Helper class, intended to be viewed in the debugger, that is
/// similar to PrecedentVisualizer except that it collapses all precedents
/// with the same name into a single entry.</summary>
protected class PrecedentSummarizer
{
List<Precedent> _precedentsAtThisLevel;
public PrecedentSummarizer(Precedent self)
{
_precedentsAtThisLevel = new List<Precedent>();
_precedentsAtThisLevel.Add(self);
}
public override string ToString()
{
var list = _precedentsAtThisLevel;
if (list.Count > 1)
return string.Format("x{0} {1}", list.Count, list[0].VisualizerName(false));
else if (list.Count == 1)
return list[0].VisualizerName(true);
else
return "x0"; // should never happen
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public PrecedentSummarizer[] Items
{
get
{
var dict = new Dictionary<string, PrecedentSummarizer>();
foreach (var item in _precedentsAtThisLevel)
{
if (item is Computed) lock (item)
{
//if (_isComputedTree)
//{
// for (ComputedNode current = item._firstComputed; current != null; current = current.Next)
// {
// var dep = current.Computed.Target as Computed;
// if (dep != null)
// {
// PrecedentSummarizer child;
// if (dict.TryGetValue(dep.ToString(), out child))
// child._list.Add(dep);
// else
// dict[dep.ToString()] = new PrecedentSummarizer(dep, _isComputedTree);
// }
// }
//}
for (PrecedentNode current = (item as Computed)._firstPrecedent; current != null; current = current.Next)
{
Precedent p = current.Precedent;
string name = p.VisualizerName(false);
PrecedentSummarizer child;
if (dict.TryGetValue(name, out child))
child._precedentsAtThisLevel.Add(current.Precedent);
else
dict[name] = new PrecedentSummarizer(p);
}
}
}
return dict.Values.ToArray();
}
}
}
#endregion
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//==========================================================================
// File: SocketCache.cs
//
// Summary: Cache for client sockets.
//
//==========================================================================
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Threading;
namespace System.Runtime.Remoting.Channels
{
// Delegate to method that will fabricate the appropriate socket handler
internal delegate SocketHandler SocketHandlerFactory(Socket socket,
SocketCache socketCache,
String machineAndPort);
// Used to cache client connections to a single port on a server
internal class RemoteConnection
{
private static char[] colonSep = new char[]{':'};
private CachedSocketList _cachedSocketList;
// reference back to the socket cache
private SocketCache _socketCache;
// remote endpoint data
private String _machineAndPort;
private IPAddress[] _addressList;
private int _port;
private EndPoint _lkgIPEndPoint;
private bool connectIPv6 = false;
private Uri _uri;
internal RemoteConnection(SocketCache socketCache, String machineAndPort)
{
_socketCache = socketCache;
_cachedSocketList = new CachedSocketList(socketCache.SocketTimeout,
socketCache.CachePolicy);
// parse "machinename:port", add a dummy scheme to get uri parsing
_uri = new Uri("dummy://" + machineAndPort);
_port = _uri.Port;
_machineAndPort = machineAndPort;
} // RemoteConnection
internal SocketHandler GetSocket()
{
// try the cached socket list
SocketHandler socketHandler = _cachedSocketList.GetSocket();
if (socketHandler != null)
return socketHandler;
// Otherwise, we'll just create a new one.
return CreateNewSocket();
} // GetSocket
internal void ReleaseSocket(SocketHandler socket)
{
socket.ReleaseControl();
_cachedSocketList.ReturnSocket(socket);
} // ReleaseSocket
private bool HasIPv6Address(IPAddress[] addressList)
{
foreach (IPAddress address in addressList)
{
if (address.AddressFamily == AddressFamily.InterNetworkV6)
return true;
}
return false;
}
private void DisableNagleDelays(Socket socket)
{
// disable nagle delays
socket.SetSocketOption(SocketOptionLevel.Tcp,
SocketOptionName.NoDelay,
1);
}
private SocketHandler CreateNewSocket()
{
//
// We should not cache the DNS result
//
_addressList = Dns.GetHostAddresses(_uri.DnsSafeHost);
connectIPv6 = Socket.OSSupportsIPv6 && HasIPv6Address(_addressList);
// If there is only one entry in the list, just use that
// we will fail if the connect on it fails
if (_addressList.Length == 1)
return CreateNewSocket(new IPEndPoint(_addressList[0], _port));
// If LKG is set try using that
if (_lkgIPEndPoint != null)
{
try{
return CreateNewSocket(_lkgIPEndPoint);
}
catch (Exception) {
// Since this fail null out LKG
_lkgIPEndPoint = null;
}
}
// If IPv6 is enabled try connecting to IP addresses
if (connectIPv6)
{
try{
return CreateNewSocket(AddressFamily.InterNetworkV6);
}catch (Exception) {}
}
// If everything fails try ipv4 addresses
return CreateNewSocket(AddressFamily.InterNetwork);
}
private SocketHandler CreateNewSocket(EndPoint ipEndPoint)
{
Socket socket = new Socket(ipEndPoint.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp);
DisableNagleDelays(socket);
InternalRemotingServices.RemotingTrace("RemoteConnection::CreateNewSocket: connecting new socket :: " + ipEndPoint);
socket.Connect(ipEndPoint);
_lkgIPEndPoint = socket.RemoteEndPoint;
return _socketCache.CreateSocketHandler(socket, _machineAndPort);
} // CreateNewSocket
private SocketHandler CreateNewSocket(AddressFamily family)
{
Socket socket = new Socket(family,
SocketType.Stream,
ProtocolType.Tcp);
DisableNagleDelays(socket);
socket.Connect(_addressList, _port);
_lkgIPEndPoint = socket.RemoteEndPoint;
return _socketCache.CreateSocketHandler(socket, _machineAndPort);
} // CreateNewSocket
internal void TimeoutSockets(DateTime currentTime)
{
_cachedSocketList.TimeoutSockets(currentTime, _socketCache.SocketTimeout);
} // TimeoutSockets
} // class RemoteConnection
internal class CachedSocket
{
private SocketHandler _socket;
private DateTime _socketLastUsed;
private CachedSocket _next;
internal CachedSocket(SocketHandler socket, CachedSocket next)
{
_socket = socket;
_socketLastUsed = DateTime.UtcNow;
_next = next;
} // CachedSocket
internal SocketHandler Handler { get { return _socket; } }
internal DateTime LastUsed { get { return _socketLastUsed; } }
internal CachedSocket Next
{
get { return _next; }
set { _next = value; }
}
} // class CachedSocket
internal class CachedSocketList
{
private int _socketCount;
private TimeSpan _socketLifetime;
private SocketCachePolicy _socketCachePolicy;
private CachedSocket _socketList; // linked list
internal CachedSocketList(TimeSpan socketLifetime, SocketCachePolicy socketCachePolicy)
{
_socketCount = 0;
_socketLifetime = socketLifetime;
_socketCachePolicy = socketCachePolicy;
_socketList = null;
} // CachedSocketList
internal SocketHandler GetSocket()
{
if (_socketCount == 0)
return null;
lock (this)
{
if (_socketList != null)
{
SocketHandler socket = _socketList.Handler;
_socketList = _socketList.Next;
bool bRes = socket.RaceForControl();
// We should always have control since there shouldn't
// be contention here.
InternalRemotingServices.RemotingAssert(bRes, "someone else has the socket?");
_socketCount--;
return socket;
}
}
return null;
} // GetSocket
internal void ReturnSocket(SocketHandler socket)
{
TimeSpan socketActiveTime = DateTime.UtcNow - socket.CreationTime;
bool closeSocket = false;
lock (this)
{
// Check if socket active time has exceeded the lifetime
// If it has just close the Socket
if (_socketCachePolicy != SocketCachePolicy.AbsoluteTimeout ||
socketActiveTime < _socketLifetime)
{
// Ignore duplicate entries for the same socket handler
for (CachedSocket curr = _socketList; curr != null; curr = curr.Next){
if (socket == curr.Handler)
return;
}
_socketList = new CachedSocket(socket, _socketList);
_socketCount++;
}
else
{
closeSocket = true;
}
}
if(closeSocket)
{
socket.Close();
}
} // ReturnSocket
internal void TimeoutSockets(DateTime currentTime, TimeSpan socketLifetime)
{
lock (this)
{
CachedSocket prev = null;
CachedSocket curr = _socketList;
while (curr != null)
{
// see if it's lifetime has expired
if ((_socketCachePolicy == SocketCachePolicy.AbsoluteTimeout && // This is for absolute
(currentTime - curr.Handler.CreationTime) > socketLifetime) ||
(currentTime - curr.LastUsed) > socketLifetime) // This is relative behaviour
{
curr.Handler.Close();
// remove current cached socket from list
if (prev == null)
{
// it's the first item, so update _socketList
_socketList = curr.Next;
curr = _socketList;
}
else
{
// remove current item from the list
curr = curr.Next;
prev.Next = curr;
}
// decrement socket count
_socketCount--;
}
else
{
prev = curr;
curr = curr.Next;
}
}
}
} // TimeoutSockets
} // class CachedSocketList
internal class SocketCache
{
// collection of RemoteConnection's.
private static Hashtable _connections = new Hashtable();
private SocketHandlerFactory _handlerFactory;
// socket timeout data
private static RegisteredWaitHandle _registeredWaitHandle;
private static WaitOrTimerCallback _socketTimeoutDelegate;
private static AutoResetEvent _socketTimeoutWaitHandle;
private static TimeSpan _socketTimeoutPollTime = TimeSpan.FromSeconds(10);
private SocketCachePolicy _socketCachePolicy;
private TimeSpan _socketTimeout;
private int _receiveTimeout = 0;
static SocketCache()
{
InitializeSocketTimeoutHandler();
}
internal SocketCache(SocketHandlerFactory handlerFactory, SocketCachePolicy socketCachePolicy,
TimeSpan socketTimeout)
{
_handlerFactory = handlerFactory;
_socketCachePolicy = socketCachePolicy;
_socketTimeout = socketTimeout;
} // SocketCache
internal TimeSpan SocketTimeout { get { return _socketTimeout; } set { _socketTimeout = value;} }
internal int ReceiveTimeout { get { return _receiveTimeout; } set { _receiveTimeout = value;} }
internal SocketCachePolicy CachePolicy { get { return _socketCachePolicy; } set { _socketCachePolicy = value;}}
private static void InitializeSocketTimeoutHandler()
{
_socketTimeoutDelegate = new WaitOrTimerCallback(TimeoutSockets);
_socketTimeoutWaitHandle = new AutoResetEvent(false);
_registeredWaitHandle =
ThreadPool.UnsafeRegisterWaitForSingleObject(
_socketTimeoutWaitHandle,
_socketTimeoutDelegate,
"TcpChannelSocketTimeout",
_socketTimeoutPollTime,
true); // execute only once
} // InitializeSocketTimeoutHandler
private static void TimeoutSockets(Object state, Boolean wasSignalled)
{
DateTime currentTime = DateTime.UtcNow;
lock (_connections)
{
foreach (DictionaryEntry entry in _connections)
{
RemoteConnection connection = (RemoteConnection)entry.Value;
connection.TimeoutSockets(currentTime);
}
}
_registeredWaitHandle.Unregister(null);
_registeredWaitHandle =
ThreadPool.UnsafeRegisterWaitForSingleObject(
_socketTimeoutWaitHandle,
_socketTimeoutDelegate,
"TcpChannelSocketTimeout",
_socketTimeoutPollTime,
true); // execute only once
} // TimeoutSockets
internal SocketHandler CreateSocketHandler(Socket socket, String machineAndPort)
{
socket.ReceiveTimeout = _receiveTimeout;
return _handlerFactory(socket, this, machineAndPort);
}
// The key is expected to of the form "machinename:port"
public SocketHandler GetSocket(String machinePortAndSid, bool openNew)
{
RemoteConnection connection = (RemoteConnection)_connections[machinePortAndSid];
if (openNew || connection == null)
{
connection = new RemoteConnection(this, machinePortAndSid);
// doesn't matter if different RemoteConnection's get written at
// the same time (GC will come along and close them).
lock (_connections)
{
_connections[machinePortAndSid] = connection;
}
}
return connection.GetSocket();
} // GetSocket
public void ReleaseSocket(String machinePortAndSid, SocketHandler socket)
{
RemoteConnection connection = (RemoteConnection)_connections[machinePortAndSid];
if (connection != null)
{
connection.ReleaseSocket(socket);
}
else
{
// there should have been a connection, so let's just close
// this socket.
socket.Close();
}
} // ReleaseSocket
} // SocketCache
} // namespace System.Runtime.Remoting.Channels
| |
// 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!
namespace Google.Apis.Webfonts.v1
{
/// <summary>The Webfonts Service.</summary>
public class WebfontsService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public WebfontsService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public WebfontsService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
Webfonts = new WebfontsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "webfonts";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://webfonts.googleapis.com/";
#else
"https://webfonts.googleapis.com/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://webfonts.googleapis.com/batch";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch";
#endif
/// <summary>Gets the Webfonts resource.</summary>
public virtual WebfontsResource Webfonts { get; }
}
/// <summary>A base abstract class for Webfonts requests.</summary>
public abstract class WebfontsBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new WebfontsBaseServiceRequest instance.</summary>
protected WebfontsBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a
/// user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes Webfonts parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "webfonts" collection of methods.</summary>
public class WebfontsResource
{
private const string Resource = "webfonts";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public WebfontsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Retrieves the list of fonts currently served by the Google Fonts Developer API.</summary>
public virtual ListRequest List()
{
return new ListRequest(service);
}
/// <summary>Retrieves the list of fonts currently served by the Google Fonts Developer API.</summary>
public class ListRequest : WebfontsBaseServiceRequest<Google.Apis.Webfonts.v1.Data.WebfontList>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service) : base(service)
{
InitParameters();
}
/// <summary>Enables sorting of the list.</summary>
[Google.Apis.Util.RequestParameterAttribute("sort", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<SortEnum> Sort { get; set; }
/// <summary>Enables sorting of the list.</summary>
public enum SortEnum
{
/// <summary>No sorting specified, use the default sorting method.</summary>
[Google.Apis.Util.StringValueAttribute("SORT_UNDEFINED")]
SORTUNDEFINED = 0,
/// <summary>Sort alphabetically</summary>
[Google.Apis.Util.StringValueAttribute("ALPHA")]
ALPHA = 1,
/// <summary>Sort by date added</summary>
[Google.Apis.Util.StringValueAttribute("DATE")]
DATE = 2,
/// <summary>Sort by popularity</summary>
[Google.Apis.Util.StringValueAttribute("POPULARITY")]
POPULARITY = 3,
/// <summary>Sort by number of styles</summary>
[Google.Apis.Util.StringValueAttribute("STYLE")]
STYLE = 4,
/// <summary>Sort by trending</summary>
[Google.Apis.Util.StringValueAttribute("TRENDING")]
TRENDING = 5,
}
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/webfonts";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("sort", new Google.Apis.Discovery.Parameter
{
Name = "sort",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.Webfonts.v1.Data
{
/// <summary>Metadata describing a family of fonts.</summary>
public class Webfont : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The category of the font.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("category")]
public virtual string Category { get; set; }
/// <summary>The name of the font.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("family")]
public virtual string Family { get; set; }
/// <summary>
/// The font files (with all supported scripts) for each one of the available variants, as a key : value map.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("files")]
public virtual System.Collections.Generic.IDictionary<string, string> Files { get; set; }
/// <summary>This kind represents a webfont object in the webfonts service.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>The date (format "yyyy-MM-dd") the font was modified for the last time.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("lastModified")]
public virtual string LastModified { get; set; }
/// <summary>The scripts supported by the font.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("subsets")]
public virtual System.Collections.Generic.IList<string> Subsets { get; set; }
/// <summary>The available variants for the font.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("variants")]
public virtual System.Collections.Generic.IList<string> Variants { get; set; }
/// <summary>The font version.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual string Version { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Response containing the list of fonts currently served by the Google Fonts API.</summary>
public class WebfontList : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of fonts currently served by the Google Fonts API.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("items")]
public virtual System.Collections.Generic.IList<Webfont> Items { get; set; }
/// <summary>This kind represents a list of webfont objects in the webfonts service.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Template10.Common;
using Template10.Utils;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Classic = Template10.Services.NavigationService;
using CrossPlat = Template10.Portable.Navigation;
namespace Template10.Services.NavigationService
{
public class Template10NavigationStrategy: INavigationStrategy
{
public INavigationService NavigationService { get; }
public Template10NavigationStrategy(INavigationService navigationService)
{
NavigationService = navigationService;
}
private Windows.Foundation.Collections.IPropertySet PageState(Page page)
{
if (page == null)
{
throw new ArgumentNullException(nameof(page));
}
return NavigationService.Suspension.GetPageState(page.GetType()).Values;
}
public async Task SetupViewModelAsync(INavigationService service, INavigable viewmodel)
{
Services.NavigationService.NavigationService.DebugWrite();
if (viewmodel == null)
{
return;
}
viewmodel.NavigationService = service;
viewmodel.Dispatcher = service.GetDispatcherWrapper();
viewmodel.SessionState = await Services.StateService.SettingsStateContainer.GetStateAsync(StateService.StateTypes.Session);
}
public async Task NavedFromAsync(object viewmodel, NavigationMode mode, Page sourcePage, Type sourceType, object sourceParameter, Page targetPage, Type targetType, object targetParameter, bool suspending)
{
Services.NavigationService.NavigationService.DebugWrite();
if (sourcePage == null)
{
return;
}
else if (viewmodel == null)
{
return;
}
else if (viewmodel is Classic.INavigatedAwareAsync)
{
await CallClassicOnNavigatedFrom(viewmodel, sourcePage, suspending);
}
else if (viewmodel is CrossPlat.INavigatedFromAwareAsync)
{
await CallPortableOnNavigatedFrom(viewmodel, sourcePage, sourceParameter, suspending);
}
}
public async Task NavedToAsync(object viewmodel, NavigationMode mode, Page sourcePage, Type sourceType, object sourceParameter, Page targetPage, Type targetType, object targetParameter)
{
Services.NavigationService.NavigationService.DebugWrite();
if (targetPage == null)
{
throw new ArgumentNullException(nameof(targetPage));
}
if (mode == NavigationMode.New)
{
PageState(targetPage).Clear();
}
if (viewmodel == null)
{
return;
}
else if (viewmodel is Classic.INavigatedAwareAsync)
{
await CallClassicOnNavigatedTo(viewmodel, mode, targetPage, targetParameter);
}
else if (viewmodel is CrossPlat.INavigatedToAwareAsync)
{
await CallPortableOnNavigatedTo(viewmodel, mode, sourceType, sourceParameter, targetPage, targetType, targetParameter);
}
UpdateBindings(targetPage);
}
public async Task<bool> NavingFromCancelsAsync(object viewmodel, NavigationMode mode, Page sourcePage, Type sourceType, object sourceParameter, Page targetPage, Type targetType, object targetParameter, bool suspending)
{
Services.NavigationService.NavigationService.DebugWrite();
if (sourcePage == null)
{
return false;
}
else if (viewmodel == null)
{
return false;
}
else if (viewmodel is Classic.INavigatingAwareAsync)
{
var cancel = await CallClassicOnNavigatingFrom(viewmodel, mode, sourcePage, sourceParameter, targetType, targetParameter, suspending);
return cancel;
}
else if (viewmodel is Portable.Navigation.IConfirmNavigationAsync)
{
var canNavigate = await CallPortableCanNavigateAsync(viewmodel, mode, sourceType, sourceParameter, targetType, targetParameter, suspending);
if (!canNavigate)
{
return true;
}
await CallPortableNavigatingFromAsync(viewmodel, mode, sourceType, sourceParameter, targetType, targetParameter, suspending);
return false;
}
else
{
return true;
}
}
private static void UpdateBindings(Page page)
{
page.InitializeBindings();
page.UpdateBindings();
}
private async Task CallClassicOnNavigatedFrom(object viewmodel, Page sourcePage, bool suspending)
{
var vm = viewmodel as Classic.INavigatedAwareAsync;
await vm?.OnNavigatedFromAsync(PageState(sourcePage), suspending);
}
private async Task CallClassicOnNavigatedTo(object viewmodel, NavigationMode mode, Page targetPage, object targetParameter)
{
var vm = viewmodel as Classic.INavigatedAwareAsync;
await vm?.OnNavigatedToAsync(targetParameter, mode, PageState(targetPage));
}
private static async Task<bool> CallClassicOnNavigatingFrom(object viewmodel, NavigationMode mode, Page sourcePage, object sourceParameter, Type targetType, object targetParameter, bool suspending)
{
var deferral = new DeferralManager();
var navigatingEventArgs = new Classic.NavigatingEventArgs(deferral)
{
Page = sourcePage,
PageType = sourcePage?.GetType(),
Parameter = sourceParameter,
NavigationMode = mode,
TargetPageType = targetType,
TargetPageParameter = targetParameter,
Suspending = suspending,
};
try
{
var vm = viewmodel as Classic.INavigatingAwareAsync;
if (vm != null)
{
await vm.OnNavigatingFromAsync(navigatingEventArgs);
await deferral.WaitForDeferralsAsync();
}
}
catch (Exception ex)
{
Debugger.Break();
}
return navigatingEventArgs.Cancel;
}
private async Task CallPortableOnNavigatedFrom(object viewmodel, Page sourcePage, object sourceParameter, bool suspending)
{
var vm = viewmodel as CrossPlat.INavigatedFromAwareAsync;
var parameters = new NavigatedFromParameters();
parameters.Parameter = sourceParameter;
parameters.PageState = PageState(sourcePage);
parameters.Suspending = suspending;
await vm?.OnNavigatedFromAsync(parameters);
}
private async Task CallPortableOnNavigatedTo(object viewmodel, NavigationMode mode, Type sourceType, object sourceParameter, Page targetPage, Type targetType, object targetParameter)
{
var parameters = new NavigatedToParameters();
parameters.PageState = PageState(targetPage);
parameters.NavigationMode = mode.ToPortableNavigationMode();
parameters.SourceType = sourceType;
parameters.SourceParameter = sourceParameter;
parameters.TargetType = targetType;
parameters.TargetParameter = targetParameter;
var vm = viewmodel as CrossPlat.INavigatedToAwareAsync;
await vm?.OnNavigatedToAsync(parameters);
}
private static async Task<bool> CallPortableCanNavigateAsync(object viewmodel, NavigationMode mode, Type sourceType, object sourceParameter, Type targetType, object targetParameter, bool suspending)
{
var parameters = new ConfirmNavigationParameters
{
NavigationMode = mode.ToPortableNavigationMode(),
SourceType = sourceType,
SourceParameter = sourceParameter,
TargetType = targetType,
TargetParameter = targetParameter,
Suspending = suspending,
};
var vm = viewmodel as Portable.Navigation.IConfirmNavigationAsync;
var canNavigate = await vm?.CanNavigateAsync(parameters);
return canNavigate;
}
private static async Task CallPortableNavigatingFromAsync(object viewmodel, NavigationMode mode, Type sourceType, object sourceParameter, Type targetType, object targetParameter, bool suspending)
{
var parameters = new NavigatingFromParameters
{
NavigationMode = mode.ToPortableNavigationMode(),
SourceType = sourceType,
SourceParameter = sourceParameter,
TargetType = targetType,
TargetParameter = targetParameter,
Suspending = suspending,
};
var vm = viewmodel as Portable.Navigation.INavigatingFromAwareAsync;
await vm?.OnNavigatingFromAsync(parameters);
}
}
}
| |
/*
* 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 log4net.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Tests.Common;
using log4net;
using System.Reflection;
using System.Data.Common;
// DBMS-specific:
using MySql.Data.MySqlClient;
using OpenSim.Data.MySQL;
using System.Data.SqlClient;
using OpenSim.Data.MSSQL;
using Mono.Data.Sqlite;
using OpenSim.Data.SQLite;
namespace OpenSim.Data.Tests
{
[TestFixture(Description = "Inventory store tests (SQLite)")]
public class SQLiteInventoryTests : InventoryTests<SqliteConnection, SQLiteInventoryStore>
{
}
[TestFixture(Description = "Inventory store tests (MySQL)")]
public class MySqlInventoryTests : InventoryTests<MySqlConnection, MySQLInventoryData>
{
}
[TestFixture(Description = "Inventory store tests (MS SQL Server)")]
public class MSSQLInventoryTests : InventoryTests<SqlConnection, MSSQLInventoryData>
{
}
public class InventoryTests<TConn, TInvStore> : BasicDataServiceTest<TConn, TInvStore>
where TConn : DbConnection, new()
where TInvStore : class, IInventoryDataPlugin, new()
{
public IInventoryDataPlugin db;
public UUID zero = UUID.Zero;
public UUID folder1 = UUID.Random();
public UUID folder2 = UUID.Random();
public UUID folder3 = UUID.Random();
public UUID owner1 = UUID.Random();
public UUID owner2 = UUID.Random();
public UUID owner3 = UUID.Random();
public UUID item1 = UUID.Random();
public UUID item2 = UUID.Random();
public UUID item3 = UUID.Random();
public UUID asset1 = UUID.Random();
public UUID asset2 = UUID.Random();
public UUID asset3 = UUID.Random();
public string name1;
public string name2 = "First Level folder";
public string name3 = "First Level folder 2";
public string niname1 = "My Shirt";
public string iname1 = "Shirt";
public string iname2 = "Text Board";
public string iname3 = "No Pants Barrel";
public InventoryTests(string conn) : base(conn)
{
name1 = "Root Folder for " + owner1.ToString();
}
public InventoryTests() : this("") { }
protected override void InitService(object service)
{
ClearDB();
db = (IInventoryDataPlugin)service;
db.Initialise(m_connStr);
}
private void ClearDB()
{
DropTables("inventoryitems", "inventoryfolders");
ResetMigrations("InventoryStore");
}
[Test]
public void T001_LoadEmpty()
{
TestHelpers.InMethod();
Assert.That(db.getInventoryFolder(zero), Is.Null);
Assert.That(db.getInventoryFolder(folder1), Is.Null);
Assert.That(db.getInventoryFolder(folder2), Is.Null);
Assert.That(db.getInventoryFolder(folder3), Is.Null);
Assert.That(db.getInventoryItem(zero), Is.Null);
Assert.That(db.getInventoryItem(item1), Is.Null);
Assert.That(db.getInventoryItem(item2), Is.Null);
Assert.That(db.getInventoryItem(item3), Is.Null);
Assert.That(db.getUserRootFolder(zero), Is.Null);
Assert.That(db.getUserRootFolder(owner1), Is.Null);
}
// 01x - folder tests
[Test]
public void T010_FolderNonParent()
{
TestHelpers.InMethod();
InventoryFolderBase f1 = NewFolder(folder2, folder1, owner1, name2);
// the folder will go in
db.addInventoryFolder(f1);
InventoryFolderBase f1a = db.getUserRootFolder(owner1);
Assert.That(f1a, Is.Null);
}
[Test]
public void T011_FolderCreate()
{
TestHelpers.InMethod();
InventoryFolderBase f1 = NewFolder(folder1, zero, owner1, name1);
// TODO: this is probably wrong behavior, but is what we have
// db.updateInventoryFolder(f1);
// InventoryFolderBase f1a = db.getUserRootFolder(owner1);
// Assert.That(uuid1, Is.EqualTo(f1a.ID))
// Assert.That(name1, Text.Matches(f1a.Name), "Assert.That(name1, Text.Matches(f1a.Name))");
// Assert.That(db.getUserRootFolder(owner1), Is.Null);
// succeed with true
db.addInventoryFolder(f1);
InventoryFolderBase f1a = db.getUserRootFolder(owner1);
Assert.That(folder1, Is.EqualTo(f1a.ID), "Assert.That(folder1, Is.EqualTo(f1a.ID))");
Assert.That(name1, Is.StringMatching(f1a.Name), "Assert.That(name1, Text.Matches(f1a.Name))");
}
// we now have the following tree
// folder1
// +--- folder2
// +--- folder3
[Test]
public void T012_FolderList()
{
TestHelpers.InMethod();
InventoryFolderBase f2 = NewFolder(folder3, folder1, owner1, name3);
db.addInventoryFolder(f2);
Assert.That(db.getInventoryFolders(zero).Count, Is.EqualTo(1), "Assert.That(db.getInventoryFolders(zero).Count, Is.EqualTo(1))");
Assert.That(db.getInventoryFolders(folder1).Count, Is.EqualTo(2), "Assert.That(db.getInventoryFolders(folder1).Count, Is.EqualTo(2))");
Assert.That(db.getInventoryFolders(folder2).Count, Is.EqualTo(0), "Assert.That(db.getInventoryFolders(folder2).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryFolders(folder3).Count, Is.EqualTo(0), "Assert.That(db.getInventoryFolders(folder3).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryFolders(UUID.Random()).Count, Is.EqualTo(0), "Assert.That(db.getInventoryFolders(UUID.Random()).Count, Is.EqualTo(0))");
}
[Test]
public void T013_FolderHierarchy()
{
TestHelpers.InMethod();
int n = db.getFolderHierarchy(zero).Count; // (for dbg - easier to see what's returned)
Assert.That(n, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(zero).Count, Is.EqualTo(0))");
n = db.getFolderHierarchy(folder1).Count;
Assert.That(n, Is.EqualTo(2), "Assert.That(db.getFolderHierarchy(folder1).Count, Is.EqualTo(2))");
Assert.That(db.getFolderHierarchy(folder2).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(folder2).Count, Is.EqualTo(0))");
Assert.That(db.getFolderHierarchy(folder3).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(folder3).Count, Is.EqualTo(0))");
Assert.That(db.getFolderHierarchy(UUID.Random()).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(UUID.Random()).Count, Is.EqualTo(0))");
}
[Test]
public void T014_MoveFolder()
{
TestHelpers.InMethod();
InventoryFolderBase f2 = db.getInventoryFolder(folder2);
f2.ParentID = folder3;
db.moveInventoryFolder(f2);
Assert.That(db.getInventoryFolders(zero).Count, Is.EqualTo(1), "Assert.That(db.getInventoryFolders(zero).Count, Is.EqualTo(1))");
Assert.That(db.getInventoryFolders(folder1).Count, Is.EqualTo(1), "Assert.That(db.getInventoryFolders(folder1).Count, Is.EqualTo(1))");
Assert.That(db.getInventoryFolders(folder2).Count, Is.EqualTo(0), "Assert.That(db.getInventoryFolders(folder2).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryFolders(folder3).Count, Is.EqualTo(1), "Assert.That(db.getInventoryFolders(folder3).Count, Is.EqualTo(1))");
Assert.That(db.getInventoryFolders(UUID.Random()).Count, Is.EqualTo(0), "Assert.That(db.getInventoryFolders(UUID.Random()).Count, Is.EqualTo(0))");
}
[Test]
public void T015_FolderHierarchy()
{
TestHelpers.InMethod();
Assert.That(db.getFolderHierarchy(zero).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(zero).Count, Is.EqualTo(0))");
Assert.That(db.getFolderHierarchy(folder1).Count, Is.EqualTo(2), "Assert.That(db.getFolderHierarchy(folder1).Count, Is.EqualTo(2))");
Assert.That(db.getFolderHierarchy(folder2).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(folder2).Count, Is.EqualTo(0))");
Assert.That(db.getFolderHierarchy(folder3).Count, Is.EqualTo(1), "Assert.That(db.getFolderHierarchy(folder3).Count, Is.EqualTo(1))");
Assert.That(db.getFolderHierarchy(UUID.Random()).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(UUID.Random()).Count, Is.EqualTo(0))");
}
// Item tests
[Test]
public void T100_NoItems()
{
TestHelpers.InMethod();
Assert.That(db.getInventoryInFolder(zero).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(zero).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryInFolder(folder1).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(folder1).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryInFolder(folder2).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(folder2).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryInFolder(folder3).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(folder3).Count, Is.EqualTo(0))");
}
// TODO: Feeding a bad inventory item down the data path will
// crash the system. This is largely due to the builder
// routines. That should be fixed and tested for.
[Test]
public void T101_CreatItems()
{
TestHelpers.InMethod();
db.addInventoryItem(NewItem(item1, folder3, owner1, iname1, asset1));
db.addInventoryItem(NewItem(item2, folder3, owner1, iname2, asset2));
db.addInventoryItem(NewItem(item3, folder3, owner1, iname3, asset3));
Assert.That(db.getInventoryInFolder(folder3).Count, Is.EqualTo(3), "Assert.That(db.getInventoryInFolder(folder3).Count, Is.EqualTo(3))");
}
[Test]
public void T102_CompareItems()
{
TestHelpers.InMethod();
InventoryItemBase i1 = db.getInventoryItem(item1);
InventoryItemBase i2 = db.getInventoryItem(item2);
InventoryItemBase i3 = db.getInventoryItem(item3);
Assert.That(i1.Name, Is.EqualTo(iname1), "Assert.That(i1.Name, Is.EqualTo(iname1))");
Assert.That(i2.Name, Is.EqualTo(iname2), "Assert.That(i2.Name, Is.EqualTo(iname2))");
Assert.That(i3.Name, Is.EqualTo(iname3), "Assert.That(i3.Name, Is.EqualTo(iname3))");
Assert.That(i1.Owner, Is.EqualTo(owner1), "Assert.That(i1.Owner, Is.EqualTo(owner1))");
Assert.That(i2.Owner, Is.EqualTo(owner1), "Assert.That(i2.Owner, Is.EqualTo(owner1))");
Assert.That(i3.Owner, Is.EqualTo(owner1), "Assert.That(i3.Owner, Is.EqualTo(owner1))");
Assert.That(i1.AssetID, Is.EqualTo(asset1), "Assert.That(i1.AssetID, Is.EqualTo(asset1))");
Assert.That(i2.AssetID, Is.EqualTo(asset2), "Assert.That(i2.AssetID, Is.EqualTo(asset2))");
Assert.That(i3.AssetID, Is.EqualTo(asset3), "Assert.That(i3.AssetID, Is.EqualTo(asset3))");
}
[Test]
public void T103_UpdateItem()
{
TestHelpers.InMethod();
// TODO: probably shouldn't have the ability to have an
// owner of an item in a folder not owned by the user
InventoryItemBase i1 = db.getInventoryItem(item1);
i1.Name = niname1;
i1.Description = niname1;
i1.Owner = owner2;
db.updateInventoryItem(i1);
i1 = db.getInventoryItem(item1);
Assert.That(i1.Name, Is.EqualTo(niname1), "Assert.That(i1.Name, Is.EqualTo(niname1))");
Assert.That(i1.Description, Is.EqualTo(niname1), "Assert.That(i1.Description, Is.EqualTo(niname1))");
Assert.That(i1.Owner, Is.EqualTo(owner2), "Assert.That(i1.Owner, Is.EqualTo(owner2))");
}
[Test]
public void T104_RandomUpdateItem()
{
TestHelpers.InMethod();
PropertyScrambler<InventoryFolderBase> folderScrambler =
new PropertyScrambler<InventoryFolderBase>()
.DontScramble(x => x.Owner)
.DontScramble(x => x.ParentID)
.DontScramble(x => x.ID);
UUID owner = UUID.Random();
UUID folder = UUID.Random();
UUID rootId = UUID.Random();
UUID rootAsset = UUID.Random();
InventoryFolderBase f1 = NewFolder(folder, zero, owner, name1);
folderScrambler.Scramble(f1);
db.addInventoryFolder(f1);
InventoryFolderBase f1a = db.getUserRootFolder(owner);
Assert.That(f1a, Constraints.PropertyCompareConstraint(f1));
folderScrambler.Scramble(f1a);
db.updateInventoryFolder(f1a);
InventoryFolderBase f1b = db.getUserRootFolder(owner);
Assert.That(f1b, Constraints.PropertyCompareConstraint(f1a));
//Now we have a valid folder to insert into, we can insert the item.
PropertyScrambler<InventoryItemBase> inventoryScrambler =
new PropertyScrambler<InventoryItemBase>()
.DontScramble(x => x.ID)
.DontScramble(x => x.AssetID)
.DontScramble(x => x.Owner)
.DontScramble(x => x.Folder);
InventoryItemBase root = NewItem(rootId, folder, owner, iname1, rootAsset);
inventoryScrambler.Scramble(root);
db.addInventoryItem(root);
InventoryItemBase expected = db.getInventoryItem(rootId);
Assert.That(expected, Constraints.PropertyCompareConstraint(root)
.IgnoreProperty(x => x.InvType)
.IgnoreProperty(x => x.CreatorIdAsUuid)
.IgnoreProperty(x => x.Description)
.IgnoreProperty(x => x.CreatorIdentification)
.IgnoreProperty(x => x.CreatorData));
inventoryScrambler.Scramble(expected);
db.updateInventoryItem(expected);
InventoryItemBase actual = db.getInventoryItem(rootId);
Assert.That(actual, Constraints.PropertyCompareConstraint(expected)
.IgnoreProperty(x => x.InvType)
.IgnoreProperty(x => x.CreatorIdAsUuid)
.IgnoreProperty(x => x.Description)
.IgnoreProperty(x => x.CreatorIdentification)
.IgnoreProperty(x => x.CreatorData));
}
[Test]
public void T999_StillNull()
{
TestHelpers.InMethod();
// After all tests are run, these should still return no results
Assert.That(db.getInventoryFolder(zero), Is.Null);
Assert.That(db.getInventoryItem(zero), Is.Null);
Assert.That(db.getUserRootFolder(zero), Is.Null);
Assert.That(db.getInventoryInFolder(zero).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(zero).Count, Is.EqualTo(0))");
}
private InventoryItemBase NewItem(UUID id, UUID parent, UUID owner, string name, UUID asset)
{
InventoryItemBase i = new InventoryItemBase();
i.ID = id;
i.Folder = parent;
i.Owner = owner;
i.CreatorId = owner.ToString();
i.Name = name;
i.Description = name;
i.AssetID = asset;
return i;
}
private InventoryFolderBase NewFolder(UUID id, UUID parent, UUID owner, string name)
{
InventoryFolderBase f = new InventoryFolderBase();
f.ID = id;
f.ParentID = parent;
f.Owner = owner;
f.Name = name;
return f;
}
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MLifter.DAL;
using MLifter.DAL.DB.MsSqlCe;
using MLifter.DAL.Interfaces;
using MLifter.DAL.Tools;
using Npgsql;
using System.Drawing;
namespace MLifterTest.DAL
{
/// <summary>
/// TestInfrastructure
/// Have fun and keep on learning ;-)
/// </summary>
public static class TestInfrastructure
{
private static Random random = new Random((int)DateTime.Now.Ticks);
private static string tmpRepository = string.Empty;
private static string MachineName = System.Environment.MachineName.ToLower();
private static bool DBCreated = false;
private static bool dbAccessByOtherUser = false;
//Connection String to accesss the server
private static readonly string defaultConnectionString = "Server=localhost;Port=5432;Userid=postgres;password=M3m0ryL1ft3r;Protocol=3;SSL=false;Pooling=true;MinPoolSize=1;MaxPoolSize=20;Encoding=UNICODE;Timeout=15;SslMode=Disable;database=postgres";
//Connection String meant to be extended by the corresponding database name
private static readonly string connectionStringToGetExtended = "Server=localhost;Port=5432;Userid=postgres;password=M3m0ryL1ft3r;Protocol=3;SSL=false;Pooling=true;MinPoolSize=1;MaxPoolSize=20;Encoding=UNICODE;Timeout=15;SslMode=Disable;database=";
//Lines for Debug Writeline mark
public readonly static string beginLine = new string('-', 80);
public readonly static string endLine = new string('=', 80);
public static FileCleanupQueue cleanupQueue = new FileCleanupQueue();
/// <summary>
/// Gets the loopcount.
/// </summary>
/// <value>The loopcount.</value>
/// <remarks>Documented by Dev10, 2008-07-30</remarks>
public static int Loopcount
{
get { return 100; }
}
/// <summary>
/// Gets the random.
/// </summary>
/// <value>The random.</value>
/// <remarks>Documented by Dev10, 2008-07-30</remarks>
public static Random Random
{
get { return random; }
}
/// <summary>
/// Determines whether the specified test context is active.
/// </summary>
/// <param name="testContext">The test context.</param>
/// <returns>
/// <c>true</c> if the specified test context is active; otherwise, <c>false</c>.
/// </returns>
/// <remarks>Documented by Dev10, 2008-07-30</remarks>
public static bool IsActive(TestContext testContext)
{
return (bool)testContext.DataRow["IsValid"];
}
/// <summary>
/// Connections the type.
/// </summary>
/// <param name="testContext">The test context.</param>
/// <returns> string describing the connection type</returns>
/// <remarks>Documented by Dev10, 2008-25-09</remarks>
public static string ConnectionType(TestContext testContext)
{
return (string)testContext.DataRow["Type"];
}
/// <summary>
/// Class clean up.
/// </summary>
/// <remarks>Documented by Dev10, 2008-07-30</remarks>
public static void MyClassCleanup()
{
MLifterTest.Tools.TestStopWatch.Cleanup();
cleanupQueue.DoCleanup();
}
/// <summary>
/// Gets the connection. Obsolete should be replaced only for compatibility for current Unit tests.
/// Use GetLMConnection instead, because it express more what it is all about. We are getting LM Connection
/// not general connections.
/// </summary>
/// <param name="testContext">The test context.</param>
/// <returns></returns>
/// <remarks>Documented by Dev10, 2008-08-01</remarks>
[Obsolete("Should be replaced only for compatibility for current Unit tests. " +
"Use GetLMConnection(LMConnectionParameter) instead, because it express more what it is all about. We are getting LM Connection not general connections.")]
public static IDictionary GetConnection(TestContext testContext)
{
return GetLMConnection(testContext, string.Empty, false);
}
/// <summary>
/// Gets the connection and returns an IDictionary (Learning Module instance)
/// </summary>
/// <param name="testContext">The test context.</param>
/// <param name="repositoryName">Name of the repository.</param>
/// <returns>IDictionary</returns>
/// <remarks>Documented by Dev10, 2008-07-31</remarks>
public static IDictionary GetLMConnection(TestContext testContext, string repositoryName)
{
return GetLMConnection(testContext, repositoryName, false);
}
/// <summary>
/// Gets the connection and returns an IDictionary (Learning Module instance)
/// </summary>
/// <param name="testContext">The test context.</param>
/// <param name="repositoryName">Name of the repository.</param>
/// <param name="standAlone">if set to <c>true</c> a stand alone user will be created.</param>
/// <returns>IDictionary</returns>
/// <remarks>Documented by Dev10, 2008-07-31</remarks>
public static IDictionary GetLMConnection(TestContext testContext, string repositoryName, bool standAlone)
{
return GetPersistentLMConnection(testContext, repositoryName, -1, standAlone);
}
/// <summary>
/// Gets the connection and returns an IDictionary (Learning Module instance)
/// </summary>
/// <param name="testContext">The test context.</param>
/// <param name="callback">The callback.</param>
/// <returns>IDictionary</returns>
/// <remarks>Documented by Dev10, 2008-07-31</remarks>
public static IDictionary GetLMConnection(TestContext testContext, GetLoginInformation callback)
{
return GetLMConnection(testContext, callback, false);
}
/// <summary>
/// Gets the connection and returns an IDictionary (Learning Module instance)
/// </summary>
/// <param name="testContext">The test context.</param>
/// <param name="callback">The callback.</param>
/// <param name="standAlone">if set to <c>true</c> a stand alone user will be created.</param>
/// <returns>IDictionary</returns>
/// <remarks>Documented by Dev10, 2008-07-31</remarks>
public static IDictionary GetLMConnection(TestContext testContext, GetLoginInformation callback, bool standAlone)
{
return GetPersistentLMConnection(testContext, String.Empty, -1, callback, standAlone);
}
/// <summary>
/// Gets the persistent LM connection.
/// </summary>
/// <param name="testContext">The test context.</param>
/// <param name="repositoryName">Name of the repository.</param>
/// <param name="LMId">The LM id.</param>
/// <returns></returns>
/// <remarks>Documented by Dev03, 2008-09-02</remarks>
public static IDictionary GetPersistentLMConnection(TestContext testContext, string repositoryName, int LMId)
{
return GetPersistentLMConnection(testContext, repositoryName, LMId, false);
}
/// <summary>
/// Gets the persistent LM connection.
/// </summary>
/// <param name="testContext">The test context.</param>
/// <param name="repositoryName">Name of the repository.</param>
/// <param name="LMId">The LM id.</param>
/// <param name="standAlone">if set to <c>true</c> a stand alone user will be created.</param>
/// <returns></returns>
/// <remarks>Documented by Dev03, 2008-09-02</remarks>
public static IDictionary GetPersistentLMConnection(TestContext testContext, string repositoryName, int LMId, bool standAlone)
{
return GetPersistentLMConnection(testContext, repositoryName, LMId, null, standAlone);
}
/// <summary>
/// Gets the persistent LM connection.
/// </summary>
/// <param name="testContext">The test context.</param>
/// <param name="repositoryName">Name of the repository.</param>
/// <param name="LMId">The LM id.</param>
/// <param name="callback">The callback.</param>
/// <returns></returns>
/// <remarks>Documented by Dev10, 2008-25-09</remarks>
public static IDictionary GetPersistentLMConnection(TestContext testContext, string repositoryName, int LMId, GetLoginInformation callback)
{
return GetPersistentLMConnection(testContext, repositoryName, LMId, callback, false);
}
/// <summary>
/// Gets the persistent LM connection.
/// </summary>
/// <param name="testContext">The test context.</param>
/// <param name="repositoryName">Name of the repository.</param>
/// <param name="LMId">The LM id.</param>
/// <param name="callback">The callback.</param>
/// <returns></returns>
/// <remarks>Documented by Dev10, 2008-25-09</remarks>
public static IDictionary GetPersistentLMConnection(TestContext testContext, string repositoryName, int LMId, GetLoginInformation callback, bool standAlone)
{
return GetPersistentLMConnection(testContext, repositoryName, LMId, callback, string.Empty, standAlone, string.Empty, false);
}
/// <summary>
/// Gets the LM connection.
/// </summary>
/// <param name="parameter">The parameter.</param>
/// <returns></returns>
/// <remarks>Documented by Dev08, 2009-02-16</remarks>
public static IDictionary GetLMConnection(LMConnectionParameter parameter)
{
return GetPersistentLMConnection(parameter.TestContext, parameter.RepositoryName, parameter.LearningModuleId, parameter.Callback, parameter.ConnectionType,
parameter.standAlone, parameter.Password, parameter.IsProtected);
}
/// <summary>
/// Gets the persistent LM connection.
/// </summary>
/// <param name="testContext">The test context.</param>
/// <param name="repositoryName">Name of the repository (Hostname of the Server).</param>
/// <param name="LMId">The LM id.</param>
/// <param name="callback">The callback.</param>
/// <param name="connectionType">Type of the connection.</param>
/// <param name="standAlone">if set to <c>true</c> a stand alone user will be created.</param>
/// <returns></returns>
/// <remarks>Documented by Dev10, 2008-08-01</remarks>
public static IDictionary GetPersistentLMConnection(TestContext testContext, string repositoryName, int LMId, GetLoginInformation callback, string connectionType, bool standAlone, string password, bool isProtected)
{
string connectionString = string.Empty;
ConnectionStringStruct ConnectionString;
string type = connectionType == "" ? (string)testContext.DataRow["Type"] : connectionType;
bool IsValid = (bool)testContext.DataRow["IsValid"];
switch (type.ToLower())
{
case "file":
#region ODX Tests
if (repositoryName == string.Empty) //Not persistent
{
repositoryName = MachineName;
ConnectionString = new ConnectionStringStruct(DatabaseType.Xml, TestDic, false);
}
else //Persistent (During Unit Test)
{
string persistentPath;
persistentPath = Path.GetTempPath() + repositoryName + Helper.OdxExtension;
cleanupQueue.Enqueue(persistentPath);
ConnectionString = new ConnectionStringStruct(DatabaseType.Xml, persistentPath, false);
}
#endregion
break;
case "pgsql":
#region PgSQL Tests
repositoryName = MachineName.ToLower();
if (testContext.DataRow["ConnectionString"] != System.DBNull.Value)
{
connectionString = (string)testContext.DataRow["ConnectionString"];
connectionString = connectionString.Replace("DYNAMIC", repositoryName);
//Only create DataBase if it was not yet created, so only for the first time, one database for all unit tests in this run
if (!DBCreated)
{
if (dbAccessByOtherUser)
throw new Exception("DB is being accessed by other users");
else
{
try
{
DropDB(repositoryName);
}
catch (NpgsqlException exp)
{
if (exp.Code == "55006") //Pgsql error code for: Database is accessed by other users
{
dbAccessByOtherUser = true;
throw new Exception("DB is being accessed by other users");
}
}
CreateDB(repositoryName, testContext, isProtected);
DBCreated = true;
tmpRepository = repositoryName;
}
}
}
else
throw new Exception("PGSQL connection string could not be read from unit test database.");
if (LMId < 0) //Persistent (During Test Run)
LMId = AddNewLM(repositoryName, isProtected);
ConnectionString = new ConnectionStringStruct(DatabaseType.PostgreSQL, connectionString, LMId);
#endregion
break;
case "sqlce":
#region SqlCe Tests
if (repositoryName == string.Empty) //Not persistent
{
repositoryName = MachineName;
ConnectionString = new ConnectionStringStruct(DatabaseType.MsSqlCe, TestDicSqlCE, false);
}
else //Persistent (During Unit Test)
{
string persistentPath;
persistentPath = Path.GetTempPath() + repositoryName + Helper.EmbeddedDbExtension;
cleanupQueue.Enqueue(persistentPath);
ConnectionString = new ConnectionStringStruct(DatabaseType.MsSqlCe, persistentPath, false);
}
if (password != string.Empty)
{
ConnectionString.ProtectedLm = true;
ConnectionString.Password = password;
}
if (LMId < 0)
{
string sqlCeConnString = GetFullSqlCeConnectionString(ConnectionString);
using (SqlCeEngine clientEngine = new SqlCeEngine(sqlCeConnString))
{
clientEngine.CreateDatabase();
clientEngine.Dispose();
}
using (SqlCeConnection con = new SqlCeConnection(sqlCeConnString))
{
con.Open();
SqlCeTransaction transaction = con.BeginTransaction();
string tmp = Helper.GetMsSqlCeScript();
string[] msSqlScriptArray = Helper.GetMsSqlCeScript().Split(';'); //Split the whole DB-Script into single commands (SQL-CE can not execute multiple queries)
foreach (string sqlCommand in msSqlScriptArray)
{
if (sqlCommand.TrimStart(' ', '\r', '\n').StartsWith("--") || sqlCommand.TrimStart(' ', '\r', '\n').Length < 5)
continue;
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = sqlCommand;
cmd.ExecuteNonQuery();
}
}
int cat_id;
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT id FROM Categories WHERE global_id=@cat_id;";
cmd.Parameters.Add("@cat_id", 1);
cat_id = Convert.ToInt32(cmd.ExecuteScalar());
}
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO LearningModules (guid, title, categories_id, default_settings_id, allowed_settings_id, licence_key, content_protected, cal_count) " +
"VALUES (@guid, @title, @cat_id, @dset, @aset, @lk, @cp, @cals);";
cmd.Parameters.Add("@guid", new Guid().ToString());
cmd.Parameters.Add("@title", "eDB test title");
cmd.Parameters.Add("@cat_id", cat_id);
cmd.Parameters.Add("@lk", "ACDED-LicenseKey-DEDAF");
cmd.Parameters.Add("@cp", password == string.Empty ? 0 : 1);
cmd.Parameters.Add("@cals", 1);
cmd.Parameters.Add("@dset", MsSqlCeCreateNewSettings(sqlCeConnString));
cmd.Parameters.Add("@aset", MsSqlCeCreateNewAllowedSettings(sqlCeConnString));
cmd.ExecuteNonQuery();
}
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT @@IDENTITY;";
LMId = Convert.ToInt32(cmd.ExecuteScalar());
}
transaction.Commit();
}
}
ConnectionString.LmId = LMId;
#endregion
break;
default:
throw new Exception("TestInfrastructure Class: conditions where set which are not applicable to the current db connection infrastructure");
}
IUser user;
if (callback == null)
user = UserFactory.Create((GetLoginInformation)GetTestUser, ConnectionString, (DataAccessErrorDelegate)delegate { return; }, standAlone);
else
user = UserFactory.Create(callback, ConnectionString, (DataAccessErrorDelegate)delegate { return; }, standAlone);
return user.Open();
}
/// <summary>
/// Gets the testuser.
/// </summary>
/// <param name="userStr">The user struct.</param>
/// <param name="con">The connectionStringStruct.</param>
/// <returns></returns>
/// <remarks>Documented by Dev08</remarks>
public static UserStruct? GetTestUser(UserStruct userStr, ConnectionStringStruct con)
{
UserStruct userStruct = new UserStruct("testuser", UserAuthenticationTyp.ListAuthentication);
userStruct.CloseOpenSessions = true;
return userStruct;
}
/// <summary>
/// Gets the admin user.
/// </summary>
/// <param name="userStr">The user struct.</param>
/// <param name="con">The connectionStringStruct.</param>
/// <returns>The user struct.</returns>
/// <remarks>Documented by Dev08</remarks>
public static UserStruct? GetAdminUser(UserStruct userStr, ConnectionStringStruct con)
{
UserStruct userStruct = new UserStruct("admin", "admin", UserAuthenticationTyp.FormsAuthentication, false);
userStruct.CloseOpenSessions = true;
return userStruct;
}
/// <summary>
/// Checks whether the current data layer supports nullable values.
/// </summary>
/// <param name="testContext">The test context.</param>
/// <returns></returns>
/// <remarks>Documented by Dev02, 2008-08-20</remarks>
public static bool SupportsNullableValues(TestContext testContext)
{
string type = (string)testContext.DataRow["Type"];
if (type.ToLower() == "file")
return false;
else if (type.ToLower() == "pgsql")
return true;
else if (type.ToLower() == "sqlce")
return true;
else
throw new Exception("TestContext: DataType not supported.");
}
/// <summary>
/// Gets the test audio.
/// </summary>
/// <returns></returns>
/// <remarks>Documented by Dev03, 2008-08-20</remarks>
public static string GetTestAudio()
{
string testAudio = cleanupQueue.GetTempFilePath(".wav");
byte[] buffer = new byte[Properties.Resources.homer_wav.Length];
Properties.Resources.homer_wav.Read(buffer, 0, (int)Properties.Resources.homer_wav.Length);
File.WriteAllBytes(testAudio, buffer);
return testAudio;
}
/// <summary>
/// Gets the test image.
/// </summary>
/// <returns></returns>
/// <remarks>Documented by Dev03, 2008-08-20</remarks>
public static string GetTestImage()
{
string testImage = cleanupQueue.GetTempFilePath(".jpg");
Properties.Resources.homer_jpg.Save(testImage);
return testImage;
}
/// <summary>
/// Gets the test video.
/// </summary>
/// <returns></returns>
/// <remarks>Documented by Dev03, 2008-08-20</remarks>
public static string GetTestVideo()
{
string testVideo = cleanupQueue.GetTempFilePath(".avi");
byte[] buffer = new byte[Properties.Resources.homer_avi.Length];
Properties.Resources.homer_wav.Read(buffer, 0, (int)Properties.Resources.homer_avi.Length);
File.WriteAllBytes(testVideo, buffer);
return testVideo;
}
/// <summary>
/// Gets the large test video.
/// </summary>
/// <returns></returns>
/// <remarks>Documented by Dev03, 2008-08-20</remarks>
/// <remarks>Documented by Dev08</remarks>
public static string GetLargeTestImage()
{
string testImagePath = cleanupQueue.GetTempFilePath(".jpg");
Bitmap testBitmap = new Bitmap(TestInfrastructure.random.Next(1000, 2000), TestInfrastructure.random.Next(1000, 2000));
testBitmap.Save(testImagePath);
return testImagePath;
}
/// <summary>
/// Gets the large test video.
/// </summary>
/// <returns></returns>
/// <remarks>Documented by Dev03, 2008-08-20</remarks>
public static string GetLargeTestVideo()
{
string testVideo = cleanupQueue.GetTempFilePath(".avi");
byte[] buffer = new byte[TestInfrastructure.Random.Next(20000000, 50000000)];
TestInfrastructure.Random.NextBytes(buffer);
File.WriteAllBytes(testVideo, buffer);
return testVideo;
}
/// <summary>
/// Gets the large test video.
/// </summary>
/// <returns></returns>
/// <remarks>Documented by Dev03, 2008-08-20</remarks>
public static string GetLargeTestAudio()
{
string testAudio = cleanupQueue.GetTempFilePath(".wav");
byte[] buffer = new byte[TestInfrastructure.Random.Next(5000000, 20000000)];
TestInfrastructure.Random.NextBytes(buffer);
File.WriteAllBytes(testAudio, buffer);
return testAudio;
}
/// <summary>
/// To be used within unit Tests to mark the Test Start in Debug View
/// </summary>
/// <param name="testContext">The test context.</param>
/// <remarks>Documented by Dev10, 2008-07-30</remarks>
public static void DebugLineStart(TestContext testContext)
{
Debug.WriteLine(beginLine + " Now starting test '" + testContext.TestName + "'" + beginLine);
}
/// <summary>
/// To be used within unit Tests to mark the Test End in Debug View
/// </summary>
/// <param name="testContext">The test context.</param>
/// <remarks>Documented by Dev10, 2008-07-30</remarks>
public static void DebugLineEnd(TestContext testContext)
{
Debug.WriteLine(endLine + " '" + testContext.TestName + "' ended " + endLine);
}
/// <summary>
/// Compares two DateTimes with a resolution of seconds
/// </summary>
/// <param name="dateTime1">The date time1.</param>
/// <param name="dateTime2">The date time2.</param>
/// <returns></returns>
/// <remarks>Documented by Dev08, 2009-01-19</remarks>
public static bool CompareDateTimes(DateTime dateTime1, DateTime dateTime2)
{
if (dateTime1.Year == dateTime2.Year &&
dateTime1.Month == dateTime2.Month &&
dateTime1.Day == dateTime2.Day &&
dateTime1.Hour == dateTime2.Hour &&
dateTime1.Minute == dateTime2.Minute &&
dateTime1.Second == dateTime2.Second)
return true;
return false;
}
#region Private Methods
#region Private odx Methods
private static string TestDic
{
//Gets the test dic, created a random file path for a odx.
get
{
return cleanupQueue.GetTempFilePath(Helper.OdxExtension);
}
}
#endregion
#region Private PgSql Methods
private static int AddNewLM(string repositoryName, bool contentProtected)
{
return AddNewLM(Guid.NewGuid().ToString(), 1, "SlipStreamResearch", repositoryName, contentProtected);
}
private static int AddNewLM(string guid, int categoryId, string title, string repositoryName, bool contentProtected)
{
string ConnectionString = connectionStringToGetExtended + repositoryName.ToLower();
int newLmId;
using (NpgsqlConnection con = CreateConnectionForLMCreation(ConnectionString))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
//if no specific id is provided LM will be created with auto id from DB
cmd.CommandText = "SELECT \"CreateNewLearningModule\"(:guid, :categoryid, :title)";
cmd.Parameters.Add("guid", guid);
cmd.Parameters.Add("categoryid", categoryId);
cmd.Parameters.Add("title", title);
//return newly created id if data set has been newly created
newLmId = Convert.ToInt32(cmd.ExecuteScalar());
}
if (contentProtected)
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "UPDATE \"LearningModules\" SET content_protected = true";
cmd.ExecuteNonQuery();
}
}
return newLmId;
}
}
private static void CreateDB(string repositoryName, TestContext testContext, bool isProtected)
{
using (NpgsqlConnection con = CreateConnectionForDBCreation())
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
//we always have low char strings
repositoryName = repositoryName.ToLower();
//get the sql script
string TablesCmdString = File.ReadAllText(Path.Combine(testContext.TestDeploymentDir, Properties.Resources.MLIFTERDBSQL));
string DBCreateCmdString;
//create the db
DBCreateCmdString = "CREATE DATABASE " + repositoryName + " ENCODING 'UTF8';";
cmd.CommandText = DBCreateCmdString;
cmd.ExecuteNonQuery();
//Why?? Fabthe
//fill it with data from sql script above
con.ChangeDatabase(repositoryName);
cmd.CommandText = TablesCmdString;
cmd.ExecuteNonQuery();
//create test user
string DBCreateTestuserCmdString = "SELECT \"InsertUserProfile\"('testuser', '', '', 'ListAuthentication'); SELECT \"AddGroupToUserByName\"('testuser', 'Student');";
cmd.CommandText = DBCreateTestuserCmdString;
cmd.ExecuteNonQuery();
if (isProtected)
{
using (NpgsqlCommand cmd2 = con.CreateCommand())
{
cmd2.CommandText = "UPDATE \"LearningModules\" SET content_protected = true";
cmd2.ExecuteNonQuery();
}
}
}
}
}
private static void DropDB(string repositoryName)
{
using (NpgsqlConnection con = CreateConnectionForDBCreation())
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
//we always have low char strings
repositoryName = repositoryName.ToLower();
//delete already existent table
string DBCreateCmdString;
DBCreateCmdString = "DROP DATABASE IF EXISTS " + repositoryName + ";";
cmd.CommandText = DBCreateCmdString;
cmd.ExecuteNonQuery();
con.Close();
}
}
}
private static NpgsqlConnection CreateConnectionForDBCreation()
{
return CreateConnectionForLMCreation(defaultConnectionString);
}
private static NpgsqlConnection CreatetDBConnectionBasedOnCurrentDBSession()
{
return CreateConnectionForLMCreation(connectionStringToGetExtended + tmpRepository);
}
private static NpgsqlConnection CreateConnectionForLMCreation(string ConnectionString)
{
NpgsqlConnection conn = new NpgsqlConnection(ConnectionString);
conn.Open();
return conn;
}
#endregion
#region Private SqlCe Methods
private static int MsSqlCeCreateNewSettings(string connectionString)
{
using (SqlCeConnection con = new SqlCeConnection(connectionString))
{
con.Open();
//1. SnoozeOptions Table
int snoozeOptionsId;
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO \"SnoozeOptions\"(cards_enabled,rights_enabled,time_enabled) VALUES(0,0,0);";
cmd.ExecuteNonQuery();
using (SqlCeCommand cmd2 = con.CreateCommand())
{
cmd2.CommandText = "SELECT @@IDENTITY;";
snoozeOptionsId = Convert.ToInt32(cmd2.ExecuteScalar());
}
}
//2. MultipleChoiceOptions Table
int multipleChoiceOptionsId;
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO\"MultipleChoiceOptions\" (allow_multiple_correct_answers, allow_random_distractors, max_correct_answers, number_of_choices)" +
"VALUES(0, 1, 1, 3);";
cmd.ExecuteNonQuery();
using (SqlCeCommand cmd2 = con.CreateCommand())
{
cmd2.CommandText = "SELECT @@IDENTITY;";
multipleChoiceOptionsId = Convert.ToInt32(cmd2.ExecuteScalar());
}
}
//3. QueryTypes Table
int queryTypesId;
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO \"QueryTypes\"(image_recognition, listening_comprehension, multiple_choice, sentence, word)" +
"VALUES(0, 0, 1, 0, 1);";
cmd.ExecuteNonQuery();
using (SqlCeCommand cmd2 = con.CreateCommand())
{
cmd2.CommandText = "SELECT @@IDENTITY;";
queryTypesId = Convert.ToInt32(cmd2.ExecuteScalar());
}
}
//4. TypeGradings Table
int typeGradingsId;
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO \"TypeGradings\"(all_correct, half_correct, none_correct, prompt) VALUES(0, 1, 0, 0);";
cmd.ExecuteNonQuery();
using (SqlCeCommand cmd2 = con.CreateCommand())
{
cmd2.CommandText = "SELECT @@IDENTITY;";
typeGradingsId = Convert.ToInt32(cmd2.ExecuteScalar());
}
}
//5. SynonymGradings Table
int synonymGradingsId;
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO \"SynonymGradings\"(all_known, half_known, one_known, first_known, prompt) VALUES(0, 0, 1, 0, 0);";
cmd.ExecuteNonQuery();
using (SqlCeCommand cmd2 = con.CreateCommand())
{
cmd2.CommandText = "SELECT @@IDENTITY;";
synonymGradingsId = Convert.ToInt32(cmd2.ExecuteScalar());
}
}
//6. QueryDirections Table
int queryDirectionsId;
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO \"QueryDirections\"(question2answer, answer2question, mixed) VALUES(1, 0, 0);";
cmd.ExecuteNonQuery();
using (SqlCeCommand cmd2 = con.CreateCommand())
{
cmd2.CommandText = "SELECT @@IDENTITY;";
queryDirectionsId = Convert.ToInt32(cmd2.ExecuteScalar());
}
}
//7. CardStyles Table
int cardStylesId;
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO \"CardStyles\"(value) VALUES(NULL);";
cmd.ExecuteNonQuery();
using (SqlCeCommand cmd2 = con.CreateCommand())
{
cmd2.CommandText = "SELECT @@IDENTITY;";
cardStylesId = Convert.ToInt32(cmd2.ExecuteScalar());
}
}
//8. Boxes Table
int boxesId;
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO \"Boxes\"(box1_size, box2_size, box3_size, box4_size, box5_size, box6_size, box7_size, box8_size, box9_size) " +
"VALUES(10, 20, 50, 100, 250, 500, 1000, 2000, 4000);";
cmd.ExecuteNonQuery();
using (SqlCeCommand cmd2 = con.CreateCommand())
{
cmd2.CommandText = "SELECT @@IDENTITY;";
boxesId = Convert.ToInt32(cmd2.ExecuteScalar());
}
}
//9. Settings Table --> insert all foreign keys into the settings table:
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO \"Settings\"" +
"(snooze_options, multiple_choice_options, query_types, type_gradings, synonym_gradings, query_directions, cardstyle, boxes, " +
"autoplay_audio, case_sensitive, confirm_demote, enable_commentary, correct_on_the_fly, enable_timer, random_pool, self_assessment, " +
"show_images, stripchars, auto_boxsize, pool_empty_message_shown, show_statistics, skip_correct_answers, use_lm_stylesheets)" +
"VALUES(@snooze_options_id, @multiple_choice_options_id, @query_types_id, @type_gradings_id, @synonym_gradings_id, @query_directions_id, " +
"@card_styles_id, @boxes_id, 1, 0, 0, 0, 0, 0, 1, 0, 1, @stripchars, 0, 0, 1, 0, 0);";
cmd.Parameters.Add("@snooze_options_id", snoozeOptionsId);
cmd.Parameters.Add("@multiple_choice_options_id", multipleChoiceOptionsId);
cmd.Parameters.Add("@query_types_id", queryTypesId);
cmd.Parameters.Add("@type_gradings_id", typeGradingsId);
cmd.Parameters.Add("@synonym_gradings_id", synonymGradingsId);
cmd.Parameters.Add("@query_directions_id", queryDirectionsId);
cmd.Parameters.Add("@card_styles_id", cardStylesId);
cmd.Parameters.Add("@boxes_id", boxesId);
cmd.Parameters.Add("@stripchars", "!,.?;");
cmd.ExecuteNonQuery();
using (SqlCeCommand cmd2 = con.CreateCommand())
{
cmd2.CommandText = "SELECT @@IDENTITY;";
return Convert.ToInt32(cmd2.ExecuteScalar());
}
}
}
}
private static int MsSqlCeCreateNewAllowedSettings(string connectionString)
{
using (SqlCeConnection con = new SqlCeConnection(connectionString))
{
con.Open();
//1. SnoozeOptions Table
int snoozeOptionsId;
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO \"SnoozeOptions\"(cards_enabled,rights_enabled,time_enabled) VALUES(1,1,1);";
cmd.ExecuteNonQuery();
using (SqlCeCommand cmd2 = con.CreateCommand())
{
cmd2.CommandText = "SELECT @@IDENTITY;";
snoozeOptionsId = Convert.ToInt32(cmd2.ExecuteScalar());
}
}
//2. MultipleChoiceOptions Table
int multipleChoiceOptionsId;
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO\"MultipleChoiceOptions\" (allow_multiple_correct_answers, allow_random_distractors)" +
"VALUES(1, 1);";
cmd.ExecuteNonQuery();
using (SqlCeCommand cmd2 = con.CreateCommand())
{
cmd2.CommandText = "SELECT @@IDENTITY;";
multipleChoiceOptionsId = Convert.ToInt32(cmd2.ExecuteScalar());
}
}
//3. QueryTypes Table
int queryTypesId;
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO \"QueryTypes\"(image_recognition, listening_comprehension, multiple_choice, sentence, word)" +
"VALUES(1, 1, 1, 1, 1);";
cmd.ExecuteNonQuery();
using (SqlCeCommand cmd2 = con.CreateCommand())
{
cmd2.CommandText = "SELECT @@IDENTITY;";
queryTypesId = Convert.ToInt32(cmd2.ExecuteScalar());
}
}
//4. TypeGradings Table
int typeGradingsId;
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO \"TypeGradings\"(all_correct, half_correct, none_correct, prompt) VALUES(1, 1, 1, 1);";
cmd.ExecuteNonQuery();
using (SqlCeCommand cmd2 = con.CreateCommand())
{
cmd2.CommandText = "SELECT @@IDENTITY;";
typeGradingsId = Convert.ToInt32(cmd2.ExecuteScalar());
}
}
//5. SynonymGradings Table
int synonymGradingsId;
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO \"SynonymGradings\"(all_known, half_known, one_known, first_known, prompt) VALUES(1, 1, 1, 1, 1);";
cmd.ExecuteNonQuery();
using (SqlCeCommand cmd2 = con.CreateCommand())
{
cmd2.CommandText = "SELECT @@IDENTITY;";
synonymGradingsId = Convert.ToInt32(cmd2.ExecuteScalar());
}
}
//6. QueryDirections Table
int queryDirectionsId;
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO \"QueryDirections\"(question2answer, answer2question, mixed) VALUES(1, 1, 1);";
cmd.ExecuteNonQuery();
using (SqlCeCommand cmd2 = con.CreateCommand())
{
cmd2.CommandText = "SELECT @@IDENTITY;";
queryDirectionsId = Convert.ToInt32(cmd2.ExecuteScalar());
}
}
//7. CardStyles Table
int cardStylesId;
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO \"CardStyles\"(value) VALUES(NULL);";
cmd.ExecuteNonQuery();
using (SqlCeCommand cmd2 = con.CreateCommand())
{
cmd2.CommandText = "SELECT @@IDENTITY;";
cardStylesId = Convert.ToInt32(cmd2.ExecuteScalar());
}
}
//8. Boxes Table
int boxesId;
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO \"Boxes\"(box1_size, box2_size, box3_size, box4_size, box5_size, box6_size, box7_size, box8_size, box9_size) " +
"VALUES(null, null, null, null, null, null, null, null, null);";
cmd.ExecuteNonQuery();
using (SqlCeCommand cmd2 = con.CreateCommand())
{
cmd2.CommandText = "SELECT @@IDENTITY;";
boxesId = Convert.ToInt32(cmd2.ExecuteScalar());
}
}
//9. Settings Table --> insert all foreign keys into the settings table:
using (SqlCeCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO \"Settings\"" +
"(snooze_options, multiple_choice_options, query_types, type_gradings, synonym_gradings, query_directions, cardstyle, boxes, " +
"autoplay_audio, case_sensitive, confirm_demote, enable_commentary, correct_on_the_fly, enable_timer, random_pool, self_assessment, " +
"show_images, stripchars, auto_boxsize, pool_empty_message_shown, show_statistics, skip_correct_answers, use_lm_stylesheets)" +
"VALUES(@snooze_options_id, @multiple_choice_options_id, @query_types_id, @type_gradings_id, @synonym_gradings_id, @query_directions_id, " +
"@card_styles_id, @boxes_id, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);";
cmd.Parameters.Add("@snooze_options_id", snoozeOptionsId);
cmd.Parameters.Add("@multiple_choice_options_id", multipleChoiceOptionsId);
cmd.Parameters.Add("@query_types_id", queryTypesId);
cmd.Parameters.Add("@type_gradings_id", typeGradingsId);
cmd.Parameters.Add("@synonym_gradings_id", synonymGradingsId);
cmd.Parameters.Add("@query_directions_id", queryDirectionsId);
cmd.Parameters.Add("@card_styles_id", cardStylesId);
cmd.Parameters.Add("@boxes_id", boxesId);
cmd.ExecuteNonQuery();
using (SqlCeCommand cmd2 = con.CreateCommand())
{
cmd2.CommandText = "SELECT @@IDENTITY;";
return Convert.ToInt32(cmd2.ExecuteScalar());
}
}
}
}
private static string GetFullSqlCeConnectionString(string filePath)
{
return "Data Source=" + filePath + ";Max Database Size=4091;Persist Security Info=False;";
}
private static string GetFullSqlCeConnectionString(ConnectionStringStruct connectionString)
{
string output = GetFullSqlCeConnectionString(connectionString.ConnectionString);
if (connectionString.Password != string.Empty)
output += "Encrypt Database=True;Password=" + connectionString.Password + ";";
return output;
}
private static string TestDicSqlCE
{
get
{
//Gets the test dic SQL CE.
return cleanupQueue.GetTempFilePath(Helper.EmbeddedDbExtension);
}
}
#endregion
#endregion
}
public struct LMConnectionParameter
{
public TestContext TestContext;
public string RepositoryName;
public int LearningModuleId;
public GetLoginInformation Callback;
public string ConnectionType;
public bool standAlone;
public string Password;
public bool IsProtected;
public LMConnectionParameter(TestContext testContext)
{
this.TestContext = testContext;
RepositoryName = string.Empty;
LearningModuleId = -1;
Callback = null;
ConnectionType = string.Empty;
standAlone = false;
Password = string.Empty;
IsProtected = false;
}
}
}
| |
using System.Diagnostics.CodeAnalysis;
namespace Signum.Engine.Maps;
public class TableIndex
{
public ITable Table { get; private set; }
public IColumn[] Columns { get; private set; }
public IColumn[]? IncludeColumns { get; set; }
public string? Where { get; set; }
public static IColumn[] GetColumnsFromFields(params Field[] fields)
{
if (fields == null || fields.IsEmpty())
throw new InvalidOperationException("No fields");
if (fields.Any(f => f is FieldEmbedded || f is FieldMixin))
throw new InvalidOperationException("Embedded fields not supported for indexes");
return fields.SelectMany(f => f.Columns()).ToArray();
}
public TableIndex(ITable table, params IColumn[] columns)
{
if (table == null)
throw new ArgumentNullException(nameof(table));
if (columns == null || columns.IsEmpty())
throw new ArgumentNullException(nameof(columns));
this.Table = table;
this.Columns = columns;
}
public virtual string GetIndexName(ObjectName tableName)
{
int maxLength = MaxNameLength();
return StringHashEncoder.ChopHash("IX_{0}_{1}".FormatWith(tableName.Name, ColumnSignature()), maxLength) + WhereSignature();
}
protected static int MaxNameLength()
{
return Connector.Current.MaxNameLength - StringHashEncoder.HashSize - 2;
}
public string IndexName => GetIndexName(Table.Name);
protected string ColumnSignature()
{
return Columns.ToString(c => c.Name, "_");
}
public string? WhereSignature()
{
var includeColumns = IncludeColumns.HasItems() ? IncludeColumns.ToString(c => c.Name, "_") : null;
if (string.IsNullOrEmpty(Where) && includeColumns == null)
return null;
return "__" + StringHashEncoder.Codify(Where + includeColumns);
}
public override string ToString()
{
return IndexName;
}
public string HintText()
{
return $"INDEX([{this.IndexName}])";
}
}
public class PrimaryKeyIndex : TableIndex
{
public PrimaryKeyIndex(ITable table) : base(table, new[] { table.PrimaryKey })
{
}
public override string GetIndexName(ObjectName tableName) => GetPrimaryKeyName(tableName);
public static string GetPrimaryKeyName(ObjectName tableName)
{
return "PK_" + tableName.Schema.Name + "_" + tableName.Name;
}
}
public class UniqueTableIndex : TableIndex
{
public UniqueTableIndex(ITable table, IColumn[] columns)
: base(table, columns)
{
}
public override string GetIndexName(ObjectName tableName)
{
var maxSize = MaxNameLength();
return StringHashEncoder.ChopHash("UIX_{0}_{1}".FormatWith(tableName.Name, ColumnSignature()), maxSize) + WhereSignature();
}
public string? ViewName
{
get
{
if (!Where.HasText())
return null;
if (Connector.Current.AllowsIndexWithWhere(Where))
return null;
var maxSize = MaxNameLength();
return StringHashEncoder.ChopHash("VIX_{0}_{1}".FormatWith(Table.Name.Name, ColumnSignature()), maxSize) + WhereSignature();
}
}
public bool AvoidAttachToUniqueIndexes { get; set; }
}
public class IndexKeyColumns
{
public static IColumn[] Split(IFieldFinder finder, LambdaExpression columns)
{
if (columns == null)
throw new ArgumentNullException(nameof(columns));
if (columns.Body.NodeType == ExpressionType.New)
{
var resultColumns = (from a in ((NewExpression)columns.Body).Arguments
from c in GetColumns(finder, Expression.Lambda(Expression.Convert(a, typeof(object)), columns.Parameters))
select c);
return resultColumns.ToArray();
}
return GetColumns(finder, columns);
}
static string[] ignoreMembers = new string[] { "ToLite", "ToLiteFat" };
static IColumn[] GetColumns(IFieldFinder finder, LambdaExpression field)
{
var body = field.Body;
Type? type = RemoveCasting(ref body);
body = IndexWhereExpressionVisitor.RemoveLiteEntity(body);
var members = Reflector.GetMemberListBase(body);
if (members.Any(a => ignoreMembers.Contains(a.Name)))
members = members.Where(a => !ignoreMembers.Contains(a.Name)).ToArray();
Field f = Schema.FindField(finder, members);
if (type != null)
{
var ib = f as FieldImplementedBy;
if (ib == null)
throw new InvalidOperationException("Casting only supported for {0}".FormatWith(typeof(FieldImplementedBy).Name));
return (from ic in ib.ImplementationColumns
where type.IsAssignableFrom(ic.Key)
select (IColumn)ic.Value).ToArray();
}
return TableIndex.GetColumnsFromFields(f);
}
static Type? RemoveCasting(ref Expression body)
{
if (body.NodeType == ExpressionType.Convert && body.Type == typeof(object))
body = ((UnaryExpression)body).Operand;
Type? type = null;
if ((body.NodeType == ExpressionType.Convert || body.NodeType == ExpressionType.TypeAs) &&
body.Type != typeof(object))
{
type = body.Type;
body = ((UnaryExpression)body).Operand;
}
return type;
}
}
public class IndexWhereExpressionVisitor : ExpressionVisitor
{
StringBuilder sb = new StringBuilder();
IFieldFinder RootFinder;
bool isPostgres;
public IndexWhereExpressionVisitor(IFieldFinder rootFinder)
{
RootFinder = rootFinder;
this.isPostgres = Schema.Current.Settings.IsPostgres;
}
public static string GetIndexWhere(LambdaExpression lambda, IFieldFinder rootFiender)
{
IndexWhereExpressionVisitor visitor = new IndexWhereExpressionVisitor(rootFiender);
var newLambda = (LambdaExpression)ExpressionEvaluator.PartialEval(lambda);
visitor.Visit(newLambda.Body);
return visitor.sb.ToString();
}
public Field GetField(Expression exp)
{
if (exp.NodeType == ExpressionType.Convert)
exp = ((UnaryExpression)exp).Operand;
return Schema.FindField(RootFinder, Reflector.GetMemberListBase(exp));
}
[return: NotNullIfNotNull("exp")]
public override Expression? Visit(Expression? exp)
{
switch (exp!.NodeType)
{
case ExpressionType.Conditional:
case ExpressionType.Constant:
case ExpressionType.Parameter:
case ExpressionType.Call:
case ExpressionType.Lambda:
case ExpressionType.New:
case ExpressionType.NewArrayInit:
case ExpressionType.NewArrayBounds:
case ExpressionType.Invoke:
case ExpressionType.MemberInit:
case ExpressionType.ListInit:
throw new NotSupportedException("Expression of type {0} not supported: {1}".FormatWith(exp.NodeType, exp.ToString()));
default:
return base.Visit(exp);
}
}
protected override Expression VisitTypeBinary(TypeBinaryExpression b)
{
var exp = RemoveLiteEntity(b.Expression);
var f = GetField(exp);
if (f is FieldReference fr)
{
if (b.TypeOperand.IsAssignableFrom(fr.FieldType))
sb.Append(fr.Name.SqlEscape(isPostgres) + " IS NOT NULL");
else
throw new InvalidOperationException("A {0} will never be {1}".FormatWith(fr.FieldType.TypeName(), b.TypeOperand.TypeName()));
return b;
}
if (f is FieldImplementedBy fib)
{
var typeOperant = b.TypeOperand.CleanType();
var imp = fib.ImplementationColumns.Where(kvp => typeOperant.IsAssignableFrom(kvp.Key));
if (imp.Any())
sb.Append(imp.ToString(kvp => kvp.Value.Name.SqlEscape(isPostgres) + " IS NOT NULL", " OR "));
else
throw new InvalidOperationException("No implementation ({0}) will never be {1}".FormatWith(fib.ImplementationColumns.Keys.ToString(t => t.TypeName(), ", "), b.TypeOperand.TypeName()));
return b;
}
throw new NotSupportedException("'is' only works with ImplementedBy or Reference fields");
}
public static Expression RemoveLiteEntity(Expression exp)
{
if (exp is MemberExpression m && m.Member is PropertyInfo pi && m.Expression!.Type.IsInstantiationOf(typeof(Lite<>)) &&
(pi.Name == nameof(Lite<Entity>.Entity) || pi.Name == nameof(Lite<Entity>.EntityOrNull)))
return m.Expression;
return exp;
}
protected override Expression VisitMember(MemberExpression m)
{
var field = GetField(m);
sb.Append(Equals(field, value: true, equals: true, isPostgres));
return m;
}
protected override Expression VisitUnary(UnaryExpression u)
{
switch (u.NodeType)
{
case ExpressionType.Not:
sb.Append(" NOT ");
this.Visit(u.Operand);
break;
case ExpressionType.Negate:
sb.Append(" - ");
this.Visit(u.Operand);
break;
case ExpressionType.UnaryPlus:
sb.Append(" + ");
this.Visit(u.Operand);
break;
case ExpressionType.Convert:
//Las unicas conversiones explicitas son a Binary y desde datetime a numeros
this.Visit(u.Operand);
break;
default:
throw new NotSupportedException(string.Format("The unary perator {0} is not supported", u.NodeType));
}
return u;
}
public static string IsNull(Field field, bool equals, bool isPostgres)
{
string isNull = equals ? "{0} IS NULL" : "{0} IS NOT NULL";
if (field is IColumn col)
{
string result = isNull.FormatWith(col.Name.SqlEscape(isPostgres));
if (!col.DbType.IsString())
return result;
return result + (equals ? " OR " : " AND ") + (col.Name.SqlEscape(isPostgres) + (equals ? " = " : " <> ") + "''");
}
else if (field is FieldImplementedBy ib)
{
return ib.ImplementationColumns.Values.Select(ic => isNull.FormatWith(ic.Name.SqlEscape(isPostgres))).ToString(equals ? " AND " : " OR ");
}
else if (field is FieldImplementedByAll iba)
{
return isNull.FormatWith(iba.Column.Name.SqlEscape(isPostgres)) +
(equals ? " AND " : " OR ") +
isNull.FormatWith(iba.ColumnType.Name.SqlEscape(isPostgres));
}
else if (field is FieldEmbedded fe)
{
if (fe.HasValue == null)
throw new NotSupportedException("{0} is not nullable".FormatWith(field));
return fe.HasValue.Name.SqlEscape(isPostgres) + " = 1";
}
throw new NotSupportedException(isNull.FormatWith(field.GetType()));
}
static string Equals(Field field, object value, bool equals, bool isPostgres)
{
if (value == null)
{
return IsNull(field, equals, isPostgres);
}
else
{
if (field is IColumn)
{
return ((IColumn)field).Name.SqlEscape(isPostgres) +
(equals ? " = " : " <> ") + SqlPreCommandSimple.Encode(value);
}
throw new NotSupportedException("Impossible to compare {0} to {1}".FormatWith(field, value));
}
}
protected override Expression VisitBinary(BinaryExpression b)
{
if (b.NodeType == ExpressionType.Coalesce)
{
sb.Append("IsNull(");
Visit(b.Left);
sb.Append(',');
Visit(b.Right);
sb.Append(')');
}
else if (b.NodeType == ExpressionType.Equal || b.NodeType == ExpressionType.NotEqual)
{
if (b.Left is ConstantExpression)
{
if (b.Right is ConstantExpression)
throw new NotSupportedException("NULL == NULL not supported");
Field field = GetField(b.Right);
sb.Append(Equals(field, ((ConstantExpression)b.Left).Value!, b.NodeType == ExpressionType.Equal, isPostgres));
}
else if (b.Right is ConstantExpression)
{
Field field = GetField(b.Left);
sb.Append(Equals(field, ((ConstantExpression)b.Right).Value!, b.NodeType == ExpressionType.Equal, isPostgres));
}
else
throw new NotSupportedException("Impossible to translate {0}".FormatWith(b.ToString()));
}
else
{
sb.Append('(');
this.Visit(b.Left);
switch (b.NodeType)
{
case ExpressionType.And:
case ExpressionType.AndAlso:
sb.Append(b.Type.UnNullify() == typeof(bool) ? " AND " : " & ");
break;
case ExpressionType.Or:
case ExpressionType.OrElse:
sb.Append(b.Type.UnNullify() == typeof(bool) ? " OR " : " | ");
break;
case ExpressionType.ExclusiveOr:
sb.Append(" ^ ");
break;
case ExpressionType.LessThan:
sb.Append(" < ");
break;
case ExpressionType.LessThanOrEqual:
sb.Append(" <= ");
break;
case ExpressionType.GreaterThan:
sb.Append(" > ");
break;
case ExpressionType.GreaterThanOrEqual:
sb.Append(" >= ");
break;
case ExpressionType.Add:
case ExpressionType.AddChecked:
sb.Append(" + ");
break;
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
sb.Append(" - ");
break;
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
sb.Append(" * ");
break;
case ExpressionType.Divide:
sb.Append(" / ");
break;
case ExpressionType.Modulo:
sb.Append(" % ");
break;
default:
throw new NotSupportedException(string.Format("The binary operator {0} is not supported", b.NodeType));
}
this.Visit(b.Right);
sb.Append(')');
}
return b;
}
}
| |
namespace IdSharp.Tagging.ID3v2.Frames
{
using IdSharp.Tagging.ID3v2;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
internal sealed class RelativeVolumeAdjustment : IRelativeVolumeAdjustment, IFrame, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public RelativeVolumeAdjustment()
{
this.m_FrameHeader = new IdSharp.Tagging.ID3v2.FrameHeader();
}
private void FirePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler1 = this.PropertyChanged;
if (handler1 != null)
{
handler1(this, new PropertyChangedEventArgs(propertyName));
}
}
public byte[] GetBytes(ID3v2TagVersion tagVersion)
{
return new byte[0];
}
public string GetFrameID(ID3v2TagVersion tagVersion)
{
switch (tagVersion)
{
case ID3v2TagVersion.ID3v22:
return "RVA";
case ID3v2TagVersion.ID3v23:
return "RVAD";
case ID3v2TagVersion.ID3v24:
return "RVA2";
}
throw new ArgumentException("Unknown tag version");
}
public void Read(TagReadingInfo tagReadingInfo, Stream stream)
{
this.m_FrameHeader.Read(tagReadingInfo, ref stream);
int num1 = this.m_FrameHeader.FrameSizeExcludingAdditions;
if (num1 > 0)
{
bool flag1 = this.m_FrameHeader.TagVersion == ID3v2TagVersion.ID3v24;
if (flag1)
{
this.Identification = Utils.ReadString(EncodingType.ISO88591, stream, ref num1);
while (num1 >= 3)
{
Utils.ReadByte(stream, ref num1);
Utils.ReadInt16(stream, ref num1);
if (num1 > 0)
{
byte num2 = Utils.ReadByte(stream, ref num1);
if ((num2 == 0) || (num1 < num2))
{
break;
}
byte[] buffer1 = Utils.Read(stream, num2);
num1 -= buffer1.Length;
}
}
if (num1 > 0)
{
stream.Seek((long) (num1 - this.m_FrameHeader.FrameSizeExcludingAdditions), SeekOrigin.Current);
num1 = this.m_FrameHeader.FrameSizeExcludingAdditions;
flag1 = false;
}
}
if (!flag1)
{
byte num3 = Utils.ReadByte(stream, ref num1);
if (num1 > 0)
{
byte num4 = Utils.ReadByte(stream, ref num1);
int num5 = num4 / 8;
if (num1 >= num5)
{
byte[] buffer2 = Utils.Read(stream, num5, ref num1);
this.FrontRightAdjustment = (decimal) (Utils.ConvertToInt64(buffer2) * (Utils.IsBitSet(num3, 0) ? ((long) 1) : ((long) (-1))));
}
if (num1 >= num5)
{
byte[] buffer3 = Utils.Read(stream, num5, ref num1);
this.FrontLeftAdjustment = (decimal) (Utils.ConvertToInt64(buffer3) * (Utils.IsBitSet(num3, 1) ? ((long) 1) : ((long) (-1))));
}
if (num1 >= num5)
{
byte[] buffer4 = Utils.Read(stream, num5, ref num1);
this.FrontRightPeak = (decimal) Utils.ConvertToInt64(buffer4);
}
if (num1 >= num5)
{
byte[] buffer5 = Utils.Read(stream, num5, ref num1);
this.FrontLeftPeak = (decimal) Utils.ConvertToInt64(buffer5);
}
if (num1 >= num5)
{
byte[] buffer6 = Utils.Read(stream, num5, ref num1);
this.BackRightAdjustment = (decimal) (Utils.ConvertToInt64(buffer6) * (Utils.IsBitSet(num3, 2) ? ((long) 1) : ((long) (-1))));
}
if (num1 >= num5)
{
byte[] buffer7 = Utils.Read(stream, num5, ref num1);
this.BackLeftAdjustment = (decimal) (Utils.ConvertToInt64(buffer7) * (Utils.IsBitSet(num3, 3) ? ((long) 1) : ((long) (-1))));
}
if (num1 >= num5)
{
byte[] buffer8 = Utils.Read(stream, num5, ref num1);
this.BackRightPeak = (decimal) Utils.ConvertToInt64(buffer8);
}
if (num1 >= num5)
{
byte[] buffer9 = Utils.Read(stream, num5, ref num1);
this.BackLeftPeak = (decimal) Utils.ConvertToInt64(buffer9);
}
if (num1 >= num5)
{
byte[] buffer10 = Utils.Read(stream, num5, ref num1);
this.FrontCenterAdjustment = (decimal) (Utils.ConvertToInt64(buffer10) * (Utils.IsBitSet(num3, 4) ? ((long) 1) : ((long) (-1))));
}
if (num1 >= num5)
{
byte[] buffer11 = Utils.Read(stream, num5, ref num1);
this.FrontCenterPeak = (decimal) Utils.ConvertToInt64(buffer11);
}
if (num1 >= num5)
{
byte[] buffer12 = Utils.Read(stream, num5, ref num1);
this.SubwooferAdjustment = (decimal) (Utils.ConvertToInt64(buffer12) * (Utils.IsBitSet(num3, 5) ? ((long) 1) : ((long) (-1))));
}
if (num1 >= num5)
{
byte[] buffer13 = Utils.Read(stream, num5, ref num1);
this.SubwooferPeak = (decimal) Utils.ConvertToInt64(buffer13);
}
}
}
if (num1 > 0)
{
Trace.WriteLine("Invalid RVA2/RVAD/RVA frame");
stream.Seek((long) num1, SeekOrigin.Current);
}
}
}
private void WriteID3v24ChannelItem(MemoryStream memoryStream, ChannelType channelType, decimal adjustment, decimal peak)
{
if ((adjustment != new decimal(0)) || (peak != new decimal(0)))
{
memoryStream.WriteByte((byte) channelType);
if (adjustment <= new decimal(0x40))
{
bool flag1 = adjustment >= new decimal(-64);
}
throw new NotImplementedException();
}
}
public decimal BackCenterAdjustment
{
get
{
return this.m_BackCenterAdjustment;
}
set
{
this.m_BackCenterAdjustment = value;
this.FirePropertyChanged("BackCenterAdjustment");
}
}
public decimal BackCenterPeak
{
get
{
return this.m_BackCenterPeak;
}
set
{
this.m_BackCenterPeak = value;
this.FirePropertyChanged("BackCenterPeak");
}
}
public decimal BackLeftAdjustment
{
get
{
return this.m_BackLeftAdjustment;
}
set
{
this.m_BackLeftAdjustment = value;
this.FirePropertyChanged("BackLeftAdjustment");
}
}
public decimal BackLeftPeak
{
get
{
return this.m_BackLeftPeak;
}
set
{
this.m_BackLeftPeak = value;
this.FirePropertyChanged("BackLeftPeak");
}
}
public decimal BackRightAdjustment
{
get
{
return this.m_BackRightAdjustment;
}
set
{
this.m_BackRightAdjustment = value;
this.FirePropertyChanged("BackRightAdjustment");
}
}
public decimal BackRightPeak
{
get
{
return this.m_BackRightPeak;
}
set
{
this.m_BackRightPeak = value;
this.FirePropertyChanged("BackRightPeak");
}
}
public IFrameHeader FrameHeader
{
get
{
return this.m_FrameHeader;
}
}
public decimal FrontCenterAdjustment
{
get
{
return this.m_FrontCenterAdjustment;
}
set
{
this.m_FrontCenterAdjustment = value;
this.FirePropertyChanged("FrontCenterAdjustment");
}
}
public decimal FrontCenterPeak
{
get
{
return this.m_FrontCenterPeak;
}
set
{
this.m_FrontCenterPeak = value;
this.FirePropertyChanged("FrontCenterPeak");
}
}
public decimal FrontLeftAdjustment
{
get
{
return this.m_FrontLeftAdjustment;
}
set
{
this.m_FrontLeftAdjustment = value;
this.FirePropertyChanged("FrontLeftAdjustment");
}
}
public decimal FrontLeftPeak
{
get
{
return this.m_FrontLeftPeak;
}
set
{
this.m_FrontLeftPeak = value;
this.FirePropertyChanged("FrontLeftPeak");
}
}
public decimal FrontRightAdjustment
{
get
{
return this.m_FrontRightAdjustment;
}
set
{
this.m_FrontRightAdjustment = value;
this.FirePropertyChanged("FrontRightAdjustment");
}
}
public decimal FrontRightPeak
{
get
{
return this.m_FrontRightPeak;
}
set
{
this.m_FrontRightPeak = value;
this.FirePropertyChanged("FrontRightPeak");
}
}
public string Identification
{
get
{
return this.m_Identification;
}
set
{
this.m_Identification = value;
this.FirePropertyChanged("Identification");
}
}
public decimal MasterAdjustment
{
get
{
return this.m_MasterAdjustment;
}
set
{
this.m_MasterAdjustment = value;
this.FirePropertyChanged("MasterAdjustment");
}
}
public decimal MasterPeak
{
get
{
return this.m_MasterPeak;
}
set
{
this.m_MasterPeak = value;
this.FirePropertyChanged("MasterPeak");
}
}
public decimal OtherAdjustment
{
get
{
return this.m_OtherAdjustment;
}
set
{
this.m_OtherAdjustment = value;
this.FirePropertyChanged("OtherAdjustment");
}
}
public decimal OtherPeak
{
get
{
return this.m_OtherPeak;
}
set
{
this.m_OtherPeak = value;
this.FirePropertyChanged("OtherPeak");
}
}
public decimal SubwooferAdjustment
{
get
{
return this.m_SubwooferAdjustment;
}
set
{
this.m_SubwooferAdjustment = value;
this.FirePropertyChanged("SubwooferAdjustment");
}
}
public decimal SubwooferPeak
{
get
{
return this.m_SubwooferPeak;
}
set
{
this.m_SubwooferPeak = value;
this.FirePropertyChanged("SubwooferPeak");
}
}
private decimal m_BackCenterAdjustment;
private decimal m_BackCenterPeak;
private decimal m_BackLeftAdjustment;
private decimal m_BackLeftPeak;
private decimal m_BackRightAdjustment;
private decimal m_BackRightPeak;
private IdSharp.Tagging.ID3v2.FrameHeader m_FrameHeader;
private decimal m_FrontCenterAdjustment;
private decimal m_FrontCenterPeak;
private decimal m_FrontLeftAdjustment;
private decimal m_FrontLeftPeak;
private decimal m_FrontRightAdjustment;
private decimal m_FrontRightPeak;
private const byte m_ID3v24BitsRepresentingPeak = 0x10;
private string m_Identification;
private decimal m_MasterAdjustment;
private decimal m_MasterPeak;
private decimal m_OtherAdjustment;
private decimal m_OtherPeak;
private decimal m_SubwooferAdjustment;
private decimal m_SubwooferPeak;
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using Bloom.Utils;
using SIL.IO;
using SIL.Xml;
using TidyManaged;
namespace Bloom
{
public static class XmlHtmlConverter
{
private const string SvgPlaceholder = "****RestoreSvgHere****";
private static readonly Regex _selfClosingRegex = new Regex(@"<([ubi]|em|strong|span)(\s+[^><]+\s*)/>");
private static readonly Regex _emptySelfClosingElementsToRemoveRegex = new Regex(@"<([ubi]|em|strong|span)\s*/>");
private static readonly Regex _emptyElementsWithAttributesRegex = new Regex(@"<([ubi]|em|strong|span|cite)(\s+[^><]+\s*)>(\s*)</\1>");
private static readonly Regex _emptyElementsToPreserveRegex = new Regex(@"<(p|cite)\s*>(\s*)</\1>");
private static readonly Regex _selfClosingElementsToPreserveRegex = new Regex(@"<(p|cite)(\s+[^><]*\s*)/>");
public static XmlDocument GetXmlDomFromHtmlFile(string path, bool includeXmlDeclaration = false)
{
return GetXmlDomFromHtml(RobustFile.ReadAllText(path), includeXmlDeclaration);
}
/// <summary></summary>
/// <param name="content"></param>
/// <param name="includeXmlDeclaration"></param>
/// <exception>Throws if there are parsing errors</exception>
/// <returns></returns>
public static XmlDocument GetXmlDomFromHtml(string content, bool includeXmlDeclaration = false)
{
var dom = new XmlDocument();
content = AddFillerToKeepTidyFromRemovingEmptyElements(content);
//in BL-2250, we found that in previous versions, this method would turn, for example, "<u> </u>" REMOVEWHITESPACE.
//That is fixed now, but this is needed to give to clean up existing books.
content = content.Replace(@"REMOVEWHITESPACE", "");
// tidy likes to insert newlines before <b>, <u>, <i>, and these other elements and convert any existing whitespace
// there to a space. (span was found by pursuing BL-7558)
content = new Regex(@"<([ubi]|em|strong|sup|sub|span[^>]*)>").Replace(content, "REMOVEWHITESPACE<$1>");
// fix for <br></br> tag doubling
content = content.Replace("<br></br>", "<br />");
// fix for > and similar in <style> element protected by CDATA.
// At present we only need to account for this occurring once.
// See Browser.SaveCustomizedCssRules.
var startOfCdata = content.IndexOf(Browser.CdataPrefix, StringComparison.InvariantCulture);
const string restoreCdataHere = "/****RestoreCDATAHere*****/";
var endOfCdata = content.IndexOf(Browser.CdataSuffix, StringComparison.InvariantCulture);
var savedCdata = "";
if (startOfCdata >= 0 && endOfCdata >= startOfCdata)
{
endOfCdata += Browser.CdataSuffix.Length;
savedCdata = content.Substring(startOfCdata, endOfCdata - startOfCdata);
content = content.Substring(0, startOfCdata) + restoreCdataHere + content.Substring(endOfCdata, content.Length - endOfCdata);
}
var removedSvgs = new List<string>();
content = RemoveSvgs(content, removedSvgs);
//using (var temp = new TempFile())
var temp = new TempFile();
{
RobustFile.WriteAllText(temp.Path, content, Encoding.UTF8);
using (var tidy = RobustIO.DocumentFromFile(temp.Path))
{
tidy.ShowWarnings = false;
tidy.Quiet = true;
tidy.WrapAt = 0; // prevents textarea wrapping.
tidy.AddTidyMetaElement = false;
tidy.OutputXml = true;
tidy.CharacterEncoding = EncodingType.Utf8;
tidy.InputCharacterEncoding = EncodingType.Utf8;
tidy.OutputCharacterEncoding = EncodingType.Utf8;
tidy.DocType = DocTypeMode.Omit; //when it supports html5, then we will let it out it
//maybe try this? tidy.Markup = true;
tidy.AddXmlDeclaration = includeXmlDeclaration;
//NB: this does not prevent tidy from deleting <span data-libray='somethingImportant'></span>
tidy.MergeSpans = AutoBool.No;
tidy.DropEmptyParagraphs = false;
tidy.MergeDivs = AutoBool.No;
var errors = tidy.CleanAndRepair();
if (!string.IsNullOrEmpty(errors))
{
throw new ApplicationException(errors);
}
var newContents = tidy.Save();
try
{
newContents = RestoreSvgs(newContents, removedSvgs);
newContents = RemoveFillerInEmptyElements(newContents);
newContents = newContents.Replace(" ", " ");
//REVIEW: 1) are there others? & and such are fine. 2) shoul we to convert back to on save?
// The regex here is mainly for the \s* as a convenient way to remove whatever whitespace TIDY
// has inserted. It's a fringe benefit that we can use the[biu]|... to deal with all these elements in one replace.
newContents = Regex.Replace(newContents, @"REMOVEWHITESPACE\s*<([biu]|em|strong|sup|sub|span[^>]*)>", "<$1>");
//In BL2250, we still had REMOVEWHITESPACE sticking around sometimes. The way we reproduced it was
//with <u> </u>. That is, we started with
//"REMOVEWHITESPACE <u> </u>", then libtidy (properly) removed the <u></u>, leaving us with only
//"REMOVEWHITESPACE".
newContents = Regex.Replace(newContents, @"REMOVEWHITESPACE", "");
// remove blank lines at the end of style blocks
newContents = Regex.Replace(newContents, @"\s+<\/style>", "</style>");
// remove <br> elements immediately preceding </p> close tag (BL-2557)
// These are apparently inserted by ckeditor as far as we can tell. They don't show up on
// fields that have never had a ckeditor activated, and always show up on fields that have
// received focus and activated an inline ckeditor. The ideal ckeditor use case appears
// to be for data entry as part of a web page that get stored separately, with the data
// obtained something like the following in javascript:
// ckedit.on('blur', function(evt) {
// var editor = evt['editor'];
// var data = editor.getData();
// <at this point, the data looks okay, with any <br> element before the </p> tag.>
// <store the data somewhere: the following lines have no effect, and may be silly.>
// var div = mapCkeditDiv[editor.id];
// div.innerHTML = data;
// });
// Examining the initial value of div.innerHTML shows the unwanted <br> element, but it is
// not in the data returned by editor.getData(). Since assigning to div.innerHTML doesn't
// affect what gets written to the file, this hack was implemented instead.
newContents = Regex.Replace(newContents, @"(<br></br>|<br ?/>)[\r\n]*</p>", "</p>");
newContents = newContents.Replace(restoreCdataHere, savedCdata);
// Don't let spaces between <strong>, <em>, or <u> elements be removed. (BL-2484)
dom.PreserveWhitespace = true;
dom.LoadXml(newContents);
}
catch (Exception e)
{
var exceptionWithHtmlContents = new Exception(string.Format("{0}{2}{2}{1}",
e.Message, newContents, Environment.NewLine), innerException: e);
throw exceptionWithHtmlContents;
}
}
}
try
{
//It's a mystery but http://jira.palaso.org/issues/browse/BL-46 was reported by several people on Win XP, even though a look at html tidy dispose indicates that it does dispose (and thus close) the stream.
// Therefore, I'm moving the dispose to an explict call so that I can catch the error and ignore it, leaving an extra file in Temp.
temp.Dispose();
//enhance... could make a version of this which collects up any failed deletes and re-attempts them with each call to this
}
catch (Exception error)
{
//swallow
Bloom.Utils.MiscUtils.SuppressUnusedExceptionVarWarning(error);
Debug.Fail("Repro of http://jira.palaso.org/issues/browse/BL-46 ");
}
//this is a hack... each time we write the content, we add a new <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
//so for now, we remove it when we read it in. It'll get added again when we write it out
RemoveAllContentTypesMetas(dom);
return dom;
}
/// <summary>
/// Tidy is over-zealous. This is a work-around. After running Tidy, then call RemoveFillerInEmptyElements() on the same text
/// </summary>
/// <returns></returns>
private static string AddFillerToKeepTidyFromRemovingEmptyElements(string content)
{
// This handles empty elements in the form of XML contractions like <i some-important-attributes />
content = ConvertSelfClosingTags(content, "REMOVEME");
// hack. Tidy deletes <span data-libray='somethingImportant'></span>
// and also (sometimes...apparently only the first child in a parent) <i some-important-attributes></i>.
// $1 is the tag name.
// $2 is the tag attributes.
// $3 is the blank space between the opening and closing tags, if any.
content = _emptyElementsWithAttributesRegex.Replace(content, "<$1$2>REMOVEME$3</$1>");
// Tidy deletes <p></p>, though that's obviously not something to delete!
content = _emptyElementsToPreserveRegex.Replace(content, "<$1$2>REMOVEME</$1>");
// Prevent Tidy from deleting <p/> too
content = _selfClosingElementsToPreserveRegex.Replace(content, "<$1$2>REMOVEME</$1>");
return content;
}
/// <summary>
/// This is to be run after running tidy
/// </summary>
private static string RemoveFillerInEmptyElements(string contents)
{
return contents.Replace("REMOVEME", "").Replace("\0", "");
}
private static string ConvertSelfClosingTags(string html, string innerHtml = "")
{
html = RemoveEmptySelfClosingTags(html);
// $1 is the tag name.
// $2 is the tag attributes.
return _selfClosingRegex.Replace(html, "<$1$2>" + innerHtml + "</$1>");
}
public static string RemoveEmptySelfClosingTags(string html)
{
return _emptySelfClosingElementsToRemoveRegex.Replace(html, "");
}
/// <summary>
/// Beware... htmltidy doesn't consider such things as a second <body> element to warrant any more than a "warning", so this won't throw!
/// </summary>
/// <param name="content"></param>
public static void ThrowIfHtmlHasErrors(string content)
{
// Tidy chokes on embedded svgs so just take them out. Here we don't use the removed svgs.
var dummy = new List<string>();
content = RemoveSvgs(content, dummy);
using (var tidy = Document.FromString(content))
{
tidy.ShowWarnings = false;
tidy.Quiet = true;
tidy.AddTidyMetaElement = false;
tidy.OutputXml = true;
tidy.DocType = DocTypeMode.Omit; //when it supports html5, then we will let it out it
using (var log = new MemoryStream())
{
tidy.CleanAndRepair(log);
string errors = ASCIIEncoding.ASCII.GetString(log.ToArray());
if (!string.IsNullOrEmpty(errors))
{
throw new ApplicationException(errors);
}
}
}
}
/// <summary>
/// If an element has empty contents, like <textarea></textarea>, browsers will sometimes drop the end tag, so that now, when we read it back into xml,
/// anything following the <textarea> will be interpreted as part of the <textarea>! This method makes sure such tags are never totally empty.
/// </summary>
/// <param name="dom"></param>
public static void MakeXmlishTagsSafeForInterpretationAsHtml(XmlDocument dom)
{
foreach (XmlElement node in dom.SafeSelectNodes("//textarea"))
{
if (!node.HasChildNodes)
{
node.AppendChild(node.OwnerDocument.CreateTextNode(""));
}
}
foreach (XmlElement node in dom.SafeSelectNodes("//div"))
{
if (!node.HasChildNodes)
{
node.AppendChild(node.OwnerDocument.CreateTextNode(""));
}
}
foreach (XmlElement node in dom.SafeSelectNodes("//p"))
//without this, an empty paragraph suddenly takes over the subsequent elements. Browser sees <p></p> and thinks... let's just make it <p>, shall we? Stupid optional-closing language, html is....
{
if (!node.HasChildNodes)
{
node.AppendChild(node.OwnerDocument.CreateTextNode(""));
}
}
foreach (XmlElement node in dom.SafeSelectNodes("//span"))
{
if (!node.HasChildNodes)
{
node.AppendChild(node.OwnerDocument.CreateTextNode(""));
}
}
foreach (XmlElement node in dom.SafeSelectNodes("//cite"))
{
if (!node.HasChildNodes)
{
node.AppendChild(node.OwnerDocument.CreateTextNode(""));
}
}
foreach (XmlElement node in dom.SafeSelectNodes("//script"))
{
if (string.IsNullOrEmpty(node.InnerText) && node.ChildNodes.Count == 0)
{
node.InnerText = " ";
}
}
foreach (XmlElement node in dom.SafeSelectNodes("//style"))
{
if (string.IsNullOrEmpty(node.InnerText) && node.ChildNodes.Count == 0)
{
node.InnerText = " ";
}
}
foreach (XmlElement node in dom.SafeSelectNodes("//iframe"))
{
if (!node.HasChildNodes)
{
node.AppendChild(node.OwnerDocument.CreateTextNode("Must have a closing tag in HTML"));
}
}
}
/// <summary>
/// Convert the DOM (which is expected to be XHTML5) to HTML5
/// </summary>
public static string SaveDOMAsHtml5(XmlDocument dom, string targetPath)
{
var html = ConvertDomToHtml5(dom);
try
{
RobustFile.WriteAllText(targetPath, html, Encoding.UTF8);
}
catch (UnauthorizedAccessException e)
{
// Re-throw with some additional debugging info.
throw new BloomUnauthorizedAccessException(targetPath, e);
}
return targetPath;
}
/// <summary>
/// Convert a single element into equivalent HTML.
/// </summary>
/// <param name="elt"></param>
/// <returns></returns>
public static string ConvertElementToHtml5(XmlElement elt)
{
var xmlStringBuilder = new StringBuilder();
// There may be some way to make Tidy work on something that isn't a whole HTML document,
// but adding and removing this doesn't cost much.
xmlStringBuilder.Append("<html><body>");
var settings = new XmlWriterSettings { Indent = true, CheckCharacters = true, OmitXmlDeclaration = true, ConformanceLevel = ConformanceLevel.Fragment};
using (var writer = XmlWriter.Create(xmlStringBuilder, settings))
{
elt.WriteTo(writer);
writer.Close();
}
xmlStringBuilder.Append("</body></html>");
var docHtml = ConvertXhtmlToHtml5(xmlStringBuilder.ToString());
int bodyIndex = docHtml.IndexOf("<body>", StringComparison.InvariantCulture);
int endBodyIndex = docHtml.LastIndexOf("</body>", StringComparison.InvariantCulture);
int start = bodyIndex + "<body>".Length;
return docHtml.Substring(start, endBodyIndex - start);
}
public static string ConvertDomToHtml5(XmlDocument dom)
{
// First we write the DOM out to string
var settings = new XmlWriterSettings {Indent = true, CheckCharacters = true, OmitXmlDeclaration = true};
var xmlStringBuilder = new StringBuilder();
using (var writer = XmlWriter.Create(xmlStringBuilder, settings))
{
dom.WriteContentTo(writer);
writer.Close();
}
return ConvertXhtmlToHtml5(xmlStringBuilder.ToString());
}
static string ConvertXhtmlToHtml5(string input)
{
var xml = input;
// HTML Tidy will mess many things up, so we have these work arounds to make it "safe from libtidy"
xml = AddFillerToKeepTidyFromRemovingEmptyElements(xml);
// Tidy will convert <br /> to <br></br> which is not valid and produces an unexpected double line break.
var BrPlaceholder = "$$ConvertThisBackToBr$$";
xml = xml.Replace("<br />", BrPlaceholder);
var removedSvgs = new List<string>();
xml = RemoveSvgs(xml, removedSvgs);
// Now re-write as html, indented nicely
string html;
using (var tidy = Document.FromString(xml))
{
tidy.ShowWarnings = false;
tidy.Quiet = true;
// Removing comments is unfortunate, I can imagine cases where it would be helpful to be able to
// have comments. But currently our ckeditor instances are never "destroy()"ed, and are dumping
// e.g. 50 k of comment text into a single field, when you paste from MS Word. So we're
// going to dump all comments for now.
tidy.RemoveComments = true;
tidy.AddTidyMetaElement = false;
tidy.OutputXml = false;
tidy.OutputHtml = true;
tidy.DocType = DocTypeMode.Html5;
tidy.MergeDivs = AutoBool.No;
tidy.MergeSpans = AutoBool.No;
tidy.PreserveEntities = true;
tidy.JoinStyles = false;
tidy.IndentBlockElements = AutoBool.Auto; //instructions say avoid 'yes'
tidy.WrapAt = 9999;
tidy.IndentSpaces = 4;
tidy.CharacterEncoding = EncodingType.Utf8;
tidy.CleanAndRepair();
using (var stream = new MemoryStream())
{
tidy.Save(stream);
stream.Flush();
stream.Seek(0L, SeekOrigin.Begin);
using (var sr = new StreamReader(stream, Encoding.UTF8))
html = sr.ReadToEnd();
}
}
// Now revert the stuff we did to make it "safe from libtidy"
html = RestoreSvgs(html, removedSvgs);
html = html.Replace(BrPlaceholder, "<br />");
html = RemoveFillerInEmptyElements(html);
return html;
}
public static void RemoveAllContentTypesMetas(XmlDocument dom)
{
foreach (XmlElement n in dom.SafeSelectNodes("//head/meta[@http-equiv='Content-Type']"))
{
n.ParentNode.RemoveChild(n);
}
}
public static string RemoveSvgs(string input, List<string> svgs)
{
// Tidy utterly chokes (exits the whole program without even a green screen) on SVGs.
var regexSvg = new Regex("<svg .*?</svg>", RegexOptions.Singleline);
// This is probably not the most efficient way to remove and restore them but the common case is that none are found,
// and this is not too bad for that case.
var result = input;
for (var matchSvg = regexSvg.Match(result); matchSvg.Success; matchSvg = regexSvg.Match(result))
{
svgs.Add(matchSvg.Value);
result = result.Substring(0, matchSvg.Index) + SvgPlaceholder +
result.Substring(matchSvg.Index + matchSvg.Length);
}
return result;
}
public static string RestoreSvgs(string input, List<string> svgs)
{
var result = input;
foreach (var svg in svgs)
{
// We want a ReplaceFirst but .Net doesn't have it.
int index = result.IndexOf(SvgPlaceholder);
result = result.Substring(0, index) + svg + result.Substring(index + SvgPlaceholder.Length);
}
return result;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
[Export(typeof(AnalyzerDependencyCheckingService))]
internal sealed class AnalyzerDependencyCheckingService
{
private static readonly object s_dependencyConflictErrorId = new object();
private static readonly IIgnorableAssemblyList s_systemPrefixList = new IgnorableAssemblyNamePrefixList("System");
private static readonly IIgnorableAssemblyList s_codeAnalysisPrefixList = new IgnorableAssemblyNamePrefixList("Microsoft.CodeAnalysis");
private static readonly IIgnorableAssemblyList s_explicitlyIgnoredAssemblyList = new IgnorableAssemblyIdentityList(GetExplicitlyIgnoredAssemblyIdentities());
private static readonly IIgnorableAssemblyList s_assembliesIgnoredByNameList = new IgnorableAssemblyNameList(ImmutableHashSet.Create("mscorlib"));
private readonly VisualStudioWorkspaceImpl _workspace;
private readonly HostDiagnosticUpdateSource _updateSource;
private readonly BindingRedirectionService _bindingRedirectionService;
private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private Task<AnalyzerDependencyResults> _task = Task.FromResult(AnalyzerDependencyResults.Empty);
private ImmutableHashSet<string> _analyzerPaths = ImmutableHashSet.Create<string>(StringComparer.OrdinalIgnoreCase);
private readonly DiagnosticDescriptor _missingAnalyzerReferenceRule = new DiagnosticDescriptor(
id: IDEDiagnosticIds.MissingAnalyzerReferenceId,
title: ServicesVSResources.MissingAnalyzerReference,
messageFormat: ServicesVSResources.Analyzer_assembly_0_depends_on_1_but_it_was_not_found_Analyzers_may_not_run_correctly_unless_the_missing_assembly_is_added_as_an_analyzer_reference_as_well,
category: FeaturesResources.Roslyn_HostError,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
private readonly DiagnosticDescriptor _analyzerDependencyConflictRule = new DiagnosticDescriptor(
id: IDEDiagnosticIds.AnalyzerDependencyConflictId,
title: ServicesVSResources.AnalyzerDependencyConflict,
messageFormat: ServicesVSResources.Analyzer_assemblies_0_and_1_both_have_identity_2_but_different_contents_Only_one_will_be_loaded_and_analyzers_using_these_assemblies_may_not_run_correctly,
category: FeaturesResources.Roslyn_HostError,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
[ImportingConstructor]
public AnalyzerDependencyCheckingService(
VisualStudioWorkspaceImpl workspace,
HostDiagnosticUpdateSource updateSource)
{
_workspace = workspace;
_updateSource = updateSource;
_bindingRedirectionService = new BindingRedirectionService();
}
public async void CheckForConflictsAsync()
{
AnalyzerDependencyResults results = null;
try
{
results = await GetConflictsAsync().ConfigureAwait(continueOnCapturedContext: true);
}
catch
{
return;
}
if (results == null)
{
return;
}
var builder = ImmutableArray.CreateBuilder<DiagnosticData>();
var conflicts = results.Conflicts;
var missingDependencies = results.MissingDependencies;
foreach (var project in _workspace.ProjectTracker.ImmutableProjects)
{
builder.Clear();
foreach (var conflict in conflicts)
{
if (project.CurrentProjectAnalyzersContains(conflict.AnalyzerFilePath1) ||
project.CurrentProjectAnalyzersContains(conflict.AnalyzerFilePath2))
{
var messageArguments = new string[] { conflict.AnalyzerFilePath1, conflict.AnalyzerFilePath2, conflict.Identity.ToString() };
DiagnosticData diagnostic;
if (DiagnosticData.TryCreate(_analyzerDependencyConflictRule, messageArguments, project.Id, _workspace, out diagnostic))
{
builder.Add(diagnostic);
}
}
}
foreach (var missingDependency in missingDependencies)
{
if (project.CurrentProjectAnalyzersContains(missingDependency.AnalyzerPath))
{
var messageArguments = new string[] { missingDependency.AnalyzerPath, missingDependency.DependencyIdentity.ToString() };
DiagnosticData diagnostic;
if (DiagnosticData.TryCreate(_missingAnalyzerReferenceRule, messageArguments, project.Id, _workspace, out diagnostic))
{
builder.Add(diagnostic);
}
}
}
_updateSource.UpdateDiagnosticsForProject(project.Id, s_dependencyConflictErrorId, builder.ToImmutable());
}
foreach (var conflict in conflicts)
{
LogConflict(conflict);
}
foreach (var missingDependency in missingDependencies)
{
LogMissingDependency(missingDependency);
}
}
private void LogConflict(AnalyzerDependencyConflict conflict)
{
Logger.Log(
FunctionId.AnalyzerDependencyCheckingService_LogConflict,
KeyValueLogMessage.Create(m =>
{
m["Identity"] = conflict.Identity.ToString();
m["Analyzer1"] = conflict.AnalyzerFilePath1;
m["Analyzer2"] = conflict.AnalyzerFilePath2;
}));
}
private void LogMissingDependency(MissingAnalyzerDependency missingDependency)
{
Logger.Log(
FunctionId.AnalyzerDependencyCheckingService_LogMissingDependency,
KeyValueLogMessage.Create(m =>
{
m["Analyzer"] = missingDependency.AnalyzerPath;
m["Identity"] = missingDependency.DependencyIdentity;
}));
}
private Task<AnalyzerDependencyResults> GetConflictsAsync()
{
ImmutableHashSet<string> currentAnalyzerPaths = _workspace.CurrentSolution
.Projects
.SelectMany(p => p.AnalyzerReferences)
.OfType<AnalyzerFileReference>()
.Select(a => a.FullPath)
.ToImmutableHashSet(StringComparer.OrdinalIgnoreCase);
if (currentAnalyzerPaths.SetEquals(_analyzerPaths))
{
return _task;
}
_cancellationTokenSource.Cancel();
_cancellationTokenSource = new CancellationTokenSource();
_analyzerPaths = currentAnalyzerPaths;
_task = _task.SafeContinueWith(_ =>
{
IEnumerable<AssemblyIdentity> loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().Select(assembly => AssemblyIdentity.FromAssemblyDefinition(assembly));
IgnorableAssemblyIdentityList loadedAssembliesList = new IgnorableAssemblyIdentityList(loadedAssemblies);
IIgnorableAssemblyList[] ignorableAssemblyLists = new[] { s_systemPrefixList, s_codeAnalysisPrefixList, s_explicitlyIgnoredAssemblyList, s_assembliesIgnoredByNameList, loadedAssembliesList };
return new AnalyzerDependencyChecker(currentAnalyzerPaths, ignorableAssemblyLists, _bindingRedirectionService).Run(_cancellationTokenSource.Token);
},
TaskScheduler.Default);
return _task;
}
private static IEnumerable<AssemblyIdentity> GetExplicitlyIgnoredAssemblyIdentities()
{
// Microsoft.VisualBasic.dll
var list = new List<AssemblyIdentity>();
AddAssemblyIdentity(list, "Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
AddAssemblyIdentity(list, "Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
return list;
}
private static void AddAssemblyIdentity(List<AssemblyIdentity> list, string dllName)
{
AssemblyIdentity identity;
if (!AssemblyIdentity.TryParseDisplayName(dllName, out identity))
{
return;
}
list.Add(identity);
}
private class BindingRedirectionService : IBindingRedirectionService
{
public AssemblyIdentity ApplyBindingRedirects(AssemblyIdentity originalIdentity)
{
string redirectedAssemblyName = AppDomain.CurrentDomain.ApplyPolicy(originalIdentity.ToString());
AssemblyIdentity redirectedAssemblyIdentity;
if (AssemblyIdentity.TryParseDisplayName(redirectedAssemblyName, out redirectedAssemblyIdentity))
{
return redirectedAssemblyIdentity;
}
return originalIdentity;
}
}
}
}
| |
using System;
#if !XBOX && !WINDOWS_PHONE
using System.Numerics;
#endif
#if XBOX || WINDOWS_PHONE
using BigInteger = System.Int32;
#endif
namespace GameLibrary.Dependencies.Entities
{
public sealed class Entity
{
private int id;
private long uniqueId;
private BigInteger typeBits = 0;
private BigInteger systemBits = 0;
private EntityWorld world;
private EntityManager entityManager;
private bool enabled = true;
private bool refreshingState = false;
private bool deletingState = false;
internal Entity(EntityWorld world, int id)
{
this.world = world;
this.entityManager = world.EntityManager;
this.id = id;
}
/**
* The internal id for this entity within the framework. No other entity will have the same ID, but
* ID's are however reused so another entity may acquire this ID if the previous entity was deleted.
*
* @return id of the entity.
*/
public int Id
{
get { return id; }
}
public long UniqueId
{
get { return uniqueId; }
internal set
{
//System.Diagnostics.Debug.Assert(uniqueId >= 0);
uniqueId = value;
}
}
internal BigInteger TypeBits
{
get { return typeBits; }
set { typeBits = value; }
}
internal void AddTypeBit(BigInteger bit)
{
typeBits |= bit;
}
internal void RemoveTypeBit(BigInteger bit)
{
typeBits &= ~bit;
}
public bool RefreshingState
{
get { return refreshingState; }
set { refreshingState = value; }
}
public bool DeletingState
{
get { return deletingState; }
set { deletingState = value; }
}
internal BigInteger SystemBits
{
get { return systemBits; }
set { systemBits = value; }
}
internal void AddSystemBit(BigInteger bit)
{
systemBits |= bit;
}
internal void RemoveSystemBit(BigInteger bit)
{
systemBits &= ~bit;
}
public void Reset()
{
systemBits = 0;
typeBits = 0;
enabled = true;
}
public override String ToString()
{
return "Entity[" + id + "]";
}
public bool Enabled
{
get
{
return enabled;
}
set
{
enabled = value;
}
}
/**
* Add a component to this entity.
* @param component to add to this entity
*/
public Component AddComponent(Component component)
{
System.Diagnostics.Debug.Assert(component != null);
return entityManager.AddComponent(this, component);
}
public T AddComponent<T>(T component) where T : Component
{
System.Diagnostics.Debug.Assert(component != null);
return entityManager.AddComponent<T>(this, component);
}
/**
* Removes the component from this entity.
* @param component to remove from this entity.
*/
public void RemoveComponent<T>(Component component) where T : Component
{
System.Diagnostics.Debug.Assert(component != null);
entityManager.RemoveComponent<T>(this, component);
}
/**
* Faster removal of components from a entity.
* @param component to remove from this entity.
*/
public void RemoveComponent(ComponentType type)
{
System.Diagnostics.Debug.Assert(type != null);
entityManager.RemoveComponent(this, type);
}
/**
* Checks if the entity has been deleted from somewhere.
* @return if it's active.
*/
public bool isActive
{
get
{
return entityManager.IsActive(id);
}
}
/**
* This is the preferred method to use when retrieving a component from a entity. It will provide good performance.
*
* @param type in order to retrieve the component fast you must provide a ComponentType instance for the expected component.
* @return
*/
public Component GetComponent(ComponentType type)
{
System.Diagnostics.Debug.Assert(type != null);
return entityManager.GetComponent(this, type);
}
/**
* Slower retrieval of components from this entity. Minimize usage of this, but is fine to use e.g. when creating new entities
* and setting data in components.
* @param <T> the expected return component type.
* @param type the expected return component type.
* @return component that matches, or null if none is found.
*/
public T GetComponent<T>() where T : Component
{
return (T)GetComponent(ComponentTypeManager.GetTypeFor<T>());
}
public bool HasComponent<T>() where T : Component
{
return (T)GetComponent(ComponentTypeManager.GetTypeFor<T>()) != null;
}
/**
* Get all components belonging to this entity.
* WARNING. Use only for debugging purposes, it is dead slow.
* WARNING. The returned bag is only valid until this method is called again, then it is overwritten.
* @return all components of this entity.
*/
public Bag<Component> Components
{
get
{
return entityManager.GetComponents(this);
}
}
/**
* Refresh all changes to components for this entity. After adding or removing components, you must call
* this method. It will update all relevant systems.
* It is typical to call this after adding components to a newly created entity.
*/
public void Refresh()
{
if (refreshingState == true)
{
return;
}
world.RefreshEntity(this);
refreshingState = true;
}
/**
* Delete this entity from the world.
*/
public void Delete()
{
if (Tag == "Player")
{
Console.WriteLine("The player was deleted");
}
if (deletingState == true)
{
return;
}
world.DeleteEntity(this);
deletingState = true;
}
/**
* Set the group of the entity. Same as World.setGroup().
* @param group of the entity.
*/
public String Group
{
get
{
return world.GroupManager.GetGroupOf(this);
}
set
{
world.GroupManager.Set(value, this);
}
}
/**
* Assign a tag to this entity. Same as World.setTag().
* @param tag of the entity.
*/
public String Tag
{
get
{
return world.TagManager.GetTagOfEntity(this);
}
set
{
world.TagManager.Register(value, this);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using NSubstitute;
using Xunit;
namespace Octokit.Tests.Clients
{
/// <summary>
/// Client tests mostly just need to make sure they call the IApiConnection with the correct
/// relative Uri. No need to fake up the response. All *those* tests are in ApiConnectionTests.cs.
/// </summary>
public class RepositoryBranchesClientTests
{
public class TheCtor
{
[Fact]
public void EnsuresNonNullArguments()
{
Assert.Throws<ArgumentNullException>(() => new RepositoryBranchesClient(null));
}
}
public class TheGetAllMethod
{
[Fact]
public async Task RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
await client.GetAll("owner", "name");
connection.Received()
.GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/branches"), null, "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json", Args.ApiOptions);
}
[Fact]
public async Task RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
await client.GetAll(1);
connection.Received()
.GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches"), null, "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json", Args.ApiOptions);
}
[Fact]
public async Task RequestsTheCorrectUrlWithApiOptions()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var options = new ApiOptions
{
PageCount = 1,
StartPage = 1,
PageSize = 1
};
await client.GetAll("owner", "name", options);
connection.Received()
.GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/branches"), null, "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json", options);
}
[Fact]
public async Task RequestsTheCorrectUrlWithRepositoryIdWithApiOptions()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var options = new ApiOptions
{
PageCount = 1,
StartPage = 1,
PageSize = 1
};
await client.GetAll(1, options);
connection.Received()
.GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches"), null, "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json", options);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll(null, "name"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll(null, "name", ApiOptions.None));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", null, ApiOptions.None));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", "name", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("", "name"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("owner", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("", "name", ApiOptions.None));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("owner", "", ApiOptions.None));
}
}
public class TheGetMethod
{
[Fact]
public async Task RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
await client.Get("owner", "repo", "branch");
connection.Received()
.Get<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch"), null, "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json");
}
[Fact]
public async Task RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
await client.Get(1, "branch");
connection.Received()
.Get<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch"), null, "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json");
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.Get("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "repo", ""));
}
}
public class TheGetBranchProtectectionMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.GetBranchProtection("owner", "repo", "branch");
connection.Received()
.Get<BranchProtectionSettings>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.GetBranchProtection(1, "branch");
connection.Received()
.Get<BranchProtectionSettings>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranchProtection(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranchProtection("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranchProtection("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranchProtection(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranchProtection("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranchProtection("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranchProtection("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranchProtection(1, ""));
}
}
public class TheUpdateBranchProtectionMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new BranchProtectionSettingsUpdate(
new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" }));
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.UpdateBranchProtection("owner", "repo", "branch", update);
connection.Received()
.Put<BranchProtectionSettings>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection"), Arg.Any<BranchProtectionSettingsUpdate>(), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new BranchProtectionSettingsUpdate(
new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" }));
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.UpdateBranchProtection(1, "branch", update);
connection.Received()
.Put<BranchProtectionSettings>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection"), Arg.Any<BranchProtectionSettingsUpdate>(), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var update = new BranchProtectionSettingsUpdate(
new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" }));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection(null, "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection("owner", null, "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection("owner", "repo", null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection(1, null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateBranchProtection("", "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateBranchProtection("owner", "", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateBranchProtection("owner", "repo", "", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateBranchProtection(1, "", update));
}
}
public class TheDeleteBranchProtectectionMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.DeleteBranchProtection("owner", "repo", "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.DeleteBranchProtection(1, "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteBranchProtection(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteBranchProtection("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteBranchProtection("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteBranchProtection(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteBranchProtection("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteBranchProtection("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteBranchProtection("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteBranchProtection(1, ""));
}
}
public class TheGetRequiredStatusChecksMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.GetRequiredStatusChecks("owner", "repo", "branch");
connection.Received()
.Get<BranchProtectionRequiredStatusChecks>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.GetRequiredStatusChecks(1, "branch");
connection.Received()
.Get<BranchProtectionRequiredStatusChecks>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetRequiredStatusChecks(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetRequiredStatusChecks("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetRequiredStatusChecks("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetRequiredStatusChecks(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetRequiredStatusChecks("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetRequiredStatusChecks("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetRequiredStatusChecks("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetRequiredStatusChecks(1, ""));
}
}
public class TheUpdateRequiredStatusChecksMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" });
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.UpdateRequiredStatusChecks("owner", "repo", "branch", update);
connection.Received()
.Patch<BranchProtectionRequiredStatusChecks>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks"), Arg.Any<BranchProtectionRequiredStatusChecksUpdate>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" });
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.UpdateRequiredStatusChecks(1, "branch", update);
connection.Received()
.Patch<BranchProtectionRequiredStatusChecks>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks"), Arg.Any<BranchProtectionRequiredStatusChecksUpdate>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var update = new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" });
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks(null, "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks("owner", null, "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks("owner", "repo", null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks(1, null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecks("", "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecks("owner", "", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecks("owner", "repo", "", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecks(1, "", update));
}
}
public class TheDeleteRequiredStatusChecksMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.DeleteRequiredStatusChecks("owner", "repo", "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.DeleteRequiredStatusChecks(1, "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecks(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecks("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecks("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecks(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecks("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecks("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecks("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecks(1, ""));
}
}
public class TheGetAllRequiredStatusChecksContextsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.GetAllRequiredStatusChecksContexts("owner", "repo", "branch");
connection.Received()
.Get<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks/contexts"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.GetAllRequiredStatusChecksContexts(1, "branch");
connection.Received()
.Get<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks/contexts"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllRequiredStatusChecksContexts(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllRequiredStatusChecksContexts("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllRequiredStatusChecksContexts("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllRequiredStatusChecksContexts(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllRequiredStatusChecksContexts("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllRequiredStatusChecksContexts("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllRequiredStatusChecksContexts("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllRequiredStatusChecksContexts(1, ""));
}
}
public class TheUpdateRequiredStatusChecksContextsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new List<string>() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.UpdateRequiredStatusChecksContexts("owner", "repo", "branch", update);
connection.Received()
.Put<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new List<string>() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.UpdateRequiredStatusChecksContexts(1, "branch", update);
connection.Received()
.Put<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var update = new List<string>() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts(null, "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts("owner", null, "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts("owner", "repo", null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts(1, null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecksContexts("", "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecksContexts("owner", "", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecksContexts("owner", "repo", "", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecksContexts(1, "", update));
}
}
public class TheAddRequiredStatusChecksContextsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newContexts = new List<string>() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.AddRequiredStatusChecksContexts("owner", "repo", "branch", newContexts);
connection.Received()
.Post<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newContexts = new List<string>() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.AddRequiredStatusChecksContexts(1, "branch", newContexts);
connection.Received()
.Post<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var newContexts = new List<string>() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts(null, "repo", "branch", newContexts));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts("owner", null, "branch", newContexts));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts("owner", "repo", null, newContexts));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts(1, null, newContexts));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddRequiredStatusChecksContexts("", "repo", "branch", newContexts));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddRequiredStatusChecksContexts("owner", "", "branch", newContexts));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddRequiredStatusChecksContexts("owner", "repo", "", newContexts));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddRequiredStatusChecksContexts(1, "", newContexts));
}
}
public class TheDeleteRequiredStatusChecksContextsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var contextsToRemove = new List<string>() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.DeleteRequiredStatusChecksContexts("owner", "repo", "branch", contextsToRemove);
connection.Received()
.Delete<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var contextsToRemove = new List<string>() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.DeleteRequiredStatusChecksContexts(1, "branch", contextsToRemove);
connection.Received()
.Delete<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var contextsToRemove = new List<string>() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts(null, "repo", "branch", contextsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts("owner", null, "branch", contextsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts("owner", "repo", null, contextsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts(1, null, contextsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecksContexts("", "repo", "branch", contextsToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecksContexts("owner", "", "branch", contextsToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecksContexts("owner", "repo", "", contextsToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecksContexts(1, "", contextsToRemove));
}
}
public class TheGetReviewEnforcementMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.GetReviewEnforcement("owner", "repo", "branch");
connection.Received()
.Get<BranchProtectionRequiredReviews>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_pull_request_reviews"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.GetReviewEnforcement(1, "branch");
connection.Received()
.Get<BranchProtectionRequiredReviews>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_pull_request_reviews"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetReviewEnforcement(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetReviewEnforcement("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetReviewEnforcement("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetReviewEnforcement(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetReviewEnforcement("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetReviewEnforcement("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetReviewEnforcement("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetReviewEnforcement(1, ""));
}
}
public class TheUpdateReviewEnforcementMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new BranchProtectionRequiredReviewsUpdate(false, false, 2);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.UpdateReviewEnforcement("owner", "repo", "branch", update);
connection.Received()
.Patch<BranchProtectionRequiredReviews>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_pull_request_reviews"), Arg.Any<BranchProtectionRequiredReviewsUpdate>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new BranchProtectionRequiredReviewsUpdate(false, false, 2);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.UpdateReviewEnforcement(1, "branch", update);
connection.Received()
.Patch<BranchProtectionRequiredReviews>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_pull_request_reviews"), Arg.Any<BranchProtectionRequiredReviewsUpdate>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var update = new BranchProtectionRequiredReviewsUpdate(false, false, 2);
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateReviewEnforcement(null, "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateReviewEnforcement("owner", null, "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateReviewEnforcement("owner", "repo", null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateReviewEnforcement("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateReviewEnforcement(1, null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateReviewEnforcement(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateReviewEnforcement("", "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateReviewEnforcement("owner", "", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateReviewEnforcement("owner", "repo", "", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateReviewEnforcement(1, "", update));
}
}
public class TheRemoveReviewEnforcementMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.RemoveReviewEnforcement("owner", "repo", "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_pull_request_reviews"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.RemoveReviewEnforcement(1, "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_pull_request_reviews"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveReviewEnforcement(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveReviewEnforcement("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveReviewEnforcement("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveReviewEnforcement(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveReviewEnforcement("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveReviewEnforcement("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveReviewEnforcement("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveReviewEnforcement(1, ""));
}
}
public class TheGetAdminEnforcementMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.GetAdminEnforcement("owner", "repo", "branch");
connection.Received()
.Get<EnforceAdmins>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/enforce_admins"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.GetAdminEnforcement(1, "branch");
connection.Received()
.Get<EnforceAdmins>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/enforce_admins"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAdminEnforcement(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAdminEnforcement("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAdminEnforcement("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAdminEnforcement(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAdminEnforcement("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAdminEnforcement("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAdminEnforcement("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAdminEnforcement(1, ""));
}
}
public class TheAddAdminEnforcementMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.AddAdminEnforcement("owner", "repo", "branch");
connection.Received()
.Post<EnforceAdmins>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/enforce_admins"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.AddAdminEnforcement(1, "branch");
connection.Received()
.Post<EnforceAdmins>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/enforce_admins"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddAdminEnforcement(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddAdminEnforcement("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddAdminEnforcement("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddAdminEnforcement(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddAdminEnforcement("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddAdminEnforcement("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddAdminEnforcement("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddAdminEnforcement(1, ""));
}
}
public class TheRemoveAdminEnforcementMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.RemoveAdminEnforcement("owner", "repo", "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/enforce_admins"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.RemoveAdminEnforcement(1, "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/enforce_admins"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveAdminEnforcement(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveAdminEnforcement("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveAdminEnforcement("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveAdminEnforcement(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveAdminEnforcement("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveAdminEnforcement("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveAdminEnforcement("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveAdminEnforcement(1, ""));
}
}
public class TheGetProtectedBranchRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.GetProtectedBranchRestrictions("owner", "repo", "branch");
connection.Received()
.Get<BranchProtectionPushRestrictions>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.GetProtectedBranchRestrictions(1, "branch");
connection.Received()
.Get<BranchProtectionPushRestrictions>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchRestrictions(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchRestrictions("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchRestrictions("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchRestrictions(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchRestrictions("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchRestrictions("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchRestrictions("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchRestrictions(1, ""));
}
}
public class TheDeleteProtectedBranchRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.DeleteProtectedBranchRestrictions("owner", "repo", "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.DeleteProtectedBranchRestrictions(1, "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchRestrictions(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchRestrictions("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchRestrictions("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchRestrictions(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchRestrictions("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchRestrictions("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchRestrictions("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchRestrictions(1, ""));
}
}
public class TheGetAllProtectedBranchTeamRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
client.GetAllProtectedBranchTeamRestrictions("owner", "repo", "branch");
connection.Received()
.Get<IReadOnlyList<Team>>(
Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/teams"),
null,
"application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json,application/vnd.github.hellcat-preview+json");
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
client.GetAllProtectedBranchTeamRestrictions(1, "branch");
connection.Received()
.Get<IReadOnlyList<Team>>(
Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/teams"),
null,
"application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json,application/vnd.github.hellcat-preview+json");
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchTeamRestrictions(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchTeamRestrictions("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchTeamRestrictions("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchTeamRestrictions(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchTeamRestrictions("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchTeamRestrictions("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchTeamRestrictions("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchTeamRestrictions(1, ""));
}
}
public class TheSetProtectedBranchTeamRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newTeams = new BranchProtectionTeamCollection() { "test" };
client.UpdateProtectedBranchTeamRestrictions("owner", "repo", "branch", newTeams);
connection.Received()
.Put<IReadOnlyList<Team>>(
Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/teams"),
Arg.Any<IReadOnlyList<string>>(),
null,
"application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json,application/vnd.github.hellcat-preview+json");
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newTeams = new BranchProtectionTeamCollection() { "test" };
client.UpdateProtectedBranchTeamRestrictions(1, "branch", newTeams);
connection.Received()
.Put<IReadOnlyList<Team>>(
Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/teams"),
Arg.Any<IReadOnlyList<string>>(),
null,
"application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json,application/vnd.github.hellcat-preview+json");
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var newTeams = new BranchProtectionTeamCollection() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions(null, "repo", "branch", newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions("owner", null, "branch", newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions("owner", "repo", null, newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions(1, null, newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchTeamRestrictions("", "repo", "branch", newTeams));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchTeamRestrictions("owner", "", "branch", newTeams));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchTeamRestrictions("owner", "repo", "", newTeams));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchTeamRestrictions(1, "", newTeams));
}
}
public class TheAddProtectedBranchTeamRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newTeams = new BranchProtectionTeamCollection() { "test" };
client.AddProtectedBranchTeamRestrictions("owner", "repo", "branch", newTeams);
connection.Received()
.Post<IReadOnlyList<Team>>(
Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/teams"),
Arg.Any<IReadOnlyList<string>>(),
"application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json,application/vnd.github.hellcat-preview+json");
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newTeams = new BranchProtectionTeamCollection() { "test" };
client.AddProtectedBranchTeamRestrictions(1, "branch", newTeams);
connection.Received()
.Post<IReadOnlyList<Team>>(
Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/teams"),
Arg.Any<IReadOnlyList<string>>(),
"application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json,application/vnd.github.hellcat-preview+json");
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var newTeams = new BranchProtectionTeamCollection() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions(null, "repo", "branch", newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions("owner", null, "branch", newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions("owner", "repo", null, newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions(1, null, newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchTeamRestrictions("", "repo", "branch", newTeams));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchTeamRestrictions("owner", "", "branch", newTeams));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchTeamRestrictions("owner", "repo", "", newTeams));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchTeamRestrictions(1, "", newTeams));
}
}
public class TheDeleteProtectedBranchTeamRestrictions
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var teamsToRemove = new BranchProtectionTeamCollection() { "test" };
client.DeleteProtectedBranchTeamRestrictions("owner", "repo", "branch", teamsToRemove);
connection.Received()
.Delete<IReadOnlyList<Team>>(
Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/teams"),
Arg.Any<BranchProtectionTeamCollection>(),
"application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json,application/vnd.github.hellcat-preview+json");
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var teamsToRemove = new BranchProtectionTeamCollection() { "test" };
client.DeleteProtectedBranchTeamRestrictions(1, "branch", teamsToRemove);
connection.Received()
.Delete<IReadOnlyList<Team>>(
Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/teams"),
Arg.Any<IReadOnlyList<string>>(),
"application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json,application/vnd.github.hellcat-preview+json");
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var teamsToRemove = new BranchProtectionTeamCollection() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions(null, "repo", "branch", teamsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions("owner", null, "branch", teamsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions("owner", "repo", null, teamsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions(1, null, teamsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchTeamRestrictions("", "repo", "branch", teamsToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchTeamRestrictions("owner", "", "branch", teamsToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchTeamRestrictions("owner", "repo", "", teamsToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchTeamRestrictions(1, "", teamsToRemove));
}
}
public class TheGetAllProtectedBranchUserRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.GetAllProtectedBranchUserRestrictions("owner", "repo", "branch");
connection.Received()
.Get<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/users"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.GetAllProtectedBranchUserRestrictions(1, "branch");
connection.Received()
.Get<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/users"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchUserRestrictions(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchUserRestrictions("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchUserRestrictions("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllProtectedBranchUserRestrictions(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchUserRestrictions("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchUserRestrictions("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchUserRestrictions("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllProtectedBranchUserRestrictions(1, ""));
}
}
public class TheSetProtectedBranchUserRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newUsers = new BranchProtectionUserCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.UpdateProtectedBranchUserRestrictions("owner", "repo", "branch", newUsers);
connection.Received()
.Put<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newUsers = new BranchProtectionUserCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.UpdateProtectedBranchUserRestrictions(1, "branch", newUsers);
connection.Received()
.Put<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var newUsers = new BranchProtectionUserCollection() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions(null, "repo", "branch", newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions("owner", null, "branch", newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions("owner", "repo", null, newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions(1, null, newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchUserRestrictions("", "repo", "branch", newUsers));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchUserRestrictions("owner", "", "branch", newUsers));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchUserRestrictions("owner", "repo", "", newUsers));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchUserRestrictions(1, "", newUsers));
}
}
public class TheAddProtectedBranchUserRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newUsers = new BranchProtectionUserCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.AddProtectedBranchUserRestrictions("owner", "repo", "branch", newUsers);
connection.Received()
.Post<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newUsers = new BranchProtectionUserCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.AddProtectedBranchUserRestrictions(1, "branch", newUsers);
connection.Received()
.Post<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var newUsers = new BranchProtectionUserCollection() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions(null, "repo", "branch", newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions("owner", null, "branch", newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions("owner", "repo", null, newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions(1, null, newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchUserRestrictions("", "repo", "branch", newUsers));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchUserRestrictions("owner", "", "branch", newUsers));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchUserRestrictions("owner", "repo", "", newUsers));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchUserRestrictions(1, "", newUsers));
}
}
public class TheDeleteProtectedBranchUserRestrictions
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var usersToRemove = new BranchProtectionUserCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.DeleteProtectedBranchUserRestrictions("owner", "repo", "branch", usersToRemove);
connection.Received()
.Delete<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var usersToRemove = new BranchProtectionUserCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json,application/vnd.github.luke-cage-preview+json";
client.DeleteProtectedBranchUserRestrictions(1, "branch", usersToRemove);
connection.Received()
.Delete<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var usersToRemove = new BranchProtectionUserCollection() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions(null, "repo", "branch", usersToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions("owner", null, "branch", usersToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions("owner", "repo", null, usersToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions(1, null, usersToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchUserRestrictions("", "repo", "branch", usersToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchUserRestrictions("owner", "", "branch", usersToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchUserRestrictions("owner", "repo", "", usersToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchUserRestrictions(1, "", usersToRemove));
}
}
}
}
| |
// <copyright file="TurnBasedMultiplayerManager.cs" company="Google Inc.">
// Copyright (C) 2014 Google Inc.
//
// 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>
#if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS))
namespace GooglePlayGames.Native.Cwrapper
{
using System;
using System.Runtime.InteropServices;
using System.Text;
internal static class TurnBasedMultiplayerManager
{
internal delegate void TurnBasedMatchCallback(
/* from(TurnBasedMultiplayerManager_TurnBasedMatchResponse_t) */ IntPtr arg0,
/* from(void *) */ IntPtr arg1);
internal delegate void MultiplayerStatusCallback(
/* from(MultiplayerStatus_t) */ CommonErrorStatus.MultiplayerStatus arg0,
/* from(void *) */ IntPtr arg1);
internal delegate void TurnBasedMatchesCallback(
/* from(TurnBasedMultiplayerManager_TurnBasedMatchesResponse_t) */ IntPtr arg0,
/* from(void *) */ IntPtr arg1);
internal delegate void MatchInboxUICallback(
/* from(TurnBasedMultiplayerManager_MatchInboxUIResponse_t) */ IntPtr arg0,
/* from(void *) */ IntPtr arg1);
internal delegate void PlayerSelectUICallback(
/* from(TurnBasedMultiplayerManager_PlayerSelectUIResponse_t) */ IntPtr arg0,
/* from(void *) */ IntPtr arg1);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern void TurnBasedMultiplayerManager_ShowPlayerSelectUI(
HandleRef self,
/* from(uint32_t) */uint minimum_players,
/* from(uint32_t) */uint maximum_players,
[MarshalAs(UnmanagedType.I1)] /* from(bool) */ bool allow_automatch,
/* from(TurnBasedMultiplayerManager_PlayerSelectUICallback_t) */PlayerSelectUICallback callback,
/* from(void *) */IntPtr callback_arg);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern void TurnBasedMultiplayerManager_CancelMatch(
HandleRef self,
/* from(TurnBasedMatch_t) */IntPtr match,
/* from(TurnBasedMultiplayerManager_MultiplayerStatusCallback_t) */MultiplayerStatusCallback callback,
/* from(void *) */IntPtr callback_arg);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern void TurnBasedMultiplayerManager_DismissMatch(
HandleRef self,
/* from(TurnBasedMatch_t) */IntPtr match);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern void TurnBasedMultiplayerManager_ShowMatchInboxUI(
HandleRef self,
/* from(TurnBasedMultiplayerManager_MatchInboxUICallback_t) */MatchInboxUICallback callback,
/* from(void *) */IntPtr callback_arg);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern void TurnBasedMultiplayerManager_SynchronizeData(
HandleRef self);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern void TurnBasedMultiplayerManager_Rematch(
HandleRef self,
/* from(TurnBasedMatch_t) */IntPtr match,
/* from(TurnBasedMultiplayerManager_TurnBasedMatchCallback_t) */TurnBasedMatchCallback callback,
/* from(void *) */IntPtr callback_arg);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern void TurnBasedMultiplayerManager_DismissInvitation(
HandleRef self,
/* from(MultiplayerInvitation_t) */IntPtr invitation);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern void TurnBasedMultiplayerManager_FetchMatch(
HandleRef self,
/* from(char const *) */string match_id,
/* from(TurnBasedMultiplayerManager_TurnBasedMatchCallback_t) */TurnBasedMatchCallback callback,
/* from(void *) */IntPtr callback_arg);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern void TurnBasedMultiplayerManager_DeclineInvitation(
HandleRef self,
/* from(MultiplayerInvitation_t) */IntPtr invitation);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern void TurnBasedMultiplayerManager_FinishMatchDuringMyTurn(
HandleRef self,
/* from(TurnBasedMatch_t) */IntPtr match,
/* from(uint8_t const *) */byte[] match_data,
/* from(size_t) */UIntPtr match_data_size,
/* from(ParticipantResults_t) */IntPtr results,
/* from(TurnBasedMultiplayerManager_TurnBasedMatchCallback_t) */TurnBasedMatchCallback callback,
/* from(void *) */IntPtr callback_arg);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern void TurnBasedMultiplayerManager_FetchMatches(
HandleRef self,
/* from(TurnBasedMultiplayerManager_TurnBasedMatchesCallback_t) */TurnBasedMatchesCallback callback,
/* from(void *) */IntPtr callback_arg);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern void TurnBasedMultiplayerManager_CreateTurnBasedMatch(
HandleRef self,
/* from(TurnBasedMatchConfig_t) */IntPtr config,
/* from(TurnBasedMultiplayerManager_TurnBasedMatchCallback_t) */TurnBasedMatchCallback callback,
/* from(void *) */IntPtr callback_arg);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern void TurnBasedMultiplayerManager_AcceptInvitation(
HandleRef self,
/* from(MultiplayerInvitation_t) */IntPtr invitation,
/* from(TurnBasedMultiplayerManager_TurnBasedMatchCallback_t) */TurnBasedMatchCallback callback,
/* from(void *) */IntPtr callback_arg);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern void TurnBasedMultiplayerManager_TakeMyTurn(
HandleRef self,
/* from(TurnBasedMatch_t) */IntPtr match,
/* from(uint8_t const *) */byte[] match_data,
/* from(size_t) */UIntPtr match_data_size,
/* from(ParticipantResults_t) */IntPtr results,
/* from(MultiplayerParticipant_t) */IntPtr next_participant,
/* from(TurnBasedMultiplayerManager_TurnBasedMatchCallback_t) */TurnBasedMatchCallback callback,
/* from(void *) */IntPtr callback_arg);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern void TurnBasedMultiplayerManager_ConfirmPendingCompletion(
HandleRef self,
/* from(TurnBasedMatch_t) */IntPtr match,
/* from(TurnBasedMultiplayerManager_TurnBasedMatchCallback_t) */TurnBasedMatchCallback callback,
/* from(void *) */IntPtr callback_arg);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern void TurnBasedMultiplayerManager_LeaveMatchDuringMyTurn(
HandleRef self,
/* from(TurnBasedMatch_t) */IntPtr match,
/* from(MultiplayerParticipant_t) */IntPtr next_participant,
/* from(TurnBasedMultiplayerManager_MultiplayerStatusCallback_t) */MultiplayerStatusCallback callback,
/* from(void *) */IntPtr callback_arg);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern void TurnBasedMultiplayerManager_LeaveMatchDuringTheirTurn(
HandleRef self,
/* from(TurnBasedMatch_t) */IntPtr match,
/* from(TurnBasedMultiplayerManager_MultiplayerStatusCallback_t) */MultiplayerStatusCallback callback,
/* from(void *) */IntPtr callback_arg);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern void TurnBasedMultiplayerManager_TurnBasedMatchResponse_Dispose(
HandleRef self);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern /* from(MultiplayerStatus_t) */ CommonErrorStatus.MultiplayerStatus TurnBasedMultiplayerManager_TurnBasedMatchResponse_GetStatus(
HandleRef self);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern /* from(TurnBasedMatch_t) */ IntPtr TurnBasedMultiplayerManager_TurnBasedMatchResponse_GetMatch(
HandleRef self);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern void TurnBasedMultiplayerManager_TurnBasedMatchesResponse_Dispose(
HandleRef self);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern /* from(MultiplayerStatus_t) */ CommonErrorStatus.MultiplayerStatus TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetStatus(
HandleRef self);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern /* from(size_t) */ UIntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetInvitations_Length(
HandleRef self);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern /* from(MultiplayerInvitation_t) */ IntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetInvitations_GetElement(
HandleRef self,
/* from(size_t) */UIntPtr index);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern /* from(size_t) */ UIntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetMyTurnMatches_Length(
HandleRef self);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern /* from(TurnBasedMatch_t) */ IntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetMyTurnMatches_GetElement(
HandleRef self,
/* from(size_t) */UIntPtr index);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern /* from(size_t) */ UIntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetTheirTurnMatches_Length(
HandleRef self);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern /* from(TurnBasedMatch_t) */ IntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetTheirTurnMatches_GetElement(
HandleRef self,
/* from(size_t) */UIntPtr index);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern /* from(size_t) */ UIntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetCompletedMatches_Length(
HandleRef self);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern /* from(TurnBasedMatch_t) */ IntPtr TurnBasedMultiplayerManager_TurnBasedMatchesResponse_GetCompletedMatches_GetElement(
HandleRef self,
/* from(size_t) */UIntPtr index);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern void TurnBasedMultiplayerManager_MatchInboxUIResponse_Dispose(
HandleRef self);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern /* from(UIStatus_t) */ CommonErrorStatus.UIStatus TurnBasedMultiplayerManager_MatchInboxUIResponse_GetStatus(
HandleRef self);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern /* from(TurnBasedMatch_t) */ IntPtr TurnBasedMultiplayerManager_MatchInboxUIResponse_GetMatch(
HandleRef self);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern void TurnBasedMultiplayerManager_PlayerSelectUIResponse_Dispose(
HandleRef self);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern /* from(UIStatus_t) */ CommonErrorStatus.UIStatus TurnBasedMultiplayerManager_PlayerSelectUIResponse_GetStatus(
HandleRef self);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern /* from(size_t) */ UIntPtr TurnBasedMultiplayerManager_PlayerSelectUIResponse_GetPlayerIds_Length(
HandleRef self);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern /* from(size_t) */ UIntPtr TurnBasedMultiplayerManager_PlayerSelectUIResponse_GetPlayerIds_GetElement(
HandleRef self,
/* from(size_t) */UIntPtr index,
/* from(char *) */StringBuilder out_arg,
/* from(size_t) */UIntPtr out_size);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern /* from(uint32_t) */ uint TurnBasedMultiplayerManager_PlayerSelectUIResponse_GetMinimumAutomatchingPlayers(
HandleRef self);
[DllImport(SymbolLocation.NativeSymbolLocation)]
internal static extern /* from(uint32_t) */ uint TurnBasedMultiplayerManager_PlayerSelectUIResponse_GetMaximumAutomatchingPlayers(
HandleRef self);
}
}
#endif // (UNITY_ANDROID || UNITY_IPHONE)
| |
//------------------------------------------------------------------------------
// <copyright from='1997' to='2001' company='Microsoft Corporation'>
// Copyright (c) Microsoft Corporation. All Rights Reserved.
// Information Contained Herein is Proprietary and Confidential.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Management.Instrumentation
{
using System;
using System.Reflection;
using System.Management;
using System.Collections;
class SchemaMapping
{
Type classType;
ManagementClass newClass;
string className;
string classPath;
string codeClassName;
CodeWriter code = new CodeWriter();
public Type ClassType { get { return classType; } }
public ManagementClass NewClass { get { return newClass; } }
public string ClassName { get { return className; } }
public string ClassPath { get { return classPath; } }
public CodeWriter Code { get { return code; } }
public string CodeClassName { get {return codeClassName; } }
InstrumentationType instrumentationType;
public InstrumentationType InstrumentationType { get { return instrumentationType; } }
static public void ThrowUnsupportedMember(MemberInfo mi)
{
ThrowUnsupportedMember(mi, null);
}
static public void ThrowUnsupportedMember(MemberInfo mi, Exception innerException)
{
throw new ArgumentException(String.Format(RC.GetString("UNSUPPORTEDMEMBER_EXCEPT"), mi.Name), mi.Name, innerException);
}
public SchemaMapping(Type type, SchemaNaming naming, Hashtable mapTypeToConverterClassName)
{
codeClassName = (string)mapTypeToConverterClassName[type];
classType = type;
bool hasGenericEmbeddedObject = false;
string baseClassName = ManagedNameAttribute.GetBaseClassName(type);
className = ManagedNameAttribute.GetMemberName(type);
instrumentationType = InstrumentationClassAttribute.GetAttribute(type).InstrumentationType;
classPath = naming.NamespaceName + ":" + className;
if(null == baseClassName)
{
newClass = new ManagementClass(naming.NamespaceName, "", null);
newClass.SystemProperties ["__CLASS"].Value = className;
}
else
{
ManagementClass baseClass = new ManagementClass(naming.NamespaceName + ":" + baseClassName);
if(instrumentationType == InstrumentationType.Instance)
{
bool baseAbstract = false;
try
{
QualifierData o = baseClass.Qualifiers["abstract"];
if(o.Value is bool)
baseAbstract = (bool)o.Value;
}
catch(ManagementException e)
{
if(e.ErrorCode != ManagementStatus.NotFound)
throw;
}
if(!baseAbstract)
throw new Exception(RC.GetString("CLASSINST_EXCEPT"));
}
newClass = baseClass.Derive(className);
}
// Create the converter class
CodeWriter codeClass = code.AddChild("public class "+codeClassName+" : IWmiConverter");
// Create code block for one line Members
CodeWriter codeOneLineMembers = codeClass.AddChild(new CodeWriter());
codeOneLineMembers.Line("static ManagementClass managementClass = new ManagementClass(@\"" + classPath + "\");");
codeOneLineMembers.Line("static IntPtr classWbemObjectIP;");
codeOneLineMembers.Line("static Guid iidIWbemObjectAccess = new Guid(\"49353C9A-516B-11D1-AEA6-00C04FB68820\");");
codeOneLineMembers.Line("internal ManagementObject instance = managementClass.CreateInstance();");
codeOneLineMembers.Line("object reflectionInfoTempObj = null ; ");
codeOneLineMembers.Line("FieldInfo reflectionIWbemClassObjectField = null ; ");
codeOneLineMembers.Line("IntPtr emptyWbemObject = IntPtr.Zero ; ");
codeOneLineMembers.Line("IntPtr originalObject = IntPtr.Zero ; ");
codeOneLineMembers.Line("bool toWmiCalled = false ; ");
//
// Reuters VSQFE#: 750 [marioh] see comments above
// Used as a temporary pointer to the newly created instance that we create to avoid re-using the same
// object causing unbound memory usage in IWbemClassObject implementation.
codeOneLineMembers.Line("IntPtr theClone = IntPtr.Zero;");
codeOneLineMembers.Line("public static ManagementObject emptyInstance = managementClass.CreateInstance();");
//
codeOneLineMembers.Line("public IntPtr instWbemObjectAccessIP;");
// Create static constructor to initialize handles
CodeWriter codeCCTOR = codeClass.AddChild("static "+codeClassName+"()");
codeCCTOR.Line("classWbemObjectIP = (IntPtr)managementClass;");
codeCCTOR.Line("IntPtr wbemObjectAccessIP;");
codeCCTOR.Line("Marshal.QueryInterface(classWbemObjectIP, ref iidIWbemObjectAccess, out wbemObjectAccessIP);");
codeCCTOR.Line("int cimType;");
// Create constructor
CodeWriter codeCTOR = codeClass.AddChild("public "+codeClassName+"()");
codeCTOR.Line("IntPtr wbemObjectIP = (IntPtr)instance;");
codeCTOR.Line("originalObject = (IntPtr)instance;");
codeCTOR.Line("Marshal.QueryInterface(wbemObjectIP, ref iidIWbemObjectAccess, out instWbemObjectAccessIP);");
//
// Reuters VSQFE#: 750 [marioh]
// In the CCTOR we set things up only once:
// 1. We get the IWbemClassObjectFreeThreaded object '_wbemObject' from the ManagementObject instance
// 2. We then get the actual IntPtr to the underlying WMI object
// 3. Finally, the simple cast to IntPtr from the ManagementObject instance
// These fields will be used later during the ToWMI call.
codeCTOR.Line ("FieldInfo tempField = instance.GetType().GetField ( \"_wbemObject\", BindingFlags.Instance | BindingFlags.NonPublic );" );
codeCTOR.Line("if ( tempField == null )");
codeCTOR.Line("{");
codeCTOR.Line(" tempField = instance.GetType().GetField ( \"wbemObject\", BindingFlags.Instance | BindingFlags.NonPublic ) ;");
codeCTOR.Line("}");
codeCTOR.Line ("reflectionInfoTempObj = tempField.GetValue (instance) ;");
codeCTOR.Line("reflectionIWbemClassObjectField = reflectionInfoTempObj.GetType().GetField (\"pWbemClassObject\", BindingFlags.Instance | BindingFlags.NonPublic );");
codeCTOR.Line("emptyWbemObject = (IntPtr) emptyInstance;");
// Create destructor that will be called at process cleanup
CodeWriter codeDTOR = codeClass.AddChild("~"+codeClassName+"()");
codeDTOR.AddChild("if(instWbemObjectAccessIP != IntPtr.Zero)").Line("Marshal.Release(instWbemObjectAccessIP);");
// [marioh] Make sure we release the initial instance so that we dont leak
codeDTOR.Line("if ( toWmiCalled == true )");
codeDTOR.Line("{");
codeDTOR.Line(" Marshal.Release (originalObject);");
codeDTOR.Line("}");
// Create method to convert from managed code to WMI
CodeWriter codeToWMI = codeClass.AddChild("public void ToWMI(object obj)");
//
// Reuters VSQFE#: 750 [marioh] see comments above
// Ensure the release of the WbemObjectAccess interface pointer.
codeToWMI.Line( "toWmiCalled = true ;" ) ;
codeToWMI.Line( "if(instWbemObjectAccessIP != IntPtr.Zero)" ) ;
codeToWMI.Line( "{" ) ;
codeToWMI.Line(" Marshal.Release(instWbemObjectAccessIP);" ) ;
codeToWMI.Line(" instWbemObjectAccessIP = IntPtr.Zero;" ) ;
codeToWMI.Line( "}" ) ;
codeToWMI.Line( "if(theClone != IntPtr.Zero)" ) ;
codeToWMI.Line( "{" ) ;
codeToWMI.Line(" Marshal.Release(theClone);" ) ;
codeToWMI.Line(" theClone = IntPtr.Zero;" ) ;
codeToWMI.Line( "}" ) ;
codeToWMI.Line( "IWOA.Clone_f(12, emptyWbemObject, out theClone) ;" ) ;
codeToWMI.Line( "Marshal.QueryInterface(theClone, ref iidIWbemObjectAccess, out instWbemObjectAccessIP) ;" ) ;
codeToWMI.Line( "reflectionIWbemClassObjectField.SetValue ( reflectionInfoTempObj, theClone ) ;" ) ;
codeToWMI.Line(String.Format("{0} instNET = ({0})obj;", type.FullName.Replace('+', '.'))); // bug#92918 - watch for nested classes
// Explicit cast to IntPtr
CodeWriter codeIntPtrCast = codeClass.AddChild("public static explicit operator IntPtr("+codeClassName+" obj)");
codeIntPtrCast.Line("return obj.instWbemObjectAccessIP;");
// Add GetInstance
codeOneLineMembers.Line("public ManagementObject GetInstance() {return instance;}");
PropertyDataCollection props = newClass.Properties;
// type specific info
switch(instrumentationType)
{
case InstrumentationType.Event:
break;
case InstrumentationType.Instance:
props.Add("ProcessId", CimType.String, false);
props.Add("InstanceId", CimType.String, false);
props["ProcessId"].Qualifiers.Add("key", true);
props["InstanceId"].Qualifiers.Add("key", true);
newClass.Qualifiers.Add("dynamic", true, false, false, false, true);
newClass.Qualifiers.Add("provider", naming.DecoupledProviderInstanceName, false, false, false, true);
break;
case InstrumentationType.Abstract:
newClass.Qualifiers.Add("abstract", true, false, false, false, true);
break;
default:
break;
}
int propCount = 0;
bool needsNullObj = false;
foreach(MemberInfo field in type.GetMembers())
{
if(!(field is FieldInfo || field is PropertyInfo))
continue;
if(field.GetCustomAttributes(typeof(IgnoreMemberAttribute), false).Length > 0)
continue;
if(field is FieldInfo)
{
FieldInfo fi = field as FieldInfo;
// We ignore statics
if(fi.IsStatic)
ThrowUnsupportedMember(field);
}
else if (field is PropertyInfo)
{
PropertyInfo pi = field as PropertyInfo;
// We must have a 'get' property accessor
if(!pi.CanRead)
ThrowUnsupportedMember(field);
// We ignore static properties
MethodInfo mi = pi.GetGetMethod();
if(null == mi || mi.IsStatic)
ThrowUnsupportedMember(field);
// We don't support parameters on properties
if(mi.GetParameters().Length > 0)
ThrowUnsupportedMember(field);
}
String propName = ManagedNameAttribute.GetMemberName(field);
#if SUPPORTS_ALTERNATE_WMI_PROPERTY_TYPE
Type t2 = ManagedTypeAttribute.GetManagedType(field);
#else
Type t2;
if(field is FieldInfo)
t2 = (field as FieldInfo).FieldType;
else
t2 = (field as PropertyInfo).PropertyType;
#endif
bool isArray = false;
if(t2.IsArray)
{
// We only support one dimensional arrays in this version
if(t2.GetArrayRank() != 1)
ThrowUnsupportedMember(field);
isArray = true;
t2 = t2.GetElementType();
}
string embeddedTypeName = null;
string embeddedConverterName = null;
if(mapTypeToConverterClassName.Contains(t2))
{
embeddedConverterName = (string)mapTypeToConverterClassName[t2];
embeddedTypeName = ManagedNameAttribute.GetMemberName(t2);
}
bool isGenericEmbeddedObject = false;
if(t2 == typeof(object))
{
isGenericEmbeddedObject = true;
if(hasGenericEmbeddedObject == false)
{
hasGenericEmbeddedObject = true;
// Add map
codeOneLineMembers.Line("static Hashtable mapTypeToConverter = new Hashtable();");
foreach(DictionaryEntry entry in mapTypeToConverterClassName)
{
codeCCTOR.Line(String.Format("mapTypeToConverter[typeof({0})] = typeof({1});", ((Type)entry.Key).FullName.Replace('+', '.'), (string)entry.Value)); // bug#92918 - watch for nested classes
}
}
}
string propFieldName = "prop_" + (propCount);
string handleFieldName = "handle_" + (propCount++);
// Add handle for field, which is static accross all instances
codeOneLineMembers.Line("static int " + handleFieldName + ";");
codeCCTOR.Line(String.Format("IWOA.GetPropertyHandle_f27(27, wbemObjectAccessIP, \"{0}\", out cimType, out {1});", propName, handleFieldName));
// Add PropertyData for field, which is specific to each instance
codeOneLineMembers.Line("PropertyData " + propFieldName + ";");
codeCTOR.Line(String.Format("{0} = instance.Properties[\"{1}\"];", propFieldName, propName));
if(isGenericEmbeddedObject)
{
CodeWriter codeNotNull = codeToWMI.AddChild(String.Format("if(instNET.{0} != null)", field.Name));
CodeWriter codeElse = codeToWMI.AddChild("else");
codeElse.Line(String.Format("{0}.Value = null;", propFieldName));
if(isArray)
{
codeNotNull.Line(String.Format("int len = instNET.{0}.Length;", field.Name));
codeNotNull.Line("ManagementObject[] embeddedObjects = new ManagementObject[len];");
codeNotNull.Line("IWmiConverter[] embeddedConverters = new IWmiConverter[len];");
CodeWriter codeForLoop = codeNotNull.AddChild("for(int i=0;i<len;i++)");
CodeWriter codeFoundType = codeForLoop.AddChild(String.Format("if((instNET.{0}[i] != null) && mapTypeToConverter.Contains(instNET.{0}[i].GetType()))", field.Name));
codeFoundType.Line(String.Format("Type type = (Type)mapTypeToConverter[instNET.{0}[i].GetType()];", field.Name));
codeFoundType.Line("embeddedConverters[i] = (IWmiConverter)Activator.CreateInstance(type);");
codeFoundType.Line(String.Format("embeddedConverters[i].ToWMI(instNET.{0}[i]);", field.Name));
codeFoundType.Line("embeddedObjects[i] = embeddedConverters[i].GetInstance();");
codeForLoop.AddChild("else").Line(String.Format("embeddedObjects[i] = SafeAssign.GetManagementObject(instNET.{0}[i]);", field.Name));
codeNotNull.Line(String.Format("{0}.Value = embeddedObjects;", propFieldName));
}
else
{
CodeWriter codeFoundType = codeNotNull.AddChild(String.Format("if(mapTypeToConverter.Contains(instNET.{0}.GetType()))", field.Name));
codeFoundType.Line(String.Format("Type type = (Type)mapTypeToConverter[instNET.{0}.GetType()];", field.Name));
codeFoundType.Line("IWmiConverter converter = (IWmiConverter)Activator.CreateInstance(type);");
codeFoundType.Line(String.Format("converter.ToWMI(instNET.{0});", field.Name));
codeFoundType.Line(String.Format("{0}.Value = converter.GetInstance();", propFieldName));
codeNotNull.AddChild("else").Line(String.Format("{0}.Value = SafeAssign.GetInstance(instNET.{1});", propFieldName, field.Name));
}
}
else if(embeddedTypeName != null)
{
// If this is an embedded struct, it cannot be null
CodeWriter codeNotNull;
if(t2.IsValueType)
codeNotNull = codeToWMI;
else
{
codeNotNull = codeToWMI.AddChild(String.Format("if(instNET.{0} != null)", field.Name));
CodeWriter codeElse = codeToWMI.AddChild("else");
codeElse.Line(String.Format("{0}.Value = null;", propFieldName));
}
if(isArray)
{
codeNotNull.Line(String.Format("int len = instNET.{0}.Length;", field.Name));
codeNotNull.Line("ManagementObject[] embeddedObjects = new ManagementObject[len];");
codeNotNull.Line(String.Format("{0}[] embeddedConverters = new {0}[len];", embeddedConverterName));
CodeWriter codeForLoop = codeNotNull.AddChild("for(int i=0;i<len;i++)");
codeForLoop.Line(String.Format("embeddedConverters[i] = new {0}();", embeddedConverterName));
// If this is a struct array, the elements are never null
if(t2.IsValueType)
{
codeForLoop.Line(String.Format("embeddedConverters[i].ToWMI(instNET.{0}[i]);", field.Name));
}
else
{
CodeWriter codeArrayElementNotNull = codeForLoop.AddChild(String.Format("if(instNET.{0}[i] != null)", field.Name));
codeArrayElementNotNull.Line(String.Format("embeddedConverters[i].ToWMI(instNET.{0}[i]);", field.Name));
}
codeForLoop.Line("embeddedObjects[i] = embeddedConverters[i].instance;");
codeNotNull.Line(String.Format("{0}.Value = embeddedObjects;", propFieldName));
}
else
{
// We cannot create an instance of 'embeddedConverterName' because it may be the
// same type as we are defining (in other words, a cyclic loop, such as class XXX
// having an instance of an XXX as a member). To prevent an infinite loop of constructing
// converter classes, we create a 'lazy' variable that is initialized to NULL, and the first
// time it is used, we set it to a 'new embeddedConverterName'.
codeOneLineMembers.Line(String.Format("{0} lazy_embeddedConverter_{1} = null;", embeddedConverterName, propFieldName));
CodeWriter codeConverterProp = codeClass.AddChild(String.Format("{0} embeddedConverter_{1}", embeddedConverterName, propFieldName));
CodeWriter codeGet = codeConverterProp.AddChild("get");
CodeWriter codeIf = codeGet.AddChild(String.Format("if(null == lazy_embeddedConverter_{0})", propFieldName));
codeIf.Line(String.Format("lazy_embeddedConverter_{0} = new {1}();", propFieldName, embeddedConverterName));
codeGet.Line(String.Format("return lazy_embeddedConverter_{0};", propFieldName));
codeNotNull.Line(String.Format("embeddedConverter_{0}.ToWMI(instNET.{1});", propFieldName, field.Name));
codeNotNull.Line(String.Format("{0}.Value = embeddedConverter_{0}.instance;", propFieldName));
}
}
else if(!isArray)
{
if(t2 == typeof(Byte) || t2 == typeof(SByte))
{
//
// [PS#128409, marioh] CS0206 Compile error occured when instrumentated types contains public properties of type SByte, Int16, and UInt16
// Properties can not be passed as ref and therefore we store the property value in a tmp local variable before calling WritePropertyValue.
//
codeToWMI.Line(String.Format("{0} instNET_{1} = instNET.{1} ;", t2, field.Name));
codeToWMI.Line(String.Format("IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 1, ref instNET_{1});", handleFieldName, field.Name));
}
else if(t2 == typeof(Int16) || t2 == typeof(UInt16) || t2 == typeof(Char))
{
//
// [PS#128409, marioh] CS0206 Compile error occured when instrumentated types contains public properties of type SByte, Int16, and UInt16
// Properties can not be passed as ref and therefore we store the property value in a tmp local variable before calling WritePropertyValue.
//
codeToWMI.Line(String.Format("{0} instNET_{1} = instNET.{1} ;", t2, field.Name));
codeToWMI.Line(String.Format("IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 2, ref instNET_{1});", handleFieldName, field.Name));
}
else if(t2 == typeof(UInt32) || t2 == typeof(Int32) || t2 == typeof(Single))
codeToWMI.Line(String.Format("IWOA.WriteDWORD_f31(31, instWbemObjectAccessIP, {0}, instNET.{1});", handleFieldName, field.Name));
else if(t2 == typeof(UInt64) || t2 == typeof(Int64) || t2 == typeof(Double))
codeToWMI.Line(String.Format("IWOA.WriteQWORD_f33(33, instWbemObjectAccessIP, {0}, instNET.{1});", handleFieldName, field.Name));
else if(t2 == typeof(Boolean))
{
//
codeToWMI.Line(String.Format("if(instNET.{0})", field.Name));
codeToWMI.Line(String.Format(" IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 2, ref SafeAssign.boolTrue);", handleFieldName));
codeToWMI.Line("else");
codeToWMI.Line(String.Format(" IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 2, ref SafeAssign.boolFalse);", handleFieldName));
}
else if(t2 == typeof(String))
{
CodeWriter codeQuickString = codeToWMI.AddChild(String.Format("if(null != instNET.{0})", field.Name));
codeQuickString.Line(String.Format("IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, (instNET.{1}.Length+1)*2, instNET.{1});", handleFieldName, field.Name));
// codeToWMI.AddChild("else").Line(String.Format("{0}.Value = instNET.{1};", propFieldName, field.Name));
codeToWMI.AddChild("else").Line(String.Format("IWOA.Put_f5(5, instWbemObjectAccessIP, \"{0}\", 0, ref nullObj, 8);", propName));
if(needsNullObj == false)
{
needsNullObj = true;
// Bug#111623 - This line used to say 'nullObj = null;' When nullObj was passed
// to IWOA.Put, this did NOT set the value of a string variable to NULL. The correct
// thing to do was to pass a reference to DBNull.Value to IWOA.Put instead.
codeOneLineMembers.Line("object nullObj = DBNull.Value;");
}
}
else if(t2 == typeof(DateTime) || t2 == typeof(TimeSpan))
{
codeToWMI.Line(String.Format("IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 52, SafeAssign.WMITimeToString(instNET.{1}));", handleFieldName, field.Name));
// codeToWMI.Line(String.Format("{0}.Value = SafeAssign.DateTimeToString(instNET.{1});", propFieldName, field.Name));
}
else
codeToWMI.Line(String.Format("{0}.Value = instNET.{1};", propFieldName, field.Name));
}
else
{
// We have an array type
if(t2 == typeof(DateTime) || t2 == typeof(TimeSpan))
{
codeToWMI.AddChild(String.Format("if(null == instNET.{0})", field.Name)).Line(String.Format("{0}.Value = null;", propFieldName));
codeToWMI.AddChild("else").Line(String.Format("{0}.Value = SafeAssign.WMITimeArrayToStringArray(instNET.{1});", propFieldName, field.Name));
}
else
{
// This handles arrays of all primative types
codeToWMI.Line(String.Format("{0}.Value = instNET.{1};", propFieldName, field.Name));
}
}
CimType cimtype = CimType.String;
if(field.DeclaringType != type)
continue;
#if REQUIRES_EXPLICIT_DECLARATION_OF_INHERITED_PROPERTIES
if(InheritedPropertyAttribute.GetAttribute(field) != null)
continue;
#else
// See if this field already exists on the WMI class
// In other words, is it inherited from a base class
//
bool propertyExists = true;
try
{
PropertyData prop = newClass.Properties[propName];
// HACK for bug#96863 - The above line used to throw a
// not found exception. This was changed with a recent
// checkin. If this functionality is not reverted, the
// following statement should force the necessary 'not
// found' exception that we are looking for.
CimType cimType = prop.Type;
// Make sure that if the property exists, it is inherited
// If it is local, they probably named two properties with
// the same name
if(prop.IsLocal)
{
throw new ArgumentException(String.Format(RC.GetString("MEMBERCONFLILCT_EXCEPT"), field.Name), field.Name);
}
}
catch(ManagementException e)
{
if(e.ErrorCode != ManagementStatus.NotFound)
throw;
else
propertyExists = false;
}
if(propertyExists)
continue;
#endif
if(embeddedTypeName != null)
cimtype = CimType.Object;
else if(isGenericEmbeddedObject)
cimtype = CimType.Object;
else if(t2 == typeof(ManagementObject))
cimtype = CimType.Object;
else if(t2 == typeof(SByte))
cimtype = CimType.SInt8;
else if(t2 == typeof(Byte))
cimtype = CimType.UInt8;
else if(t2 == typeof(Int16))
cimtype = CimType.SInt16;
else if(t2 == typeof(UInt16))
cimtype = CimType.UInt16;
else if(t2 == typeof(Int32))
cimtype = CimType.SInt32;
else if(t2 == typeof(UInt32))
cimtype = CimType.UInt32;
else if(t2 == typeof(Int64))
cimtype = CimType.SInt64;
else if(t2 == typeof(UInt64))
cimtype = CimType.UInt64;
else if(t2 == typeof(Single))
cimtype = CimType.Real32;
else if(t2 == typeof(Double))
cimtype = CimType.Real64;
else if(t2 == typeof(Boolean))
cimtype = CimType.Boolean;
else if(t2 == typeof(String))
cimtype = CimType.String;
else if(t2 == typeof(Char))
cimtype = CimType.Char16;
else if(t2 == typeof(DateTime))
cimtype = CimType.DateTime;
else if(t2 == typeof(TimeSpan))
cimtype = CimType.DateTime;
else
ThrowUnsupportedMember(field);
// HACK: The following line cause a strange System.InvalidProgramException when run through InstallUtil
// throw new Exception("Unsupported type for event member - " + t2.Name);
//
#if SUPPORTS_WMI_DEFAULT_VAULES
Object defaultValue = ManagedDefaultValueAttribute.GetManagedDefaultValue(field);
//
if(null == defaultValue)
props.Add(propName, cimtype, false);
else
props.Add(propName, defaultValue, cimtype);
#else
try
{
props.Add(propName, cimtype, isArray);
}
catch(ManagementException e)
{
ThrowUnsupportedMember(field, e);
}
#endif
// Must at 'interval' SubType on TimeSpans
if(t2 == typeof(TimeSpan))
{
PropertyData prop = props[propName];
prop.Qualifiers.Add("SubType", "interval", false, true, true, true);
}
if(embeddedTypeName != null)
{
PropertyData prop = props[propName];
prop.Qualifiers["CIMTYPE"].Value = "object:"+embeddedTypeName;
}
}
codeCCTOR.Line("Marshal.Release(wbemObjectAccessIP);");
// codeToWMI.Line("Console.WriteLine(instance.GetText(TextFormat.Mof));");
}
}
}
| |
// <copyright file="HistoryPast.cs" company="Primas">
// Company copyright tag.
// </copyright>
namespace FPL.Data.Models.FullStats
{
using Newtonsoft.Json;
using FPL.Data.Common.Contracts;
/// <summary>
/// The past history class
/// </summary>
public class HistoryPast : FullStatsBase, IFantasyPremierLeagueId
{
/// <summary>
/// Gets or sets the identifier.
/// </summary>
/// <value>
/// The identifier.
/// </value>
[JsonProperty("id")]
public int FantasyPremierLeagueId { get; set; }
/// <summary>
/// Gets or sets the name of the season.
/// </summary>
/// <value>
/// The name of the season.
/// </value>
[JsonProperty("season_name")]
public string SeasonName { get; set; }
/// <summary>
/// Gets or sets the element code.
/// </summary>
/// <value>
/// The element code.
/// </value>
[JsonProperty("element_code")]
public int ElementCode { get; set; }
/// <summary>
/// Gets or sets the start cost.
/// </summary>
/// <value>
/// The start cost.
/// </value>
[JsonProperty("start_cost")]
public int StartCost { get; set; }
/// <summary>
/// Gets or sets the end cost.
/// </summary>
/// <value>
/// The end cost.
/// </value>
[JsonProperty("end_cost")]
public int EndCost { get; set; }
/// <summary>
/// Gets or sets the total points.
/// </summary>
/// <value>
/// The total points.
/// </value>
[JsonProperty("total_points")]
public int TotalPoints { get; set; }
/// <summary>
/// Gets or sets the minutes.
/// </summary>
/// <value>
/// The minutes.
/// </value>
[JsonProperty("minutes")]
public int Minutes { get; set; }
/// <summary>
/// Gets or sets the goals scored.
/// </summary>
/// <value>
/// The goals scored.
/// </value>
[JsonProperty("goals_scored")]
public int GoalsScored { get; set; }
/// <summary>
/// Gets or sets the assists.
/// </summary>
/// <value>
/// The assists.
/// </value>
[JsonProperty("assists")]
public int Assists { get; set; }
/// <summary>
/// Gets or sets the clean sheets.
/// </summary>
/// <value>
/// The clean sheets.
/// </value>
[JsonProperty("clean_sheets")]
public int CleanSheets { get; set; }
/// <summary>
/// Gets or sets the goals conceded.
/// </summary>
/// <value>
/// The goals conceded.
/// </value>
[JsonProperty("goals_conceded")]
public int GoalsConceded { get; set; }
/// <summary>
/// Gets or sets the own goals.
/// </summary>
/// <value>
/// The own goals.
/// </value>
[JsonProperty("own_goals")]
public int OwnGoals { get; set; }
/// <summary>
/// Gets or sets the penalties saved.
/// </summary>
/// <value>
/// The penalties saved.
/// </value>
[JsonProperty("penalties_saved")]
public int PenaltiesSaved { get; set; }
/// <summary>
/// Gets or sets the penalties missed.
/// </summary>
/// <value>
/// The penalties missed.
/// </value>
[JsonProperty("penalties_missed")]
public int PenaltiesMissed { get; set; }
/// <summary>
/// Gets or sets the yellow cards.
/// </summary>
/// <value>
/// The yellow cards.
/// </value>
[JsonProperty("yellow_cards")]
public int YellowCards { get; set; }
/// <summary>
/// Gets or sets the red cards.
/// </summary>
/// <value>
/// The red cards.
/// </value>
[JsonProperty("red_cards")]
public int RedCards { get; set; }
/// <summary>
/// Gets or sets the saves.
/// </summary>
/// <value>
/// The saves.
/// </value>
[JsonProperty("saves")]
public int Saves { get; set; }
/// <summary>
/// Gets or sets the bonus.
/// </summary>
/// <value>
/// The bonus.
/// </value>
[JsonProperty("bonus")]
public int Bonus { get; set; }
/// <summary>
/// Gets or sets the BPS.
/// </summary>
/// <value>
/// The BPS.
/// </value>
[JsonProperty("bps")]
public int Bps { get; set; }
/// <summary>
/// Gets or sets the influence.
/// </summary>
/// <value>
/// The influence.
/// </value>
[JsonProperty("influence")]
public string Influence { get; set; }
/// <summary>
/// Gets or sets the creativity.
/// </summary>
/// <value>
/// The creativity.
/// </value>
[JsonProperty("creativity")]
public string Creativity { get; set; }
/// <summary>
/// Gets or sets the threat.
/// </summary>
/// <value>
/// The threat.
/// </value>
[JsonProperty("threat")]
public string Threat { get; set; }
/// <summary>
/// Gets or sets the index of the Influence, Creativity and Threat.
/// </summary>
/// <value>
/// The index of the Influence, Creativity and Threat.
/// </value>
[JsonProperty("ict_index")]
public string IctIndex { get; set; }
/// <summary>
/// Gets or sets the index of the electronic arts.
/// </summary>
/// <value>
/// The index of the electronic arts.
/// </value>
[JsonProperty("ea_index")]
public int EaIndex { get; set; }
/// <summary>
/// Gets or sets the season.
/// </summary>
/// <value>
/// The season.
/// </value>
[JsonProperty("season")]
public int Season { get; set; }
}
}
| |
using System;
using System.Reflection;
using System.IO;
using System.Linq;
namespace Microsoft.Zing
{
/// <summary>
/// Stores the current Exploration Cost.
/// This value is used to check if the bound is exceeded
/// </summary>
[Serializable]
public class ZingerBounds
{
public Int32 ExecutionCost;
public Int32 ChoiceCost;
public ZingerBounds(Int32 searchB, Int32 choiceB)
{
ExecutionCost = searchB;
ChoiceCost = choiceB;
}
public ZingerBounds()
{
ExecutionCost = 0;
ChoiceCost = 0;
}
public void IncrementDepthCost()
{
if (!ZingerConfiguration.DoDelayBounding && !ZingerConfiguration.DoPreemptionBounding)
{
ExecutionCost++;
}
}
public void IncrementDelayCost()
{
if (ZingerConfiguration.DoDelayBounding)
{
ExecutionCost++;
}
}
public void IncrementPreemptionCost()
{
if (ZingerConfiguration.DoPreemptionBounding)
{
ExecutionCost++;
}
}
}
/// <summary>
/// Stores the configuration for zinger bounded search
/// </summary>
public class ZingerBoundedSearch
{
#region Bounds
public int FinalExecutionCutOff;
public int FinalChoiceCutOff;
public int IterativeIncrement;
public int IterativeCutoff;
#endregion Bounds
#region Contructor
public ZingerBoundedSearch(int exeFinalCutoff, int exeIterativeInc, int finalChoiceCutoff)
{
FinalExecutionCutOff = exeFinalCutoff;
FinalChoiceCutOff = finalChoiceCutoff;
IterativeIncrement = exeIterativeInc;
IterativeCutoff = 0;
}
public ZingerBoundedSearch()
{
FinalExecutionCutOff = int.MaxValue;
FinalChoiceCutOff = int.MaxValue;
IterativeIncrement = 1;
IterativeCutoff = 0;
}
#endregion Contructor
#region Functions
public bool checkIfFinalCutOffReached()
{
if (IterativeCutoff > FinalExecutionCutOff)
{
return true;
}
else
{
return false;
}
}
public bool checkIfIterativeCutOffReached(ZingerBounds currBounds)
{
if ((currBounds.ExecutionCost > IterativeCutoff) || (ZingerConfiguration.BoundChoices && currBounds.ChoiceCost > FinalChoiceCutOff))
{
return true;
}
else
{
return false;
}
}
public void IncrementIterativeBound()
{
IterativeCutoff += IterativeIncrement;
}
#endregion Functions
}
/// <summary>
/// Zing External Plugin
/// </summary>
public class ZingerExternalPlugin
{
// Zing plugin state
public ZingerPluginState zPluginState;
// Zing plugin implementation
public ZingerPluginInterface zPlugin;
}
/// <summary>
/// Zing External Scheduler
/// </summary>
public class ZingerExternalScheduler
{
// Zing Delaying Scheduler
public ZingerDelayingScheduler zDelaySched;
// Zing External Scheduler State
public ZingerSchedulerState zSchedState;
public ZingerExternalScheduler()
{
var zingerPath = new Uri(
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
).LocalPath;
var schedDllPath = zingerPath + "\\" + "RunToCompletionDelayingScheduler.dll";
if (!File.Exists(schedDllPath))
{
ZingerUtilities.PrintErrorMessage(String.Format("Scheduler file {0} not found", schedDllPath));
ZingerConfiguration.DoDelayBounding = false;
return;
}
var schedAssembly = Assembly.LoadFrom(schedDllPath);
// get class name
string schedClassName = schedAssembly.GetTypes().Where(t => (t.BaseType.Name == "ZingerDelayingScheduler")).First().FullName;
var schedStateClassName = schedAssembly.GetTypes().Where(t => (t.BaseType.Name == "ZingerSchedulerState")).First().FullName;
var schedClassType = schedAssembly.GetType(schedClassName);
var schedStateClassType = schedAssembly.GetType(schedStateClassName);
zDelaySched = Activator.CreateInstance(schedClassType) as ZingerDelayingScheduler;
zSchedState = Activator.CreateInstance(schedStateClassType) as ZingerSchedulerState;
}
}
/// <summary>
/// Maceliveness configuration
/// </summary>
public class ZingerMaceLiveness
{
//Exhaustive Search Depth
public int exSearchDepth;
//iterative live-state period
public int liveStatePeriod;
//random walk final cutoff
public int randomFinalCutOff;
public ZingerMaceLiveness()
{
exSearchDepth = 10;
liveStatePeriod = 1000;
randomFinalCutOff = 100000;
}
public ZingerMaceLiveness(int exS, int liveP, int ranF)
{
exSearchDepth = exS;
liveStatePeriod = liveP;
randomFinalCutOff = ranF;
}
}
/// <summary>
/// Zinger Configuration
/// </summary>
public class ZingerConfiguration
{
private ZingerConfiguration()
{
}
//Zing Bounded Search Configuration
public static ZingerBoundedSearch zBoundedSearch = new ZingerBoundedSearch();
//zing model file
public static string ZingModelFile = "";
//trace log file
public static string traceLogFile = "";
// Commandline Option to dump trace based counter example in a file
private static bool enableTrace = false;
public static bool EnableTrace
{
get { return ZingerConfiguration.enableTrace; }
set { ZingerConfiguration.enableTrace = value; }
}
// commandline option to dump out detailed Zing stack trace
private static bool detailedZingTrace = false;
public static bool DetailedZingTrace
{
get { return ZingerConfiguration.detailedZingTrace; }
set { ZingerConfiguration.detailedZingTrace = value; }
}
// Avoid Fingerprinting single transition states in Zing (default value is true).
private static bool notFingerprintSingleTransitionStates = true;
public static bool FingerprintSingleTransitionStates
{
get { return notFingerprintSingleTransitionStates; }
set { notFingerprintSingleTransitionStates = value; }
}
// Probability of fingerprinting single transition states
private static double nonChooseProbability = 0;
public static double NonChooseProbability
{
get { return nonChooseProbability; }
set { nonChooseProbability = (double)value / (double)1000000; }
}
//degree of parallelism (default = single threaded)
private static int degreeOfParallelism = 1;
public static int DegreeOfParallelism
{
get { return degreeOfParallelism; }
set { degreeOfParallelism = value; }
}
//print detailed states after each iteration.
private static bool printStats = false;
public static bool PrintStats
{
get { return ZingerConfiguration.printStats; }
set { ZingerConfiguration.printStats = value; }
}
//Configuration for work-stealing (default is 10 items from other threads queue)
private static int workStealAmount = 10;
public static int WorkStealAmount
{
get { return workStealAmount; }
set { workStealAmount = value; }
}
//Compact Execution traces (not store the step taken if the state has single successor).
private static bool compactTraces = false;
public static bool CompactTraces
{
get { return compactTraces; }
set { compactTraces = value; }
}
//do PCT based prioritization
private static bool doPCT = false;
public static bool DoPCT
{
get { return ZingerConfiguration.doPCT; }
set { ZingerConfiguration.doPCT = value; }
}
//do preemption bounding
private static bool doPreemptionBounding = false;
public static bool DoPreemptionBounding
{
get { return ZingerConfiguration.doPreemptionBounding; }
set { ZingerConfiguration.doPreemptionBounding = value; }
}
//do delay bounding
private static bool doDelayBounding = true;
public static bool DoDelayBounding
{
get { return ZingerConfiguration.doDelayBounding; }
set { ZingerConfiguration.doDelayBounding = value; }
}
//do Random sampling
private static bool doRandomSampling = false;
public static bool DoRandomSampling
{
get { return ZingerConfiguration.doRandomSampling; }
set { ZingerConfiguration.doRandomSampling = value; }
}
//number of schedules explored
public static int numberOfSchedulesExplored = 0;
//maximum number of schedules per iteration
private static int maxSchedulesPerIteration = 100;
public static int MaxSchedulesPerIteration
{
get { return ZingerConfiguration.maxSchedulesPerIteration; }
set { ZingerConfiguration.maxSchedulesPerIteration = value; }
}
//maximum depth per schedule when performing random sampleing
public static int MaxDepthPerSchedule = 600;
//Zing External Scheduler for delay bounding
private static ZingerExternalScheduler zExternalScheduler = new ZingerExternalScheduler();
public static ZingerExternalScheduler ZExternalScheduler
{
get { return ZingerConfiguration.zExternalScheduler; }
set { ZingerConfiguration.zExternalScheduler = value; }
}
//Do NDFS based liveness checking
private static bool doNDFSLiveness = false;
public static bool DoNDFSLiveness
{
get { return ZingerConfiguration.doNDFSLiveness; }
set { ZingerConfiguration.doNDFSLiveness = value; }
}
//Bound the max stack length, this is used in cases where zing has infinite stack trace.
private static int boundDFSStackLength = int.MaxValue;
public static int BoundDFSStackLength
{
get { return ZingerConfiguration.boundDFSStackLength; }
set { ZingerConfiguration.boundDFSStackLength = value; }
}
// bound the choice points
private static bool boundChoices = false;
public static bool BoundChoices
{
get { return ZingerConfiguration.boundChoices; }
set { ZingerConfiguration.boundChoices = value; }
}
private static bool doLivenessSampling = false;
public static bool DoLivenessSampling
{
get { return ZingerConfiguration.doLivenessSampling; }
set { ZingerConfiguration.doLivenessSampling = value; }
}
//perform Iterative MAP algorithm for liveness
private static bool doRandomLiveness = false;
public static bool DoRandomLiveness
{
get { return ZingerConfiguration.doRandomLiveness; }
set { ZingerConfiguration.doRandomLiveness = value; }
}
//push all the frontiers to disk
private static bool frontierToDisk = false;
public static bool FrontierToDisk
{
get { return ZingerConfiguration.frontierToDisk; }
set { ZingerConfiguration.frontierToDisk = value; }
}
//do state caching after memory usage has exceeded
private static double maxMemoryConsumption = double.MaxValue;
public static double MaxMemoryConsumption
{
get { return ZingerConfiguration.maxMemoryConsumption; }
set { ZingerConfiguration.maxMemoryConsumption = value; }
}
//find all errors in the program.
private static bool stopOnError = true;
public static bool StopOnError
{
get { return ZingerConfiguration.stopOnError; }
set { ZingerConfiguration.stopOnError = value; }
}
//execute TraceStatements when in Error Trace generation mode.
private static bool executeTraceStatements = false;
public static bool ExecuteTraceStatements
{
get { return ZingerConfiguration.executeTraceStatements; }
set { ZingerConfiguration.executeTraceStatements = value; }
}
//Zinger time out in seconds
private static int timeout = 24 * 60 * 60; //default is 24 hours.
public static int Timeout
{
get { return timeout; }
set { timeout = value; }
}
//Integrate motionplanning with Zing
private static bool dronacharyaEnabled = false;
public static bool DronacharyaEnabled
{
get { return ZingerConfiguration.dronacharyaEnabled; }
set { ZingerConfiguration.dronacharyaEnabled = value; }
}
// Is this the main dronaCharya instance
private static bool isDronaMain = true;
public static bool IsDronaMain
{
get { return ZingerConfiguration.isDronaMain; }
set { ZingerConfiguration.isDronaMain = value; }
}
private static ZingDronacharya zDronacharya;
public static ZingDronacharya ZDronacharya
{
get { return ZingerConfiguration.zDronacharya; }
set { ZingerConfiguration.zDronacharya = value; }
}
private static bool isPluginEnabled = false;
public static bool IsPluginEnabled
{
get { return ZingerConfiguration.isPluginEnabled; }
set { ZingerConfiguration.isPluginEnabled = value; }
}
//Plugin dll
private static ZingerExternalPlugin zPlugin = null;
public static ZingerExternalPlugin ZPlugin
{
get { return ZingerConfiguration.zPlugin; }
set { ZingerConfiguration.zPlugin = value; }
}
public static void InferConfiguration()
{
//Initialize the conflicting settings
//The set of conflicting configurations are
//Randomwalk + Statefull
//NDFliveness + iterative + sequential
if (DoNDFSLiveness)
{
zBoundedSearch.IterativeIncrement = zBoundedSearch.FinalExecutionCutOff;
DegreeOfParallelism = 1;
DoRandomSampling = false;
DoDelayBounding = false;
}
if (DoDelayBounding)
{
DoPreemptionBounding = false;
}
}
public static void PrintConfiguration()
{
ZingerUtilities.PrintMessage("Zinger Configuration :");
ZingerUtilities.PrintMessage(String.Format("EnableTrace : {0} and TraceFile: {1}", EnableTrace, traceLogFile));
ZingerUtilities.PrintMessage(String.Format("DetailedZingTrace: {0}", DetailedZingTrace));
ZingerUtilities.PrintMessage(String.Format("FingerPrint Single Transition States : {0}", !notFingerprintSingleTransitionStates));
ZingerUtilities.PrintMessage(String.Format("Degree Of Parallelism: {0}", DegreeOfParallelism));
ZingerUtilities.PrintMessage(String.Format("Print Statistics: {0}", PrintStats));
ZingerUtilities.PrintMessage(String.Format("Compact Trace : {0}", CompactTraces));
ZingerUtilities.PrintMessage(String.Format("Do Preemption Bounding :{0}", doPreemptionBounding));
ZingerUtilities.PrintMessage(String.Format("Delay Bounding : {0}", doDelayBounding));
ZingerUtilities.PrintMessage(String.Format("Do RanddomWalk : {0} and max schedules per iteration {1}, max depth {2}", doRandomSampling, maxSchedulesPerIteration, MaxDepthPerSchedule));
ZingerUtilities.PrintMessage(String.Format("Do NDFLiveness : {0}", doNDFSLiveness));
ZingerUtilities.PrintMessage(String.Format("Max Stack Size : {0}", boundDFSStackLength));
ZingerUtilities.PrintMessage(String.Format("Bound Choices: {0} and max Bound {1}", BoundChoices, zBoundedSearch.FinalChoiceCutOff));
ZingerUtilities.PrintMessage(String.Format("Bounded Search : Iterative bound {0} and Max Bound {1}", zBoundedSearch.IterativeIncrement, zBoundedSearch.FinalExecutionCutOff));
ZingerUtilities.PrintMessage(String.Format("Do Random liveness: {0}, max depth {1}, max schedules per iteration {2}", doLivenessSampling, MaxDepthPerSchedule, maxSchedulesPerIteration));
ZingerUtilities.PrintMessage(String.Format("Frontier to Disk :{0}", frontierToDisk));
ZingerUtilities.PrintMessage(String.Format("Max memory : {0}", maxMemoryConsumption));
ZingerUtilities.PrintMessage(String.Format("Stop on First Error: {0}", stopOnError));
ZingerUtilities.PrintMessage(String.Format("Dronacharya Enabled execution : {0}", DronacharyaEnabled));
ZingerUtilities.PrintMessage(String.Format("Plugin Enabled execution : {0}", IsPluginEnabled));
ZingerUtilities.PrintMessage("");
}
}
}
| |
#region License
/*
* WebSocketService.cs
*
* The MIT License
*
* Copyright (c) 2012-2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Threading;
using WebSocketSharp.Net;
using WebSocketSharp.Net.WebSockets;
namespace WebSocketSharp.Server
{
/// <summary>
/// Provides the basic functions of the WebSocket service used by the WebSocket service host.
/// </summary>
/// <remarks>
/// The WebSocketService class is an abstract class.
/// </remarks>
public abstract class WebSocketService : IWebSocketSession
{
#region Private Fields
private WebSocket _websocket;
private WebSocketContext _context;
private WebSocketSessionManager _sessions;
private DateTime _start;
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketService"/> class.
/// </summary>
public WebSocketService ()
{
_start = DateTime.MaxValue;
}
#endregion
#region Protected Properties
/// <summary>
/// Gets or sets the logging functions.
/// </summary>
/// <remarks>
/// If you want to change the current logger to the service own logger, you set this property
/// to a new <see cref="Logger"/> instance that you created.
/// </remarks>
/// <value>
/// A <see cref="Logger"/> that provides the logging functions.
/// </value>
protected Logger Log {
get {
return _websocket != null
? _websocket.Log
: null;
}
set {
if (_websocket != null)
_websocket.Log = value;
}
}
/// <summary>
/// Gets the manager of the sessions to the WebSocket service.
/// </summary>
/// <value>
/// A <see cref="WebSocketSessionManager"/> that manages the sessions to the WebSocket service.
/// </value>
protected WebSocketSessionManager Sessions {
get {
return _sessions;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets the WebSocket connection request information.
/// </summary>
/// <value>
/// A <see cref="WebSocketContext"/> that contains the WebSocket connection request information.
/// </value>
public WebSocketContext Context {
get {
return _context;
}
}
/// <summary>
/// Gets the unique ID of the current <see cref="WebSocketService"/> instance.
/// </summary>
/// <value>
/// A <see cref="string"/> that contains the unique ID.
/// </value>
public string ID {
get; private set;
}
/// <summary>
/// Gets the time that the current <see cref="WebSocketService"/> instance has been started.
/// </summary>
/// <value>
/// A <see cref="DateTime"/> that represents the time that the current <see cref="WebSocketService"/>
/// instance has been started.
/// </value>
public DateTime StartTime {
get {
return _start;
}
}
/// <summary>
/// Gets the state of the WebSocket connection.
/// </summary>
/// <value>
/// One of the <see cref="WebSocketState"/> values.
/// </value>
public WebSocketState State {
get {
return _websocket != null
? _websocket.ReadyState
: WebSocketState.CONNECTING;
}
}
#endregion
#region Private Methods
private void onClose (object sender, CloseEventArgs e)
{
if (ID == null)
return;
_sessions.Remove (ID);
OnClose (e);
}
private void onError (object sender, ErrorEventArgs e)
{
OnError (e);
}
private void onMessage (object sender, MessageEventArgs e)
{
OnMessage (e);
}
private void onOpen (object sender, EventArgs e)
{
ID = _sessions.Add (this);
if (ID == null)
{
_websocket.Close (CloseStatusCode.AWAY);
return;
}
_start = DateTime.Now;
OnOpen ();
}
#endregion
#region Internal Methods
internal void Start (WebSocketContext context, WebSocketSessionManager sessions)
{
_context = context;
_sessions = sessions;
_websocket = context.WebSocket;
_websocket.CookiesValidation = ValidateCookies;
_websocket.OnOpen += onOpen;
_websocket.OnMessage += onMessage;
_websocket.OnError += onError;
_websocket.OnClose += onClose;
_websocket.ConnectAsServer ();
}
#endregion
#region Protected Methods
/// <summary>
/// Calls the <see cref="OnError"/> method with the specified <paramref name="message"/>.
/// </summary>
/// <param name="message">
/// A <see cref="string"/> that contains an error message.
/// </param>
protected void Error (string message)
{
if (!message.IsNullOrEmpty ())
OnError (new ErrorEventArgs (message));
}
/// <summary>
/// Is called when the WebSocket connection has been closed.
/// </summary>
/// <param name="e">
/// A <see cref="CloseEventArgs"/> that contains an event data associated with
/// an inner <see cref="WebSocket.OnClose"/> event.
/// </param>
protected virtual void OnClose (CloseEventArgs e)
{
}
/// <summary>
/// Is called when the inner <see cref="WebSocket"/> or current <see cref="WebSocketService"/>
/// gets an error.
/// </summary>
/// <param name="e">
/// An <see cref="ErrorEventArgs"/> that contains an event data associated with
/// an inner <see cref="WebSocket.OnError"/> event.
/// </param>
protected virtual void OnError (ErrorEventArgs e)
{
}
/// <summary>
/// Is called when the inner <see cref="WebSocket"/> receives a data frame.
/// </summary>
/// <param name="e">
/// A <see cref="MessageEventArgs"/> that contains an event data associated with
/// an inner <see cref="WebSocket.OnMessage"/> event.
/// </param>
protected virtual void OnMessage (MessageEventArgs e)
{
}
/// <summary>
/// Is called when the WebSocket connection has been established.
/// </summary>
protected virtual void OnOpen ()
{
}
/// <summary>
/// Sends a Ping to the client of the current <see cref="WebSocketService"/> instance.
/// </summary>
/// <returns>
/// <c>true</c> if the current <see cref="WebSocketService"/> instance receives a Pong
/// from the client in a time; otherwise, <c>false</c>.
/// </returns>
protected bool Ping ()
{
return _websocket != null
? _websocket.Ping ()
: false;
}
/// <summary>
/// Sends a Ping with the specified <paramref name="message"/> to the client of
/// the current <see cref="WebSocketService"/> instance.
/// </summary>
/// <returns>
/// <c>true</c> if the current <see cref="WebSocketService"/> instance receives a Pong
/// from the client in a time; otherwise, <c>false</c>.
/// </returns>
/// <param name="message">
/// A <see cref="string"/> that contains a message to send.
/// </param>
protected bool Ping (string message)
{
return _websocket != null
? _websocket.Ping (message)
: false;
}
/// <summary>
/// Sends a binary <paramref name="data"/> to the client of the current
/// <see cref="WebSocketService"/> instance.
/// </summary>
/// <remarks>
/// This method does not wait for the send to be complete.
/// </remarks>
/// <param name="data">
/// An array of <see cref="byte"/> that contains a binary data to send.
/// </param>
protected void Send (ArraySegment<byte> data)
{
if (_websocket != null)
_websocket.Send (data, null);
}
/// <summary>
/// Sends a binary data from the specified <see cref="FileInfo"/> to
/// the client of the current <see cref="WebSocketService"/> instance.
/// </summary>
/// <remarks>
/// This method does not wait for the send to be complete.
/// </remarks>
/// <param name="file">
/// A <see cref="FileInfo"/> from which contains a binary data to send.
/// </param>
protected void Send (FileInfo file)
{
if (_websocket != null)
_websocket.Send (file, null);
}
/// <summary>
/// Sends a text <paramref name="data"/> to the client of the current
/// <see cref="WebSocketService"/> instance.
/// </summary>
/// <remarks>
/// This method does not wait for the send to be complete.
/// </remarks>
/// <param name="data">
/// A <see cref="string"/> that contains a text data to send.
/// </param>
protected void Send (string data)
{
if (_websocket != null)
_websocket.Send (data, null);
}
/// <summary>
/// Sends a binary <paramref name="data"/> to the client of the current
/// <see cref="WebSocketService"/> instance.
/// </summary>
/// <remarks>
/// This method does not wait for the send to be complete.
/// </remarks>
/// <param name="data">
/// An array of <see cref="byte"/> that contains a binary data to send.
/// </param>
/// <param name="completed">
/// An Action<bool> delegate that references the method(s) called when
/// the send is complete.
/// A <see cref="bool"/> passed to this delegate is <c>true</c> if the send is
/// complete successfully; otherwise, <c>false</c>.
/// </param>
protected void Send (ArraySegment<byte> data, Action<bool> completed)
{
if (_websocket != null)
_websocket.Send (data, completed);
}
/// <summary>
/// Sends a binary data from the specified <see cref="FileInfo"/> to
/// the client of the current <see cref="WebSocketService"/> instance.
/// </summary>
/// <remarks>
/// This method does not wait for the send to be complete.
/// </remarks>
/// <param name="file">
/// A <see cref="FileInfo"/> from which contains a binary data to send.
/// </param>
/// <param name="completed">
/// An Action<bool> delegate that references the method(s) called when
/// the send is complete.
/// A <see cref="bool"/> passed to this delegate is <c>true</c> if the send is
/// complete successfully; otherwise, <c>false</c>.
/// </param>
protected void Send (FileInfo file, Action<bool> completed)
{
if (_websocket != null)
_websocket.Send (file, completed);
}
/// <summary>
/// Sends a text <paramref name="data"/> to the client of the current
/// <see cref="WebSocketService"/> instance.
/// </summary>
/// <remarks>
/// This method does not wait for the send to be complete.
/// </remarks>
/// <param name="data">
/// A <see cref="string"/> that contains a text data to send.
/// </param>
/// <param name="completed">
/// An Action<bool> delegate that references the method(s) called when
/// the send is complete.
/// A <see cref="bool"/> passed to this delegate is <c>true</c> if the send is
/// complete successfully; otherwise, <c>false</c>.
/// </param>
protected void Send (string data, Action<bool> completed)
{
if (_websocket != null)
_websocket.Send (data, completed);
}
/// <summary>
/// Sends a binary data from the specified <see cref="Stream"/> to
/// the client of the current <see cref="WebSocketService"/> instance.
/// </summary>
/// <remarks>
/// This method does not wait for the send to be complete.
/// </remarks>
/// <param name="stream">
/// A <see cref="Stream"/> object from which contains a binary data to send.
/// </param>
/// <param name="length">
/// An <see cref="int"/> that contains the number of bytes to send.
/// </param>
protected void Send (Stream stream, int length)
{
if (_websocket != null)
_websocket.Send (stream, length, null);
}
/// <summary>
/// Sends a binary data from the specified <see cref="Stream"/> to
/// the client of the current <see cref="WebSocketService"/> instance.
/// </summary>
/// <remarks>
/// This method does not wait for the send to be complete.
/// </remarks>
/// <param name="stream">
/// A <see cref="Stream"/> object from which contains a binary data to send.
/// </param>
/// <param name="length">
/// An <see cref="int"/> that contains the number of bytes to send.
/// </param>
/// <param name="completed">
/// An Action<bool> delegate that references the method(s) called when
/// the send is complete.
/// A <see cref="bool"/> passed to this delegate is <c>true</c> if the send is
/// complete successfully; otherwise, <c>false</c>.
/// </param>
protected void Send (Stream stream, int length, Action<bool> completed)
{
if (_websocket != null)
_websocket.Send (stream, length, completed);
}
/// <summary>
/// Stops the current <see cref="WebSocketService"/> instance.
/// </summary>
protected void Stop ()
{
if (_websocket != null)
_websocket.Close ();
}
/// <summary>
/// Stops the current <see cref="WebSocketService"/> instance with the specified
/// <see cref="ushort"/> and <see cref="string"/>.
/// </summary>
/// <param name="code">
/// A <see cref="ushort"/> that contains a status code indicating the reason for stop.
/// </param>
/// <param name="reason">
/// A <see cref="string"/> that contains the reason for stop.
/// </param>
protected void Stop (ushort code, string reason)
{
if (_websocket != null)
_websocket.Close (code, reason);
}
/// <summary>
/// Stops the current <see cref="WebSocketService"/> instance with the specified
/// <see cref="CloseStatusCode"/> and <see cref="string"/>.
/// </summary>
/// <param name="code">
/// One of the <see cref="CloseStatusCode"/> values that indicates a status code
/// indicating the reason for stop.
/// </param>
/// <param name="reason">
/// A <see cref="string"/> that contains the reason for stop.
/// </param>
protected void Stop (CloseStatusCode code, string reason)
{
if (_websocket != null)
_websocket.Close (code, reason);
}
/// <summary>
/// Validates the cookies used in the WebSocket connection request.
/// </summary>
/// <remarks>
/// This method is called when the inner <see cref="WebSocket"/> validates
/// the WebSocket connection request.
/// </remarks>
/// <returns>
/// <c>true</c> if the cookies is valid; otherwise, <c>false</c>.
/// The default returns <c>true</c>.
/// </returns>
/// <param name="request">
/// A <see cref="CookieCollection"/> that contains a collection of the HTTP Cookies
/// to validate.
/// </param>
/// <param name="response">
/// A <see cref="CookieCollection"/> that receives the HTTP Cookies to send to the client.
/// </param>
protected virtual bool ValidateCookies (CookieCollection request, CookieCollection response)
{
return true;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using NHibernate;
using Orchard.ContentManagement.Records;
using Orchard.Utility.Extensions;
namespace Orchard.ContentManagement {
public class DefaultHqlQuery : IHqlQuery {
private readonly ISession _session;
private VersionOptions _versionOptions;
protected IJoin _from;
protected readonly List<Tuple<IAlias, Join>> _joins = new List<Tuple<IAlias, Join>>();
protected readonly List<Tuple<IAlias, Action<IHqlExpressionFactory>>> _wheres = new List<Tuple<IAlias, Action<IHqlExpressionFactory>>>();
protected readonly List<Tuple<IAlias, Action<IHqlSortFactory>>> _sortings = new List<Tuple<IAlias, Action<IHqlSortFactory>>>();
public IContentManager ContentManager { get; private set; }
public DefaultHqlQuery(IContentManager contentManager, ISession session) {
_session = session;
ContentManager = contentManager;
}
internal string PathToAlias(string path) {
if (String.IsNullOrWhiteSpace(path)) {
throw new ArgumentException("Path can't be empty");
}
return Char.ToLower(path[0], CultureInfo.InvariantCulture) + path.Substring(1);
}
internal Join BindNamedAlias(string alias) {
var tuple = _joins.FirstOrDefault(x => x.Item2.Name == alias);
return tuple == null ? null : tuple.Item2;
}
internal IAlias BindCriteriaByPath(IAlias alias, string path) {
return BindCriteriaByAlias(alias, path, PathToAlias(path));
}
internal IAlias BindCriteriaByAlias(IAlias alias, string path, string aliasName) {
// is this Join already existing (based on aliasName)
Join join = BindNamedAlias(aliasName);
if (join == null) {
join = new Join(path, aliasName);
_joins.Add(new Tuple<IAlias, Join>(alias, join));
}
return join;
}
internal IAlias BindTypeCriteria() {
// ([ContentItemVersionRecord] >join> [ContentItemRecord]) >join> [ContentType]
return BindCriteriaByAlias(BindItemCriteria(), "ContentType", "ct");
}
internal IAlias BindItemCriteria() {
// [ContentItemVersionRecord] >join> [ContentItemRecord]
return BindCriteriaByAlias(BindItemVersionCriteria(), typeof(ContentItemRecord).Name, "ci");
}
internal IAlias BindItemVersionCriteria() {
return _from ?? (_from = new Join(typeof(ContentItemVersionRecord).FullName, "civ", ""));
}
internal IAlias BindPartCriteria<TRecord>() where TRecord : ContentPartRecord {
return BindPartCriteria(typeof(TRecord));
}
internal IAlias BindPartCriteria(Type contentPartRecordType) {
if (!contentPartRecordType.IsSubclassOf(typeof(ContentPartRecord))) {
throw new ArgumentException("The type must inherit from ContentPartRecord", "contentPartRecordType");
}
if (contentPartRecordType.IsSubclassOf(typeof(ContentPartVersionRecord))) {
return BindCriteriaByPath(BindItemVersionCriteria(), contentPartRecordType.Name);
}
return BindCriteriaByPath(BindItemCriteria(), contentPartRecordType.Name);
}
internal void Where(IAlias alias, Action<IHqlExpressionFactory> predicate) {
_wheres.Add(new Tuple<IAlias, Action<IHqlExpressionFactory>>(alias, predicate));
}
internal IAlias ApplyHqlVersionOptionsRestrictions(VersionOptions versionOptions) {
var alias = BindItemVersionCriteria();
if (versionOptions == null) {
Where(alias, x => x.Eq("Published", true));
}
else if (versionOptions.IsPublished) {
Where(alias, x => x.Eq("Published", true));
}
else if (versionOptions.IsLatest) {
Where(alias, x => x.Eq("Latest", true));
}
else if (versionOptions.IsDraft) {
Where(alias, x => x.And(y => y.Eq("Latest", true), y => y.Eq("Published", false)));
}
else if (versionOptions.IsAllVersions) {
// no-op... all versions will be returned by default
}
else {
throw new ApplicationException("Invalid VersionOptions for content query");
}
return alias;
}
public IHqlQuery Join(Action<IAliasFactory> alias) {
var aliasFactory = new DefaultAliasFactory(this);
alias(aliasFactory);
return this;
}
public IHqlQuery Where(Action<IAliasFactory> alias, Action<IHqlExpressionFactory> predicate) {
var aliasFactory = new DefaultAliasFactory(this);
alias(aliasFactory);
Where(aliasFactory.Current, predicate);
return this;
}
public IHqlQuery OrderBy(Action<IAliasFactory> alias, Action<IHqlSortFactory> order) {
var aliasFactory = new DefaultAliasFactory(this);
alias(aliasFactory);
_sortings.Add(new Tuple<IAlias, Action<IHqlSortFactory>>(aliasFactory.Current, order));
return this;
}
public IHqlQuery ForType(params string[] contentTypeNames) {
if (contentTypeNames != null && contentTypeNames.Length != 0) {
Where(BindTypeCriteria(), x => x.InG("Name", contentTypeNames));
}
return this;
}
public IHqlQuery ForVersion(VersionOptions options) {
_versionOptions = options;
return this;
}
public IHqlQuery<T> ForPart<T>() where T : IContent {
return new DefaultHqlQuery<T>(this);
}
public IEnumerable<ContentItem> List() {
return Slice(0, 0);
}
public IEnumerable<ContentItem> Slice(int skip, int count) {
ApplyHqlVersionOptionsRestrictions(_versionOptions);
var hql = ToHql(false);
var query = _session.CreateQuery(hql);
if (skip != 0) {
query.SetFirstResult(skip);
}
if (count != 0) {
query.SetMaxResults(count);
}
return query.List<ContentItemVersionRecord>()
.Select(x => ContentManager.Get(x.Id, VersionOptions.VersionRecord(x.Id)))
.ToReadOnlyCollection();
}
public int Count() {
ApplyHqlVersionOptionsRestrictions(_versionOptions);
return Convert.ToInt32(_session.CreateQuery(ToHql(true)).UniqueResult());
}
public string ToHql(bool count) {
var sb = new StringBuilder();
if (count) {
sb.Append("select count(civ) ").AppendLine();
}
else {
sb.Append("select civ ").AppendLine();
}
sb.Append("from ").Append(_from.TableName).Append(" as ").Append(_from.Name).AppendLine();
foreach (var join in _joins) {
sb.Append(join.Item2.Type).Append(" ").Append(join.Item1.Name + "." + join.Item2.TableName).Append(" as ").Append(join.Item2.Name).AppendLine();
}
// generating where clause
if (_wheres.Any()) {
sb.Append("where ");
var expressions = new List<string>();
foreach (var where in _wheres) {
var expressionFactory = new DefaultHqlExpressionFactory();
where.Item2(expressionFactory);
expressions.Add(expressionFactory.Criterion.ToHql(where.Item1));
}
sb.Append("(").Append(String.Join(") AND (", expressions.ToArray())).Append(")").AppendLine();
}
// generating order by clause
bool firstSort = true;
foreach (var sort in _sortings) {
if (!firstSort) {
sb.Append(", ");
}
else {
sb.Append("order by ");
firstSort = false;
}
var sortFactory = new DefaultHqlSortFactory();
sort.Item2(sortFactory);
if (sortFactory.Randomize) {
sb.Append(" newid()");
}
else {
sb.Append(sort.Item1.Name).Append(".").Append(sortFactory.PropertyName);
if (!sortFactory.Ascending) {
sb.Append(" desc");
}
}
}
return sb.ToString();
}
}
public class DefaultHqlQuery<TPart> : IHqlQuery<TPart> where TPart : IContent {
private readonly DefaultHqlQuery _query;
public DefaultHqlQuery(DefaultHqlQuery query) {
_query = query;
}
public IContentManager ContentManager {
get { return _query.ContentManager; }
}
public IHqlQuery<TPart> ForType(params string[] contentTypes) {
_query.ForType(contentTypes);
return new DefaultHqlQuery<TPart>(_query);
}
public IHqlQuery<TPart> ForVersion(VersionOptions options) {
_query.ForVersion(options);
return new DefaultHqlQuery<TPart>(_query);
}
IEnumerable<TPart> IHqlQuery<TPart>.List() {
return _query.List().AsPart<TPart>();
}
IEnumerable<TPart> IHqlQuery<TPart>.Slice(int skip, int count) {
return _query.Slice(skip, count).AsPart<TPart>();
}
int IHqlQuery<TPart>.Count() {
return _query.Count();
}
public IHqlQuery<TPart> Join(Action<IAliasFactory> alias) {
_query.Join(alias);
return new DefaultHqlQuery<TPart>(_query);
}
public IHqlQuery<TPart> Where(Action<IAliasFactory> alias, Action<IHqlExpressionFactory> predicate) {
_query.Where(alias, predicate);
return new DefaultHqlQuery<TPart>(_query);
}
public IHqlQuery<TPart> OrderBy(Action<IAliasFactory> alias, Action<IHqlSortFactory> order) {
_query.OrderBy(alias, order);
return new DefaultHqlQuery<TPart>(_query);
}
}
public class Alias : IAlias {
public Alias(string name) {
if (String.IsNullOrEmpty(name)) {
throw new ArgumentException("Alias can't be empty");
}
Name = name;
}
public DefaultHqlQuery<IContent> Query { get; set; }
public string Name { get; set; }
}
public interface IJoin : IAlias {
string TableName { get; set; }
string Type { get; set; }
}
public class Sort {
public Sort(IAlias alias, string propertyName, bool ascending) {
Alias = alias;
PropertyName = propertyName;
Ascending = ascending;
}
public IAlias Alias { get; set; }
public string PropertyName { get; set; }
public bool Ascending { get; set; }
}
public class Join : Alias, IJoin {
public Join(string tableName, string alias)
: this(tableName, alias, "join") {}
public Join(string tableName, string alias, string type)
: base(alias) {
if (String.IsNullOrEmpty(tableName)) {
throw new ArgumentException("Table Name can't be empty");
}
TableName = tableName;
Type = type;
}
public string TableName { get; set; }
public string Type { get; set; }
}
public class DefaultHqlSortFactory : IHqlSortFactory
{
public bool Ascending { get; set; }
public string PropertyName { get; set; }
public bool Randomize { get; set; }
public void Asc(string propertyName) {
PropertyName = propertyName;
Ascending = true;
}
public void Desc(string propertyName) {
PropertyName = propertyName;
Ascending = false;
}
public void Random() {
Randomize = true;
}
}
public class DefaultAliasFactory : IAliasFactory{
private readonly DefaultHqlQuery _query;
public IAlias Current { get; private set; }
public DefaultAliasFactory(DefaultHqlQuery query) {
_query = query;
Current = _query.BindItemCriteria();
}
public IAliasFactory ContentPartRecord<TRecord>() where TRecord : ContentPartRecord {
Current = _query.BindPartCriteria<TRecord>();
return this;
}
public IAliasFactory ContentPartRecord(Type contentPartRecord) {
if(!contentPartRecord.IsSubclassOf(typeof(ContentPartRecord))) {
throw new ArgumentException("Type must inherit from ContentPartRecord", "contentPartRecord");
}
Current = _query.BindPartCriteria(contentPartRecord);
return this;
}
public IAliasFactory Property(string propertyName, string alias) {
Current = _query.BindCriteriaByAlias(Current, propertyName, alias);
return this;
}
public IAliasFactory Named(string alias) {
Current = _query.BindNamedAlias(alias);
return this;
}
public IAliasFactory ContentItem() {
return Named("ci");
}
public IAliasFactory ContentItemVersion() {
Current = _query.BindItemVersionCriteria();
return this;
}
public IAliasFactory ContentType() {
return Named("ct");
}
}
public class DefaultHqlExpressionFactory : IHqlExpressionFactory {
public IHqlCriterion Criterion { get; private set; }
public void Eq(string propertyName, object value) {
Criterion = HqlRestrictions.Eq(propertyName, value);
}
public void Like(string propertyName, string value, HqlMatchMode matchMode) {
Criterion = HqlRestrictions.Like(propertyName, value, matchMode);
}
public void InsensitiveLike(string propertyName, string value, HqlMatchMode matchMode) {
Criterion = HqlRestrictions.InsensitiveLike(propertyName, value, matchMode);
}
public void Gt(string propertyName, object value) {
Criterion = HqlRestrictions.Gt(propertyName, value);
}
public void Lt(string propertyName, object value) {
Criterion = HqlRestrictions.Lt(propertyName, value);
}
public void Le(string propertyName, object value) {
Criterion = HqlRestrictions.Le(propertyName, value);
}
public void Ge(string propertyName, object value) {
Criterion = HqlRestrictions.Ge(propertyName, value);
}
public void Between(string propertyName, object lo, object hi) {
Criterion = HqlRestrictions.Between(propertyName, lo, hi);
}
public void In(string propertyName, object[] values) {
Criterion = HqlRestrictions.In(propertyName, values);
}
public void In(string propertyName, ICollection values) {
Criterion = HqlRestrictions.In(propertyName, values);
}
public void InG<T>(string propertyName, ICollection<T> values) {
Criterion = HqlRestrictions.InG(propertyName, values);
}
public void IsNull(string propertyName) {
Criterion = HqlRestrictions.IsNull(propertyName);
}
public void EqProperty(string propertyName, string otherPropertyName) {
Criterion = HqlRestrictions.EqProperty(propertyName, otherPropertyName);
}
public void NotEqProperty(string propertyName, string otherPropertyName) {
Criterion = HqlRestrictions.NotEqProperty(propertyName, otherPropertyName);
}
public void GtProperty(string propertyName, string otherPropertyName) {
Criterion = HqlRestrictions.GtProperty(propertyName, otherPropertyName);
}
public void GeProperty(string propertyName, string otherPropertyName) {
Criterion = HqlRestrictions.GeProperty(propertyName, otherPropertyName);
}
public void LtProperty(string propertyName, string otherPropertyName) {
Criterion = HqlRestrictions.LtProperty(propertyName, otherPropertyName);
}
public void LeProperty(string propertyName, string otherPropertyName) {
Criterion = HqlRestrictions.LeProperty(propertyName, otherPropertyName);
}
public void IsNotNull(string propertyName) {
Criterion = HqlRestrictions.IsNotNull(propertyName);
}
public void IsNotEmpty(string propertyName) {
Criterion = HqlRestrictions.IsNotEmpty(propertyName);
}
public void IsEmpty(string propertyName) {
Criterion = HqlRestrictions.IsEmpty(propertyName);
}
public void And(Action<IHqlExpressionFactory> lhs, Action<IHqlExpressionFactory> rhs) {
lhs(this);
var a = Criterion;
rhs(this);
var b = Criterion;
Criterion = HqlRestrictions.And(a, b);
}
public void Or(Action<IHqlExpressionFactory> lhs, Action<IHqlExpressionFactory> rhs) {
lhs(this);
var a = Criterion;
rhs(this);
var b = Criterion;
Criterion = HqlRestrictions.Or(a, b);
}
public void Not(Action<IHqlExpressionFactory> expression) {
expression(this);
var a = Criterion;
Criterion = HqlRestrictions.Not(a);
}
public void Conjunction(Action<IHqlExpressionFactory> expression, params Action<IHqlExpressionFactory>[] otherExpressions) {
var junction = HqlRestrictions.Conjunction();
foreach (var exp in Enumerable.Empty<Action<IHqlExpressionFactory>>().Union(new[] { expression }).Union(otherExpressions)) {
exp(this);
junction.Add(Criterion);
}
Criterion = junction;
}
public void Disjunction(Action<IHqlExpressionFactory> expression, params Action<IHqlExpressionFactory>[] otherExpressions) {
var junction = HqlRestrictions.Disjunction();
foreach (var exp in Enumerable.Empty<Action<IHqlExpressionFactory>>().Union(new[] { expression }).Union(otherExpressions)) {
exp(this);
junction.Add(Criterion);
}
Criterion = junction;
}
public void AllEq(IDictionary propertyNameValues) {
Criterion = HqlRestrictions.AllEq(propertyNameValues);
}
public void NaturalId() {
Criterion = HqlRestrictions.NaturalId();
}
}
public enum HqlMatchMode {
Exact,
Start,
End,
Anywhere
}
}
| |
// ***********************************************************************
// Copyright (c) 2004 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
namespace NUnit.Framework.Assertions
{
[TestFixture]
public class LowTrustFixture
{
private TestSandBox _sandBox;
[OneTimeSetUp]
public void CreateSandBox()
{
_sandBox = new TestSandBox();
}
[OneTimeTearDown]
public void DisposeSandBox()
{
if (_sandBox != null)
{
_sandBox.Dispose();
_sandBox = null;
}
}
[Test]
public void AssertEqualityInLowTrustSandBox()
{
_sandBox.Run(() =>
{
Assert.That(1, Is.EqualTo(1));
});
}
[Test, Platform(Exclude="Mono,MonoTouch", Reason= "Mono does not implement Code Access Security")]
public void AssertThrowsInLowTrustSandBox()
{
_sandBox.Run(() =>
{
Assert.Throws<SecurityException>(() => new SecurityPermission(SecurityPermissionFlag.Infrastructure).Demand());
});
}
}
/// <summary>
/// A facade for an <see cref="AppDomain"/> with partial trust privileges.
/// </summary>
public class TestSandBox : IDisposable
{
private AppDomain _appDomain;
#region Constructor(s)
/// <summary>
/// Creates a low trust <see cref="TestSandBox"/> instance.
/// </summary>
/// <param name="fullTrustAssemblies">Strong named assemblies that will have full trust in the sandbox.</param>
public TestSandBox(params Assembly[] fullTrustAssemblies)
: this(null, fullTrustAssemblies)
{ }
/// <summary>
/// Creates a partial trust <see cref="TestSandBox"/> instance with a given set of permissions.
/// </summary>
/// <param name="permissions">Optional <see cref="TestSandBox"/> permission set. By default a minimal trust
/// permission set is used.</param>
/// <param name="fullTrustAssemblies">Strong named assemblies that will have full trust in the sandbox.</param>
public TestSandBox(PermissionSet permissions, params Assembly[] fullTrustAssemblies)
{
var setup = new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory };
var strongNames = new HashSet<StrongName>();
// Grant full trust to NUnit.Framework assembly to enable use of NUnit assertions in sandboxed test code.
strongNames.Add(GetStrongName(typeof(TestAttribute).Assembly));
if (fullTrustAssemblies != null)
{
foreach (var assembly in fullTrustAssemblies)
{
strongNames.Add(GetStrongName(assembly));
}
}
_appDomain = AppDomain.CreateDomain(
"TestSandBox" + DateTime.Now.Ticks, null, setup,
permissions ?? GetLowTrustPermissionSet(),
strongNames.ToArray());
}
#endregion
#region Finalizer and Dispose methods
/// <summary>
/// The <see cref="TestSandBox"/> finalizer.
/// </summary>
~TestSandBox()
{
Dispose(false);
}
/// <summary>
/// Unloads the <see cref="AppDomain"/>.
/// </summary>
public void Dispose()
{
Dispose(true);
}
/// <summary>
/// Unloads the <see cref="AppDomain"/>.
/// </summary>
/// <param name="disposing">Indicates whether this method is called from <see cref="Dispose()"/>.</param>
protected virtual void Dispose(bool disposing)
{
if (_appDomain != null)
{
AppDomain.Unload(_appDomain);
_appDomain = null;
}
}
#endregion
#region PermissionSet factory methods
public static PermissionSet GetLowTrustPermissionSet()
{
var permissions = new PermissionSet(PermissionState.None);
permissions.AddPermission(new SecurityPermission(
SecurityPermissionFlag.Execution | // Required to execute test code
SecurityPermissionFlag.SerializationFormatter)); // Required to support cross-appdomain test result formatting by NUnit TestContext
permissions.AddPermission(new ReflectionPermission(
ReflectionPermissionFlag.MemberAccess)); // Required to instantiate classes that contain test code and to get cross-appdomain communication to work.
return permissions;
}
#endregion
#region Run methods
public T Run<T>(Func<T> func)
{
return (T)Run(func.Method);
}
public void Run(Action action)
{
Run(action.Method);
}
public object Run(MethodInfo method, params object[] parameters)
{
if (method == null) throw new ArgumentNullException("method");
if (_appDomain == null) throw new ObjectDisposedException(null);
var methodRunnerType = typeof(MethodRunner);
var methodRunnerProxy = (MethodRunner)_appDomain.CreateInstanceAndUnwrap(
methodRunnerType.Assembly.FullName, methodRunnerType.FullName);
try
{
return methodRunnerProxy.Run(method, parameters);
}
catch (Exception e)
{
throw e is TargetInvocationException
? e.InnerException
: e;
}
}
#endregion
#region Private methods
private static StrongName GetStrongName(Assembly assembly)
{
AssemblyName assemblyName = assembly.GetName();
byte[] publicKey = assembly.GetName().GetPublicKey();
if (publicKey == null || publicKey.Length == 0)
{
throw new InvalidOperationException("Assembly is not strongly named");
}
return new StrongName(new StrongNamePublicKeyBlob(publicKey), assemblyName.Name, assemblyName.Version);
}
#endregion
#region Inner classes
[Serializable]
internal class MethodRunner : MarshalByRefObject
{
public object Run(MethodInfo method, params object[] parameters)
{
var instance = method.IsStatic
? null
: Activator.CreateInstance(method.ReflectedType);
try
{
return method.Invoke(instance, parameters);
}
catch (TargetInvocationException e)
{
if (e.InnerException == null) throw;
throw e.InnerException;
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Display;
using OrchardCore.ContentPreview.Models;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.Modules;
using OrchardCore.Mvc.Utilities;
namespace OrchardCore.ContentPreview.Controllers
{
public class PreviewController : Controller
{
private readonly IContentManager _contentManager;
private readonly IContentManagerSession _contentManagerSession;
private readonly IContentItemDisplayManager _contentItemDisplayManager;
private readonly IAuthorizationService _authorizationService;
private readonly IClock _clock;
private readonly IUpdateModelAccessor _updateModelAccessor;
public PreviewController(
IContentManager contentManager,
IContentItemDisplayManager contentItemDisplayManager,
IContentManagerSession contentManagerSession,
IAuthorizationService authorizationService,
IClock clock,
IUpdateModelAccessor updateModelAccessor)
{
_authorizationService = authorizationService;
_clock = clock;
_contentItemDisplayManager = contentItemDisplayManager;
_contentManager = contentManager;
_contentManagerSession = contentManagerSession;
_updateModelAccessor = updateModelAccessor;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Render()
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ContentPreview))
{
return this.ChallengeOrForbid();
}
var contentItemType = Request.Form["ContentItemType"];
var contentItem = await _contentManager.NewAsync(contentItemType);
// Assign the ids from the currently edited item so that validation thinks
// it's working on the same item. For instance if drivers are checking name unicity
// they need to think this is the same existing item (AutoroutePart).
var contentItemId = Request.Form["PreviewContentItemId"];
var contentItemVersionId = Request.Form["PreviewContentItemVersionId"];
// Unique contentItem.Id that only Preview is using such that another
// stored document can't have the same one in the IContentManagerSession index
contentItem.Id = -1;
contentItem.ContentItemId = contentItemId;
contentItem.ContentItemVersionId = contentItemVersionId;
contentItem.CreatedUtc = _clock.UtcNow;
contentItem.ModifiedUtc = _clock.UtcNow;
contentItem.PublishedUtc = _clock.UtcNow;
contentItem.Published = true;
// TODO: we should probably get this value from the main editor as it might impact validators
var model = await _contentItemDisplayManager.UpdateEditorAsync(contentItem, _updateModelAccessor.ModelUpdater, true);
if (!ModelState.IsValid)
{
var errors = new List<string>();
foreach (var modelState in ValidationHelpers.GetModelStateList(ViewData, false))
{
for (var i = 0; i < modelState.Errors.Count; i++)
{
var modelError = modelState.Errors[i];
var errorText = ValidationHelpers.GetModelErrorMessageOrDefault(modelError);
errors.Add(errorText);
}
}
return StatusCode(500, new { errors = errors });
}
var previewAspect = await _contentManager.PopulateAspectAsync(contentItem, new PreviewAspect());
if (!String.IsNullOrEmpty(previewAspect.PreviewUrl))
{
// The PreviewPart is configured, we need to set the fake content item
_contentManagerSession.Store(contentItem);
if (!previewAspect.PreviewUrl.StartsWith('/'))
{
previewAspect.PreviewUrl = "/" + previewAspect.PreviewUrl;
}
Request.HttpContext.Items["PreviewPath"] = previewAspect.PreviewUrl;
return Ok();
}
model = await _contentItemDisplayManager.BuildDisplayAsync(contentItem, _updateModelAccessor.ModelUpdater, "Detail");
return View(model);
}
}
internal static class ValidationHelpers
{
public static string GetModelErrorMessageOrDefault(ModelError modelError)
{
Debug.Assert(modelError != null);
if (!string.IsNullOrEmpty(modelError.ErrorMessage))
{
return modelError.ErrorMessage;
}
// Default in the ValidationSummary case is no error message.
return string.Empty;
}
public static string GetModelErrorMessageOrDefault(
ModelError modelError,
ModelStateEntry containingEntry,
ModelExplorer modelExplorer)
{
Debug.Assert(modelError != null);
Debug.Assert(containingEntry != null);
Debug.Assert(modelExplorer != null);
if (!string.IsNullOrEmpty(modelError.ErrorMessage))
{
return modelError.ErrorMessage;
}
// Default in the ValidationMessage case is a fallback error message.
var attemptedValue = containingEntry.AttemptedValue ?? "null";
return modelExplorer.Metadata.ModelBindingMessageProvider.ValueIsInvalidAccessor(attemptedValue);
}
// Returns non-null list of model states, which caller will render in order provided.
public static IList<ModelStateEntry> GetModelStateList(
ViewDataDictionary viewData,
bool excludePropertyErrors)
{
if (excludePropertyErrors)
{
viewData.ModelState.TryGetValue(viewData.TemplateInfo.HtmlFieldPrefix, out var ms);
if (ms != null)
{
return new[] { ms };
}
}
else if (viewData.ModelState.Count > 0)
{
var metadata = viewData.ModelMetadata;
var modelStateDictionary = viewData.ModelState;
var entries = new List<ModelStateEntry>();
Visit(modelStateDictionary.Root, metadata, entries);
if (entries.Count < modelStateDictionary.Count)
{
// Account for entries in the ModelStateDictionary that do not have corresponding ModelMetadata values.
foreach (var entry in modelStateDictionary)
{
if (!entries.Contains(entry.Value))
{
entries.Add(entry.Value);
}
}
}
return entries;
}
return Array.Empty<ModelStateEntry>();
}
private static void Visit(
ModelStateEntry modelStateEntry,
ModelMetadata metadata,
List<ModelStateEntry> orderedModelStateEntries)
{
if (metadata.ElementMetadata != null && modelStateEntry.Children != null)
{
foreach (var indexEntry in modelStateEntry.Children)
{
Visit(indexEntry, metadata.ElementMetadata, orderedModelStateEntries);
}
}
else
{
for (var i = 0; i < metadata.Properties.Count; i++)
{
var propertyMetadata = metadata.Properties[i];
var propertyModelStateEntry = modelStateEntry.GetModelStateForProperty(propertyMetadata.PropertyName);
if (propertyModelStateEntry != null)
{
Visit(propertyModelStateEntry, propertyMetadata, orderedModelStateEntries);
}
}
}
if (!modelStateEntry.IsContainerNode)
{
orderedModelStateEntries.Add(modelStateEntry);
}
}
}
}
| |
#region Header
// --------------------------------------------------------------------------
// Prism.EventAggregator
// ==========================================================================
//
// This library contains the event aggregator part of Microsoft Prism 5.
// Prism has been released by Microsoft as open source software, licensed
// under the Apache License, Version 2.0.
//
// ===========================================================================
//
// <copyright file="PubSubEventFixture.cs" company="Tethys">
// Copyright (c) Microsoft Corporation. All rights reserved.
// Copyright for modification by Thomas Graf.
// All rights reserved.
// Licensed under the Apache License, Version 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.
// </copyright>
//
// ---------------------------------------------------------------------------
#endregion
namespace TestPrism.EventAggregator
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Prism.EventAggregator;
[TestClass]
public class PubSubEventFixture
{
[TestMethod]
public void CanSubscribeAndRaiseEvent()
{
var pubSubEvent = new TestablePubSubEvent<string>();
bool published = false;
pubSubEvent.Subscribe(delegate { published = true; },
ThreadOption.PublisherThread, true, delegate { return true; });
pubSubEvent.Publish(null);
Assert.IsTrue(published);
}
[TestMethod]
public void CanSubscribeAndRaiseCustomEvent()
{
var customEvent = new TestablePubSubEvent<Payload>();
Payload payload = new Payload();
var action = new ActionHelper();
customEvent.Subscribe(action.Action);
customEvent.Publish(payload);
Assert.AreSame(action.ActionArg<Payload>(), payload);
}
[TestMethod]
public void CanHaveMultipleSubscribersAndRaiseCustomEvent()
{
var customEvent = new TestablePubSubEvent<Payload>();
Payload payload = new Payload();
var action1 = new ActionHelper();
var action2 = new ActionHelper();
customEvent.Subscribe(action1.Action);
customEvent.Subscribe(action2.Action);
customEvent.Publish(payload);
Assert.AreSame(action1.ActionArg<Payload>(), payload);
Assert.AreSame(action2.ActionArg<Payload>(), payload);
}
[TestMethod]
public void SubscribeTakesExecuteDelegateThreadOptionAndFilter()
{
TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>();
var action = new ActionHelper();
pubSubEvent.Subscribe(action.Action);
pubSubEvent.Publish("test");
Assert.AreEqual("test", action.ActionArg<string>());
}
[TestMethod]
public void FilterEnablesActionTarget()
{
TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>();
var goodFilter = new MockFilter { FilterReturnValue = true };
var actionGoodFilter = new ActionHelper();
var badFilter = new MockFilter { FilterReturnValue = false };
var actionBadFilter = new ActionHelper();
pubSubEvent.Subscribe(actionGoodFilter.Action, ThreadOption.PublisherThread,
true, goodFilter.FilterString);
pubSubEvent.Subscribe(actionBadFilter.Action, ThreadOption.PublisherThread,
true, badFilter.FilterString);
pubSubEvent.Publish("test");
Assert.IsTrue(actionGoodFilter.ActionCalled);
Assert.IsFalse(actionBadFilter.ActionCalled);
}
[TestMethod]
public void SubscribeDefaultsThreadOptionAndNoFilter()
{
var pubSubEvent = new TestablePubSubEvent<string>();
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
SynchronizationContext calledSyncContext = null;
var myAction = new ActionHelper
{
ActionToExecute =
() => calledSyncContext = SynchronizationContext.Current
};
pubSubEvent.Subscribe(myAction.Action);
pubSubEvent.Publish("test");
Assert.AreEqual(SynchronizationContext.Current, calledSyncContext);
}
[TestMethod]
public void ShouldUnsubscribeFromPublisherThread()
{
var pubSubEvent = new TestablePubSubEvent<string>();
var actionEvent = new ActionHelper();
pubSubEvent.Subscribe(
actionEvent.Action,
ThreadOption.PublisherThread);
Assert.IsTrue(pubSubEvent.Contains(actionEvent.Action));
pubSubEvent.Unsubscribe(actionEvent.Action);
Assert.IsFalse(pubSubEvent.Contains(actionEvent.Action));
}
[TestMethod]
public void UnsubscribeShouldNotFailWithNonSubscriber()
{
TestablePubSubEvent<string> pubSubEvent = new TestablePubSubEvent<string>();
Action<string> subscriber = delegate { };
pubSubEvent.Unsubscribe(subscriber);
}
[TestMethod]
public void ShouldUnsubscribeFromBackgroundThread()
{
var pubSubEvent = new TestablePubSubEvent<string>();
var actionEvent = new ActionHelper();
pubSubEvent.Subscribe(
actionEvent.Action,
ThreadOption.BackgroundThread);
Assert.IsTrue(pubSubEvent.Contains(actionEvent.Action));
pubSubEvent.Unsubscribe(actionEvent.Action);
Assert.IsFalse(pubSubEvent.Contains(actionEvent.Action));
}
[TestMethod]
public void ShouldUnsubscribeFromUIThread()
{
var pubSubEvent = new TestablePubSubEvent<string>();
pubSubEvent.SynchronizationContext = new SynchronizationContext();
var actionEvent = new ActionHelper();
pubSubEvent.Subscribe(
actionEvent.Action,
ThreadOption.UIThread);
Assert.IsTrue(pubSubEvent.Contains(actionEvent.Action));
pubSubEvent.Unsubscribe(actionEvent.Action);
Assert.IsFalse(pubSubEvent.Contains(actionEvent.Action));
}
[TestMethod]
public void ShouldUnsubscribeASingleDelegate()
{
var pubSubEvent = new TestablePubSubEvent<string>();
var callCount = 0;
var actionEvent = new ActionHelper
{
ActionToExecute = () => callCount++
};
pubSubEvent.Subscribe(actionEvent.Action);
pubSubEvent.Subscribe(actionEvent.Action);
pubSubEvent.Publish(null);
Assert.AreEqual(2, callCount);
callCount = 0;
pubSubEvent.Unsubscribe(actionEvent.Action);
pubSubEvent.Publish(null);
Assert.AreEqual(1, callCount);
}
[TestMethod]
public void ShouldNotExecuteOnGarbageCollectedDelegateReferenceWhenNotKeepAlive()
{
var pubSubEvent = new TestablePubSubEvent<string>();
var externalAction = new ExternalAction();
pubSubEvent.Subscribe(externalAction.ExecuteAction);
pubSubEvent.Publish("testPayload");
Assert.AreEqual("testPayload", externalAction.PassedValue);
var actionEventReference = new WeakReference(externalAction);
externalAction = null;
GC.Collect();
Assert.IsFalse(actionEventReference.IsAlive);
pubSubEvent.Publish("testPayload");
}
[TestMethod]
public void ShouldNotExecuteOnGarbageCollectedFilterReferenceWhenNotKeepAlive()
{
var pubSubEvent = new TestablePubSubEvent<string>();
var wasCalled = false;
var actionEvent = new ActionHelper
{
ActionToExecute = () => wasCalled = true
};
var filter = new ExternalFilter();
pubSubEvent.Subscribe(actionEvent.Action, ThreadOption.PublisherThread,
false, filter.AlwaysTrueFilter);
pubSubEvent.Publish("testPayload");
Assert.IsTrue(wasCalled);
wasCalled = false;
var filterReference = new WeakReference(filter);
filter = null;
GC.Collect();
Assert.IsFalse(filterReference.IsAlive);
pubSubEvent.Publish("testPayload");
Assert.IsFalse(wasCalled);
}
[TestMethod]
public void CanAddSubscriptionWhileEventIsFiring()
{
var pubSubEvent = new TestablePubSubEvent<string>();
var emptyAction = new ActionHelper();
var subscriptionAction = new ActionHelper
{
ActionToExecute = () => pubSubEvent.Subscribe(emptyAction.Action)
};
pubSubEvent.Subscribe(subscriptionAction.Action);
Assert.IsFalse(pubSubEvent.Contains(emptyAction.Action));
pubSubEvent.Publish(null);
Assert.IsTrue(pubSubEvent.Contains(emptyAction.Action));
}
[TestMethod]
public void InlineDelegateDeclarationsDoesNotGetCollectedIncorrectlyWithWeakReferences()
{
var pubSubEvent = new TestablePubSubEvent<string>();
var published = false;
pubSubEvent.Subscribe(delegate { published = true; },
ThreadOption.PublisherThread, false, delegate { return true; });
GC.Collect();
pubSubEvent.Publish(null);
Assert.IsTrue(published);
}
[TestMethod]
public void ShouldNotGarbageCollectDelegateReferenceWhenUsingKeepAlive()
{
var pubSubEvent = new TestablePubSubEvent<string>();
var externalAction = new ExternalAction();
pubSubEvent.Subscribe(externalAction.ExecuteAction, ThreadOption.PublisherThread, true);
var actionEventReference = new WeakReference(externalAction);
externalAction = null;
GC.Collect();
GC.Collect();
Assert.IsTrue(actionEventReference.IsAlive);
pubSubEvent.Publish("testPayload");
Assert.AreEqual("testPayload", ((ExternalAction)actionEventReference.Target).PassedValue);
}
[TestMethod]
public void RegisterReturnsTokenThatCanBeUsedToUnsubscribe()
{
var pubSubEvent = new TestablePubSubEvent<string>();
var emptyAction = new ActionHelper();
var token = pubSubEvent.Subscribe(emptyAction.Action);
pubSubEvent.Unsubscribe(token);
Assert.IsFalse(pubSubEvent.Contains(emptyAction.Action));
}
[TestMethod]
public void ContainsShouldSearchByToken()
{
var pubSubEvent = new TestablePubSubEvent<string>();
var emptyAction = new ActionHelper();
var token = pubSubEvent.Subscribe(emptyAction.Action);
Assert.IsTrue(pubSubEvent.Contains(token));
pubSubEvent.Unsubscribe(emptyAction.Action);
Assert.IsFalse(pubSubEvent.Contains(token));
}
[TestMethod]
public void SubscribeDefaultsToPublisherThread()
{
var pubSubEvent = new TestablePubSubEvent<string>();
Action<string> action = delegate { };
var token = pubSubEvent.Subscribe(action, true);
Assert.AreEqual(1, pubSubEvent.BaseSubscriptions.Count);
Assert.AreEqual(typeof(EventSubscription<string>),
pubSubEvent.BaseSubscriptions.ElementAt(0).GetType());
}
public class ExternalFilter
{
public bool AlwaysTrueFilter(string value)
{
return true;
}
}
public class ExternalAction
{
public string PassedValue;
public void ExecuteAction(string value)
{
this.PassedValue = value;
}
}
public class TestablePubSubEvent<TPayload> : PubSubEvent<TPayload>
{
public ICollection<IEventSubscription> BaseSubscriptions
{
get { return base.Subscriptions; }
}
}
public class Payload { }
}
public class ActionHelper
{
public bool ActionCalled;
public Action ActionToExecute = null;
private object actionArg;
public T ActionArg<T>()
{
return (T)this.actionArg;
}
public void Action(PubSubEventFixture.Payload arg)
{
this.Action((object)arg);
}
public void Action(string arg)
{
this.Action((object)arg);
}
public void Action(object arg)
{
this.actionArg = arg;
this.ActionCalled = true;
if (this.ActionToExecute != null)
{
this.ActionToExecute.Invoke();
}
}
}
public class MockFilter
{
public bool FilterReturnValue;
public bool FilterString(string arg)
{
return this.FilterReturnValue;
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using JetBrains.Annotations;
#if !SILVERLIGHT
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.Net.Mail;
using System.Text;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
/// <summary>
/// Sends log messages by email using SMTP protocol.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/Mail-target">Documentation on NLog Wiki</seealso>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/Mail/Simple/NLog.config" />
/// <p>
/// This assumes just one target and a single rule. More configuration
/// options are described <a href="config.html">here</a>.
/// </p>
/// <p>
/// To set up the log target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/Mail/Simple/Example.cs" />
/// <p>
/// Mail target works best when used with BufferingWrapper target
/// which lets you send multiple log messages in single mail
/// </p>
/// <p>
/// To set up the buffered mail target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/Mail/Buffered/NLog.config" />
/// <p>
/// To set up the buffered mail target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/Mail/Buffered/Example.cs" />
/// </example>
[Target("Mail")]
public class MailTarget : TargetWithLayoutHeaderAndFooter
{
private const string RequiredPropertyIsEmptyFormat = "After the processing of the MailTarget's '{0}' property it appears to be empty. The email message will not be sent.";
/// <summary>
/// Initializes a new instance of the <see cref="MailTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "This one is safe.")]
public MailTarget()
{
this.Body = "${message}${newline}";
this.Subject = "Message from NLog on ${machinename}";
this.Encoding = Encoding.UTF8;
this.SmtpPort = 25;
this.SmtpAuthentication = SmtpAuthenticationMode.None;
this.Timeout = 10000;
}
/// <summary>
/// Gets or sets sender's email address (e.g. joe@domain.com).
/// </summary>
/// <docgen category='Message Options' order='10' />
[RequiredParameter]
public Layout From { get; set; }
/// <summary>
/// Gets or sets recipients' email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com).
/// </summary>
/// <docgen category='Message Options' order='11' />
[RequiredParameter]
public Layout To { get; set; }
/// <summary>
/// Gets or sets CC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com).
/// </summary>
/// <docgen category='Message Options' order='12' />
public Layout CC { get; set; }
/// <summary>
/// Gets or sets BCC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com).
/// </summary>
/// <docgen category='Message Options' order='13' />
public Layout Bcc { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to add new lines between log entries.
/// </summary>
/// <value>A value of <c>true</c> if new lines should be added; otherwise, <c>false</c>.</value>
/// <docgen category='Layout Options' order='99' />
public bool AddNewLines { get; set; }
/// <summary>
/// Gets or sets the mail subject.
/// </summary>
/// <docgen category='Message Options' order='5' />
[DefaultValue("Message from NLog on ${machinename}")]
[RequiredParameter]
public Layout Subject { get; set; }
/// <summary>
/// Gets or sets mail message body (repeated for each log message send in one mail).
/// </summary>
/// <remarks>Alias for the <c>Layout</c> property.</remarks>
/// <docgen category='Message Options' order='6' />
[DefaultValue("${message}${newline}")]
public Layout Body
{
get { return this.Layout; }
set { this.Layout = value; }
}
/// <summary>
/// Gets or sets encoding to be used for sending e-mail.
/// </summary>
/// <docgen category='Layout Options' order='20' />
[DefaultValue("UTF8")]
public Encoding Encoding { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to send message as HTML instead of plain text.
/// </summary>
/// <docgen category='Layout Options' order='11' />
[DefaultValue(false)]
public bool Html { get; set; }
/// <summary>
/// Gets or sets SMTP Server to be used for sending.
/// </summary>
/// <docgen category='SMTP Options' order='10' />
[RequiredParameter]
public Layout SmtpServer { get; set; }
/// <summary>
/// Gets or sets SMTP Authentication mode.
/// </summary>
/// <docgen category='SMTP Options' order='11' />
[DefaultValue("None")]
public SmtpAuthenticationMode SmtpAuthentication { get; set; }
/// <summary>
/// Gets or sets the username used to connect to SMTP server (used when SmtpAuthentication is set to "basic").
/// </summary>
/// <docgen category='SMTP Options' order='12' />
public Layout SmtpUserName { get; set; }
/// <summary>
/// Gets or sets the password used to authenticate against SMTP server (used when SmtpAuthentication is set to "basic").
/// </summary>
/// <docgen category='SMTP Options' order='13' />
public Layout SmtpPassword { get; set; }
/// <summary>
/// Gets or sets a value indicating whether SSL (secure sockets layer) should be used when communicating with SMTP server.
/// </summary>
/// <docgen category='SMTP Options' order='14' />
[DefaultValue(false)]
public bool EnableSsl { get; set; }
/// <summary>
/// Gets or sets the port number that SMTP Server is listening on.
/// </summary>
/// <docgen category='SMTP Options' order='15' />
[DefaultValue(25)]
public int SmtpPort { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the default Settings from System.Net.MailSettings should be used.
/// </summary>
/// <docgen category='SMTP Options' order='16' />
[DefaultValue(false)]
public bool UseSystemNetMailSettings { get; set; }
/// <summary>
/// Gets or sets the priority used for sending mails.
/// </summary>
public Layout Priority { get; set; }
/// <summary>
/// Gets or sets a value indicating whether NewLine characters in the body should be replaced with <br/> tags.
/// </summary>
/// <remarks>Only happens when <see cref="Html"/> is set to true.</remarks>
[DefaultValue(false)]
public bool ReplaceNewlineWithBrTagInHtml { get; set; }
/// <summary>
/// Gets or sets a value indicating the SMTP client timeout.
/// </summary>
/// <remarks>Warning: zero is not infinit waiting</remarks>
[DefaultValue(10000)]
public int Timeout { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "This is a factory method.")]
internal virtual ISmtpClient CreateSmtpClient()
{
return new MySmtpClient();
}
/// <summary>
/// Renders the logging event message and adds it to the internal ArrayList of log messages.
/// </summary>
/// <param name="logEvent">The logging event.</param>
protected override void Write(AsyncLogEventInfo logEvent)
{
this.Write(new[] { logEvent });
}
/// <summary>
/// Renders an array logging events.
/// </summary>
/// <param name="logEvents">Array of logging events.</param>
protected override void Write(AsyncLogEventInfo[] logEvents)
{
foreach (var bucket in logEvents.BucketSort(c => this.GetSmtpSettingsKey(c.LogEvent)))
{
var eventInfos = bucket.Value;
this.ProcessSingleMailMessage(eventInfos);
}
}
/// <summary>
/// Create mail and send with SMTP
/// </summary>
/// <param name="events">event printed in the body of the event</param>
private void ProcessSingleMailMessage([NotNull] List<AsyncLogEventInfo> events)
{
try
{
if (events.Count == 0)
{
throw new NLogRuntimeException("We need at least one event.");
}
LogEventInfo firstEvent = events[0].LogEvent;
LogEventInfo lastEvent = events[events.Count - 1].LogEvent;
// unbuffered case, create a local buffer, append header, body and footer
var bodyBuffer = CreateBodyBuffer(events, firstEvent, lastEvent);
using (var msg = CreateMailMessage(lastEvent, bodyBuffer.ToString()))
{
using (ISmtpClient client = this.CreateSmtpClient())
{
if (!UseSystemNetMailSettings)
ConfigureMailClient(lastEvent, client);
InternalLogger.Debug("Sending mail to {0} using {1}:{2} (ssl={3})", msg.To, client.Host, client.Port, client.EnableSsl);
InternalLogger.Trace(" Subject: '{0}'", msg.Subject);
InternalLogger.Trace(" From: '{0}'", msg.From.ToString());
client.Send(msg);
foreach (var ev in events)
{
ev.Continuation(null);
}
}
}
}
catch (Exception exception)
{
//always log
InternalLogger.Error(exception.ToString());
if (exception.MustBeRethrown())
{
throw;
}
foreach (var ev in events)
{
ev.Continuation(exception);
}
}
}
/// <summary>
/// Create buffer for body
/// </summary>
/// <param name="events">all events</param>
/// <param name="firstEvent">first event for header</param>
/// <param name="lastEvent">last event for footer</param>
/// <returns></returns>
private StringBuilder CreateBodyBuffer(IEnumerable<AsyncLogEventInfo> events, LogEventInfo firstEvent, LogEventInfo lastEvent)
{
var bodyBuffer = new StringBuilder();
if (this.Header != null)
{
bodyBuffer.Append(this.Header.Render(firstEvent));
if (this.AddNewLines)
{
bodyBuffer.Append("\n");
}
}
foreach (AsyncLogEventInfo eventInfo in events)
{
bodyBuffer.Append(this.Layout.Render(eventInfo.LogEvent));
if (this.AddNewLines)
{
bodyBuffer.Append("\n");
}
}
if (this.Footer != null)
{
bodyBuffer.Append(this.Footer.Render(lastEvent));
if (this.AddNewLines)
{
bodyBuffer.Append("\n");
}
}
return bodyBuffer;
}
/// <summary>
/// Set propertes of <paramref name="client"/>
/// </summary>
/// <param name="lastEvent">last event for username/password</param>
/// <param name="client">client to set properties on</param>
private void ConfigureMailClient(LogEventInfo lastEvent, ISmtpClient client)
{
var renderedSmtpServer = this.SmtpServer.Render(lastEvent);
if (string.IsNullOrEmpty(renderedSmtpServer))
{
throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer"));
}
client.Host = renderedSmtpServer;
client.Port = this.SmtpPort;
client.EnableSsl = this.EnableSsl;
client.Timeout = this.Timeout;
if (this.SmtpAuthentication == SmtpAuthenticationMode.Ntlm)
{
InternalLogger.Trace(" Using NTLM authentication.");
client.Credentials = CredentialCache.DefaultNetworkCredentials;
}
else if (this.SmtpAuthentication == SmtpAuthenticationMode.Basic)
{
string username = this.SmtpUserName.Render(lastEvent);
string password = this.SmtpPassword.Render(lastEvent);
InternalLogger.Trace(" Using basic authentication: Username='{0}' Password='{1}'", username, new string('*', password.Length));
client.Credentials = new NetworkCredential(username, password);
}
}
/// <summary>
/// Create key for grouping. Needed for multiple events in one mailmessage
/// </summary>
/// <param name="logEvent">event for rendering layouts </param>
///<returns>string to group on</returns>
private string GetSmtpSettingsKey(LogEventInfo logEvent)
{
var sb = new StringBuilder();
AppendLayout(sb, logEvent, this.From);
AppendLayout(sb, logEvent, this.To);
AppendLayout(sb, logEvent, this.CC);
AppendLayout(sb, logEvent, this.Bcc);
AppendLayout(sb, logEvent, this.SmtpServer);
AppendLayout(sb, logEvent, this.SmtpPassword);
AppendLayout(sb, logEvent, this.SmtpUserName);
return sb.ToString();
}
/// <summary>
/// Append rendered layout to the stringbuilder
/// </summary>
/// <param name="sb">append to this</param>
/// <param name="logEvent">event for rendering <paramref name="layout"/></param>
/// <param name="layout">append if not <c>null</c></param>
private static void AppendLayout(StringBuilder sb, LogEventInfo logEvent, Layout layout)
{
sb.Append("|");
if (layout != null)
sb.Append(layout.Render(logEvent));
}
/// <summary>
/// Create the mailmessage with the addresses, properties and body.
/// </summary>
private MailMessage CreateMailMessage(LogEventInfo lastEvent, string body)
{
var msg = new MailMessage();
var renderedFrom = this.From == null ? null : this.From.Render(lastEvent);
if (string.IsNullOrEmpty(renderedFrom))
{
throw new NLogRuntimeException(RequiredPropertyIsEmptyFormat, "From");
}
msg.From = new MailAddress(renderedFrom);
var addedTo = AddAddresses(msg.To, this.To, lastEvent);
var addedCc = AddAddresses(msg.CC, this.CC, lastEvent);
var addedBcc = AddAddresses(msg.Bcc, this.Bcc, lastEvent);
if (!addedTo && !addedCc && !addedBcc)
{
throw new NLogRuntimeException(RequiredPropertyIsEmptyFormat, "To/Cc/Bcc");
}
msg.Subject = this.Subject == null ? string.Empty : this.Subject.Render(lastEvent).Trim();
msg.BodyEncoding = this.Encoding;
msg.IsBodyHtml = this.Html;
if (this.Priority != null)
{
var renderedPriority = this.Priority.Render(lastEvent);
try
{
msg.Priority = (MailPriority)Enum.Parse(typeof(MailPriority), renderedPriority, true);
}
catch
{
InternalLogger.Warn("Could not convert '{0}' to MailPriority, valid values are Low, Normal and High. Using normal priority as fallback.");
msg.Priority = MailPriority.Normal;
}
}
msg.Body = body;
if (msg.IsBodyHtml && ReplaceNewlineWithBrTagInHtml && msg.Body != null)
msg.Body = msg.Body.Replace(EnvironmentHelper.NewLine, "<br/>");
return msg;
}
/// <summary>
/// Render <paramref name="layout"/> and add the addresses to <paramref name="mailAddressCollection"/>
/// </summary>
/// <param name="mailAddressCollection">Addresses appended to this list</param>
/// <param name="layout">layout with addresses, ; separated</param>
/// <param name="logEvent">event for rendering the <paramref name="layout"/></param>
/// <returns>added a address?</returns>
private static bool AddAddresses(MailAddressCollection mailAddressCollection, Layout layout, LogEventInfo logEvent)
{
var added = false;
if (layout != null)
{
foreach (string mail in layout.Render(logEvent).Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
mailAddressCollection.Add(mail);
added = true;
}
}
return added;
}
}
}
#endif
| |
using System;
using System.Collections;
using System.IO;
using NUnit.Framework;
using Org.BouncyCastle.Asn1.Utilities;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.Test;
namespace Org.BouncyCastle.Asn1.Tests
{
[TestFixture]
public class CertificateTest
: SimpleTest
{
//
// server.crt
//
private static readonly byte[] cert1 = Base64.Decode(
"MIIDXjCCAsegAwIBAgIBBzANBgkqhkiG9w0BAQQFADCBtzELMAkGA1UEBhMCQVUx"
+ "ETAPBgNVBAgTCFZpY3RvcmlhMRgwFgYDVQQHEw9Tb3V0aCBNZWxib3VybmUxGjAY"
+ "BgNVBAoTEUNvbm5lY3QgNCBQdHkgTHRkMR4wHAYDVQQLExVDZXJ0aWZpY2F0ZSBB"
+ "dXRob3JpdHkxFTATBgNVBAMTDENvbm5lY3QgNCBDQTEoMCYGCSqGSIb3DQEJARYZ"
+ "d2VibWFzdGVyQGNvbm5lY3Q0LmNvbS5hdTAeFw0wMDA2MDIwNzU2MjFaFw0wMTA2"
+ "MDIwNzU2MjFaMIG4MQswCQYDVQQGEwJBVTERMA8GA1UECBMIVmljdG9yaWExGDAW"
+ "BgNVBAcTD1NvdXRoIE1lbGJvdXJuZTEaMBgGA1UEChMRQ29ubmVjdCA0IFB0eSBM"
+ "dGQxFzAVBgNVBAsTDldlYnNlcnZlciBUZWFtMR0wGwYDVQQDExR3d3cyLmNvbm5l"
+ "Y3Q0LmNvbS5hdTEoMCYGCSqGSIb3DQEJARYZd2VibWFzdGVyQGNvbm5lY3Q0LmNv"
+ "bS5hdTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEArvDxclKAhyv7Q/Wmr2re"
+ "Gw4XL9Cnh9e+6VgWy2AWNy/MVeXdlxzd7QAuc1eOWQkGQEiLPy5XQtTY+sBUJ3AO"
+ "Rvd2fEVJIcjf29ey7bYua9J/vz5MG2KYo9/WCHIwqD9mmG9g0xLcfwq/s8ZJBswE"
+ "7sb85VU+h94PTvsWOsWuKaECAwEAAaN3MHUwJAYDVR0RBB0wG4EZd2VibWFzdGVy"
+ "QGNvbm5lY3Q0LmNvbS5hdTA6BglghkgBhvhCAQ0ELRYrbW9kX3NzbCBnZW5lcmF0"
+ "ZWQgY3VzdG9tIHNlcnZlciBjZXJ0aWZpY2F0ZTARBglghkgBhvhCAQEEBAMCBkAw"
+ "DQYJKoZIhvcNAQEEBQADgYEAotccfKpwSsIxM1Hae8DR7M/Rw8dg/RqOWx45HNVL"
+ "iBS4/3N/TO195yeQKbfmzbAA2jbPVvIvGgTxPgO1MP4ZgvgRhasaa0qCJCkWvpM4"
+ "yQf33vOiYQbpv4rTwzU8AmRlBG45WdjyNIigGV+oRc61aKCTnLq7zB8N3z1TF/bF"
+ "5/8=");
//
// ca.crt
//
private static readonly byte[] cert2 = Base64.Decode(
"MIIDbDCCAtWgAwIBAgIBADANBgkqhkiG9w0BAQQFADCBtzELMAkGA1UEBhMCQVUx"
+ "ETAPBgNVBAgTCFZpY3RvcmlhMRgwFgYDVQQHEw9Tb3V0aCBNZWxib3VybmUxGjAY"
+ "BgNVBAoTEUNvbm5lY3QgNCBQdHkgTHRkMR4wHAYDVQQLExVDZXJ0aWZpY2F0ZSBB"
+ "dXRob3JpdHkxFTATBgNVBAMTDENvbm5lY3QgNCBDQTEoMCYGCSqGSIb3DQEJARYZ"
+ "d2VibWFzdGVyQGNvbm5lY3Q0LmNvbS5hdTAeFw0wMDA2MDIwNzU1MzNaFw0wMTA2"
+ "MDIwNzU1MzNaMIG3MQswCQYDVQQGEwJBVTERMA8GA1UECBMIVmljdG9yaWExGDAW"
+ "BgNVBAcTD1NvdXRoIE1lbGJvdXJuZTEaMBgGA1UEChMRQ29ubmVjdCA0IFB0eSBM"
+ "dGQxHjAcBgNVBAsTFUNlcnRpZmljYXRlIEF1dGhvcml0eTEVMBMGA1UEAxMMQ29u"
+ "bmVjdCA0IENBMSgwJgYJKoZIhvcNAQkBFhl3ZWJtYXN0ZXJAY29ubmVjdDQuY29t"
+ "LmF1MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDgs5ptNG6Qv1ZpCDuUNGmv"
+ "rhjqMDPd3ri8JzZNRiiFlBA4e6/ReaO1U8ASewDeQMH6i9R6degFdQRLngbuJP0s"
+ "xcEE+SksEWNvygfzLwV9J/q+TQDyJYK52utb++lS0b48A1KPLwEsyL6kOAgelbur"
+ "ukwxowprKUIV7Knf1ajetQIDAQABo4GFMIGCMCQGA1UdEQQdMBuBGXdlYm1hc3Rl"
+ "ckBjb25uZWN0NC5jb20uYXUwDwYDVR0TBAgwBgEB/wIBADA2BglghkgBhvhCAQ0E"
+ "KRYnbW9kX3NzbCBnZW5lcmF0ZWQgY3VzdG9tIENBIGNlcnRpZmljYXRlMBEGCWCG"
+ "SAGG+EIBAQQEAwICBDANBgkqhkiG9w0BAQQFAAOBgQCsGvfdghH8pPhlwm1r3pQk"
+ "msnLAVIBb01EhbXm2861iXZfWqGQjrGAaA0ZpXNk9oo110yxoqEoSJSzniZa7Xtz"
+ "soTwNUpE0SLHvWf/SlKdFWlzXA+vOZbzEv4UmjeelekTm7lc01EEa5QRVzOxHFtQ"
+ "DhkaJ8VqOMajkQFma2r9iA==");
//
// testx509.pem
//
private static readonly byte[] cert3 = Base64.Decode(
"MIIBWzCCAQYCARgwDQYJKoZIhvcNAQEEBQAwODELMAkGA1UEBhMCQVUxDDAKBgNV"
+ "BAgTA1FMRDEbMBkGA1UEAxMSU1NMZWF5L3JzYSB0ZXN0IENBMB4XDTk1MDYxOTIz"
+ "MzMxMloXDTk1MDcxNzIzMzMxMlowOjELMAkGA1UEBhMCQVUxDDAKBgNVBAgTA1FM"
+ "RDEdMBsGA1UEAxMUU1NMZWF5L3JzYSB0ZXN0IGNlcnQwXDANBgkqhkiG9w0BAQEF"
+ "AANLADBIAkEAqtt6qS5GTxVxGZYWa0/4u+IwHf7p2LNZbcPBp9/OfIcYAXBQn8hO"
+ "/Re1uwLKXdCjIoaGs4DLdG88rkzfyK5dPQIDAQABMAwGCCqGSIb3DQIFBQADQQAE"
+ "Wc7EcF8po2/ZO6kNCwK/ICH6DobgLekA5lSLr5EvuioZniZp5lFzAw4+YzPQ7XKJ"
+ "zl9HYIMxATFyqSiD9jsx");
//
// v3-cert1.pem
//
private static readonly byte[] cert4 = Base64.Decode(
"MIICjTCCAfigAwIBAgIEMaYgRzALBgkqhkiG9w0BAQQwRTELMAkGA1UEBhMCVVMx"
+ "NjA0BgNVBAoTLU5hdGlvbmFsIEFlcm9uYXV0aWNzIGFuZCBTcGFjZSBBZG1pbmlz"
+ "dHJhdGlvbjAmFxE5NjA1MjgxMzQ5MDUrMDgwMBcROTgwNTI4MTM0OTA1KzA4MDAw"
+ "ZzELMAkGA1UEBhMCVVMxNjA0BgNVBAoTLU5hdGlvbmFsIEFlcm9uYXV0aWNzIGFu"
+ "ZCBTcGFjZSBBZG1pbmlzdHJhdGlvbjEgMAkGA1UEBRMCMTYwEwYDVQQDEwxTdGV2"
+ "ZSBTY2hvY2gwWDALBgkqhkiG9w0BAQEDSQAwRgJBALrAwyYdgxmzNP/ts0Uyf6Bp"
+ "miJYktU/w4NG67ULaN4B5CnEz7k57s9o3YY3LecETgQ5iQHmkwlYDTL2fTgVfw0C"
+ "AQOjgaswgagwZAYDVR0ZAQH/BFowWDBWMFQxCzAJBgNVBAYTAlVTMTYwNAYDVQQK"
+ "Ey1OYXRpb25hbCBBZXJvbmF1dGljcyBhbmQgU3BhY2UgQWRtaW5pc3RyYXRpb24x"
+ "DTALBgNVBAMTBENSTDEwFwYDVR0BAQH/BA0wC4AJODMyOTcwODEwMBgGA1UdAgQR"
+ "MA8ECTgzMjk3MDgyM4ACBSAwDQYDVR0KBAYwBAMCBkAwCwYJKoZIhvcNAQEEA4GB"
+ "AH2y1VCEw/A4zaXzSYZJTTUi3uawbbFiS2yxHvgf28+8Js0OHXk1H1w2d6qOHH21"
+ "X82tZXd/0JtG0g1T9usFFBDvYK8O0ebgz/P5ELJnBL2+atObEuJy1ZZ0pBDWINR3"
+ "WkDNLCGiTkCKp0F5EWIrVDwh54NNevkCQRZita+z4IBO");
//
// v3-cert2.pem
//
private static readonly byte[] cert5 = Base64.Decode(
"MIICiTCCAfKgAwIBAgIEMeZfHzANBgkqhkiG9w0BAQQFADB9MQswCQYDVQQGEwJD"
+ "YTEPMA0GA1UEBxMGTmVwZWFuMR4wHAYDVQQLExVObyBMaWFiaWxpdHkgQWNjZXB0"
+ "ZWQxHzAdBgNVBAoTFkZvciBEZW1vIFB1cnBvc2VzIE9ubHkxHDAaBgNVBAMTE0Vu"
+ "dHJ1c3QgRGVtbyBXZWIgQ0EwHhcNOTYwNzEyMTQyMDE1WhcNOTYxMDEyMTQyMDE1"
+ "WjB0MSQwIgYJKoZIhvcNAQkBExVjb29rZUBpc3NsLmF0bC5ocC5jb20xCzAJBgNV"
+ "BAYTAlVTMScwJQYDVQQLEx5IZXdsZXR0IFBhY2thcmQgQ29tcGFueSAoSVNTTCkx"
+ "FjAUBgNVBAMTDVBhdWwgQS4gQ29va2UwXDANBgkqhkiG9w0BAQEFAANLADBIAkEA"
+ "6ceSq9a9AU6g+zBwaL/yVmW1/9EE8s5you1mgjHnj0wAILuoB3L6rm6jmFRy7QZT"
+ "G43IhVZdDua4e+5/n1ZslwIDAQABo2MwYTARBglghkgBhvhCAQEEBAMCB4AwTAYJ"
+ "YIZIAYb4QgENBD8WPVRoaXMgY2VydGlmaWNhdGUgaXMgb25seSBpbnRlbmRlZCBm"
+ "b3IgZGVtb25zdHJhdGlvbiBwdXJwb3Nlcy4wDQYJKoZIhvcNAQEEBQADgYEAi8qc"
+ "F3zfFqy1sV8NhjwLVwOKuSfhR/Z8mbIEUeSTlnH3QbYt3HWZQ+vXI8mvtZoBc2Fz"
+ "lexKeIkAZXCesqGbs6z6nCt16P6tmdfbZF3I3AWzLquPcOXjPf4HgstkyvVBn0Ap"
+ "jAFN418KF/Cx4qyHB4cjdvLrRjjQLnb2+ibo7QU=");
private static readonly byte[] cert6 = Base64.Decode(
"MIIEDjCCAvagAwIBAgIEFAAq2jANBgkqhkiG9w0BAQUFADBLMSowKAYDVQQDEyFT"
+ "dW4gTWljcm9zeXN0ZW1zIEluYyBDQSAoQ2xhc3MgQikxHTAbBgNVBAoTFFN1biBN"
+ "aWNyb3N5c3RlbXMgSW5jMB4XDTA0MDIyOTAwNDMzNFoXDTA5MDMwMTAwNDMzNFow"
+ "NzEdMBsGA1UEChMUU3VuIE1pY3Jvc3lzdGVtcyBJbmMxFjAUBgNVBAMTDXN0b3Jl"
+ "LnN1bi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAP9ErzFT7MPg2bVV"
+ "LNmHTgN4kmiRNlPpuLGWS7EDIXYBbLeSSOCp/e1ANcOGnsuf0WIq9ejd/CPyEfh4"
+ "sWoVvQzpOfHZ/Jyei29PEuxzWT+4kQmCx3+sLK25lAnDFsz1KiFmB6Y3GJ/JSjpp"
+ "L0Yy1R9YlIc82I8gSw44y5JDABW5AgMBAAGjggGQMIIBjDAOBgNVHQ8BAf8EBAMC"
+ "BaAwHQYDVR0OBBYEFG1WB3PApZM7OPPVWJ31UrERaoKWMEcGA1UdIARAMD4wPAYL"
+ "YIZIAYb3AIN9k18wLTArBggrBgEFBQcCARYfaHR0cDovL3d3dy5zdW4uY29tL3Br"
+ "aS9jcHMuaHRtbDCBhQYDVR0fBH4wfDB6oCegJYYjaHR0cDovL3d3dy5zdW4uY29t"
+ "L3BraS9wa2lzbWljYS5jcmyiT6RNMEsxKjAoBgNVBAMTIVN1biBNaWNyb3N5c3Rl"
+ "bXMgSW5jIENBIChDbGFzcyBCKTEdMBsGA1UEChMUU3VuIE1pY3Jvc3lzdGVtcyBJ"
+ "bmMwHwYDVR0jBBgwFoAUT7ZnqR/EEBSgG6h1wdYMI5RiiWswVAYIKwYBBQUHAQEE"
+ "SDBGMB0GCCsGAQUFBzABhhFodHRwOi8vdmEuc3VuLmNvbTAlBggrBgEFBQcwAYYZ"
+ "aHR0cDovL3ZhLmNlbnRyYWwuc3VuLmNvbTATBgNVHSUEDDAKBggrBgEFBQcDATAN"
+ "BgkqhkiG9w0BAQUFAAOCAQEAq3byQgyU24tBpR07iQK7agm1zQyzDQ6itdbji0ln"
+ "T7fOd5Pnp99iig8ovwWliNtXKAmgtJY60jWz7nEuk38AioZJhS+RPWIWX/+2PRV7"
+ "s2aWTzM3n43BypD+jU2qF9c9kDWP/NW9K9IcrS7SfU/2MZVmiCMD/9FEL+CWndwE"
+ "JJQ/oenXm44BFISI/NjV7fMckN8EayPvgtzQkD5KnEiggOD6HOrwTDFR+tmAEJ0K"
+ "ZttQNwOzCOcEdxXTg6qBHUbONdL7bjTT5NzV+JR/bnfiCqHzdnGwfbHzhmrnXw8j"
+ "QCVXcfBfL9++nmpNNRlnJMRdYGeCY6OAfh/PRo8/fXak1Q==");
private static readonly byte[] cert7 = Base64.Decode(
"MIIFJDCCBAygAwIBAgIKEcJZuwAAAAAABzANBgkqhkiG9w0BAQUFADAPMQ0wCwYD"
+ "VQQDEwRNU0NBMB4XDTA0MDUyMjE2MTM1OFoXDTA1MDUyMjE2MjM1OFowaTEbMBkG"
+ "CSqGSIb3DQEJCBMMMTkyLjE2OC4xLjMzMScwJQYJKoZIhvcNAQkCExhwaXhmaXJl"
+ "d2FsbC5jaXNjb3BpeC5jb20xITAfBgNVBAMTGHBpeGZpcmV3YWxsLmNpc2NvcGl4"
+ "LmNvbTB8MA0GCSqGSIb3DQEBAQUAA2sAMGgCYQCbcsY7vrjweXZiFQdhUafEjJV+"
+ "HRy5UKmuCy0237ffmYrN+XNLw0h90cdCSK6KPZebd2E2Bc2UmTikc/FY8meBT3/E"
+ "O/Osmywzi++Ur8/IrDvtuR1zd0c/xEPnV1ZRezkCAwEAAaOCAs4wggLKMAsGA1Ud"
+ "DwQEAwIFoDAdBgNVHQ4EFgQUzJBSxkQiN9TKvhTMQ1/Aq4gZnHswHwYDVR0jBBgw"
+ "FoAUMsxzXVh+5UKMNpwNHmqSfcRYfJ4wgfcGA1UdHwSB7zCB7DCB6aCB5qCB44aB"
+ "r2xkYXA6Ly8vQ049TVNDQSxDTj1NQVVELENOPUNEUCxDTj1QdWJsaWMlMjBLZXkl"
+ "MjBTZXJ2aWNlcyxDTj1TZXJ2aWNlcyxDTj1Db25maWd1cmF0aW9uLERDPWludCxE"
+ "Qz1wcmltZWtleSxEQz1zZT9jZXJ0aWZpY2F0ZVJldm9jYXRpb25MaXN0P2Jhc2U/"
+ "b2JqZWN0Q2xhc3M9Y1JMRGlzdHJpYnV0aW9uUG9pbnSGL2h0dHA6Ly9tYXVkLmlu"
+ "dC5wcmltZWtleS5zZS9DZXJ0RW5yb2xsL01TQ0EuY3JsMIIBEAYIKwYBBQUHAQEE"
+ "ggECMIH/MIGqBggrBgEFBQcwAoaBnWxkYXA6Ly8vQ049TVNDQSxDTj1BSUEsQ049"
+ "UHVibGljJTIwS2V5JTIwU2VydmljZXMsQ049U2VydmljZXMsQ049Q29uZmlndXJh"
+ "dGlvbixEQz1pbnQsREM9cHJpbWVrZXksREM9c2U/Y0FDZXJ0aWZpY2F0ZT9iYXNl"
+ "P29iamVjdENsYXNzPWNlcnRpZmljYXRpb25BdXRob3JpdHkwUAYIKwYBBQUHMAKG"
+ "RGh0dHA6Ly9tYXVkLmludC5wcmltZWtleS5zZS9DZXJ0RW5yb2xsL01BVUQuaW50"
+ "LnByaW1la2V5LnNlX01TQ0EuY3J0MCwGA1UdEQEB/wQiMCCCGHBpeGZpcmV3YWxs"
+ "LmNpc2NvcGl4LmNvbYcEwKgBITA/BgkrBgEEAYI3FAIEMh4wAEkAUABTAEUAQwBJ"
+ "AG4AdABlAHIAbQBlAGQAaQBhAHQAZQBPAGYAZgBsAGkAbgBlMA0GCSqGSIb3DQEB"
+ "BQUAA4IBAQCa0asiPbObLJjpSz6ndJ7y4KOWMiuuBc/VQBnLr7RBCF3ZlZ6z1+e6"
+ "dmv8se/z11NgateKfxw69IhLCriA960HEgX9Z61MiVG+DrCFpbQyp8+hPFHoqCZN"
+ "b7upc8k2OtJW6KPaP9k0DW52YQDIky4Vb2rZeC4AMCorWN+KlndHhr1HFA14HxwA"
+ "4Mka0FM6HNWnBV2UmTjBZMDr/OrGH1jLYIceAaZK0X2R+/DWXeeqIga8jwP5empq"
+ "JetYnkXdtTbEh3xL0BX+mZl8vDI+/PGcwox/7YjFmyFWphRMxk9CZ3rF2/FQWMJP"
+ "YqQpKiQOmQg5NAhcwffLAuVjVVibPYqi");
private static readonly byte[] cert8 = Base64.Decode(
"MIIB0zCCATwCAQEwbqBsMGekZTBjMQswCQYDVQQGEwJERTELMAkGA1UECBMCQlkx"
+ "EzARBgNVBAcTClJlZ2Vuc2J1cmcxEDAOBgNVBAoTB0FDIFRlc3QxCzAJBgNVBAsT"
+ "AkNBMRMwEQYDVQQDEwpBQyBUZXN0IENBAgEBoHYwdKRyMHAxCzAJBgNVBAYTAkRF"
+ "MQswCQYDVQQIEwJCWTETMBEGA1UEBxMKUmVnZW5zYnVyZzESMBAGA1UEChMJQUMg"
+ "SXNzdWVyMRowGAYDVQQLExFBQyBJc3N1ZXIgc2VjdGlvbjEPMA0GA1UEAxMGQUMg"
+ "TWFuMA0GCSqGSIb3DQEBBQUAAgEBMCIYDzIwMDQxMTI2MTI1MjUxWhgPMjAwNDEy"
+ "MzEyMzAwMDBaMBkwFwYDVRhIMRAwDoEMREFVMTIzNDU2Nzg5MA0GCSqGSIb3DQEB"
+ "BQUAA4GBABd4Odx3yEMGL/BvItuT1RafNR2uuWuZbajg0pD6bshUsl+WCIfRiEkq"
+ "lHMkpI7WqAZikdnAEQ5jQsVWEuVejWxR6gjejKxc0fb9qpIui7/GoI5Eh6dmG20e"
+ "xbwJL3+6YYFrZwxR8cC5rPvWrblUR5XKJy+Zp/H5+t9iANnL1L8J");
private static readonly string[] subjects =
{
"C=AU,ST=Victoria,L=South Melbourne,O=Connect 4 Pty Ltd,OU=Webserver Team,CN=www2.connect4.com.au,E=webmaster@connect4.com.au",
"C=AU,ST=Victoria,L=South Melbourne,O=Connect 4 Pty Ltd,OU=Certificate Authority,CN=Connect 4 CA,E=webmaster@connect4.com.au",
"C=AU,ST=QLD,CN=SSLeay/rsa test cert",
"C=US,O=National Aeronautics and Space Administration,SERIALNUMBER=16+CN=Steve Schoch",
"E=cooke@issl.atl.hp.com,C=US,OU=Hewlett Packard Company (ISSL),CN=Paul A. Cooke",
"O=Sun Microsystems Inc,CN=store.sun.com",
"unstructuredAddress=192.168.1.33,unstructuredName=pixfirewall.ciscopix.com,CN=pixfirewall.ciscopix.com"
};
public override string Name
{
get { return "Certificate"; }
}
public void CheckCertificate(
int id,
byte[] cert)
{
Asn1Object seq = Asn1Object.FromByteArray(cert);
string dump = Asn1Dump.DumpAsString(seq);
X509CertificateStructure obj = X509CertificateStructure.GetInstance(seq);
TbsCertificateStructure tbsCert = obj.TbsCertificate;
if (!tbsCert.Subject.ToString().Equals(subjects[id - 1]))
{
Fail("failed subject test for certificate id " + id
+ " got " + tbsCert.Subject.ToString());
}
if (tbsCert.Version == 3)
{
X509Extensions ext = tbsCert.Extensions;
if (ext != null)
{
foreach (DerObjectIdentifier oid in ext.ExtensionOids)
{
X509Extension extVal = ext.GetExtension(oid);
Asn1Object extObj = Asn1Object.FromByteArray(extVal.Value.GetOctets());
if (oid.Equals(X509Extensions.SubjectKeyIdentifier))
{
SubjectKeyIdentifier.GetInstance(extObj);
}
else if (oid.Equals(X509Extensions.KeyUsage))
{
KeyUsage.GetInstance(extObj);
}
else if (oid.Equals(X509Extensions.ExtendedKeyUsage))
{
ExtendedKeyUsage ku = ExtendedKeyUsage.GetInstance(extObj);
Asn1Sequence sq = (Asn1Sequence)ku.ToAsn1Object();
for (int i = 0; i != sq.Count; i++)
{
KeyPurposeID.GetInstance(sq[i]);
}
}
else if (oid.Equals(X509Extensions.SubjectAlternativeName))
{
GeneralNames gn = GeneralNames.GetInstance(extObj);
Asn1Sequence sq = (Asn1Sequence)gn.ToAsn1Object();
for (int i = 0; i != sq.Count; i++)
{
GeneralName.GetInstance(sq[i]);
}
}
else if (oid.Equals(X509Extensions.IssuerAlternativeName))
{
GeneralNames gn = GeneralNames.GetInstance(extObj);
Asn1Sequence sq = (Asn1Sequence)gn.ToAsn1Object();
for (int i = 0; i != sq.Count; i++)
{
GeneralName.GetInstance(sq[i]);
}
}
else if (oid.Equals(X509Extensions.CrlDistributionPoints))
{
CrlDistPoint p = CrlDistPoint.GetInstance(extObj);
DistributionPoint[] points = p.GetDistributionPoints();
for (int i = 0; i != points.Length; i++)
{
// do nothing
}
}
else if (oid.Equals(X509Extensions.CertificatePolicies))
{
Asn1Sequence cp = (Asn1Sequence) extObj;
for (int i = 0; i != cp.Count; i++)
{
PolicyInformation.GetInstance(cp[i]);
}
}
else if (oid.Equals(X509Extensions.AuthorityKeyIdentifier))
{
AuthorityKeyIdentifier.GetInstance(extObj);
}
else if (oid.Equals(X509Extensions.BasicConstraints))
{
BasicConstraints.GetInstance(extObj);
}
else
{
//Console.WriteLine(oid.Id);
}
}
}
}
}
public void CheckAttributeCertificate(
int id,
byte[] cert)
{
Asn1Sequence seq = (Asn1Sequence) Asn1Object.FromByteArray(cert);
string dump = Asn1Dump.DumpAsString(seq);
AttributeCertificate obj = AttributeCertificate.GetInstance(seq);
AttributeCertificateInfo acInfo = obj.ACInfo;
// Version
if (!(acInfo.Version.Equals(new DerInteger(1)))
&& (!(acInfo.Version.Equals(new DerInteger(2)))))
{
Fail("failed AC Version test for id " + id);
}
// Holder
Holder h = acInfo.Holder;
if (h == null)
{
Fail("failed AC Holder test, it's null, for id " + id);
}
// Issuer
AttCertIssuer aci = acInfo.Issuer;
if (aci == null)
{
Fail("failed AC Issuer test, it's null, for id " + id);
}
// Signature
AlgorithmIdentifier sig = acInfo.Signature;
if (sig == null)
{
Fail("failed AC Signature test for id " + id);
}
// Serial
DerInteger serial = acInfo.SerialNumber;
// Validity
AttCertValidityPeriod validity = acInfo.AttrCertValidityPeriod;
if (validity == null)
{
Fail("failed AC AttCertValidityPeriod test for id " + id);
}
// Attributes
Asn1Sequence attribSeq = acInfo.Attributes;
AttributeX509[] att = new AttributeX509[attribSeq.Count];
for (int i = 0; i < attribSeq.Count; i++)
{
att[i] = AttributeX509.GetInstance(attribSeq[i]);
}
// IssuerUniqueId
// TODO, how to best test?
// X509 Extensions
X509Extensions ext = acInfo.Extensions;
if (ext != null)
{
foreach (DerObjectIdentifier oid in ext.ExtensionOids)
{
X509Extension extVal = ext.GetExtension(oid);
}
}
}
public override void PerformTest()
{
CheckCertificate(1, cert1);
CheckCertificate(2, cert2);
CheckCertificate(3, cert3);
CheckCertificate(4, cert4);
CheckCertificate(5, cert5);
CheckCertificate(6, cert6);
CheckCertificate(7, cert7);
CheckAttributeCertificate(8, cert8);
}
public static void Main(
string[] args)
{
RunTest(new CertificateTest());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
/*
* PropertyBuilder.cs - Implementation of the
* "System.Reflection.Emit.PropertyBuilder" class.
*
* Copyright (C) 2002 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Reflection.Emit
{
#if CONFIG_REFLECTION_EMIT
using System;
using System.Reflection;
using System.Globalization;
using System.Runtime.CompilerServices;
public sealed class PropertyBuilder
: PropertyInfo, IClrProgramItem, IDetachItem
{
// Internal state.
private TypeBuilder type;
private Type returnType;
private MethodInfo getMethod;
private MethodInfo setMethod;
private IntPtr privateData;
// Constructor.
internal PropertyBuilder(TypeBuilder type, String name,
PropertyAttributes attributes,
Type returnType, Type[] parameterTypes)
{
// Validate the parameters.
if(name == null)
{
throw new ArgumentNullException("name");
}
else if(returnType == null)
{
throw new ArgumentNullException("returnType");
}
// Initialize this object's internal state.
this.type = type;
this.returnType = returnType;
this.getMethod = null;
this.setMethod = null;
// Register this item to be detached later.
type.module.assembly.AddDetach(this);
// Create the property signature.
SignatureHelper helper =
SignatureHelper.GetPropertySigHelper
(type.module, returnType, parameterTypes);
// Create the property.
lock(typeof(AssemblyBuilder))
{
this.privateData = ClrPropertyCreate
(((IClrProgramItem)type).ClrHandle, name,
attributes, helper.sig);
}
}
// Add an "other" method to this property.
public void AddOtherMethod(MethodBuilder mdBuilder)
{
try
{
type.StartSync();
if(mdBuilder == null)
{
throw new ArgumentNullException("mdBuilder");
}
lock(typeof(AssemblyBuilder))
{
ClrPropertyAddSemantics
(privateData, MethodSemanticsAttributes.Other,
type.module.GetMethodToken(mdBuilder));
}
}
finally
{
type.EndSync();
}
}
// Get the accessor methods for this property.
public override MethodInfo[] GetAccessors(bool nonPublic)
{
throw new NotSupportedException(_("NotSupp_Builder"));
}
// Get custom attributes form this property.
public override Object[] GetCustomAttributes(bool inherit)
{
throw new NotSupportedException(_("NotSupp_Builder"));
}
public override Object[] GetCustomAttributes(Type attributeType,
bool inherit)
{
throw new NotSupportedException(_("NotSupp_Builder"));
}
// Get the "get" method for this property.
public override MethodInfo GetGetMethod(bool nonPublic)
{
if(getMethod == null || nonPublic)
{
return getMethod;
}
else if((getMethod.Attributes &
MethodAttributes.MemberAccessMask) ==
MethodAttributes.Public)
{
return getMethod;
}
else
{
return null;
}
}
// Get the index parameters for this property.
public override ParameterInfo[] GetIndexParameters()
{
throw new NotSupportedException(_("NotSupp_Builder"));
}
// Get the "set" method for this property.
public override MethodInfo GetSetMethod(bool nonPublic)
{
if(setMethod == null || nonPublic)
{
return setMethod;
}
else if((setMethod.Attributes &
MethodAttributes.MemberAccessMask) ==
MethodAttributes.Public)
{
return setMethod;
}
else
{
return null;
}
}
// Get the value of this property on an object.
public override Object GetValue(Object obj, Object[] index)
{
throw new NotSupportedException(_("NotSupp_Builder"));
}
public override Object GetValue(Object obj, BindingFlags invokeAttr,
Binder binder, Object[] index,
CultureInfo culture)
{
throw new NotSupportedException(_("NotSupp_Builder"));
}
// Determine if a particular custom attribute is defined on this property.
public override bool IsDefined(Type attributeType, bool inherit)
{
throw new NotSupportedException(_("NotSupp_Builder"));
}
// Set the constant value on this property.
public void SetConstant(Object defaultValue)
{
try
{
type.StartSync();
FieldBuilder.ValidateConstant(returnType, defaultValue);
lock(typeof(AssemblyBuilder))
{
FieldBuilder.ClrFieldSetConstant
(privateData, defaultValue);
}
}
finally
{
type.EndSync();
}
}
// Set a custom attribute on this property.
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
try
{
type.StartSync();
type.module.assembly.SetCustomAttribute
(this, customBuilder);
}
finally
{
type.EndSync();
}
}
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
try
{
type.StartSync();
type.module.assembly.SetCustomAttribute
(this, con, binaryAttribute);
}
finally
{
type.EndSync();
}
}
// Set the "get" method on this property.
public void SetGetMethod(MethodBuilder mdBuilder)
{
try
{
type.StartSync();
if(mdBuilder == null)
{
throw new ArgumentNullException("mdBuilder");
}
else if(getMethod != null)
{
throw new ArgumentException
(_("Emit_GetAlreadyDefined"));
}
lock(typeof(AssemblyBuilder))
{
ClrPropertyAddSemantics
(privateData, MethodSemanticsAttributes.Getter,
type.module.GetMethodToken(mdBuilder));
}
getMethod = mdBuilder;
}
finally
{
type.EndSync();
}
}
// Set the "set" method on this property.
public void SetSetMethod(MethodBuilder mdBuilder)
{
try
{
type.StartSync();
if(mdBuilder == null)
{
throw new ArgumentNullException("mdBuilder");
}
else if(setMethod != null)
{
throw new ArgumentException
(_("Emit_SetAlreadyDefined"));
}
lock(typeof(AssemblyBuilder))
{
ClrPropertyAddSemantics
(privateData, MethodSemanticsAttributes.Setter,
type.module.GetMethodToken(mdBuilder));
}
setMethod = mdBuilder;
}
finally
{
type.EndSync();
}
}
// Set the value of this property on an object.
public override void SetValue(Object obj, Object value, Object[] index)
{
throw new NotSupportedException(_("NotSupp_Builder"));
}
public override void SetValue(Object obj, Object value,
BindingFlags invokeAttr,
Binder binder, Object[] index,
CultureInfo culture)
{
throw new NotSupportedException(_("NotSupp_Builder"));
}
// Get the attributes for this property.
public override PropertyAttributes Attributes
{
get
{
lock(typeof(AssemblyBuilder))
{
return (PropertyAttributes)
ClrHelpers.GetMemberAttrs(privateData);
}
}
}
// Determine if we can read from this property.
public override bool CanRead
{
get
{
return (getMethod != null);
}
}
// Determine if we can write to this property.
public override bool CanWrite
{
get
{
return (setMethod != null);
}
}
// Get the type that this property is declared within.
public override Type DeclaringType
{
get
{
return type;
}
}
// Get the name of this property.
public override String Name
{
get
{
lock(typeof(AssemblyBuilder))
{
return ClrHelpers.GetName(this);
}
}
}
// Get the token associated with this property.
public PropertyToken PropertyToken
{
get
{
lock(typeof(AssemblyBuilder))
{
return new PropertyToken
(AssemblyBuilder.ClrGetItemToken(privateData));
}
}
}
// Get the type associated with this property.
public override Type PropertyType
{
get
{
return returnType;
}
}
// Get the reflected type that this property exists within.
public override Type ReflectedType
{
get
{
return type;
}
}
// Get the CLR handle for this property.
IntPtr IClrProgramItem.ClrHandle
{
get
{
return privateData;
}
}
// Detach this item.
void IDetachItem.Detach()
{
privateData = IntPtr.Zero;
}
// Create a new property and attach it to a particular class.
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static IntPtr ClrPropertyCreate
(IntPtr classInfo, String name,
PropertyAttributes attributes, IntPtr signature);
// Add semantic information to this property.
[MethodImpl(MethodImplOptions.InternalCall)]
extern private static void ClrPropertyAddSemantics
(IntPtr item, MethodSemanticsAttributes attr,
MethodToken token);
}; // class PropertyBuilder
#endif // CONFIG_REFLECTION_EMIT
}; // namespace System.Reflection.Emit
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Collections;
using System.Globalization;
using OpenLiveWriter.BlogClient.Providers;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.BlogClient;
using OpenLiveWriter.BlogClient.Detection;
using OpenLiveWriter.CoreServices.Settings;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.FileDestinations;
using OpenLiveWriter.PostEditor.Configuration.Wizard;
using OpenLiveWriter.PostEditor.PostHtmlEditing;
namespace OpenLiveWriter.PostEditor.Configuration
{
public class TemporaryBlogSettings
: IBlogSettingsAccessor, IBlogSettingsDetectionContext, ITemporaryBlogSettingsDetectionContext, ICloneable
{
public static TemporaryBlogSettings CreateNew()
{
return new TemporaryBlogSettings();
}
public static TemporaryBlogSettings ForBlogId(string blogId)
{
using (BlogSettings blogSettings = BlogSettings.ForBlogId(blogId))
{
TemporaryBlogSettings tempSettings = new TemporaryBlogSettings(blogId);
tempSettings.IsNewWeblog = false;
tempSettings.IsSpacesBlog = blogSettings.IsSpacesBlog;
tempSettings.IsSharePointBlog = blogSettings.IsSharePointBlog;
tempSettings.HostBlogId = blogSettings.HostBlogId;
tempSettings.BlogName = blogSettings.BlogName;
tempSettings.HomepageUrl = blogSettings.HomepageUrl;
tempSettings.ForceManualConfig = blogSettings.ForceManualConfig;
tempSettings.ManifestDownloadInfo = blogSettings.ManifestDownloadInfo;
tempSettings.SetProvider(blogSettings.ProviderId, blogSettings.ServiceName, blogSettings.PostApiUrl, blogSettings.ClientType);
tempSettings.Credentials = blogSettings.Credentials;
tempSettings.LastPublishFailed = blogSettings.LastPublishFailed;
tempSettings.Categories = blogSettings.Categories;
tempSettings.Keywords = blogSettings.Keywords;
tempSettings.Authors = blogSettings.Authors;
tempSettings.Pages = blogSettings.Pages;
tempSettings.FavIcon = blogSettings.FavIcon;
tempSettings.Image = blogSettings.Image;
tempSettings.WatermarkImage = blogSettings.WatermarkImage;
tempSettings.OptionOverrides = blogSettings.OptionOverrides;
tempSettings.UserOptionOverrides = blogSettings.UserOptionOverrides;
tempSettings.ButtonDescriptions = blogSettings.ButtonDescriptions;
tempSettings.HomePageOverrides = blogSettings.HomePageOverrides;
//set the save password flag
tempSettings.SavePassword = blogSettings.Credentials.Password != null &&
blogSettings.Credentials.Password != String.Empty;
// file upload support
tempSettings.FileUploadSupport = blogSettings.FileUploadSupport;
// get ftp settings if necessary
if (blogSettings.FileUploadSupport == FileUploadSupport.FTP)
{
FtpUploaderSettings.Copy(blogSettings.FileUploadSettings, tempSettings.FileUploadSettings);
}
blogSettings.PublishingPluginSettings.CopyTo(tempSettings.PublishingPluginSettings);
using (PostHtmlEditingSettings editSettings = new PostHtmlEditingSettings(blogId))
{
tempSettings.TemplateFiles = editSettings.EditorTemplateHtmlFiles;
}
return tempSettings;
}
}
public void Save(BlogSettings settings)
{
settings.HostBlogId = this.HostBlogId;
settings.IsSpacesBlog = this.IsSpacesBlog;
settings.IsSharePointBlog = this.IsSharePointBlog;
settings.BlogName = this.BlogName;
settings.HomepageUrl = this.HomepageUrl;
settings.ForceManualConfig = this.ForceManualConfig;
settings.ManifestDownloadInfo = this.ManifestDownloadInfo;
settings.SetProvider(this.ProviderId, this.ServiceName);
settings.ClientType = this.ClientType;
settings.PostApiUrl = this.PostApiUrl;
if (IsSpacesBlog || !(SavePassword ?? false)) // clear out password so we don't save it
Credentials.Password = "";
settings.Credentials = this.Credentials;
if (Categories != null)
settings.Categories = this.Categories;
if (Keywords != null)
settings.Keywords = this.Keywords;
settings.Authors = this.Authors;
settings.Pages = this.Pages;
settings.FavIcon = this.FavIcon;
settings.Image = this.Image;
settings.WatermarkImage = this.WatermarkImage;
if (OptionOverrides != null)
settings.OptionOverrides = this.OptionOverrides;
if (UserOptionOverrides != null)
settings.UserOptionOverrides = this.UserOptionOverrides;
if (HomePageOverrides != null)
settings.HomePageOverrides = this.HomePageOverrides;
settings.ButtonDescriptions = this.ButtonDescriptions;
// file upload support
settings.FileUploadSupport = this.FileUploadSupport;
// save ftp settings if necessary
if (FileUploadSupport == FileUploadSupport.FTP)
{
FtpUploaderSettings.Copy(FileUploadSettings, settings.FileUploadSettings);
}
PublishingPluginSettings.CopyTo(settings.PublishingPluginSettings);
using (PostHtmlEditingSettings editSettings = new PostHtmlEditingSettings(settings.Id))
{
editSettings.EditorTemplateHtmlFiles = TemplateFiles;
}
}
public void SetBlogInfo(BlogInfo blogInfo)
{
if (blogInfo.Id != _hostBlogId)
{
_blogName = blogInfo.Name;
_hostBlogId = blogInfo.Id;
_homePageUrl = blogInfo.HomepageUrl;
if (!UrlHelper.IsUrl(_homePageUrl))
{
Trace.Assert(!string.IsNullOrEmpty(_homePageUrl), "Homepage URL was null or empty");
string baseUrl = UrlHelper.GetBaseUrl(_postApiUrl);
_homePageUrl = UrlHelper.UrlCombineIfRelative(baseUrl, _homePageUrl);
}
// reset categories, authors, and pages
Categories = new BlogPostCategory[] { };
Keywords = new BlogPostKeyword[] { };
Authors = new AuthorInfo[] { };
Pages = new PageInfo[] { };
// reset option overrides
if (OptionOverrides != null)
OptionOverrides.Clear();
if (UserOptionOverrides != null)
UserOptionOverrides.Clear();
if (HomePageOverrides != null)
HomePageOverrides.Clear();
// reset provider buttons
if (ButtonDescriptions != null)
ButtonDescriptions = new IBlogProviderButtonDescription[0];
// reset template
TemplateFiles = new BlogEditingTemplateFile[0];
}
}
public void SetProvider(string providerId, string serviceName, string postApiUrl, string clientType)
{
// for dirty states only
if (ProviderId != providerId ||
ServiceName != serviceName ||
PostApiUrl != postApiUrl ||
ClientType != clientType)
{
// reset the provider info
_providerId = providerId;
_serviceName = serviceName;
_postApiUrl = postApiUrl;
_clientType = clientType;
}
}
public void ClearProvider()
{
_providerId = String.Empty;
_serviceName = String.Empty;
_postApiUrl = String.Empty;
_clientType = String.Empty;
_hostBlogId = String.Empty;
_manifestDownloadInfo = null;
_optionOverrides.Clear();
_templateFiles = new BlogEditingTemplateFile[0];
_homepageOptionOverrides.Clear();
_buttonDescriptions = new BlogProviderButtonDescription[0];
_categories = new BlogPostCategory[0];
}
public string Id
{
get
{
return _id;
}
set
{
_id = value;
}
}
public bool IsSpacesBlog
{
get
{
return _isSpacesBlog;
}
set
{
_isSpacesBlog = value;
}
}
public bool? SavePassword
{
get
{
return _savePassword;
}
set
{
_savePassword = value;
}
}
public bool IsSharePointBlog
{
get
{
return _isSharePointBlog;
}
set
{
_isSharePointBlog = value;
}
}
public string HostBlogId
{
get
{
return _hostBlogId;
}
set
{
_hostBlogId = value;
}
}
public string BlogName
{
get
{
return _blogName;
}
set
{
_blogName = value;
}
}
public string HomepageUrl
{
get
{
return _homePageUrl;
}
set
{
_homePageUrl = value;
}
}
public bool ForceManualConfig
{
get
{
return _forceManualConfig;
}
set
{
_forceManualConfig = value;
}
}
public WriterEditingManifestDownloadInfo ManifestDownloadInfo
{
get
{
return _manifestDownloadInfo;
}
set
{
_manifestDownloadInfo = value;
}
}
public IDictionary OptionOverrides
{
get
{
return _optionOverrides;
}
set
{
_optionOverrides = value;
}
}
public IDictionary UserOptionOverrides
{
get
{
return _userOptionOverrides;
}
set
{
_userOptionOverrides = value;
}
}
public IDictionary HomePageOverrides
{
get
{
return _homepageOptionOverrides;
}
set
{
_homepageOptionOverrides = value;
}
}
public void UpdatePostBodyBackgroundColor(Color color)
{
IDictionary dictionary = HomePageOverrides ?? new Hashtable();
dictionary[BlogClientOptions.POST_BODY_BACKGROUND_COLOR] = color.ToArgb().ToString(CultureInfo.InvariantCulture);
HomePageOverrides = dictionary;
}
public IBlogProviderButtonDescription[] ButtonDescriptions
{
get
{
return _buttonDescriptions;
}
set
{
_buttonDescriptions = new BlogProviderButtonDescription[value.Length];
for (int i = 0; i < value.Length; i++)
_buttonDescriptions[i] = new BlogProviderButtonDescription(value[i]);
}
}
public string ProviderId
{
get { return _providerId; }
}
public string ServiceName
{
get { return _serviceName; }
}
public string ClientType
{
get { return _clientType; }
set { _clientType = value; }
}
public string PostApiUrl
{
get { return _postApiUrl; }
}
IBlogCredentialsAccessor IBlogSettingsAccessor.Credentials
{
get
{
return new BlogCredentialsAccessor(Id, Credentials);
}
}
IBlogCredentialsAccessor IBlogSettingsDetectionContext.Credentials
{
get
{
return new BlogCredentialsAccessor(Id, Credentials);
}
}
public IBlogCredentials Credentials
{
get
{
return _credentials;
}
set
{
BlogCredentialsHelper.Copy(value, _credentials);
}
}
public bool LastPublishFailed
{
get
{
return _lastPublishFailed;
}
set
{
_lastPublishFailed = value;
}
}
public BlogPostCategory[] Categories
{
get
{
return _categories;
}
set
{
_categories = value;
}
}
public BlogPostKeyword[] Keywords
{
get
{
return _keywords;
}
set
{
_keywords = value;
}
}
public AuthorInfo[] Authors
{
get
{
return _authors;
}
set
{
_authors = value;
}
}
public PageInfo[] Pages
{
get
{
return _pages;
}
set
{
_pages = value;
}
}
public byte[] FavIcon
{
get
{
return _favIcon;
}
set
{
_favIcon = value;
}
}
public byte[] Image
{
get
{
return _image;
}
set
{
_image = value;
}
}
public byte[] WatermarkImage
{
get
{
return _watermarkImage;
}
set
{
_watermarkImage = value;
}
}
public FileUploadSupport FileUploadSupport
{
get
{
return _fileUploadSupport;
}
set
{
_fileUploadSupport = value;
}
}
public IBlogFileUploadSettings FileUploadSettings
{
get { return _fileUploadSettings; }
}
public IBlogFileUploadSettings AtomPublishingProtocolSettings
{
get { return _atomPublishingProtocolSettings; }
}
public BlogPublishingPluginSettings PublishingPluginSettings
{
get { return new BlogPublishingPluginSettings(_pluginSettings); }
}
public BlogEditingTemplateFile[] TemplateFiles
{
get
{
return _templateFiles;
}
set
{
_templateFiles = value;
}
}
public bool IsNewWeblog
{
get { return _isNewWeblog; }
set { _isNewWeblog = value; }
}
public bool SwitchToWeblog
{
get { return _switchToWeblog; }
set { _switchToWeblog = value; }
}
public BlogInfo[] HostBlogs
{
get
{
return _hostBlogs;
}
set
{
_hostBlogs = value;
}
}
public bool InstrumentationOptIn
{
get
{
return _instrumentationOptIn;
}
set
{
_instrumentationOptIn = value;
}
}
public BlogInfo[] AvailableImageEndpoints
{
get { return _availableImageEndpoints; }
set { _availableImageEndpoints = value; }
}
//
// IMPORTANT NOTE: When adding member variables you MUST update the CopyFrom() implementation below!!!!
//
private string _id = String.Empty;
private bool? _savePassword;
private bool _isSpacesBlog = false;
private bool _isSharePointBlog = false;
private string _hostBlogId = String.Empty;
private string _blogName = String.Empty;
private string _homePageUrl = String.Empty;
private bool _forceManualConfig = false;
private WriterEditingManifestDownloadInfo _manifestDownloadInfo = null;
private string _providerId = String.Empty;
private string _serviceName = String.Empty;
private string _clientType = String.Empty;
private string _postApiUrl = String.Empty;
private TemporaryBlogCredentials _credentials = new TemporaryBlogCredentials();
private bool _lastPublishFailed = false;
private BlogEditingTemplateFile[] _templateFiles = new BlogEditingTemplateFile[0];
private bool _isNewWeblog = true;
private bool _switchToWeblog = false;
private BlogPostCategory[] _categories = null;
private BlogPostKeyword[] _keywords = null;
private AuthorInfo[] _authors = new AuthorInfo[0];
private PageInfo[] _pages = new PageInfo[0];
private BlogProviderButtonDescription[] _buttonDescriptions = new BlogProviderButtonDescription[0];
private byte[] _favIcon = null;
private byte[] _image = null;
private byte[] _watermarkImage = null;
private IDictionary _homepageOptionOverrides = new Hashtable();
private IDictionary _optionOverrides = new Hashtable();
private IDictionary _userOptionOverrides = new Hashtable();
private BlogInfo[] _hostBlogs = new BlogInfo[] { };
private FileUploadSupport _fileUploadSupport = FileUploadSupport.Weblog;
private TemporaryFileUploadSettings _fileUploadSettings = new TemporaryFileUploadSettings();
private TemporaryFileUploadSettings _atomPublishingProtocolSettings = new TemporaryFileUploadSettings();
private SettingsPersisterHelper _pluginSettings = new SettingsPersisterHelper(new MemorySettingsPersister());
private BlogInfo[] _availableImageEndpoints;
private bool _instrumentationOptIn = false;
//
// IMPORTANT NOTE: When adding member variables you MUST update the CopyFrom() implementation below!!!!
//
private TemporaryBlogSettings()
{
Id = Guid.NewGuid().ToString();
}
private TemporaryBlogSettings(string id)
{
Id = id;
}
public void Dispose()
{
}
public void CopyFrom(TemporaryBlogSettings sourceSettings)
{
// simple members
_id = sourceSettings._id;
_switchToWeblog = sourceSettings._switchToWeblog;
_isNewWeblog = sourceSettings._isNewWeblog;
_savePassword = sourceSettings._savePassword;
_isSpacesBlog = sourceSettings._isSpacesBlog;
_isSharePointBlog = sourceSettings._isSharePointBlog;
_hostBlogId = sourceSettings._hostBlogId;
_blogName = sourceSettings._blogName;
_homePageUrl = sourceSettings._homePageUrl;
_manifestDownloadInfo = sourceSettings._manifestDownloadInfo;
_providerId = sourceSettings._providerId;
_serviceName = sourceSettings._serviceName;
_clientType = sourceSettings._clientType;
_postApiUrl = sourceSettings._postApiUrl;
_lastPublishFailed = sourceSettings._lastPublishFailed;
_fileUploadSupport = sourceSettings._fileUploadSupport;
_instrumentationOptIn = sourceSettings._instrumentationOptIn;
if (sourceSettings._availableImageEndpoints == null)
{
_availableImageEndpoints = null;
}
else
{
// Good thing BlogInfo is immutable!
_availableImageEndpoints = (BlogInfo[])sourceSettings._availableImageEndpoints.Clone();
}
// credentials
BlogCredentialsHelper.Copy(sourceSettings._credentials, _credentials);
// template files
_templateFiles = new BlogEditingTemplateFile[sourceSettings._templateFiles.Length];
for (int i = 0; i < sourceSettings._templateFiles.Length; i++)
{
BlogEditingTemplateFile sourceFile = sourceSettings._templateFiles[i];
_templateFiles[i] = new BlogEditingTemplateFile(sourceFile.TemplateType, sourceFile.TemplateFile);
}
// option overrides
if (sourceSettings._optionOverrides != null)
{
_optionOverrides.Clear();
foreach (DictionaryEntry entry in sourceSettings._optionOverrides)
_optionOverrides.Add(entry.Key, entry.Value);
}
// user option overrides
if (sourceSettings._userOptionOverrides != null)
{
_userOptionOverrides.Clear();
foreach (DictionaryEntry entry in sourceSettings._userOptionOverrides)
_userOptionOverrides.Add(entry.Key, entry.Value);
}
// homepage overrides
if (sourceSettings._homepageOptionOverrides != null)
{
_homepageOptionOverrides.Clear();
foreach (DictionaryEntry entry in sourceSettings._homepageOptionOverrides)
_homepageOptionOverrides.Add(entry.Key, entry.Value);
}
// categories
if (sourceSettings._categories != null)
{
_categories = new BlogPostCategory[sourceSettings._categories.Length];
for (int i = 0; i < sourceSettings._categories.Length; i++)
{
BlogPostCategory sourceCategory = sourceSettings._categories[i];
_categories[i] = sourceCategory.Clone() as BlogPostCategory;
}
}
else
{
_categories = null;
}
if (sourceSettings._keywords != null)
{
_keywords = new BlogPostKeyword[sourceSettings._keywords.Length];
for (int i = 0; i < sourceSettings._keywords.Length; i++)
{
BlogPostKeyword sourceKeyword = sourceSettings._keywords[i];
_keywords[i] = sourceKeyword.Clone() as BlogPostKeyword;
}
}
else
{
_keywords = null;
}
// authors and pages
_authors = sourceSettings._authors.Clone() as AuthorInfo[];
_pages = sourceSettings._pages.Clone() as PageInfo[];
// buttons
if (sourceSettings._buttonDescriptions != null)
{
_buttonDescriptions = new BlogProviderButtonDescription[sourceSettings._buttonDescriptions.Length];
for (int i = 0; i < sourceSettings._buttonDescriptions.Length; i++)
_buttonDescriptions[i] = sourceSettings._buttonDescriptions[i].Clone() as BlogProviderButtonDescription;
}
else
{
_buttonDescriptions = null;
}
// favicon
_favIcon = sourceSettings._favIcon;
// images
_image = sourceSettings._image;
_watermarkImage = sourceSettings._watermarkImage;
// host blogs
_hostBlogs = new BlogInfo[sourceSettings._hostBlogs.Length];
for (int i = 0; i < sourceSettings._hostBlogs.Length; i++)
{
BlogInfo sourceBlog = sourceSettings._hostBlogs[i];
_hostBlogs[i] = new BlogInfo(sourceBlog.Id, sourceBlog.Name, sourceBlog.HomepageUrl);
}
// file upload settings
_fileUploadSettings = sourceSettings._fileUploadSettings.Clone() as TemporaryFileUploadSettings;
_pluginSettings = new SettingsPersisterHelper(new MemorySettingsPersister());
_pluginSettings.CopyFrom(sourceSettings._pluginSettings, true, true);
}
public object Clone()
{
TemporaryBlogSettings newSettings = new TemporaryBlogSettings();
newSettings.CopyFrom(this);
return newSettings;
}
}
public class TemporaryBlogCredentials : IBlogCredentials
{
public string Username
{
get { return _username; }
set { _username = value; }
}
private string _username = String.Empty;
public string Password
{
get { return _password; }
set { _password = value; }
}
private string _password = String.Empty;
public string[] CustomValues
{
get
{
string[] customValues = new string[_values.Count];
if (_values.Count > 0)
_values.Keys.CopyTo(customValues, 0);
return customValues;
}
}
public string GetCustomValue(string name)
{
if (_values.Contains(name))
{
return _values[name] as string;
}
else
{
return String.Empty;
}
}
public void SetCustomValue(string name, string value)
{
_values[name] = value;
}
public ICredentialsDomain Domain
{
get { return _domain; }
set { _domain = value; }
}
private ICredentialsDomain _domain;
public void Clear()
{
_username = String.Empty;
_password = String.Empty;
_values.Clear();
}
private Hashtable _values = new Hashtable();
}
public class TemporaryFileUploadSettings : IBlogFileUploadSettings, ICloneable
{
public TemporaryFileUploadSettings()
{
}
public string GetValue(string name)
{
if (_values.Contains(name))
{
return _values[name] as string;
}
else
{
return String.Empty;
}
}
public void SetValue(string name, string value)
{
_values[name] = value;
}
public string[] Names
{
get { return (string[])new ArrayList(_values.Keys).ToArray(typeof(string)); }
}
public void Clear()
{
_values.Clear();
}
private Hashtable _values = new Hashtable();
public object Clone()
{
TemporaryFileUploadSettings newSettings = new TemporaryFileUploadSettings();
foreach (DictionaryEntry entry in _values)
newSettings.SetValue(entry.Key as string, entry.Value as string);
return newSettings;
}
}
}
| |
/*
* 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.Timers;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.Framework.Scenes
{
/// <summary>
/// Collect statistics from the scene to send to the client and for access by other monitoring tools.
/// </summary>
/// <remarks>
/// FIXME: This should be a monitoring region module
/// </remarks>
public class SimStatsReporter
{
private static readonly log4net.ILog m_log
= log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public const string LastReportedObjectUpdateStatName = "LastReportedObjectUpdates";
public const string SlowFramesStatName = "SlowFrames";
public delegate void SendStatResult(SimStats stats);
public delegate void YourStatsAreWrong();
public event SendStatResult OnSendStatsResult;
public event YourStatsAreWrong OnStatsIncorrect;
private SendStatResult handlerSendStatResult;
private YourStatsAreWrong handlerStatsIncorrect;
/// <summary>
/// These are the IDs of stats sent in the StatsPacket to the viewer.
/// </summary>
/// <remarks>
/// Some of these are not relevant to OpenSimulator since it is architected differently to other simulators
/// (e.g. script instructions aren't executed as part of the frame loop so 'script time' is tricky).
/// </remarks>
public enum Stats : uint
{
TimeDilation = 0,
SimFPS = 1,
PhysicsFPS = 2,
AgentUpdates = 3,
FrameMS = 4,
NetMS = 5,
OtherMS = 6,
PhysicsMS = 7,
AgentMS = 8,
ImageMS = 9,
ScriptMS = 10,
TotalPrim = 11,
ActivePrim = 12,
Agents = 13,
ChildAgents = 14,
ActiveScripts = 15,
ScriptLinesPerSecond = 16,
InPacketsPerSecond = 17,
OutPacketsPerSecond = 18,
PendingDownloads = 19,
PendingUploads = 20,
VirtualSizeKb = 21,
ResidentSizeKb = 22,
PendingLocalUploads = 23,
UnAckedBytes = 24,
PhysicsPinnedTasks = 25,
PhysicsLodTasks = 26,
SimPhysicsStepMs = 27,
SimPhysicsShapeMs = 28,
SimPhysicsOtherMs = 29,
SimPhysicsMemory = 30,
ScriptEps = 31,
SimSpareMs = 32,
SimSleepMs = 33,
SimIoPumpTime = 34
}
/// <summary>
/// This is for llGetRegionFPS
/// </summary>
public float LastReportedSimFPS
{
get { return lastReportedSimFPS; }
}
/// <summary>
/// Number of object updates performed in the last stats cycle
/// </summary>
/// <remarks>
/// This isn't sent out to the client but it is very useful data to detect whether viewers are being sent a
/// large number of object updates.
/// </remarks>
public float LastReportedObjectUpdates { get; private set; }
public float[] LastReportedSimStats
{
get { return lastReportedSimStats; }
}
/// <summary>
/// Number of frames that have taken longer to process than Scene.MIN_FRAME_TIME
/// </summary>
public Stat SlowFramesStat { get; private set; }
/// <summary>
/// The threshold at which we log a slow frame.
/// </summary>
public int SlowFramesStatReportThreshold { get; private set; }
/// <summary>
/// Extra sim statistics that are used by monitors but not sent to the client.
/// </summary>
/// <value>
/// The keys are the stat names.
/// </value>
private Dictionary<string, float> m_lastReportedExtraSimStats = new Dictionary<string, float>();
// Sending a stats update every 3 seconds-
private int m_statsUpdatesEveryMS = 3000;
private float m_statsUpdateFactor;
private float m_timeDilation;
private int m_fps;
/// <summary>
/// Number of the last frame on which we processed a stats udpate.
/// </summary>
private uint m_lastUpdateFrame;
/// <summary>
/// Our nominal fps target, as expected in fps stats when a sim is running normally.
/// </summary>
private float m_nominalReportedFps = 55;
/// <summary>
/// Parameter to adjust reported scene fps
/// </summary>
/// <remarks>
/// Our scene loop runs slower than other server implementations, apparantly because we work somewhat differently.
/// However, we will still report an FPS that's closer to what people are used to seeing. A lower FPS might
/// affect clients and monitoring scripts/software.
/// </remarks>
private float m_reportedFpsCorrectionFactor = 5;
// saved last reported value so there is something available for llGetRegionFPS
private float lastReportedSimFPS;
private float[] lastReportedSimStats = new float[22];
private float m_pfps;
/// <summary>
/// Number of agent updates requested in this stats cycle
/// </summary>
private int m_agentUpdates;
/// <summary>
/// Number of object updates requested in this stats cycle
/// </summary>
private int m_objectUpdates;
private int m_frameMS;
private int m_spareMS;
private int m_netMS;
private int m_agentMS;
private int m_physicsMS;
private int m_imageMS;
private int m_otherMS;
//Ckrinke: (3-21-08) Comment out to remove a compiler warning. Bring back into play when needed.
//Ckrinke private int m_scriptMS = 0;
private int m_rootAgents;
private int m_childAgents;
private int m_numPrim;
private int m_inPacketsPerSecond;
private int m_outPacketsPerSecond;
private int m_activePrim;
private int m_unAckedBytes;
private int m_pendingDownloads;
private int m_pendingUploads = 0; // FIXME: Not currently filled in
private int m_activeScripts;
private int m_scriptLinesPerSecond;
private int m_objectCapacity = 45000;
private Scene m_scene;
private RegionInfo ReportingRegion;
private Timer m_report = new Timer();
private IEstateModule estateModule;
public SimStatsReporter(Scene scene)
{
m_scene = scene;
m_reportedFpsCorrectionFactor = scene.MinFrameTime * m_nominalReportedFps;
m_statsUpdateFactor = (float)(m_statsUpdatesEveryMS / 1000);
ReportingRegion = scene.RegionInfo;
m_objectCapacity = scene.RegionInfo.ObjectCapacity;
m_report.AutoReset = true;
m_report.Interval = m_statsUpdatesEveryMS;
m_report.Elapsed += TriggerStatsHeartbeat;
m_report.Enabled = true;
if (StatsManager.SimExtraStats != null)
OnSendStatsResult += StatsManager.SimExtraStats.ReceiveClassicSimStatsPacket;
/// At the moment, we'll only report if a frame is over 120% of target, since commonly frames are a bit
/// longer than ideal (which in itself is a concern).
SlowFramesStatReportThreshold = (int)Math.Ceiling(m_scene.MinFrameTime * 1000 * 1.2);
SlowFramesStat
= new Stat(
"SlowFrames",
"Slow Frames",
"Number of frames where frame time has been significantly longer than the desired frame time.",
" frames",
"scene",
m_scene.Name,
StatType.Push,
null,
StatVerbosity.Info);
StatsManager.RegisterStat(SlowFramesStat);
}
public void Close()
{
m_report.Elapsed -= TriggerStatsHeartbeat;
m_report.Close();
}
/// <summary>
/// Sets the number of milliseconds between stat updates.
/// </summary>
/// <param name='ms'></param>
public void SetUpdateMS(int ms)
{
m_statsUpdatesEveryMS = ms;
m_statsUpdateFactor = (float)(m_statsUpdatesEveryMS / 1000);
m_report.Interval = m_statsUpdatesEveryMS;
}
private void TriggerStatsHeartbeat(object sender, EventArgs args)
{
try
{
statsHeartBeat(sender, args);
}
catch (Exception e)
{
m_log.Warn(string.Format(
"[SIM STATS REPORTER] Update for {0} failed with exception ",
m_scene.RegionInfo.RegionName), e);
}
}
private void statsHeartBeat(object sender, EventArgs e)
{
if (!m_scene.Active)
return;
SimStatsPacket.StatBlock[] sb = new SimStatsPacket.StatBlock[22];
SimStatsPacket.RegionBlock rb = new SimStatsPacket.RegionBlock();
// Know what's not thread safe in Mono... modifying timers.
// m_log.Debug("Firing Stats Heart Beat");
lock (m_report)
{
uint regionFlags = 0;
try
{
if (estateModule == null)
estateModule = m_scene.RequestModuleInterface<IEstateModule>();
regionFlags = estateModule != null ? estateModule.GetRegionFlags() : (uint) 0;
}
catch (Exception)
{
// leave region flags at 0
}
#region various statistic googly moogly
// We're going to lie about the FPS because we've been lying since 2008. The actual FPS is currently
// locked at a maximum of 11. Maybe at some point this can change so that we're not lying.
int reportedFPS = (int)(m_fps * m_reportedFpsCorrectionFactor);
// save the reported value so there is something available for llGetRegionFPS
lastReportedSimFPS = reportedFPS / m_statsUpdateFactor;
float physfps = ((m_pfps / 1000));
//if (physfps > 600)
//physfps = physfps - (physfps - 600);
if (physfps < 0)
physfps = 0;
#endregion
m_rootAgents = m_scene.SceneGraph.GetRootAgentCount();
m_childAgents = m_scene.SceneGraph.GetChildAgentCount();
m_numPrim = m_scene.SceneGraph.GetTotalObjectsCount();
m_activePrim = m_scene.SceneGraph.GetActiveObjectsCount();
m_activeScripts = m_scene.SceneGraph.GetActiveScriptsCount();
// FIXME: Checking for stat sanity is a complex approach. What we really need to do is fix the code
// so that stat numbers are always consistent.
CheckStatSanity();
//Our time dilation is 0.91 when we're running a full speed,
// therefore to make sure we get an appropriate range,
// we have to factor in our error. (0.10f * statsUpdateFactor)
// multiplies the fix for the error times the amount of times it'll occur a second
// / 10 divides the value by the number of times the sim heartbeat runs (10fps)
// Then we divide the whole amount by the amount of seconds pass in between stats updates.
// 'statsUpdateFactor' is how often stats packets are sent in seconds. Used below to change
// values to X-per-second values.
uint thisFrame = m_scene.Frame;
float framesUpdated = (float)(thisFrame - m_lastUpdateFrame) * m_reportedFpsCorrectionFactor;
m_lastUpdateFrame = thisFrame;
// Avoid div-by-zero if somehow we've not updated any frames.
if (framesUpdated == 0)
framesUpdated = 1;
for (int i = 0; i < 22; i++)
{
sb[i] = new SimStatsPacket.StatBlock();
}
sb[0].StatID = (uint) Stats.TimeDilation;
sb[0].StatValue = (Single.IsNaN(m_timeDilation)) ? 0.1f : m_timeDilation ; //((((m_timeDilation + (0.10f * statsUpdateFactor)) /10) / statsUpdateFactor));
sb[1].StatID = (uint) Stats.SimFPS;
sb[1].StatValue = reportedFPS / m_statsUpdateFactor;
sb[2].StatID = (uint) Stats.PhysicsFPS;
sb[2].StatValue = physfps / m_statsUpdateFactor;
sb[3].StatID = (uint) Stats.AgentUpdates;
sb[3].StatValue = (m_agentUpdates / m_statsUpdateFactor);
sb[4].StatID = (uint) Stats.Agents;
sb[4].StatValue = m_rootAgents;
sb[5].StatID = (uint) Stats.ChildAgents;
sb[5].StatValue = m_childAgents;
sb[6].StatID = (uint) Stats.TotalPrim;
sb[6].StatValue = m_numPrim;
sb[7].StatID = (uint) Stats.ActivePrim;
sb[7].StatValue = m_activePrim;
sb[8].StatID = (uint)Stats.FrameMS;
sb[8].StatValue = m_frameMS / framesUpdated;
sb[9].StatID = (uint)Stats.NetMS;
sb[9].StatValue = m_netMS / framesUpdated;
sb[10].StatID = (uint)Stats.PhysicsMS;
sb[10].StatValue = m_physicsMS / framesUpdated;
sb[11].StatID = (uint)Stats.ImageMS ;
sb[11].StatValue = m_imageMS / framesUpdated;
sb[12].StatID = (uint)Stats.OtherMS;
sb[12].StatValue = m_otherMS / framesUpdated;
sb[13].StatID = (uint)Stats.InPacketsPerSecond;
sb[13].StatValue = (m_inPacketsPerSecond / m_statsUpdateFactor);
sb[14].StatID = (uint)Stats.OutPacketsPerSecond;
sb[14].StatValue = (m_outPacketsPerSecond / m_statsUpdateFactor);
sb[15].StatID = (uint)Stats.UnAckedBytes;
sb[15].StatValue = m_unAckedBytes;
sb[16].StatID = (uint)Stats.AgentMS;
sb[16].StatValue = m_agentMS / framesUpdated;
sb[17].StatID = (uint)Stats.PendingDownloads;
sb[17].StatValue = m_pendingDownloads;
sb[18].StatID = (uint)Stats.PendingUploads;
sb[18].StatValue = m_pendingUploads;
sb[19].StatID = (uint)Stats.ActiveScripts;
sb[19].StatValue = m_activeScripts;
sb[20].StatID = (uint)Stats.ScriptLinesPerSecond;
sb[20].StatValue = m_scriptLinesPerSecond / m_statsUpdateFactor;
sb[21].StatID = (uint)Stats.SimSpareMs;
sb[21].StatValue = m_spareMS / framesUpdated;
for (int i = 0; i < 22; i++)
{
lastReportedSimStats[i] = sb[i].StatValue;
}
SimStats simStats
= new SimStats(
ReportingRegion.RegionLocX, ReportingRegion.RegionLocY, regionFlags, (uint)m_objectCapacity,
rb, sb, m_scene.RegionInfo.originRegionID);
handlerSendStatResult = OnSendStatsResult;
if (handlerSendStatResult != null)
{
handlerSendStatResult(simStats);
}
// Extra statistics that aren't currently sent to clients
lock (m_lastReportedExtraSimStats)
{
m_lastReportedExtraSimStats[LastReportedObjectUpdateStatName] = m_objectUpdates / m_statsUpdateFactor;
m_lastReportedExtraSimStats[SlowFramesStat.ShortName] = (float)SlowFramesStat.Value;
Dictionary<string, float> physicsStats = m_scene.PhysicsScene.GetStats();
if (physicsStats != null)
{
foreach (KeyValuePair<string, float> tuple in physicsStats)
{
// FIXME: An extremely dirty hack to divide MS stats per frame rather than per second
// Need to change things so that stats source can indicate whether they are per second or
// per frame.
if (tuple.Key.EndsWith("MS"))
m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / framesUpdated;
else
m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / m_statsUpdateFactor;
}
}
}
ResetValues();
}
}
private void ResetValues()
{
m_timeDilation = 0;
m_fps = 0;
m_pfps = 0;
m_agentUpdates = 0;
m_objectUpdates = 0;
//m_inPacketsPerSecond = 0;
//m_outPacketsPerSecond = 0;
m_unAckedBytes = 0;
m_scriptLinesPerSecond = 0;
m_frameMS = 0;
m_agentMS = 0;
m_netMS = 0;
m_physicsMS = 0;
m_imageMS = 0;
m_otherMS = 0;
m_spareMS = 0;
//Ckrinke This variable is not used, so comment to remove compiler warning until it is used.
//Ckrinke m_scriptMS = 0;
}
# region methods called from Scene
// The majority of these functions are additive
// so that you can easily change the amount of
// seconds in between sim stats updates
public void AddTimeDilation(float td)
{
//float tdsetting = td;
//if (tdsetting > 1.0f)
//tdsetting = (tdsetting - (tdsetting - 0.91f));
//if (tdsetting < 0)
//tdsetting = 0.0f;
m_timeDilation = td;
}
internal void CheckStatSanity()
{
if (m_rootAgents < 0 || m_childAgents < 0)
{
handlerStatsIncorrect = OnStatsIncorrect;
if (handlerStatsIncorrect != null)
{
handlerStatsIncorrect();
}
}
if (m_rootAgents == 0 && m_childAgents == 0)
{
m_unAckedBytes = 0;
}
}
public void AddFPS(int frames)
{
m_fps += frames;
}
public void AddPhysicsFPS(float frames)
{
m_pfps += frames;
}
public void AddObjectUpdates(int numUpdates)
{
m_objectUpdates += numUpdates;
}
public void AddAgentUpdates(int numUpdates)
{
m_agentUpdates += numUpdates;
}
public void AddInPackets(int numPackets)
{
m_inPacketsPerSecond = numPackets;
}
public void AddOutPackets(int numPackets)
{
m_outPacketsPerSecond = numPackets;
}
public void AddunAckedBytes(int numBytes)
{
m_unAckedBytes += numBytes;
if (m_unAckedBytes < 0) m_unAckedBytes = 0;
}
public void addFrameMS(int ms)
{
m_frameMS += ms;
// At the moment, we'll only report if a frame is over 120% of target, since commonly frames are a bit
// longer than ideal due to the inaccuracy of the Sleep in Scene.Update() (which in itself is a concern).
if (ms > SlowFramesStatReportThreshold)
SlowFramesStat.Value++;
}
public void AddSpareMS(int ms)
{
m_spareMS += ms;
}
public void addNetMS(int ms)
{
m_netMS += ms;
}
public void addAgentMS(int ms)
{
m_agentMS += ms;
}
public void addPhysicsMS(int ms)
{
m_physicsMS += ms;
}
public void addImageMS(int ms)
{
m_imageMS += ms;
}
public void addOtherMS(int ms)
{
m_otherMS += ms;
}
public void AddPendingDownloads(int count)
{
m_pendingDownloads += count;
if (m_pendingDownloads < 0)
m_pendingDownloads = 0;
//m_log.InfoFormat("[stats]: Adding {0} to pending downloads to make {1}", count, m_pendingDownloads);
}
public void addScriptLines(int count)
{
m_scriptLinesPerSecond += count;
}
public void AddPacketsStats(int inPackets, int outPackets, int unAckedBytes)
{
AddInPackets(inPackets);
AddOutPackets(outPackets);
AddunAckedBytes(unAckedBytes);
}
#endregion
public Dictionary<string, float> GetExtraSimStats()
{
lock (m_lastReportedExtraSimStats)
return new Dictionary<string, float>(m_lastReportedExtraSimStats);
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Web;
using System.Web.Hosting;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting.AspNet.Util;
namespace Microsoft.Scripting.AspNet {
internal class DynamicLanguageHttpModule : IHttpModule, IBuildProvider {
private const string globalFileName = "global";
private static GlobalAsaxBuildResult s_buildResult;
private static string s_globalVirtualPathWithoutExtension;
private static string s_globalVirtualPath;
private static bool s_globalFileCompiled;
private static int s_globalFileVersion = 1;
private static bool s_firstRequest = true;
private static int s_moduleCount = 0;
private static string s_merlinWebHeader;
private ScriptScope _globalScope;
private int _globalFileCompiledVersion = 0;
private Dictionary<string, EventHandlerWrapper> _handlers;
static DynamicLanguageHttpModule() {
s_globalVirtualPathWithoutExtension = VirtualPathUtility.ToAbsolute("~/" + globalFileName);
foreach (string extension in EngineHelper.FileExtensions) {
// Register for global.<ext> file change notifications
FileChangeNotifier.Register(Path.Combine(HttpRuntime.AppDomainAppPath, globalFileName + extension),
OnFileChanged);
}
// Create string with the special response header
string mwName = typeof(DynamicLanguageHttpModule).Assembly.FullName.Split(',')[0];
Version mwVersion = typeof(DynamicLanguageHttpModule).Assembly.GetName().Version;
Version dlrVersion = typeof(ScriptEngine).Assembly.GetName().Version;
s_merlinWebHeader = string.Format("{0} v{1}.{2}(CTP); DLR v{3}.{4}",
mwName, mwVersion.Major, mwVersion.Minor, dlrVersion.Major, dlrVersion.Minor);
}
public virtual void Init(HttpApplication app) {
// Keep track of the number of modules
Interlocked.Increment(ref s_moduleCount);
// Register our BeginRequest handler first so we can make sure everything is up to date
// before trying to invoke user code
app.BeginRequest += new EventHandler(OnBeginRequest);
// Register for all the events on HttpApplication, and keep track of them in a dictionary
_handlers = new Dictionary<string, EventHandlerWrapper>();
EventInfo[] eventInfos = typeof(HttpApplication).GetEvents();
foreach (EventInfo eventInfo in eventInfos) {
EventHandlerWrapper eventHandlerWrapper = new EventHandlerWrapper(this);
EventHandler handler = eventHandlerWrapper.Handler;
try {
eventInfo.AddEventHandler(app, handler);
} catch (TargetInvocationException tiException) {
if (tiException.InnerException is PlatformNotSupportedException) {
// Ignore the event if we failed to add the handler. This can happen with IIS7
// which has new events that only work in Integrated Pipeline mode
continue;
}
throw;
}
_handlers[eventInfo.Name] = eventHandlerWrapper;
}
}
public virtual void Dispose() {
Interlocked.Decrement(ref s_moduleCount);
// If it's the last module, the app is shutting down. Call Application_OnEnd (if any)
if (s_moduleCount == 0) {
if (s_buildResult != null) {
s_buildResult.CallOnEndMethod();
}
}
}
#region IBuildProvider Members
ScriptEngine IBuildProvider.GetScriptEngine() {
Debug.Assert(s_globalVirtualPath != null);
return EngineHelper.GetScriptEngineByExtension(VirtualPathUtility.GetExtension(s_globalVirtualPath));
}
string IBuildProvider.GetScriptCode() {
// Return the full content of the 'global' file
return Util.Misc.GetStringFromVirtualPath(s_globalVirtualPath);
}
BuildResult IBuildProvider.CreateBuildResult(CompiledCode compiledCode, string scriptVirtualPath) {
return new GlobalAsaxBuildResult(((IBuildProvider)this).GetScriptEngine(), compiledCode, scriptVirtualPath);
}
#endregion
private void OnBeginRequest(object sender, EventArgs eventArgs) {
EnsureGlobalFileCompiled();
if (_globalScope == null && s_buildResult != null && s_buildResult.CompiledCode != null) {
_globalScope = EngineHelper.ScriptRuntime.CreateScope();
EngineHelper.ExecuteCode(_globalScope, s_buildResult.CompiledCode, s_globalVirtualPath);
s_buildResult.InitMethods(typeof(HttpApplication), _globalScope);
}
// If a 'global' file changed, we need to hook up its event handlers
if (_globalFileCompiledVersion < s_globalFileVersion) {
HookupScriptHandlers();
_globalFileCompiledVersion = s_globalFileVersion;
}
// Turn off the first request flag
s_firstRequest = false;
// Add special marker response header
if (s_merlinWebHeader != null) {
((HttpApplication)sender).Response.AddHeader("X-DLR-Version", s_merlinWebHeader);
}
}
private void EnsureGlobalFileCompiled() {
// This is done only once for all the HttpModule instances every time the file changes
Debug.Assert(s_buildResult == null || s_globalFileCompiled);
if (s_globalFileCompiled)
return;
lock (typeof(DynamicLanguageHttpModule)) {
if (s_globalFileCompiled)
return;
_globalScope = null;
s_globalVirtualPath = null;
string globalVirtualPath;
foreach (string extension in EngineHelper.FileExtensions) {
globalVirtualPath = s_globalVirtualPathWithoutExtension + extension;
if (HostingEnvironment.VirtualPathProvider.FileExists(globalVirtualPath)) {
// Fail if we had already found a global file
if (s_globalVirtualPath != null) {
throw new Exception(String.Format("A web application can only have one global file. Found both '{0}' and '{1}'",
s_globalVirtualPath, globalVirtualPath));
}
s_globalVirtualPath = globalVirtualPath;
}
}
// If we found a global file, compile it
if (s_globalVirtualPath != null) {
s_buildResult = (GlobalAsaxBuildResult)EngineHelper.GetBuildResult(s_globalVirtualPath, this);
}
// We set this even when there is no file to compile
s_globalFileCompiled = true;
}
}
private void HookupScriptHandlers() {
// This is done once per HttpApplication/HttpModule instance every time
// a global.<ext> file changes
// If it's the first request in the domain, call Application_OnStart (if any)
if (s_firstRequest && s_buildResult != null) {
s_buildResult.CallOnStartMethod();
}
// Hook up all the events implemented in the 'global' file
foreach (string handlerName in _handlers.Keys) {
EventHandlerWrapper eventHandlerWrapper = _handlers[handlerName];
DynamicFunction f = null;
if (s_buildResult != null && s_buildResult.EventHandlers != null) {
s_buildResult.EventHandlers.TryGetValue(handlerName, out f);
}
eventHandlerWrapper.SetDynamicFunction(f, s_globalVirtualPath);
}
}
private static void OnFileChanged(string path) {
// The file changed, and needs to be reprocessed
s_globalFileCompiled = false;
s_buildResult = null;
s_globalFileVersion++;
}
class GlobalAsaxBuildResult : TypeWithEventsBuildResult {
private const string HandlerPrefix = "Application_";
private Dictionary<string, DynamicFunction> _eventHandlers;
private DynamicFunction _onStartMethod, _onEndMethod;
private ScriptEngine _engine;
internal GlobalAsaxBuildResult(ScriptEngine engine, CompiledCode compiledCode, string scriptVirtualPath)
: base(compiledCode, scriptVirtualPath) {
_engine = engine;
}
public Dictionary<string, DynamicFunction> EventHandlers { get { return _eventHandlers; } }
internal override bool ProcessEventHandler(string handlerName, Type type, DynamicFunction f) {
// Does it look like a handler?
if (!handlerName.StartsWith(HandlerPrefix))
return false;
// Handle the special pseudo-events
if (String.Equals(handlerName, "Application_OnStart", StringComparison.OrdinalIgnoreCase) ||
String.Equals(handlerName, "Application_Start", StringComparison.OrdinalIgnoreCase)) {
_onStartMethod = f;
return true;
} else if (String.Equals(handlerName, "Application_OnEnd", StringComparison.OrdinalIgnoreCase) ||
String.Equals(handlerName, "Application_End", StringComparison.OrdinalIgnoreCase)) {
_onEndMethod = f;
return true;
} else if (String.Equals(handlerName, "Session_OnEnd", StringComparison.OrdinalIgnoreCase) ||
String.Equals(handlerName, "Session_End", StringComparison.OrdinalIgnoreCase)) {
// REVIEW: can we support Session_End?
throw new Exception("Session_End is not supported!");
}
string eventName = handlerName.Substring(HandlerPrefix.Length);
// This will throw if the event doesn't exist
EventHookupHelper.GetEventInfo(type, eventName, f, ScriptVirtualPath);
if (_eventHandlers == null)
_eventHandlers = new Dictionary<string, DynamicFunction>();
_eventHandlers[eventName] = f;
return true;
}
internal void CallOnStartMethod() {
CallFunction(_engine, _onStartMethod);
}
internal void CallOnEndMethod() {
CallFunction(_engine, _onEndMethod);
}
private void CallFunction(ScriptEngine engine, DynamicFunction f) {
if (f == null)
return;
try {
f.Invoke(engine);
} catch (Exception e) {
if (!EngineHelper.ProcessRuntimeException(engine, e, ScriptVirtualPath))
throw;
}
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
[Cmdlet(VerbsCommon.New, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "ContainerServiceConfig", SupportsShouldProcess = true)]
[OutputType(typeof(PSContainerService))]
public partial class NewAzureRmContainerServiceConfigCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet
{
[Parameter(
Mandatory = false,
Position = 0,
ValueFromPipelineByPropertyName = true)]
[LocationCompleter("Microsoft.ContainerService/containerServices")]
public string Location { get; set; }
[Parameter(
Mandatory = false,
Position = 1,
ValueFromPipelineByPropertyName = true)]
public Hashtable Tag { get; set; }
[Parameter(
Mandatory = false,
Position = 2,
ValueFromPipelineByPropertyName = true)]
public ContainerServiceOrchestratorTypes? OrchestratorType { get; set; }
[Parameter(
Mandatory = false,
Position = 3,
ValueFromPipelineByPropertyName = true)]
public int MasterCount { get; set; }
[Parameter(
Mandatory = false,
Position = 4,
ValueFromPipelineByPropertyName = true)]
public string MasterDnsPrefix { get; set; }
[Parameter(
Mandatory = false,
Position = 5,
ValueFromPipelineByPropertyName = true)]
public ContainerServiceAgentPoolProfile[] AgentPoolProfile { get; set; }
[Parameter(
Mandatory = false,
Position = 6,
ValueFromPipelineByPropertyName = true)]
public string WindowsProfileAdminUsername { get; set; }
[Parameter(
Mandatory = false,
Position = 7,
ValueFromPipelineByPropertyName = true)]
public string WindowsProfileAdminPassword { get; set; }
[Parameter(
Mandatory = false,
Position = 8,
ValueFromPipelineByPropertyName = true)]
public string AdminUsername { get; set; }
[Parameter(
Mandatory = false,
Position = 9,
ValueFromPipelineByPropertyName = true)]
public string[] SshPublicKey { get; set; }
[Parameter(
Mandatory = false,
Position = 10,
ValueFromPipelineByPropertyName = true)]
public bool VmDiagnosticsEnabled { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string CustomProfileOrchestrator { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string ServicePrincipalProfileClientId { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string ServicePrincipalProfileSecret { get; set; }
protected override void ProcessRecord()
{
if (ShouldProcess("ContainerService", "New"))
{
Run();
}
}
private void Run()
{
// OrchestratorProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceOrchestratorProfile vOrchestratorProfile = null;
// CustomProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceCustomProfile vCustomProfile = null;
// ServicePrincipalProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceServicePrincipalProfile vServicePrincipalProfile = null;
// MasterProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceMasterProfile vMasterProfile = null;
// WindowsProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceWindowsProfile vWindowsProfile = null;
// LinuxProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceLinuxProfile vLinuxProfile = null;
// DiagnosticsProfile
Microsoft.Azure.Management.Compute.Models.ContainerServiceDiagnosticsProfile vDiagnosticsProfile = null;
if (this.MyInvocation.BoundParameters.ContainsKey("OrchestratorType"))
{
if (vOrchestratorProfile == null)
{
vOrchestratorProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceOrchestratorProfile();
}
vOrchestratorProfile.OrchestratorType = this.OrchestratorType.Value;
}
if (this.MyInvocation.BoundParameters.ContainsKey("CustomProfileOrchestrator"))
{
if (vCustomProfile == null)
{
vCustomProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceCustomProfile();
}
vCustomProfile.Orchestrator = this.CustomProfileOrchestrator;
}
if (this.MyInvocation.BoundParameters.ContainsKey("ServicePrincipalProfileClientId"))
{
if (vServicePrincipalProfile == null)
{
vServicePrincipalProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceServicePrincipalProfile();
}
vServicePrincipalProfile.ClientId = this.ServicePrincipalProfileClientId;
}
if (this.MyInvocation.BoundParameters.ContainsKey("ServicePrincipalProfileSecret"))
{
if (vServicePrincipalProfile == null)
{
vServicePrincipalProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceServicePrincipalProfile();
}
vServicePrincipalProfile.Secret = this.ServicePrincipalProfileSecret;
}
if (this.MyInvocation.BoundParameters.ContainsKey("MasterCount"))
{
if (vMasterProfile == null)
{
vMasterProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceMasterProfile();
}
vMasterProfile.Count = this.MasterCount;
}
if (this.MyInvocation.BoundParameters.ContainsKey("MasterDnsPrefix"))
{
if (vMasterProfile == null)
{
vMasterProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceMasterProfile();
}
vMasterProfile.DnsPrefix = this.MasterDnsPrefix;
}
if (this.MyInvocation.BoundParameters.ContainsKey("WindowsProfileAdminUsername"))
{
if (vWindowsProfile == null)
{
vWindowsProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceWindowsProfile();
}
vWindowsProfile.AdminUsername = this.WindowsProfileAdminUsername;
}
if (this.MyInvocation.BoundParameters.ContainsKey("WindowsProfileAdminPassword"))
{
if (vWindowsProfile == null)
{
vWindowsProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceWindowsProfile();
}
vWindowsProfile.AdminPassword = this.WindowsProfileAdminPassword;
}
if (this.MyInvocation.BoundParameters.ContainsKey("AdminUsername"))
{
if (vLinuxProfile == null)
{
vLinuxProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceLinuxProfile();
}
vLinuxProfile.AdminUsername = this.AdminUsername;
}
if (this.MyInvocation.BoundParameters.ContainsKey("SshPublicKey"))
{
if (vLinuxProfile == null)
{
vLinuxProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceLinuxProfile();
}
if (vLinuxProfile.Ssh == null)
{
vLinuxProfile.Ssh = new Microsoft.Azure.Management.Compute.Models.ContainerServiceSshConfiguration();
}
if (vLinuxProfile.Ssh.PublicKeys == null)
{
vLinuxProfile.Ssh.PublicKeys = new List<Microsoft.Azure.Management.Compute.Models.ContainerServiceSshPublicKey>();
}
foreach (var element in this.SshPublicKey)
{
var vPublicKeys = new Microsoft.Azure.Management.Compute.Models.ContainerServiceSshPublicKey();
vPublicKeys.KeyData = element;
vLinuxProfile.Ssh.PublicKeys.Add(vPublicKeys);
}
}
if (vDiagnosticsProfile == null)
{
vDiagnosticsProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceDiagnosticsProfile();
}
if (vDiagnosticsProfile.VmDiagnostics == null)
{
vDiagnosticsProfile.VmDiagnostics = new Microsoft.Azure.Management.Compute.Models.ContainerServiceVMDiagnostics();
}
vDiagnosticsProfile.VmDiagnostics.Enabled = this.VmDiagnosticsEnabled;
var vContainerService = new PSContainerService
{
Location = this.MyInvocation.BoundParameters.ContainsKey("Location") ? this.Location : null,
Tags = this.MyInvocation.BoundParameters.ContainsKey("Tag") ? this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value) : null,
AgentPoolProfiles = this.MyInvocation.BoundParameters.ContainsKey("AgentPoolProfile") ? this.AgentPoolProfile : null,
OrchestratorProfile = vOrchestratorProfile,
CustomProfile = vCustomProfile,
ServicePrincipalProfile = vServicePrincipalProfile,
MasterProfile = vMasterProfile,
WindowsProfile = vWindowsProfile,
LinuxProfile = vLinuxProfile,
DiagnosticsProfile = vDiagnosticsProfile,
};
WriteObject(vContainerService);
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace WebApplication2
{
/// <summary>
/// Summary description for frmResourcesInfo.
/// </summary>
public partial class frmResTypesAll: System.Web.UI.Page
{
/*SqlConnection epsDbConn=new SqlConnection("Server=cp2693-a\\eps1;database=eps1;"+
"uid=tauheed;pwd=tauheed;");*/
private static string strURL =
System.Configuration.ConfigurationSettings.AppSettings["local_url"];
private static string strDB =
System.Configuration.ConfigurationSettings.AppSettings["local_db"];
public SqlConnection epsDbConn=new SqlConnection(strDB);
protected void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
loadForm();
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
#endregion
private void loadForm()
{
if (!IsPostBack)
{
if (Session["CallerServicesAll"].ToString() == "frmProfileServices")
{
lblContent1.Text="Select Services for profile "
+ Session["ProfileName"].ToString()
+ ". You may identify services not included in this list by clicking"
+ " on the 'Add Services' button.";
}
loadData();
}
}
private void loadData()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.Connection=this.epsDbConn;
cmd.CommandText="eps_RetrieveResourceTypes";
cmd.Parameters.Add ("@OrgId",SqlDbType.Int);
cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString();
cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int);
cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString();
cmd.Parameters.Add ("@LicenseId",SqlDbType.Int);
cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString();
cmd.Parameters.Add ("@DomainId",SqlDbType.Int);
cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"Courses");
Session["ds"] = ds;
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
refreshGrid();
}
protected void btnOK_Click(object sender, System.EventArgs e)
{
updateGrid();
Exit();
}
private void updateGrid()
{
if (Session["CallerServicesAll"].ToString() == "frmProfileServices")
{
foreach (DataGridItem i in DataGrid1.Items)
{
CheckBox cb = (CheckBox) (i.Cells[2].FindControl("cbxSel"));
if ((cb.Checked == true) & (cb.Enabled==true))
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="eps_UpdateProfileServiceTypes";//"eps_UpdateSkillCourses";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add("@ResTypeId", SqlDbType.Int);
cmd.Parameters ["@ResTypeId"].Value=i.Cells[0].Text;
cmd.Parameters.Add("@ProfileId", SqlDbType.Int);
cmd.Parameters ["@ProfileId"].Value=Session["ProfileId"].ToString();
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
}
else if (Session["CallerServicesAll"].ToString() == "frmTaskInputs")
{
foreach (DataGridItem i in DataGrid1.Items)
{
CheckBox cb = (CheckBox) (i.Cells[2].FindControl("cbxSel"));
if ((cb.Checked == true) & (cb.Enabled==true))
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="eps_AddTaskInput";//"eps_UpdateSkillCourses";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add("@ResTypeId", SqlDbType.Int);
cmd.Parameters ["@ResTypeId"].Value=i.Cells[0].Text;
cmd.Parameters.Add("@TaskId", SqlDbType.Int);
cmd.Parameters ["@TaskId"].Value=Session["TaskId"].ToString();
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
}
}
private void refreshGrid()
{
if (Session["CallerServicesAll"].ToString() == "frmProfileServices")
{
foreach (DataGridItem i in DataGrid1.Items)
{
CheckBox cb = (CheckBox)(i.Cells[2].FindControl("cbxSel"));
SqlCommand cmd=new SqlCommand();
cmd.Connection=this.epsDbConn;
cmd.CommandType=CommandType.Text;
cmd.CommandText="Select Id from ProfileServices"
+ " Where ResTypeId = " + i.Cells[0].Text
+ " and ProfileId = " + Session["ProfileId"].ToString();
cmd.Connection.Open();
if (cmd.ExecuteScalar() != null)
{
cb.Checked = true;
cb.Enabled = false;
lblContent2.Text="Note that services with check marks already"
+ " present (in shaded boxes) have already been identified for this profile.";
}
cmd.Connection.Close();
}
}
else if (Session["CallerServicesAll"].ToString() == "frmTaskInputs")
{
foreach (DataGridItem i in DataGrid1.Items)
{
CheckBox cb = (CheckBox)(i.Cells[2].FindControl("cbxSel"));
SqlCommand cmd=new SqlCommand();
cmd.Connection=this.epsDbConn;
cmd.CommandType=CommandType.Text;
cmd.CommandText="Select ResTypeId from TaskInputs"
+ " Where ResTypeId = " + "'" + i.Cells[0].Text + "'"
+ " and TaskId = " + "'" + Session["TaskId"].ToString() + "'";
cmd.Connection.Open();
if (cmd.ExecuteScalar() != null)
{
cb.Checked = true;
cb.Enabled = false;
lblContent2.Text="Note that services with check marks already"
+ " present (in shaded boxes) have already been identified.";
}
cmd.Connection.Close();
}
}
}
private void Exit()
{
Response.Redirect (strURL + Session["CallerServicesAll"].ToString() + ".aspx?");
}
protected void btnCancel_Click(object sender, System.EventArgs e)
{
Response.Redirect (strURL + Session["CallerServicesAll"].ToString() + ".aspx?");
}
protected void btnAddAll_Click(object sender, System.EventArgs e)
{
Session["CUpdResType"]="frmServiceTypesAll";
Response.Redirect (strURL + "frmUpdResourceType.aspx?"
+ "&btnAction=" + "Add");
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.Internal.VisualStudio.Shell;
using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell.TableManager;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
{
[Export(typeof(VisualStudioDiagnosticListTable))]
internal partial class VisualStudioDiagnosticListTable : VisualStudioBaseDiagnosticListTable
{
internal const string IdentifierString = nameof(VisualStudioDiagnosticListTable);
private readonly IErrorList _errorList;
private readonly LiveTableDataSource _liveTableSource;
private readonly BuildTableDataSource _buildTableSource;
private const string TypeScriptLanguageName = "TypeScript";
[ImportingConstructor]
public VisualStudioDiagnosticListTable(
SVsServiceProvider serviceProvider,
VisualStudioWorkspace workspace,
IDiagnosticService diagnosticService,
ExternalErrorDiagnosticUpdateSource errorSource,
ITableManagerProvider provider) :
this(serviceProvider, (Workspace)workspace, diagnosticService, errorSource, provider)
{
ConnectWorkspaceEvents();
_errorList = serviceProvider.GetService(typeof(SVsErrorList)) as IErrorList;
if (_errorList == null)
{
AddInitialTableSource(workspace.CurrentSolution, _liveTableSource);
return;
}
_errorList.PropertyChanged += OnErrorListPropertyChanged;
AddInitialTableSource(workspace.CurrentSolution, GetCurrentDataSource());
SuppressionStateColumnDefinition.SetDefaultFilter(_errorList.TableControl);
if (ErrorListHasFullSolutionAnalysisButton())
{
SetupErrorListFullSolutionAnalysis(workspace);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void SetupErrorListFullSolutionAnalysis(Workspace workspace)
{
var errorList2 = _errorList as IErrorList2;
if (errorList2 != null)
{
InitializeFullSolutionAnalysisState(workspace, errorList2);
errorList2.AnalysisToggleStateChanged += OnErrorListFullSolutionAnalysisToggled;
workspace.Services.GetService<IOptionService>().OptionChanged += OnOptionChanged;
}
}
private ITableDataSource GetCurrentDataSource()
{
if (_errorList == null)
{
return _liveTableSource;
}
return _errorList.AreOtherErrorSourceEntriesShown ? (ITableDataSource)_liveTableSource : _buildTableSource;
}
/// this is for test only
internal VisualStudioDiagnosticListTable(Workspace workspace, IDiagnosticService diagnosticService, ITableManagerProvider provider) :
this(null, workspace, diagnosticService, null, provider)
{
AddInitialTableSource(workspace.CurrentSolution, _liveTableSource);
}
private VisualStudioDiagnosticListTable(
SVsServiceProvider serviceProvider,
Workspace workspace,
IDiagnosticService diagnosticService,
ExternalErrorDiagnosticUpdateSource errorSource,
ITableManagerProvider provider) :
base(serviceProvider, workspace, diagnosticService, provider)
{
_liveTableSource = new LiveTableDataSource(serviceProvider, workspace, diagnosticService, IdentifierString);
_buildTableSource = new BuildTableDataSource(workspace, errorSource);
}
protected override void AddTableSourceIfNecessary(Solution solution)
{
if (solution.ProjectIds.Count == 0)
{
// whenever there is a change in solution, make sure we refresh static info
// of build errors so that things like project name correctly refreshed
_buildTableSource.RefreshAllFactories();
return;
}
RemoveTableSourcesIfNecessary();
AddTableSource(GetCurrentDataSource());
}
protected override void RemoveTableSourceIfNecessary(Solution solution)
{
if (solution.ProjectIds.Count > 0)
{
// whenever there is a change in solution, make sure we refresh static info
// of build errors so that things like project name correctly refreshed
_buildTableSource.RefreshAllFactories();
return;
}
RemoveTableSourcesIfNecessary();
}
private void RemoveTableSourcesIfNecessary()
{
RemoveTableSourceIfNecessary(_buildTableSource);
RemoveTableSourceIfNecessary(_liveTableSource);
}
private void RemoveTableSourceIfNecessary(ITableDataSource source)
{
if (!this.TableManager.Sources.Any(s => s == source))
{
return;
}
this.TableManager.RemoveSource(source);
}
protected override void ShutdownSource()
{
_liveTableSource.Shutdown();
_buildTableSource.Shutdown();
}
private void OnErrorListPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(IErrorList.AreOtherErrorSourceEntriesShown))
{
AddTableSourceIfNecessary(this.Workspace.CurrentSolution);
}
}
private void OnOptionChanged(object sender, OptionChangedEventArgs e)
{
Contract.ThrowIfFalse(_errorList is IErrorList2);
if (e.Option == RuntimeOptions.FullSolutionAnalysis || e.Option == ServiceFeatureOnOffOptions.ClosedFileDiagnostic)
{
var analysisDisabled = !(bool)e.Value;
if (analysisDisabled)
{
((IErrorList2)_errorList).AnalysisToggleState = false;
}
}
}
private void OnErrorListFullSolutionAnalysisToggled(object sender, AnalysisToggleStateChangedEventArgs e)
{
Workspace.Options = Workspace.Options
.WithChangedOption(RuntimeOptions.FullSolutionAnalysis, e.NewState)
.WithChangedOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, LanguageNames.CSharp, e.NewState)
.WithChangedOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, LanguageNames.VisualBasic, e.NewState)
.WithChangedOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, TypeScriptLanguageName, e.NewState);
}
private static void InitializeFullSolutionAnalysisState(Workspace workspace, IErrorList2 errorList2)
{
// Initialize the error list toggle state based on full solution analysis state for all supported languages.
var fullAnalysisState = workspace.Options.GetOption(RuntimeOptions.FullSolutionAnalysis) &&
ServiceFeatureOnOffOptions.IsClosedFileDiagnosticsEnabled(workspace, LanguageNames.CSharp) &&
ServiceFeatureOnOffOptions.IsClosedFileDiagnosticsEnabled(workspace, LanguageNames.VisualBasic) &&
ServiceFeatureOnOffOptions.IsClosedFileDiagnosticsEnabled(workspace, TypeScriptLanguageName);
errorList2.AnalysisToggleState = fullAnalysisState;
}
internal static bool ErrorListHasFullSolutionAnalysisButton()
{
try
{
// Full solution analysis option has been moved to the error list from Dev14 Update3.
// Use reflection to check if the new interface "IErrorList2" exists in Microsoft.VisualStudio.Shell.XX.0.dll.
return typeof(ErrorHandler).Assembly.GetType("Microsoft.Internal.VisualStudio.Shell.IErrorList2") != null;
}
catch (Exception)
{
// Ignore exceptions.
return false;
}
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityModel;
using IdentityServer4.Stores;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Newtonsoft.Json.Serialization;
using CryptoRandom = IdentityModel.CryptoRandom;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Builder extension methods for registering crypto services
/// </summary>
public static class IdentityServerBuilderExtensionsCrypto
{
/// <summary>
/// Sets the signing credential.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="credential">The credential.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddSigningCredential(this IIdentityServerBuilder builder, SigningCredentials credential)
{
// todo dom
if (!(credential.Key is AsymmetricSecurityKey
|| credential.Key is JsonWebKey && ((JsonWebKey)credential.Key).HasPrivateKey))
//&& !credential.Key.IsSupportedAlgorithm(SecurityAlgorithms.RsaSha256Signature))
{
throw new InvalidOperationException("Signing key is not asymmetric");
}
builder.Services.AddSingleton<ISigningCredentialStore>(new DefaultSigningCredentialsStore(credential));
builder.Services.AddSingleton<IValidationKeysStore>(new DefaultValidationKeysStore(new[] { credential.Key }));
return builder;
}
/// <summary>
/// Sets the signing credential.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="certificate">The certificate.</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="InvalidOperationException">X509 certificate does not have a private key.</exception>
public static IIdentityServerBuilder AddSigningCredential(this IIdentityServerBuilder builder, X509Certificate2 certificate)
{
if (certificate == null) throw new ArgumentNullException(nameof(certificate));
if (!certificate.HasPrivateKey)
{
throw new InvalidOperationException("X509 certificate does not have a private key.");
}
var credential = new SigningCredentials(new X509SecurityKey(certificate), "RS256");
return builder.AddSigningCredential(credential);
}
/// <summary>
/// Sets the signing credential.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="name">The name.</param>
/// <param name="location">The location.</param>
/// <param name="nameType">Name parameter can be either a distinguished name or a thumbprint</param>
/// <exception cref="InvalidOperationException">certificate: '{name}'</exception>
public static IIdentityServerBuilder AddSigningCredential(this IIdentityServerBuilder builder, string name, StoreLocation location = StoreLocation.LocalMachine, NameType nameType = NameType.SubjectDistinguishedName)
{
var certificate = FindCertificate(name, location, nameType);
if (certificate == null) throw new InvalidOperationException($"certificate: '{name}' not found in certificate store");
return builder.AddSigningCredential(certificate);
}
/// <summary>
/// Sets the signing credential.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="rsaKey">The RSA key.</param>
/// <returns></returns>
/// <exception cref="InvalidOperationException">RSA key does not have a private key.</exception>
public static IIdentityServerBuilder AddSigningCredential(this IIdentityServerBuilder builder, RsaSecurityKey rsaKey)
{
if (rsaKey.PrivateKeyStatus == PrivateKeyStatus.DoesNotExist)
{
throw new InvalidOperationException("RSA key does not have a private key.");
}
var credential = new SigningCredentials(rsaKey, "RS256");
return builder.AddSigningCredential(credential);
}
/// <summary>
/// Sets the temporary signing credential.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="persistKey">Specifies if the temporary key should be persisted to disk.</param>
/// <param name="filename">The filename.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddDeveloperSigningCredential(this IIdentityServerBuilder builder, bool persistKey = true, string filename = null)
{
if (filename == null)
{
filename = Path.Combine(Directory.GetCurrentDirectory(), "tempkey.rsa");
}
if (File.Exists(filename))
{
var keyFile = File.ReadAllText(filename);
var tempKey = JsonConvert.DeserializeObject<TemporaryRsaKey>(keyFile, new JsonSerializerSettings { ContractResolver = new RsaKeyContractResolver() });
return builder.AddSigningCredential(CreateRsaSecurityKey(tempKey.Parameters, tempKey.KeyId));
}
else
{
var key = CreateRsaSecurityKey();
RSAParameters parameters;
if (key.Rsa != null)
parameters = key.Rsa.ExportParameters(includePrivateParameters: true);
else
parameters = key.Parameters;
var tempKey = new TemporaryRsaKey
{
Parameters = parameters,
KeyId = key.KeyId
};
if (persistKey)
{
File.WriteAllText(filename, JsonConvert.SerializeObject(tempKey, new JsonSerializerSettings { ContractResolver = new RsaKeyContractResolver() }));
}
return builder.AddSigningCredential(key);
}
}
/// <summary>
/// Creates an RSA security key.
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <param name="id">The identifier.</param>
/// <returns></returns>
public static RsaSecurityKey CreateRsaSecurityKey(RSAParameters parameters, string id)
{
var key = new RsaSecurityKey(parameters)
{
KeyId = id
};
return key;
}
/// <summary>
/// Creates a new RSA security key.
/// </summary>
/// <returns></returns>
public static RsaSecurityKey CreateRsaSecurityKey()
{
var rsa = RSA.Create();
RsaSecurityKey key;
if (rsa is RSACryptoServiceProvider)
{
rsa.Dispose();
var cng = new RSACng(2048);
var parameters = cng.ExportParameters(includePrivateParameters: true);
key = new RsaSecurityKey(parameters);
}
else
{
rsa.KeySize = 2048;
key = new RsaSecurityKey(rsa);
}
key.KeyId = CryptoRandom.CreateUniqueId(16);
return key;
}
/// <summary>
/// Adds the validation keys.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="keys">The keys.</param>
/// <returns></returns>
public static IIdentityServerBuilder AddValidationKeys(this IIdentityServerBuilder builder, params AsymmetricSecurityKey[] keys)
{
builder.Services.AddSingleton<IValidationKeysStore>(new DefaultValidationKeysStore(keys));
return builder;
}
/// <summary>
/// Adds the validation key.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="certificate">The certificate.</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public static IIdentityServerBuilder AddValidationKey(this IIdentityServerBuilder builder, X509Certificate2 certificate)
{
if (certificate == null) throw new ArgumentNullException(nameof(certificate));
var key = new X509SecurityKey(certificate);
return builder.AddValidationKeys(key);
}
/// <summary>
/// Adds the validation key from the certificate store.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="name">The name.</param>
/// <param name="location">The location.</param>
/// <param name="nameType">Name parameter can be either a distinguished name or a thumbprint</param>
public static IIdentityServerBuilder AddValidationKey(this IIdentityServerBuilder builder, string name, StoreLocation location = StoreLocation.LocalMachine, NameType nameType = NameType.SubjectDistinguishedName)
{
var certificate = FindCertificate(name, location, nameType);
if (certificate == null) throw new InvalidOperationException($"certificate: '{name}' not found in certificate store");
return builder.AddValidationKey(certificate);
}
private static X509Certificate2 FindCertificate(string name, StoreLocation location, NameType nameType)
{
X509Certificate2 certificate = null;
if (location == StoreLocation.LocalMachine)
{
if (nameType == NameType.SubjectDistinguishedName)
{
certificate = X509.LocalMachine.My.SubjectDistinguishedName.Find(name, validOnly: false).FirstOrDefault();
}
else if (nameType == NameType.Thumbprint)
{
certificate = X509.LocalMachine.My.Thumbprint.Find(name, validOnly: false).FirstOrDefault();
}
}
else
{
if (nameType == NameType.SubjectDistinguishedName)
{
certificate = X509.CurrentUser.My.SubjectDistinguishedName.Find(name, validOnly: false).FirstOrDefault();
}
else if (nameType == NameType.Thumbprint)
{
certificate = X509.CurrentUser.My.Thumbprint.Find(name, validOnly: false).FirstOrDefault();
}
}
return certificate;
}
// used for serialization to temporary RSA key
private class TemporaryRsaKey
{
public string KeyId { get; set; }
public RSAParameters Parameters { get; set; }
}
private class RsaKeyContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
property.Ignored = false;
return property;
}
}
}
/// <summary>
/// Describes the string so we know what to search for in certificate store
/// </summary>
public enum NameType
{
/// <summary>
/// subject distinguished name
/// </summary>
SubjectDistinguishedName,
/// <summary>
/// thumbprint
/// </summary>
Thumbprint
}
}
| |
// <copyright file="DescriptiveStatisticsTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System.Linq;
using System.Collections.Generic;
using MathNet.Numerics.Distributions;
using MathNet.Numerics.Random;
using MathNet.Numerics.Statistics;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.StatisticsTests
{
/// <summary>
/// Running statistics tests.
/// </summary>
/// <remarks>NOTE: this class is not included into Silverlight version, because it uses data from local files.
/// In Silverlight access to local files is forbidden, except several cases.</remarks>
[TestFixture, Category("Statistics")]
public class RunningStatisticsTests
{
/// <summary>
/// Statistics data.
/// </summary>
readonly IDictionary<string, StatTestData> _data = new Dictionary<string, StatTestData>();
/// <summary>
/// Initializes a new instance of the DescriptiveStatisticsTests class.
/// </summary>
public RunningStatisticsTests()
{
_data.Add("lottery", new StatTestData("NIST.Lottery.dat"));
_data.Add("lew", new StatTestData("NIST.Lew.dat"));
_data.Add("mavro", new StatTestData("NIST.Mavro.dat"));
_data.Add("michelso", new StatTestData("NIST.Michelso.dat"));
_data.Add("numacc1", new StatTestData("NIST.NumAcc1.dat"));
_data.Add("numacc2", new StatTestData("NIST.NumAcc2.dat"));
_data.Add("numacc3", new StatTestData("NIST.NumAcc3.dat"));
_data.Add("numacc4", new StatTestData("NIST.NumAcc4.dat"));
_data.Add("meixner", new StatTestData("NIST.Meixner.dat"));
}
/// <summary>
/// <c>IEnumerable</c> Double.
/// </summary>
/// <param name="dataSet">Dataset name.</param>
/// <param name="digits">Digits count.</param>
/// <param name="skewness">Skewness value.</param>
/// <param name="kurtosis">Kurtosis value.</param>
/// <param name="median">Median value.</param>
/// <param name="min">Min value.</param>
/// <param name="max">Max value.</param>
/// <param name="count">Count value.</param>
[TestCase("lottery", 14, -0.09333165310779, -1.19256091074856, 522.5, 4, 999, 218)]
[TestCase("lew", 14, -0.050606638756334, -1.49604979214447, -162, -579, 300, 200)]
[TestCase("mavro", 11, 0.64492948110824, -0.82052379677456, 2.0018, 2.0013, 2.0027, 50)]
[TestCase("michelso", 11, -0.0185388637725746, 0.33968459842539, 299.85, 299.62, 300.07, 100)]
[TestCase("numacc1", 15, 0, double.NaN, 10000002, 10000001, 10000003, 3)]
[TestCase("numacc2", 13, 0, -2.003003003003, 1.2, 1.1, 1.3, 1001)]
[TestCase("numacc3", 9, 0, -2.003003003003, 1000000.2, 1000000.1, 1000000.3, 1001)]
[TestCase("numacc4", 7, 0, -2.00300300299913, 10000000.2, 10000000.1, 10000000.3, 1001)]
[TestCase("meixner", 8, -0.016649617280859657, 0.8171318629552635, -0.002042931016531602, -4.825626912281697, 5.3018298664184913, 10000)]
public void ConsistentWithNist(string dataSet, int digits, double skewness, double kurtosis, double median, double min, double max, int count)
{
var data = _data[dataSet];
var stats = new RunningStatistics(data.Data);
AssertHelpers.AlmostEqualRelative(data.Mean, stats.Mean, 10);
AssertHelpers.AlmostEqualRelative(data.StandardDeviation, stats.StandardDeviation, digits);
AssertHelpers.AlmostEqualRelative(skewness, stats.Skewness, 8);
AssertHelpers.AlmostEqualRelative(kurtosis, stats.Kurtosis, 8);
Assert.AreEqual(stats.Minimum, min);
Assert.AreEqual(stats.Maximum, max);
Assert.AreEqual(stats.Count, count);
}
[TestCase("lottery", 1e-8, -0.09268823, -0.09333165)]
[TestCase("lew", 1e-8, -0.0502263, -0.05060664)]
[TestCase("mavro", 1e-6, 0.6254181, 0.6449295)]
[TestCase("michelso", 1e-8, -0.01825961, -0.01853886)]
[TestCase("numacc1", 1e-8, 0, 0)]
//[TestCase("numacc2", 1e-20, 3.254232e-15, 3.259118e-15)] TODO: accuracy
//[TestCase("numacc3", 1e-14, 1.747103e-09, 1.749726e-09)] TODO: accuracy
//[TestCase("numacc4", 1e-13, 2.795364e-08, 2.799561e-08)] TODO: accuracy
[TestCase("meixner", 1e-8, -0.01664712, -0.01664962)]
public void SkewnessConsistentWithR_e1071(string dataSet, double delta, double skewnessType1, double skewnessType2)
{
var data = _data[dataSet];
var stats = new RunningStatistics(data.Data);
Assert.That(stats.Skewness, Is.EqualTo(skewnessType2).Within(delta), "Skewness");
Assert.That(stats.PopulationSkewness, Is.EqualTo(skewnessType1).Within(delta), "PopulationSkewness");
}
[TestCase("lottery", -1.192781, -1.192561)]
[TestCase("lew", -1.48876, -1.49605)]
[TestCase("mavro", -0.858384, -0.8205238)]
[TestCase("michelso", 0.2635305, 0.3396846)]
[TestCase("numacc1", -1.5, double.NaN)]
[TestCase("numacc2", -1.999, -2.003003)]
[TestCase("numacc3", -1.999, -2.003003)]
[TestCase("numacc4", -1.999, -2.003003)]
[TestCase("meixner", 0.8161234, 0.8171319)]
public void KurtosisConsistentWithR_e1071(string dataSet, double kurtosisType1, double kurtosisType2)
{
var data = _data[dataSet];
var stats = new RunningStatistics(data.Data);
Assert.That(stats.Kurtosis, Is.EqualTo(kurtosisType2).Within(1e-6), "Kurtosis");
Assert.That(stats.PopulationKurtosis, Is.EqualTo(kurtosisType1).Within(1e-6), "PopulationKurtosis");
}
[Test]
public void ShortSequences()
{
var stats0 = new RunningStatistics(new double[0]);
Assert.That(stats0.Skewness, Is.NaN);
Assert.That(stats0.Kurtosis, Is.NaN);
var stats1 = new RunningStatistics(new[] { 1.0 });
Assert.That(stats1.Skewness, Is.NaN);
Assert.That(stats1.Kurtosis, Is.NaN);
var stats2 = new RunningStatistics(new[] { 1.0, 2.0 });
Assert.That(stats2.Skewness, Is.NaN);
Assert.That(stats2.Kurtosis, Is.NaN);
var stats3 = new RunningStatistics(new[] { 1.0, 2.0, -3.0 });
Assert.That(stats3.Skewness, Is.Not.NaN);
Assert.That(stats3.Kurtosis, Is.NaN);
var stats4 = new RunningStatistics(new[] { 1.0, 2.0, -3.0, -4.0 });
Assert.That(stats4.Skewness, Is.Not.NaN);
Assert.That(stats4.Kurtosis, Is.Not.NaN);
}
[Test]
public void ZeroVarianceSequence()
{
var stats = new RunningStatistics(new[] { 2.0, 2.0, 2.0, 2.0 });
Assert.That(stats.Skewness, Is.NaN);
Assert.That(stats.Kurtosis, Is.NaN);
}
[Test]
public void Combine()
{
var rnd = new SystemRandomSource(10);
var a = Generate.Random(200, new Erlang(2, 0.2, rnd));
var b = Generate.Random(100, new Beta(1.2, 1.4, rnd));
var c = Generate.Random(150, new Rayleigh(0.8, rnd));
var d = a.Concat(b).Concat(c).ToArray();
var x = new RunningStatistics(d);
var y = new RunningStatistics(a);
y.PushRange(b);
y.PushRange(c);
var za = new RunningStatistics(a);
var zb = new RunningStatistics(b);
var zc = new RunningStatistics(c);
var z = za + zb + zc;
Assert.That(x.Mean, Is.EqualTo(d.Mean()).Within(1e-12), "Mean Reference");
Assert.That(y.Mean, Is.EqualTo(x.Mean).Within(1e-12), "Mean y");
Assert.That(z.Mean, Is.EqualTo(x.Mean).Within(1e-12), "Mean z");
Assert.That(x.Variance, Is.EqualTo(d.Variance()).Within(1e-12), "Variance Reference");
Assert.That(y.Variance, Is.EqualTo(x.Variance).Within(1e-12), "Variance y");
Assert.That(z.Variance, Is.EqualTo(x.Variance).Within(1e-12), "Variance z");
Assert.That(x.PopulationVariance, Is.EqualTo(d.PopulationVariance()).Within(1e-12), "PopulationVariance Reference");
Assert.That(y.PopulationVariance, Is.EqualTo(x.PopulationVariance).Within(1e-12), "PopulationVariance y");
Assert.That(z.PopulationVariance, Is.EqualTo(x.PopulationVariance).Within(1e-12), "PopulationVariance z");
Assert.That(x.StandardDeviation, Is.EqualTo(d.StandardDeviation()).Within(1e-12), "StandardDeviation Reference");
Assert.That(y.StandardDeviation, Is.EqualTo(x.StandardDeviation).Within(1e-12), "StandardDeviation y");
Assert.That(z.StandardDeviation, Is.EqualTo(x.StandardDeviation).Within(1e-12), "StandardDeviation z");
Assert.That(x.PopulationStandardDeviation, Is.EqualTo(d.PopulationStandardDeviation()).Within(1e-12), "PopulationStandardDeviation Reference");
Assert.That(y.PopulationStandardDeviation, Is.EqualTo(x.PopulationStandardDeviation).Within(1e-12), "PopulationStandardDeviation y");
Assert.That(z.PopulationStandardDeviation, Is.EqualTo(x.PopulationStandardDeviation).Within(1e-12), "PopulationStandardDeviation z");
Assert.That(x.Skewness, Is.EqualTo(d.Skewness()).Within(1e-12), "Skewness Reference (not independent!)");
Assert.That(y.Skewness, Is.EqualTo(x.Skewness).Within(1e-12), "Skewness y");
Assert.That(z.Skewness, Is.EqualTo(x.Skewness).Within(1e-12), "Skewness z");
Assert.That(x.PopulationSkewness, Is.EqualTo(d.PopulationSkewness()).Within(1e-12), "PopulationSkewness Reference (not independent!)");
Assert.That(y.PopulationSkewness, Is.EqualTo(x.PopulationSkewness).Within(1e-12), "PopulationSkewness y");
Assert.That(z.PopulationSkewness, Is.EqualTo(x.PopulationSkewness).Within(1e-12), "PopulationSkewness z");
Assert.That(x.Kurtosis, Is.EqualTo(d.Kurtosis()).Within(1e-12), "Kurtosis Reference (not independent!)");
Assert.That(y.Kurtosis, Is.EqualTo(x.Kurtosis).Within(1e-12), "Kurtosis y");
Assert.That(z.Kurtosis, Is.EqualTo(x.Kurtosis).Within(1e-12), "Kurtosis z");
Assert.That(x.PopulationKurtosis, Is.EqualTo(d.PopulationKurtosis()).Within(1e-12), "PopulationKurtosis Reference (not independent!)");
Assert.That(y.PopulationKurtosis, Is.EqualTo(x.PopulationKurtosis).Within(1e-12), "PopulationKurtosis y");
Assert.That(z.PopulationKurtosis, Is.EqualTo(x.PopulationKurtosis).Within(1e-12), "PopulationKurtosis z");
}
}
}
| |
using UnityEngine;
using System;
using System.Collections.Generic;
using PixelCrushers.DialogueSystem.UnityGUI;
namespace PixelCrushers.DialogueSystem {
/// <summary>
/// This component implements a proximity-based selector that allows the player to move into
/// range and use a usable object.
///
/// To mark an object usable, add the Usable component and a collider to it. The object's
/// layer should be in the layer mask specified on the Selector component.
///
/// The proximity selector tracks the most recent usable object whose trigger the player has
/// entered. It displays a targeting reticle and information about the object. If the target
/// is in range, the inRange reticle texture is displayed; otherwise the outOfRange texture is
/// displayed.
///
/// If the player presses the use button (which defaults to spacebar and Fire2), the targeted
/// object will receive an "OnUse" message.
///
/// You can hook into SelectedUsableObject and DeselectedUsableObject to get notifications
/// when the current target has changed.
/// </summary>
[AddComponentMenu("Dialogue System/Actor/Player/Proximity Selector")]
public class ProximitySelector : MonoBehaviour {
/// <summary>
/// This class defines the textures and size of the targeting reticle.
/// </summary>
[System.Serializable]
public class Reticle {
public Texture2D inRange;
public Texture2D outOfRange;
public float width = 64f;
public float height = 64f;
}
/// <summary>
/// If <c>true</c>, uses a default OnGUI to display a selection message and
/// targeting reticle.
/// </summary>
public bool useDefaultGUI = true;
/// <summary>
/// The GUI skin to use for the target's information (name and use message).
/// </summary>
public GUISkin guiSkin;
/// <summary>
/// The name of the GUI style in the skin.
/// </summary>
public string guiStyleName = "label";
/// <summary>
/// The text alignment.
/// </summary>
public TextAnchor alignment = TextAnchor.UpperCenter;
/// <summary>
/// The color of the information labels when the target is in range.
/// </summary>
public Color color = Color.yellow;
/// <summary>
/// The text style for the text.
/// </summary>
public TextStyle textStyle = TextStyle.Shadow;
/// <summary>
/// The color of the text style's outline or shadow.
/// </summary>
public Color textStyleColor = Color.black;
/// <summary>
/// The default use message. This can be overridden in the target's Usable component.
/// </summary>
public string defaultUseMessage = "(spacebar to interact)";
/// <summary>
/// The key that sends an OnUse message.
/// </summary>
public KeyCode useKey = KeyCode.Space;
/// <summary>
/// The button that sends an OnUse message.
/// </summary>
public string useButton = "Fire2";
/// <summary>
/// Tick to enable touch triggering.
/// </summary>
public bool enableTouch = false;
/// <summary>
/// If touch triggering is enabled and there's a touch in this area,
/// the selector triggers.
/// </summary>
public ScaledRect touchArea = new ScaledRect(ScaledRect.empty);
/// <summary>
/// If ticked, the OnUse message is broadcast to the usable object's children.
/// </summary>
public bool broadcastToChildren = true;
/// <summary>
/// The actor transform to send with OnUse. Defaults to this transform.
/// </summary>
public Transform actorTransform = null;
/// <summary>
/// Occurs when the selector has targeted a usable object.
/// </summary>
public event SelectedUsableObjectDelegate SelectedUsableObject = null;
/// <summary>
/// Occurs when the selector has untargeted a usable object.
/// </summary>
public event DeselectedUsableObjectDelegate DeselectedUsableObject = null;
/// <summary>
/// Gets the current usable.
/// </summary>
/// <value>The usable.</value>
public Usable CurrentUsable { get { return currentUsable; } }
/// <summary>
/// Gets the GUI style.
/// </summary>
/// <value>The GUI style.</value>
public GUIStyle GuiStyle { get { SetGuiStyle(); return guiStyle; } }
/// <summary>
/// Keeps track of which usable objects' triggers the selector is currently inside.
/// </summary>
private List<Usable> usablesInRange = new List<Usable>();
/// <summary>
/// The current usable that will receive an OnUse message if the player hits the use button.
/// </summary>
private Usable currentUsable = null;
private string currentHeading = string.Empty;
private string currentUseMessage = string.Empty;
/// <summary>
/// Caches the GUI style to use when displaying the selection message in OnGUI.
/// </summary>
private GUIStyle guiStyle = null;
private const float MinTimeBetweenUseButton = 0.5f;
private float timeToEnableUseButton = 0;
/// <summary>
/// Sends an OnUse message to the current selection if the player presses the use button.
/// </summary>
void Update() {
// Exit if disabled or paused:
if (!enabled || (Time.timeScale <= 0)) return;
if (DialogueManager.IsConversationActive) timeToEnableUseButton = Time.time + MinTimeBetweenUseButton;
// If the player presses the use key/button, send the OnUse message:
if (IsUseButtonDown() && (currentUsable != null) && (Time.time >= timeToEnableUseButton)) {
var fromTransform = (actorTransform != null) ? actorTransform : this.transform;
if (broadcastToChildren) {
currentUsable.gameObject.BroadcastMessage("OnUse", fromTransform, SendMessageOptions.DontRequireReceiver);
} else {
currentUsable.gameObject.SendMessage("OnUse", fromTransform, SendMessageOptions.DontRequireReceiver);
}
}
}
/// <summary>
/// Checks whether the player has just pressed the use button.
/// </summary>
/// <returns>
/// <c>true</c> if the use button/key is down; otherwise, <c>false</c>.
/// </returns>
private bool IsUseButtonDown() {
if (enableTouch && IsTouchDown()) return true;
return ((useKey != KeyCode.None) && Input.GetKeyDown(useKey))
|| (!string.IsNullOrEmpty(useButton) && Input.GetButtonUp(useButton));
}
private bool IsTouchDown() {
if (Input.touchCount >= 1){
foreach (Touch touch in Input.touches) {
Vector2 screenPosition = new Vector2(touch.position.x, Screen.height - touch.position.y);
if (touchArea.GetPixelRect().Contains(screenPosition)) return true;
}
}
return false;
}
/// <summary>
/// If we entered a trigger, check if it's a usable object. If so, update the selection
/// and raise the SelectedUsableObject event.
/// </summary>
/// <param name='other'>
/// The trigger collider.
/// </param>
void OnTriggerEnter(Collider other) {
CheckTriggerEnter(other.gameObject);
}
/// <summary>
/// If we entered a 2D trigger, check if it's a usable object. If so, update the selection
/// and raise the SelectedUsableObject event.
/// </summary>
/// <param name='other'>
/// The 2D trigger collider.
/// </param>
void OnTriggerEnter2D(Collider2D other) {
CheckTriggerEnter(other.gameObject);
}
/// <summary>
/// If we just left a trigger, check if it's the current selection. If so, clear the
/// selection and raise the DeselectedUsableObject event. If we're still in range of
/// any other usables, select one of them.
/// </summary>
/// <param name='other'>
/// The trigger collider.
/// </param>
void OnTriggerExit(Collider other) {
CheckTriggerExit(other.gameObject);
}
/// <summary>
/// If we just left a 2D trigger, check if it's the current selection. If so, clear the
/// selection and raise the DeselectedUsableObject event. If we're still in range of
/// any other usables, select one of them.
/// </summary>
/// <param name='other'>
/// The 2D trigger collider.
/// </param>
void OnTriggerExit2D(Collider2D other) {
CheckTriggerExit(other.gameObject);
}
private void CheckTriggerEnter(GameObject other) {
Usable usable = other.GetComponent<Usable>();
if (usable != null) {
SetCurrentUsable(usable);
if (!usablesInRange.Contains(usable)) usablesInRange.Add(usable);
if (SelectedUsableObject != null) SelectedUsableObject(usable);
}
}
private void CheckTriggerExit(GameObject other) {
Usable usable = other.GetComponent<Usable>();
if (usable != null) {
if (usablesInRange.Contains(usable)) usablesInRange.Remove(usable);
if (currentUsable == usable) {
if (DeselectedUsableObject != null) DeselectedUsableObject(usable);
Usable newUsable = null;
if (usablesInRange.Count > 0) {
newUsable = usablesInRange[0];
if (SelectedUsableObject != null) SelectedUsableObject(newUsable);
}
SetCurrentUsable(newUsable);
}
}
}
private void SetCurrentUsable(Usable usable) {
currentUsable = usable;
if (usable != null) {
currentHeading = currentUsable.GetName();
currentUseMessage = string.IsNullOrEmpty(currentUsable.overrideUseMessage) ? defaultUseMessage : currentUsable.overrideUseMessage;
} else {
currentHeading = string.Empty;
currentUseMessage = string.Empty;
}
}
/// <summary>
/// If useDefaultGUI is <c>true</c> and a usable object has been targeted, this method
/// draws a selection message and targeting reticle.
/// </summary>
public virtual void OnGUI() {
if (useDefaultGUI) {
SetGuiStyle();
Rect screenRect = new Rect(0, 0, Screen.width, Screen.height);
if (currentUsable != null) {
UnityGUITools.DrawText(screenRect, currentHeading, guiStyle, textStyle, textStyleColor);
UnityGUITools.DrawText(new Rect(0, guiStyle.CalcSize(new GUIContent("Ay")).y, Screen.width, Screen.height), currentUseMessage, guiStyle, textStyle, textStyleColor);
}
}
}
protected void SetGuiStyle() {
GUI.skin = UnityGUITools.GetValidGUISkin(guiSkin);
if (guiStyle == null) {
guiStyle = new GUIStyle(GUI.skin.FindStyle(guiStyleName) ?? GUI.skin.label);
guiStyle.alignment = alignment;
guiStyle.normal.textColor = color;
}
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// ConcurrentStack.cs
//
// A lock-free, concurrent stack primitive, and its associated debugger view type.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
namespace System.Collections.Concurrent
{
// A stack that uses CAS operations internally to maintain thread-safety in a lock-free
// manner. Attempting to push or pop concurrently from the stack will not trigger waiting,
// although some optimistic concurrency and retry is used, possibly leading to lack of
// fairness and/or livelock. The stack uses spinning and backoff to add some randomization,
// in hopes of statistically decreasing the possibility of livelock.
//
// Note that we currently allocate a new node on every push. This avoids having to worry
// about potential ABA issues, since the CLR GC ensures that a memory address cannot be
// reused before all references to it have died.
/// <summary>
/// Represents a thread-safe last-in, first-out collection of objects.
/// </summary>
/// <typeparam name="T">Specifies the type of elements in the stack.</typeparam>
/// <remarks>
/// All public and protected members of <see cref="ConcurrentStack{T}"/> are thread-safe and may be used
/// concurrently from multiple threads.
/// </remarks>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(IProducerConsumerCollectionDebugView<>))]
public class ConcurrentStack<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T>
{
/// <summary>
/// A simple (internal) node type used to store elements of concurrent stacks and queues.
/// </summary>
private class Node
{
internal readonly T _value; // Value of the node.
internal Node? _next; // Next pointer.
/// <summary>
/// Constructs a new node with the specified value and no next node.
/// </summary>
/// <param name="value">The value of the node.</param>
internal Node(T value)
{
_value = value;
_next = null;
}
}
private volatile Node? _head; // The stack is a singly linked list, and only remembers the head.
private const int BACKOFF_MAX_YIELDS = 8; // Arbitrary number to cap backoff.
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentStack{T}"/>
/// class.
/// </summary>
public ConcurrentStack()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentStack{T}"/>
/// class that contains elements copied from the specified collection
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new <see
/// cref="ConcurrentStack{T}"/>.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="collection"/> argument is
/// null.</exception>
public ConcurrentStack(IEnumerable<T> collection)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
InitializeFromCollection(collection);
}
/// <summary>
/// Initializes the contents of the stack from an existing collection.
/// </summary>
/// <param name="collection">A collection from which to copy elements.</param>
private void InitializeFromCollection(IEnumerable<T> collection)
{
// We just copy the contents of the collection to our stack.
Node? lastNode = null;
foreach (T element in collection)
{
Node newNode = new Node(element);
newNode._next = lastNode;
lastNode = newNode;
}
_head = lastNode;
}
/// <summary>
/// Gets a value that indicates whether the <see cref="ConcurrentStack{T}"/> is empty.
/// </summary>
/// <value>true if the <see cref="ConcurrentStack{T}"/> is empty; otherwise, false.</value>
/// <remarks>
/// For determining whether the collection contains any items, use of this property is recommended
/// rather than retrieving the number of items from the <see cref="Count"/> property and comparing it
/// to 0. However, as this collection is intended to be accessed concurrently, it may be the case
/// that another thread will modify the collection after <see cref="IsEmpty"/> returns, thus invalidating
/// the result.
/// </remarks>
public bool IsEmpty
{
// Checks whether the stack is empty. Clearly the answer may be out of date even prior to
// the function returning (i.e. if another thread concurrently adds to the stack). It does
// guarantee, however, that, if another thread does not mutate the stack, a subsequent call
// to TryPop will return true -- i.e. it will also read the stack as non-empty.
get { return _head == null; }
}
/// <summary>
/// Gets the number of elements contained in the <see cref="ConcurrentStack{T}"/>.
/// </summary>
/// <value>The number of elements contained in the <see cref="ConcurrentStack{T}"/>.</value>
/// <remarks>
/// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/>
/// property is recommended rather than retrieving the number of items from the <see cref="Count"/>
/// property and comparing it to 0.
/// </remarks>
public int Count
{
// Counts the number of entries in the stack. This is an O(n) operation. The answer may be out
// of date before returning, but guarantees to return a count that was once valid. Conceptually,
// the implementation snaps a copy of the list and then counts the entries, though physically
// this is not what actually happens.
get
{
int count = 0;
// Just whip through the list and tally up the number of nodes. We rely on the fact that
// node next pointers are immutable after being enqueued for the first time, even as
// they are being dequeued. If we ever changed this (e.g. to pool nodes somehow),
// we'd need to revisit this implementation.
for (Node? curr = _head; curr != null; curr = curr._next)
{
count++; //we don't handle overflow, to be consistent with existing generic collection types in CLR
}
return count;
}
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="System.Collections.ICollection"/> is
/// synchronized with the SyncRoot.
/// </summary>
/// <value>true if access to the <see cref="System.Collections.ICollection"/> is synchronized
/// with the SyncRoot; otherwise, false. For <see cref="ConcurrentStack{T}"/>, this property always
/// returns false.</value>
bool ICollection.IsSynchronized
{
// Gets a value indicating whether access to this collection is synchronized. Always returns
// false. The reason is subtle. While access is in face thread safe, it's not the case that
// locking on the SyncRoot would have prevented concurrent pushes and pops, as this property
// would typically indicate; that's because we internally use CAS operations vs. true locks.
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the <see
/// cref="System.Collections.ICollection"/>. This property is not supported.
/// </summary>
/// <exception cref="System.NotSupportedException">The SyncRoot property is not supported</exception>
object ICollection.SyncRoot
{
get
{
throw new NotSupportedException(SR.ConcurrentCollection_SyncRoot_NotSupported);
}
}
/// <summary>
/// Removes all objects from the <see cref="ConcurrentStack{T}"/>.
/// </summary>
public void Clear()
{
// Clear the list by setting the head to null. We don't need to use an atomic
// operation for this: anybody who is mutating the head by pushing or popping
// will need to use an atomic operation to guarantee they serialize and don't
// overwrite our setting of the head to null.
_head = null;
}
/// <summary>
/// Copies the elements of the <see cref="System.Collections.ICollection"/> to an <see
/// cref="System.Array"/>, starting at a particular
/// <see cref="System.Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="System.Array"/> that is the destination of
/// the elements copied from the
/// <see cref="ConcurrentStack{T}"/>. The <see cref="System.Array"/> must
/// have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying
/// begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
/// Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
/// zero.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="array"/> is multidimensional. -or-
/// <paramref name="array"/> does not have zero-based indexing. -or-
/// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/>
/// -or- The number of elements in the source <see cref="System.Collections.ICollection"/> is
/// greater than the available space from <paramref name="index"/> to the end of the destination
/// <paramref name="array"/>. -or- The type of the source <see
/// cref="System.Collections.ICollection"/> cannot be cast automatically to the type of the
/// destination <paramref name="array"/>.
/// </exception>
void ICollection.CopyTo(Array array, int index)
{
// Validate arguments.
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
// We must be careful not to corrupt the array, so we will first accumulate an
// internal list of elements that we will then copy to the array. This requires
// some extra allocation, but is necessary since we don't know up front whether
// the array is sufficiently large to hold the stack's contents.
((ICollection)ToList()).CopyTo(array, index);
}
/// <summary>
/// Copies the <see cref="ConcurrentStack{T}"/> elements to an existing one-dimensional <see
/// cref="System.Array"/>, starting at the specified array index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="System.Array"/> that is the destination of
/// the elements copied from the
/// <see cref="ConcurrentStack{T}"/>. The <see cref="System.Array"/> must have zero-based
/// indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying
/// begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
/// Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
/// zero.</exception>
/// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the
/// length of the <paramref name="array"/>
/// -or- The number of elements in the source <see cref="ConcurrentStack{T}"/> is greater than the
/// available space from <paramref name="index"/> to the end of the destination <paramref
/// name="array"/>.
/// </exception>
public void CopyTo(T[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
// We must be careful not to corrupt the array, so we will first accumulate an
// internal list of elements that we will then copy to the array. This requires
// some extra allocation, but is necessary since we don't know up front whether
// the array is sufficiently large to hold the stack's contents.
ToList().CopyTo(array, index);
}
/// <summary>
/// Inserts an object at the top of the <see cref="ConcurrentStack{T}"/>.
/// </summary>
/// <param name="item">The object to push onto the <see cref="ConcurrentStack{T}"/>. The value can be
/// a null reference (Nothing in Visual Basic) for reference types.
/// </param>
public void Push(T item)
{
// Pushes a node onto the front of the stack thread-safely. Internally, this simply
// swaps the current head pointer using a (thread safe) CAS operation to accomplish
// lock freedom. If the CAS fails, we add some back off to statistically decrease
// contention at the head, and then go back around and retry.
Node newNode = new Node(item);
newNode._next = _head;
if (Interlocked.CompareExchange(ref _head, newNode, newNode._next) == newNode._next)
{
return;
}
// If we failed, go to the slow path and loop around until we succeed.
PushCore(newNode, newNode);
}
/// <summary>
/// Inserts multiple objects at the top of the <see cref="ConcurrentStack{T}"/> atomically.
/// </summary>
/// <param name="items">The objects to push onto the <see cref="ConcurrentStack{T}"/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference
/// (Nothing in Visual Basic).</exception>
/// <remarks>
/// When adding multiple items to the stack, using PushRange is a more efficient
/// mechanism than using <see cref="Push"/> one item at a time. Additionally, PushRange
/// guarantees that all of the elements will be added atomically, meaning that no other threads will
/// be able to inject elements between the elements being pushed. Items at lower indices in
/// the <paramref name="items"/> array will be pushed before items at higher indices.
/// </remarks>
public void PushRange(T[] items)
{
if (items == null)
{
throw new ArgumentNullException(nameof(items));
}
PushRange(items, 0, items.Length);
}
/// <summary>
/// Inserts multiple objects at the top of the <see cref="ConcurrentStack{T}"/> atomically.
/// </summary>
/// <param name="items">The objects to push onto the <see cref="ConcurrentStack{T}"/>.</param>
/// <param name="startIndex">The zero-based offset in <paramref name="items"/> at which to begin
/// inserting elements onto the top of the <see cref="ConcurrentStack{T}"/>.</param>
/// <param name="count">The number of elements to be inserted onto the top of the <see
/// cref="ConcurrentStack{T}"/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference
/// (Nothing in Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="startIndex"/> or <paramref
/// name="count"/> is negative. Or <paramref name="startIndex"/> is greater than or equal to the length
/// of <paramref name="items"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="startIndex"/> + <paramref name="count"/> is
/// greater than the length of <paramref name="items"/>.</exception>
/// <remarks>
/// When adding multiple items to the stack, using PushRange is a more efficient
/// mechanism than using <see cref="Push"/> one item at a time. Additionally, PushRange
/// guarantees that all of the elements will be added atomically, meaning that no other threads will
/// be able to inject elements between the elements being pushed. Items at lower indices in the
/// <paramref name="items"/> array will be pushed before items at higher indices.
/// </remarks>
public void PushRange(T[] items, int startIndex, int count)
{
ValidatePushPopRangeInput(items, startIndex, count);
// No op if the count is zero
if (count == 0)
return;
Node head, tail;
head = tail = new Node(items[startIndex]);
for (int i = startIndex + 1; i < startIndex + count; i++)
{
Node node = new Node(items[i]);
node._next = head;
head = node;
}
tail._next = _head;
if (Interlocked.CompareExchange(ref _head, head, tail._next) == tail._next)
{
return;
}
// If we failed, go to the slow path and loop around until we succeed.
PushCore(head, tail);
}
/// <summary>
/// Push one or many nodes into the stack, if head and tails are equal then push one node to the stack other wise push the list between head
/// and tail to the stack
/// </summary>
/// <param name="head">The head pointer to the new list</param>
/// <param name="tail">The tail pointer to the new list</param>
private void PushCore(Node head, Node tail)
{
SpinWait spin = new SpinWait();
// Keep trying to CAS the existing head with the new node until we succeed.
do
{
spin.SpinOnce(sleep1Threshold: -1);
// Reread the head and link our new node.
tail._next = _head;
}
while (Interlocked.CompareExchange(
ref _head, head, tail._next) != tail._next);
if (CDSCollectionETWBCLProvider.Log.IsEnabled())
{
CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPushFailed(spin.Count);
}
}
/// <summary>
/// Local helper function to validate the Pop Push range methods input
/// </summary>
private static void ValidatePushPopRangeInput(T[] items, int startIndex, int count)
{
if (items == null)
{
throw new ArgumentNullException(nameof(items));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ConcurrentStack_PushPopRange_CountOutOfRange);
}
int length = items.Length;
if (startIndex >= length || startIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ConcurrentStack_PushPopRange_StartOutOfRange);
}
if (length - count < startIndex) //instead of (startIndex + count > items.Length) to prevent overflow
{
throw new ArgumentException(SR.ConcurrentStack_PushPopRange_InvalidCount);
}
}
/// <summary>
/// Attempts to add an object to the <see
/// cref="System.Collections.Concurrent.IProducerConsumerCollection{T}"/>.
/// </summary>
/// <param name="item">The object to add to the <see
/// cref="System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. The value can be a null
/// reference (Nothing in Visual Basic) for reference types.
/// </param>
/// <returns>true if the object was added successfully; otherwise, false.</returns>
/// <remarks>For <see cref="ConcurrentStack{T}"/>, this operation
/// will always insert the object onto the top of the <see cref="ConcurrentStack{T}"/>
/// and return true.</remarks>
bool IProducerConsumerCollection<T>.TryAdd(T item)
{
Push(item);
return true;
}
/// <summary>
/// Attempts to return an object from the top of the <see cref="ConcurrentStack{T}"/>
/// without removing it.
/// </summary>
/// <param name="result">When this method returns, <paramref name="result"/> contains an object from
/// the top of the <see cref="System.Collections.Concurrent.ConcurrentStack{T}"/> or an
/// unspecified value if the operation failed.</param>
/// <returns>true if and object was returned successfully; otherwise, false.</returns>
public bool TryPeek([MaybeNullWhen(false)] out T result)
{
Node? head = _head;
// If the stack is empty, return false; else return the element and true.
if (head == null)
{
result = default(T)!;
return false;
}
else
{
result = head._value;
return true;
}
}
/// <summary>
/// Attempts to pop and return the object at the top of the <see cref="ConcurrentStack{T}"/>.
/// </summary>
/// <param name="result">
/// When this method returns, if the operation was successful, <paramref name="result"/> contains the
/// object removed. If no object was available to be removed, the value is unspecified.
/// </param>
/// <returns>true if an element was removed and returned from the top of the <see
/// cref="ConcurrentStack{T}"/>
/// successfully; otherwise, false.</returns>
public bool TryPop([MaybeNullWhen(false)] out T result)
{
Node? head = _head;
//stack is empty
if (head == null)
{
result = default(T)!;
return false;
}
if (Interlocked.CompareExchange(ref _head, head._next, head) == head)
{
result = head._value;
return true;
}
// Fall through to the slow path.
return TryPopCore(out result);
}
/// <summary>
/// Attempts to pop and return multiple objects from the top of the <see cref="ConcurrentStack{T}"/>
/// atomically.
/// </summary>
/// <param name="items">
/// The <see cref="System.Array"/> to which objects popped from the top of the <see
/// cref="ConcurrentStack{T}"/> will be added.
/// </param>
/// <returns>The number of objects successfully popped from the top of the <see
/// cref="ConcurrentStack{T}"/> and inserted in
/// <paramref name="items"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="items"/> is a null argument (Nothing
/// in Visual Basic).</exception>
/// <remarks>
/// When popping multiple items, if there is little contention on the stack, using
/// TryPopRange can be more efficient than using <see cref="TryPop"/>
/// once per item to be removed. Nodes fill the <paramref name="items"/>
/// with the first node to be popped at the startIndex, the second node to be popped
/// at startIndex + 1, and so on.
/// </remarks>
public int TryPopRange(T[] items)
{
if (items == null)
{
throw new ArgumentNullException(nameof(items));
}
return TryPopRange(items, 0, items.Length);
}
/// <summary>
/// Attempts to pop and return multiple objects from the top of the <see cref="ConcurrentStack{T}"/>
/// atomically.
/// </summary>
/// <param name="items">
/// The <see cref="System.Array"/> to which objects popped from the top of the <see
/// cref="ConcurrentStack{T}"/> will be added.
/// </param>
/// <param name="startIndex">The zero-based offset in <paramref name="items"/> at which to begin
/// inserting elements from the top of the <see cref="ConcurrentStack{T}"/>.</param>
/// <param name="count">The number of elements to be popped from top of the <see
/// cref="ConcurrentStack{T}"/> and inserted into <paramref name="items"/>.</param>
/// <returns>The number of objects successfully popped from the top of
/// the <see cref="ConcurrentStack{T}"/> and inserted in <paramref name="items"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference
/// (Nothing in Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="startIndex"/> or <paramref
/// name="count"/> is negative. Or <paramref name="startIndex"/> is greater than or equal to the length
/// of <paramref name="items"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="startIndex"/> + <paramref name="count"/> is
/// greater than the length of <paramref name="items"/>.</exception>
/// <remarks>
/// When popping multiple items, if there is little contention on the stack, using
/// TryPopRange can be more efficient than using <see cref="TryPop"/>
/// once per item to be removed. Nodes fill the <paramref name="items"/>
/// with the first node to be popped at the startIndex, the second node to be popped
/// at startIndex + 1, and so on.
/// </remarks>
public int TryPopRange(T[] items, int startIndex, int count)
{
ValidatePushPopRangeInput(items, startIndex, count);
// No op if the count is zero
if (count == 0)
return 0;
Node? poppedHead;
int nodesCount = TryPopCore(count, out poppedHead);
if (nodesCount > 0)
{
CopyRemovedItems(poppedHead!, items, startIndex, nodesCount);
}
return nodesCount;
}
/// <summary>
/// Local helper function to Pop an item from the stack, slow path
/// </summary>
/// <param name="result">The popped item</param>
/// <returns>True if succeeded, false otherwise</returns>
private bool TryPopCore([MaybeNullWhen(false)] out T result)
{
Node? poppedNode;
if (TryPopCore(1, out poppedNode) == 1)
{
result = poppedNode!._value;
return true;
}
result = default(T)!;
return false;
}
/// <summary>
/// Slow path helper for TryPop. This method assumes an initial attempt to pop an element
/// has already occurred and failed, so it begins spinning right away.
/// </summary>
/// <param name="count">The number of items to pop.</param>
/// <param name="poppedHead">
/// When this method returns, if the pop succeeded, contains the removed object. If no object was
/// available to be removed, the value is unspecified. This parameter is passed uninitialized.
/// </param>
/// <returns>The number of objects successfully popped from the top of
/// the <see cref="ConcurrentStack{T}"/>.</returns>
private int TryPopCore(int count, out Node? poppedHead)
{
SpinWait spin = new SpinWait();
// Try to CAS the head with its current next. We stop when we succeed or
// when we notice that the stack is empty, whichever comes first.
Node? head;
Node next;
int backoff = 1;
Random? r = null;
while (true)
{
head = _head;
// Is the stack empty?
if (head == null)
{
if (count == 1 && CDSCollectionETWBCLProvider.Log.IsEnabled())
{
CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPopFailed(spin.Count);
}
poppedHead = null;
return 0;
}
next = head;
int nodesCount = 1;
for (; nodesCount < count && next._next != null; nodesCount++)
{
next = next._next;
}
// Try to swap the new head. If we succeed, break out of the loop.
if (Interlocked.CompareExchange(ref _head, next._next, head) == head)
{
if (count == 1 && CDSCollectionETWBCLProvider.Log.IsEnabled())
{
CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPopFailed(spin.Count);
}
// Return the popped Node.
poppedHead = head;
return nodesCount;
}
// We failed to CAS the new head. Spin briefly and retry.
for (int i = 0; i < backoff; i++)
{
spin.SpinOnce(sleep1Threshold: -1);
}
if (spin.NextSpinWillYield)
{
if (r == null)
{
r = new Random();
}
backoff = r.Next(1, BACKOFF_MAX_YIELDS);
}
else
{
backoff *= 2;
}
}
}
/// <summary>
/// Local helper function to copy the popped elements into a given collection
/// </summary>
/// <param name="head">The head of the list to be copied</param>
/// <param name="collection">The collection to place the popped items in</param>
/// <param name="startIndex">the beginning of index of where to place the popped items</param>
/// <param name="nodesCount">The number of nodes.</param>
private static void CopyRemovedItems(Node head, T[] collection, int startIndex, int nodesCount)
{
Node? current = head;
for (int i = startIndex; i < startIndex + nodesCount; i++)
{
collection[i] = current!._value;
current = current._next;
}
}
/// <summary>
/// Attempts to remove and return an object from the <see
/// cref="System.Collections.Concurrent.IProducerConsumerCollection{T}"/>.
/// </summary>
/// <param name="item">
/// When this method returns, if the operation was successful, <paramref name="item"/> contains the
/// object removed. If no object was available to be removed, the value is unspecified.
/// </param>
/// <returns>true if an element was removed and returned successfully; otherwise, false.</returns>
/// <remarks>For <see cref="ConcurrentStack{T}"/>, this operation will attempt to pope the object at
/// the top of the <see cref="ConcurrentStack{T}"/>.
/// </remarks>
bool IProducerConsumerCollection<T>.TryTake(out T item)
{
return TryPop(out item);
}
/// <summary>
/// Copies the items stored in the <see cref="ConcurrentStack{T}"/> to a new array.
/// </summary>
/// <returns>A new array containing a snapshot of elements copied from the <see
/// cref="ConcurrentStack{T}"/>.</returns>
public T[] ToArray()
{
Node? curr = _head;
return curr == null ?
Array.Empty<T>() :
ToList(curr).ToArray();
}
/// <summary>
/// Returns an array containing a snapshot of the list's contents, using
/// the target list node as the head of a region in the list.
/// </summary>
/// <returns>A list of the stack's contents.</returns>
private List<T> ToList()
{
return ToList(_head);
}
/// <summary>
/// Returns an array containing a snapshot of the list's contents starting at the specified node.
/// </summary>
/// <returns>A list of the stack's contents starting at the specified node.</returns>
private List<T> ToList(Node? curr)
{
List<T> list = new List<T>();
while (curr != null)
{
list.Add(curr._value);
curr = curr._next;
}
return list;
}
/// <summary>
/// Returns an enumerator that iterates through the <see cref="ConcurrentStack{T}"/>.
/// </summary>
/// <returns>An enumerator for the <see cref="ConcurrentStack{T}"/>.</returns>
/// <remarks>
/// The enumeration represents a moment-in-time snapshot of the contents
/// of the stack. It does not reflect any updates to the collection after
/// <see cref="GetEnumerator()"/> was called. The enumerator is safe to use
/// concurrently with reads from and writes to the stack.
/// </remarks>
public IEnumerator<T> GetEnumerator()
{
// Returns an enumerator for the stack. This effectively takes a snapshot
// of the stack's contents at the time of the call, i.e. subsequent modifications
// (pushes or pops) will not be reflected in the enumerator's contents.
//If we put yield-return here, the iterator will be lazily evaluated. As a result a snapshot of
//the stack is not taken when GetEnumerator is initialized but when MoveNext() is first called.
//This is inconsistent with existing generic collections. In order to prevent it, we capture the
//value of _head in a buffer and call out to a helper method
return GetEnumerator(_head);
}
private IEnumerator<T> GetEnumerator(Node? head)
{
Node? current = head;
while (current != null)
{
yield return current._value;
current = current._next;
}
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>An <see cref="System.Collections.IEnumerator"/> that can be used to iterate through
/// the collection.</returns>
/// <remarks>
/// The enumeration represents a moment-in-time snapshot of the contents of the stack. It does not
/// reflect any updates to the collection after
/// <see cref="GetEnumerator()"/> was called. The enumerator is safe to use concurrently with reads
/// from and writes to the stack.
/// </remarks>
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<T>)this).GetEnumerator();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class IOperationTests : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_DynamicArgument()
{
string source = @"
class C
{
void M(C c, dynamic d)
{
/*<bind>*/c.M2(d)/*</bind>*/;
}
public void M2(int i)
{
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'c.M2(d)')
Expression:
IDynamicMemberReferenceExpression (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReferenceExpression, Type: null) (Syntax: 'c.M2')
Type Arguments(0)
Instance Receiver:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(1):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_MultipleApplicableSymbols()
{
string source = @"
class C
{
void M(C c, dynamic d)
{
var x = /*<bind>*/c.M2(d)/*</bind>*/;
}
public void M2(int i)
{
}
public void M2(long i)
{
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'c.M2(d)')
Expression:
IDynamicMemberReferenceExpression (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReferenceExpression, Type: null) (Syntax: 'c.M2')
Type Arguments(0)
Instance Receiver:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(1):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_MultipleArgumentsAndApplicableSymbols()
{
string source = @"
class C
{
void M(C c, dynamic d)
{
char ch = 'c';
var x = /*<bind>*/c.M2(d, ch)/*</bind>*/;
}
public void M2(int i, char ch)
{
}
public void M2(long i, char ch)
{
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'c.M2(d, ch)')
Expression:
IDynamicMemberReferenceExpression (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReferenceExpression, Type: null) (Syntax: 'c.M2')
Type Arguments(0)
Instance Receiver:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(2):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
ILocalReferenceExpression: ch (OperationKind.LocalReferenceExpression, Type: System.Char) (Syntax: 'ch')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_ArgumentNames()
{
string source = @"
class C
{
void M(C c, dynamic d, dynamic e)
{
var x = /*<bind>*/c.M2(i: d, ch: e)/*</bind>*/;
}
public void M2(int i, char ch)
{
}
public void M2(long i, char ch)
{
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'c.M2(i: d, ch: e)')
Expression:
IDynamicMemberReferenceExpression (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReferenceExpression, Type: null) (Syntax: 'c.M2')
Type Arguments(0)
Instance Receiver:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(2):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
IParameterReferenceExpression: e (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'e')
ArgumentNames(2):
""i""
""ch""
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_ArgumentRefKinds()
{
string source = @"
class C
{
void M(C c, object d, dynamic e)
{
int k;
var x = /*<bind>*/c.M2(ref d, out k, e)/*</bind>*/;
}
public void M2(ref object i, out int j, char c)
{
j = 0;
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'c.M2(ref d, out k, e)')
Expression:
IDynamicMemberReferenceExpression (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReferenceExpression, Type: null) (Syntax: 'c.M2')
Type Arguments(0)
Instance Receiver:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(3):
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: System.Object) (Syntax: 'd')
ILocalReferenceExpression: k (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'k')
IParameterReferenceExpression: e (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'e')
ArgumentNames(0)
ArgumentRefKinds(3):
Ref
Out
None
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_DelegateInvocation()
{
string source = @"
using System;
class C
{
public Action<object> F;
void M(dynamic i)
{
var x = /*<bind>*/F(i)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'F(i)')
Expression:
IFieldReferenceExpression: System.Action<System.Object> C.F (OperationKind.FieldReferenceExpression, Type: System.Action<System.Object>) (Syntax: 'F')
Instance Receiver:
IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: C, IsImplicit) (Syntax: 'F')
Arguments(1):
IParameterReferenceExpression: i (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'i')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0649: Field 'C.F' is never assigned to, and will always have its default value null
// public Action<object> F;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("C.F", "null").WithLocation(6, 27)
};
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_WithDynamicReceiver()
{
string source = @"
class C
{
void M(dynamic d, int i)
{
var x = /*<bind>*/d(i)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'd(i)')
Expression:
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
Arguments(1):
IParameterReferenceExpression: i (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'i')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_WithDynamicMemberReceiver()
{
string source = @"
class C
{
void M(dynamic c, int i)
{
var x = /*<bind>*/c.M2(i)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'c.M2(i)')
Expression:
IDynamicMemberReferenceExpression (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReferenceExpression, Type: dynamic) (Syntax: 'c.M2')
Type Arguments(0)
Instance Receiver:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'c')
Arguments(1):
IParameterReferenceExpression: i (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'i')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_WithDynamicTypedMemberReceiver()
{
string source = @"
class C
{
dynamic M2 = null;
void M(C c, int i)
{
var x = /*<bind>*/c.M2(i)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'c.M2(i)')
Expression:
IFieldReferenceExpression: dynamic C.M2 (OperationKind.FieldReferenceExpression, Type: dynamic) (Syntax: 'c.M2')
Instance Receiver:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(1):
IParameterReferenceExpression: i (OperationKind.ParameterReferenceExpression, Type: System.Int32) (Syntax: 'i')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_AllFields()
{
string source = @"
class C
{
void M(C c, dynamic d)
{
int i = 0;
var x = /*<bind>*/c.M2(ref i, c: d)/*</bind>*/;
}
public void M2(ref int i, char c)
{
}
public void M2(ref int i, long c)
{
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic) (Syntax: 'c.M2(ref i, c: d)')
Expression:
IDynamicMemberReferenceExpression (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReferenceExpression, Type: null) (Syntax: 'c.M2')
Type Arguments(0)
Instance Receiver:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(2):
ILocalReferenceExpression: i (OperationKind.LocalReferenceExpression, Type: System.Int32) (Syntax: 'i')
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic) (Syntax: 'd')
ArgumentNames(2):
""null""
""c""
ArgumentRefKinds(2):
Ref
None
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_ErrorBadDynamicMethodArgLambda()
{
string source = @"
using System;
class C
{
public void M(C c)
{
dynamic y = null;
var x = /*<bind>*/c.M2(delegate { }, y)/*</bind>*/;
}
public void M2(Action a, Action y)
{
}
}
";
string expectedOperationTree = @"
IDynamicInvocationExpression (OperationKind.DynamicInvocationExpression, Type: dynamic, IsInvalid) (Syntax: 'c.M2(delegate { }, y)')
Expression:
IDynamicMemberReferenceExpression (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReferenceExpression, Type: null) (Syntax: 'c.M2')
Type Arguments(0)
Instance Receiver:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C) (Syntax: 'c')
Arguments(2):
IAnonymousFunctionExpression (Symbol: lambda expression) (OperationKind.AnonymousFunctionExpression, Type: null, IsInvalid) (Syntax: 'delegate { }')
IBlockStatement (1 statements) (OperationKind.BlockStatement, IsInvalid) (Syntax: '{ }')
IReturnStatement (OperationKind.ReturnStatement, IsInvalid, IsImplicit) (Syntax: '{ }')
ReturnedValue:
null
ILocalReferenceExpression: y (OperationKind.LocalReferenceExpression, Type: dynamic) (Syntax: 'y')
ArgumentNames(0)
ArgumentRefKinds(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.
// var x = /*<bind>*/c.M2(delegate { }, y)/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate { }").WithLocation(9, 32)
};
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DynamicInvocation_OverloadResolutionFailure()
{
string source = @"
class C
{
void M(C c, dynamic d)
{
var x = /*<bind>*/c.M2(d)/*</bind>*/;
}
public void M2()
{
}
public void M2(int i, int j)
{
}
}
";
string expectedOperationTree = @"
IInvocationExpression ( void C.M2()) (OperationKind.InvocationExpression, Type: System.Void, IsInvalid) (Syntax: 'c.M2(d)')
Instance Receiver:
IParameterReferenceExpression: c (OperationKind.ParameterReferenceExpression, Type: C, IsInvalid) (Syntax: 'c')
Arguments(1):
IArgument (ArgumentKind.Explicit, Matching Parameter: null) (OperationKind.Argument, IsInvalid) (Syntax: 'd')
IParameterReferenceExpression: d (OperationKind.ParameterReferenceExpression, Type: dynamic, IsInvalid) (Syntax: 'd')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS7036: There is no argument given that corresponds to the required formal parameter 'j' of 'C.M2(int, int)'
// var x = /*<bind>*/c.M2(d)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M2").WithArguments("j", "C.M2(int, int)").WithLocation(6, 29),
// CS0815: Cannot assign void to an implicitly-typed variable
// var x = /*<bind>*/c.M2(d)/*</bind>*/;
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "x = /*<bind>*/c.M2(d)").WithArguments("void").WithLocation(6, 13)
};
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
}
}
| |
// ===========================================================
// Copyright (C) 2014-2015 Kendar.org
//
// 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 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.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Razor;
using System.Web.Razor.Parser;
using Microsoft.CSharp;
using Microsoft.VisualBasic;
#if NEVER
//USAGE
//string result = RazorEngine.Razor.Parse(fileContent,new object(), "test");
namespace RazorEngine
{
/// <summary>
/// Compiles razor templates.
/// </summary>
internal class RazorCompiler
{
#region Fields
private readonly IRazorProvider provider;
#endregion
#region Constructor
/// <summary>
/// Initialises a new instance of <see cref="RazorCompiler"/>.
/// </summary>
/// <param name="provider">The provider used to compile templates.</param>
public RazorCompiler(IRazorProvider provider)
{
if (provider == null)
throw new ArgumentNullException("provider");
this.provider = provider;
}
#endregion
#region Methods
/// <summary>
/// Compiles the template.
/// </summary>
/// <param name="className">The class name of the dynamic type.</param>
/// <param name="template">The template to compile.</param>
/// <param name="modelType">[Optional] The mode type.</param>
private CompilerResults Compile(string className, string template, Type modelType = null)
{
var languageService = provider.CreateLanguageService();
var codeDom = provider.CreateCodeDomProvider();
var host = new NodeRazorHost(languageService);
var generator = languageService.CreateCodeGenerator(className, "Razor.Dynamic", null, host);
var parser = new RazorParser(languageService.CreateCodeParser(), new HtmlMarkupParser());
Type baseType = (modelType == null)
? typeof(TemplateBase)
: typeof(TemplateBase<>).MakeGenericType(modelType);
//EDR generator.GeneratedClass.BaseTypes.Add(baseType);
using (var reader = new StreamReader(new MemoryStream(Encoding.ASCII.GetBytes(template))))
{
parser.Parse(reader, generator);
}
//EDRvar statement = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Clear");
//EDRgenerator.GeneratedExecuteMethod.Statements.Insert(0, new CodeExpressionStatement(statement));
var builder = new StringBuilder();
using (var writer = new StringWriter(builder))
{
//EDR codeDom.GenerateCodeFromCompileUnit(generator.GeneratedCode, writer, new CodeGeneratorOptions());
}
var @params = new CompilerParameters();
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
@params.ReferencedAssemblies.Add(assembly.Location);
}
@params.GenerateInMemory = true;
@params.IncludeDebugInformation = false;
@params.GenerateExecutable = false;
@params.CompilerOptions = "/target:library /optimize";
var result = codeDom.CompileAssemblyFromSource(@params, new[] { builder.ToString() });
return result;
}
/// <summary>
/// Creates a <see cref="ITemplate" /> from the specified template string.
/// </summary>
/// <param name="template">The template to compile.</param>
/// <param name="modelType">[Optional] The model type.</param>
/// <returns>An instance of <see cref="ITemplate"/>.</returns>
public ITemplate CreateTemplate(string template, Type modelType = null)
{
string className = Regex.Replace(Guid.NewGuid().ToString("N"), @"[^A-Za-z]*", "");
var result = Compile(className, template, modelType);
if (result.Errors != null && result.Errors.Count > 0)
throw new TemplateException(result.Errors);
ITemplate instance = (ITemplate)result.CompiledAssembly.CreateInstance("Razor.Dynamic." + className);
return instance;
}
#endregion
}
/// <summary>
/// Process razor templates.
/// </summary>
public static class Razor
{
#region Fields
private static RazorCompiler Compiler;
private static readonly IDictionary<string, ITemplate> Templates;
#endregion
#region Constructor
/// <summary>
/// Statically initialises the <see cref="Razor"/> type.
/// </summary>
static Razor()
{
Compiler = new RazorCompiler(new CSharpRazorProvider());
Templates = new Dictionary<string, ITemplate>();
}
#endregion
#region Methods
/// <summary>
/// Gets an <see cref="ITemplate"/> for the specified template.
/// </summary>
/// <param name="template">The template to parse.</param>
/// <param name="modelType">The model to use in the template.</param>
/// <param name="name">[Optional] The name of the template.</param>
/// <returns></returns>
private static ITemplate GetTemplate(string template, Type modelType, string name = null)
{
if (!string.IsNullOrEmpty(name))
{
if (Templates.ContainsKey(name))
return Templates[name];
}
var instance = Compiler.CreateTemplate(template, modelType);
if (!string.IsNullOrEmpty(name))
{
if (!Templates.ContainsKey(name))
Templates.Add(name, instance);
}
return instance;
}
/// <summary>
/// Parses the specified template using the specified model.
/// </summary>
/// <typeparam name="T">The model type.</typeparam>
/// <param name="template">The template to parse.</param>
/// <param name="model">The model to use in the template.</param>
/// <param name="name">[Optional] A name for the template used for caching.</param>
/// <returns>The parsed template.</returns>
public static string Parse<T>(string template, T model, string name = null)
{
var instance = GetTemplate(template, typeof(T), name);
if (instance is ITemplate<T>)
((ITemplate<T>)instance).Model = model;
instance.Execute();
return instance.Result;
}
/// <summary>
/// Sets the razor provider used for compiling templates.
/// </summary>
/// <param name="provider">The razor provider.</param>
public static void SetRazorProvider(IRazorProvider provider)
{
if (provider == null)
throw new ArgumentNullException("provider");
Compiler = new RazorCompiler(provider);
}
#endregion
}
/// <summary>
/// A razor template.
/// </summary>
public interface ITemplate
{
#region Properties
/// <summary>
/// Gets the parsed result of the template.
/// </summary>
string Result { get; }
#endregion
#region Methods
/// <summary>
/// Clears the template.
/// </summary>
void Clear();
/// <summary>
/// Executes the template.
/// </summary>
void Execute();
/// <summary>
/// Writes the specified object to the template.
/// </summary>
/// <param name="object"></param>
void Write(object @object);
/// <summary>
/// Writes a literal to the template.
/// </summary>
/// <param name="literal"></param>
void WriteLiteral(string literal);
#endregion
}
/// <summary>
/// A razor template with a model.
/// </summary>
/// <typeparam name="TModel">The model type</typeparam>
public interface ITemplate<TModel> : ITemplate
{
#region Properties
/// <summary>
/// Gets or sets the model.
/// </summary>
TModel Model { get; set; }
#endregion
}
/// <summary>
/// Defines a provider used to create associated compiler types.
/// </summary>
public interface IRazorProvider
{
#region Methods
/// <summary>
/// Creates a code language service.
/// </summary>
/// <returns>Creates a language service.</returns>
RazorCodeLanguage CreateLanguageService();
/// <summary>
/// Creates a <see cref="CodeDomProvider"/>.
/// </summary>
/// <returns>The a code dom provider.</returns>
CodeDomProvider CreateCodeDomProvider();
#endregion
}
/// <summary>
/// Provides a razor provider that supports the C# syntax.
/// </summary>
public class CSharpRazorProvider : IRazorProvider
{
#region Methods
/// <summary>
/// Creates a code language service.
/// </summary>
/// <returns>Creates a language service.</returns>
public RazorCodeLanguage CreateLanguageService()
{
return new CSharpRazorCodeLanguage();
}
/// <summary>
/// Creates a <see cref="CodeDomProvider"/>.
/// </summary>
/// <returns>The a code dom provider.</returns>
public CodeDomProvider CreateCodeDomProvider()
{
return new CSharpCodeProvider();
}
#endregion
}
/// <summary>
/// Provides a base implementation of a template.
/// </summary>
public abstract class TemplateBase : ITemplate
{
#region Fields
private readonly StringBuilder builder = new StringBuilder();
#endregion
#region Properties
/// <summary>
/// Gets the parsed result of the template.
/// </summary>
public string Result { get { return builder.ToString(); } }
#endregion
#region Methods
/// <summary>
/// Clears the template.
/// </summary>
public void Clear()
{
builder.Clear();
}
/// <summary>
/// Executes the template.
/// </summary>
public virtual void Execute() { }
/// <summary>
/// Writes the specified object to the template.
/// </summary>
/// <param name="object"></param>
public void Write(object @object)
{
if (@object == null)
return;
builder.Append(@object);
}
/// <summary>
/// Writes a literal to the template.
/// </summary>
/// <param name="literal"></param>
public void WriteLiteral(string literal)
{
if (literal == null)
return;
builder.Append(literal);
}
#endregion
}
/// <summary>
/// Provides a base implementation of a template.
/// </summary>
/// <typeparam name="TModel">The model type.</typeparam>
public abstract class TemplateBase<TModel> : TemplateBase, ITemplate<TModel>
{
#region Properties
/// <summary>
/// Gets or sets the model.
/// </summary>
public TModel Model { get; set; }
#endregion
}
/// <summary>
/// Provides a razor provider that supports the VB syntax.
/// </summary>
public class VBRazorProvider : IRazorProvider
{
#region Methods
/// <summary>
/// Creates a code language service.
/// </summary>
/// <returns>Creates a language service.</returns>
public RazorCodeLanguage CreateLanguageService()
{
return new VBRazorCodeLanguage();
}
/// <summary>
/// Creates a <see cref="CodeDomProvider"/>.
/// </summary>
/// <returns>The a code dom provider.</returns>
public CodeDomProvider CreateCodeDomProvider()
{
return new VBCodeProvider();
}
#endregion
}
public class TemplateException : Exception
{
#region Constructors
/// <summary>
/// Initialises a new instance of <see cref="TemplateException"/>
/// </summary>
/// <param name="errors">The collection of compilation errors.</param>
internal TemplateException(CompilerErrorCollection errors)
: base("Unable to compile template.")
{
var list = new List<CompilerError>();
foreach (CompilerError error in errors)
{
list.Add(error);
}
Errors = new ReadOnlyCollection<CompilerError>(list);
}
#endregion
#region Properties
/// <summary>
/// Gets the collection of compiler errors.
/// </summary>
public ReadOnlyCollection<CompilerError> Errors { get; private set; }
#endregion
}
}
#endif
| |
// 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.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Xunit;
namespace Microsoft.AspNetCore.HeaderPropagation.Tests
{
public class HeaderPropagationIntegrationTest
{
[Fact]
public async Task HeaderPropagation_WithoutMiddleware_Throws()
{
// Arrange
Exception captured = null;
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddHttpClient("test").AddHeaderPropagation();
services.AddHeaderPropagation(options =>
{
options.Headers.Add("X-TraceId");
});
})
.Configure(app =>
{
// note: no header propagation middleware
app.Run(async context =>
{
try
{
var client = context.RequestServices.GetRequiredService<IHttpClientFactory>().CreateClient("test");
await client.GetAsync("http://localhost/"); // will throw
}
catch (Exception ex)
{
captured = ex;
}
});
});
}).Build();
await host.StartAsync();
var server = host.GetTestServer();
var client = server.CreateClient();
var request = new HttpRequestMessage();
// Act
var response = await client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.IsType<InvalidOperationException>(captured);
Assert.Equal(
"The HeaderPropagationValues.Headers property has not been initialized. Register the header propagation middleware " +
"by adding 'app.UseHeaderPropagation()' in the 'Configure(...)' method. Header propagation can only be used within " +
"the context of an HTTP request.",
captured.Message);
}
[Fact]
public async Task HeaderPropagation_OutsideOfIncomingRequest_Throws()
{
// Arrange
var services = new ServiceCollection();
services.AddHttpClient("test").AddHeaderPropagation();
services.AddHeaderPropagation(options =>
{
options.Headers.Add("X-TraceId");
});
var serviceProvider = services.BuildServiceProvider();
// Act & Assert
var client = serviceProvider.GetRequiredService<IHttpClientFactory>().CreateClient("test");
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => client.GetAsync("http://localhost/"));
Assert.Equal(
"The HeaderPropagationValues.Headers property has not been initialized. Register the header propagation middleware " +
"by adding 'app.UseHeaderPropagation()' in the 'Configure(...)' method. Header propagation can only be used within " +
"the context of an HTTP request.",
exception.Message);
}
[Fact]
public async Task HeaderInRequest_AddCorrectValue()
{
// Arrange
var handler = new SimpleHandler();
using var host = await CreateHost(c =>
c.Headers.Add("in", "out"),
handler);
var server = host.GetTestServer();
var client = server.CreateClient();
var request = new HttpRequestMessage();
request.Headers.Add("in", "test");
// Act
var response = await client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(handler.Headers.Contains("out"));
Assert.Equal(new[] { "test" }, handler.Headers.GetValues("out"));
}
[Fact]
public async Task MultipleHeaders_HeadersInRequest_AddAllHeaders()
{
// Arrange
var handler = new SimpleHandler();
using var host = await CreateHost(c =>
{
c.Headers.Add("first");
c.Headers.Add("second");
},
handler);
var server = host.GetTestServer();
var client = server.CreateClient();
var request = new HttpRequestMessage();
request.Headers.Add("first", "value");
request.Headers.Add("second", "other");
// Act
var response = await client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(handler.Headers.Contains("first"));
Assert.Equal(new[] { "value" }, handler.Headers.GetValues("first"));
Assert.True(handler.Headers.Contains("second"));
Assert.Equal(new[] { "other" }, handler.Headers.GetValues("second"));
}
[Fact]
public async Task Builder_UseHeaderPropagation_Without_AddHeaderPropagation_Throws()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseHeaderPropagation();
});
}).Build();
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => host.StartAsync());
Assert.Equal(
"Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddHeaderPropagation' inside the call to 'ConfigureServices(...)' in the application startup code.",
exception.Message);
}
[Fact]
public async Task HeaderInRequest_OverrideHeaderPerClient_AddCorrectValue()
{
// Arrange
var handler = new SimpleHandler();
using var host = await CreateHost(
c => c.Headers.Add("in", "out"),
handler,
c => c.Headers.Add("out", "different"));
var server = host.GetTestServer();
var client = server.CreateClient();
var request = new HttpRequestMessage();
request.Headers.Add("in", "test");
// Act
var response = await client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.True(handler.Headers.Contains("different"));
Assert.Equal(new[] { "test" }, handler.Headers.GetValues("different"));
}
private async Task<IHost> CreateHost(Action<HeaderPropagationOptions> configure, HttpMessageHandler primaryHandler, Action<HeaderPropagationMessageHandlerOptions> configureClient = null)
{
var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseHeaderPropagation();
app.UseMiddleware<SimpleMiddleware>();
})
.ConfigureServices(services =>
{
services.AddHeaderPropagation(configure);
var client = services.AddHttpClient("example.com", c => c.BaseAddress = new Uri("http://example.com"))
.ConfigureHttpMessageHandlerBuilder(b =>
{
b.PrimaryHandler = primaryHandler;
});
if (configureClient != null)
{
client.AddHeaderPropagation(configureClient);
}
else
{
client.AddHeaderPropagation();
}
});
}).Build();
await host.StartAsync();
return host;
}
private class SimpleHandler : DelegatingHandler
{
public HttpHeaders Headers { get; private set; }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Headers = request.Headers;
return Task.FromResult(new HttpResponseMessage());
}
}
private class SimpleMiddleware
{
private readonly IHttpClientFactory _httpClientFactory;
public SimpleMiddleware(RequestDelegate next, IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
public Task InvokeAsync(HttpContext _)
{
var client = _httpClientFactory.CreateClient("example.com");
return client.GetAsync("");
}
}
}
}
| |
////////////////////////////////////////////////////////////////
// //
// Neoforce Controls //
// //
////////////////////////////////////////////////////////////////
// //
// File: Skin.cs //
// //
// Version: 0.7 //
// //
// Date: 11/09/2010 //
// //
// Author: Tom Shane //
// //
////////////////////////////////////////////////////////////////
// //
// Copyright (c) by Tom Shane //
// //
////////////////////////////////////////////////////////////////
#region //// Using /////////////
////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
#if (!XBOX && !XBOX_FAKE)
using System.Windows.Forms;
#endif
////////////////////////////////////////////////////////////////////////////
#endregion
namespace TomShane.Neoforce.Controls
{
#region //// Structs ///////////
////////////////////////////////////////////////////////////////////////////
public struct SkinStates<T>
{
public T Enabled;
public T Hovered;
public T Pressed;
public T Focused;
public T Disabled;
public SkinStates(T enabled, T hovered, T pressed, T focused, T disabled)
{
Enabled = enabled;
Hovered = hovered;
Pressed = pressed;
Focused = focused;
Disabled = disabled;
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public struct LayerStates
{
public int Index;
public Color Color;
public bool Overlay;
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public struct LayerOverlays
{
public int Index;
public Color Color;
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public struct SkinInfo
{
public string Name;
public string Description;
public string Author;
public string Version;
}
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Classes ///////////
////////////////////////////////////////////////////////////////////////////
public class SkinList<T>: List<T>
{
#region //// Indexers //////////
////////////////////////////////////////////////////////////////////////////
public T this[string index]
{
get
{
for (int i = 0; i < this.Count; i++)
{
SkinBase s = (SkinBase)(object)this[i];
if (s.Name.ToLower() == index.ToLower())
{
return this[i];
}
}
return default(T);
}
set
{
for (int i = 0; i < this.Count; i++)
{
SkinBase s = (SkinBase)(object)this[i];
if (s.Name.ToLower() == index.ToLower())
{
this[i] = value;
}
}
}
}
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Constructors //////
////////////////////////////////////////////////////////////////////////////
public SkinList(): base()
{
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public SkinList(SkinList<T> source): base()
{
for (int i = 0; i < source.Count; i++)
{
Type[] t = new Type[1];
t[0] = typeof(T);
object[] p = new object[1];
p[0] = source[i];
this.Add((T)t[0].GetConstructor(t).Invoke(p));
}
}
////////////////////////////////////////////////////////////////////////////
#endregion
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public class SkinBase
{
#region //// Fields ////////////
////////////////////////////////////////////////////////////////////////////
public string Name;
public bool Archive;
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Constructors //////
////////////////////////////////////////////////////////////////////////////
public SkinBase(): base()
{
Archive = false;
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public SkinBase(SkinBase source): base()
{
if (source != null)
{
this.Name = source.Name;
this.Archive = source.Archive;
}
}
////////////////////////////////////////////////////////////////////////////
#endregion
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public class SkinLayer: SkinBase
{
#region //// Fields ////////////
////////////////////////////////////////////////////////////////////////////
public SkinImage Image = new SkinImage();
public int Width;
public int Height;
public int OffsetX;
public int OffsetY;
public Alignment Alignment;
public Margins SizingMargins;
public Margins ContentMargins;
public SkinStates<LayerStates> States;
public SkinStates<LayerOverlays> Overlays;
public SkinText Text = new SkinText();
public SkinList<SkinAttribute> Attributes = new SkinList<SkinAttribute>();
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Constructors //////
////////////////////////////////////////////////////////////////////////////
public SkinLayer(): base()
{
States.Enabled.Color = Color.White;
States.Pressed.Color = Color.White;
States.Focused.Color = Color.White;
States.Hovered.Color = Color.White;
States.Disabled.Color = Color.White;
Overlays.Enabled.Color = Color.White;
Overlays.Pressed.Color = Color.White;
Overlays.Focused.Color = Color.White;
Overlays.Hovered.Color = Color.White;
Overlays.Disabled.Color = Color.White;
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public SkinLayer(SkinLayer source): base(source)
{
if (source != null)
{
this.Image = new SkinImage(source.Image);
this.Width = source.Width;
this.Height = source.Height;
this.OffsetX = source.OffsetX;
this.OffsetY = source.OffsetY;
this.Alignment = source.Alignment;
this.SizingMargins = source.SizingMargins;
this.ContentMargins = source.ContentMargins;
this.States = source.States;
this.Overlays = source.Overlays;
this.Text = new SkinText(source.Text);
this.Attributes = new SkinList<SkinAttribute>(source.Attributes);
}
else
{
throw new Exception("Parameter for SkinLayer copy constructor cannot be null.");
}
}
////////////////////////////////////////////////////////////////////////////
#endregion
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public class SkinText: SkinBase
{
#region //// Fields ////////////
////////////////////////////////////////////////////////////////////////////
public SkinFont Font;
public int OffsetX;
public int OffsetY;
public Alignment Alignment;
public SkinStates<Color> Colors;
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Constructors //////
////////////////////////////////////////////////////////////////////////////
public SkinText(): base()
{
Colors.Enabled = Color.White;
Colors.Pressed= Color.White;
Colors.Focused = Color.White;
Colors.Hovered = Color.White;
Colors.Disabled = Color.White;
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public SkinText(SkinText source): base(source)
{
if (source != null)
{
this.Font = new SkinFont(source.Font);
this.OffsetX = source.OffsetX;
this.OffsetY = source.OffsetY;
this.Alignment = source.Alignment;
this.Colors = source.Colors;
}
}
////////////////////////////////////////////////////////////////////////////
#endregion
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public class SkinFont: SkinBase
{
#region //// Fields ////////////
////////////////////////////////////////////////////////////////////////////
public SpriteFont Resource = null;
public string Asset = null;
public string Addon = null;
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Properties ////////
////////////////////////////////////////////////////////////////////////////
public int Height
{
get
{
if (Resource != null)
{
return (int)Resource.MeasureString("AaYy").Y;
}
return 0;
}
}
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Constructors //////
////////////////////////////////////////////////////////////////////////////
public SkinFont(): base()
{
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public SkinFont(SkinFont source): base(source)
{
if (source != null)
{
this.Resource = source.Resource;
this.Asset = source.Asset;
}
}
////////////////////////////////////////////////////////////////////////////
#endregion
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public class SkinImage: SkinBase
{
#region //// Fields ////////////
////////////////////////////////////////////////////////////////////////////
public Texture2D Resource = null;
public string Asset = null;
public string Addon = null;
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Constructors //////
////////////////////////////////////////////////////////////////////////////
public SkinImage(): base()
{
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public SkinImage(SkinImage source): base(source)
{
this.Resource = source.Resource;
this.Asset = source.Asset;
}
////////////////////////////////////////////////////////////////////////////
#endregion
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public class SkinCursor: SkinBase
{
#region //// Fields ////////////
////////////////////////////////////////////////////////////////////////////
#if (!XBOX && !XBOX_FAKE)
public Cursor Resource = null;
#endif
public string Asset = null;
public string Addon = null;
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Constructors //////
////////////////////////////////////////////////////////////////////////////
public SkinCursor(): base()
{
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public SkinCursor(SkinCursor source): base(source)
{
#if (!XBOX && !XBOX_FAKE)
this.Resource = source.Resource;
#endif
this.Asset = source.Asset;
}
////////////////////////////////////////////////////////////////////////////
#endregion
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public class SkinControl: SkinBase
{
#region //// Fields ////////////
////////////////////////////////////////////////////////////////////////////
public string Inherits = null;
public Size DefaultSize;
public int ResizerSize;
public Size MinimumSize;
public Margins OriginMargins;
public Margins ClientMargins;
public SkinList<SkinLayer> Layers = new SkinList<SkinLayer>();
public SkinList<SkinAttribute> Attributes = new SkinList<SkinAttribute>();
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Constructors //////
////////////////////////////////////////////////////////////////////////////
public SkinControl(): base()
{
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public SkinControl(SkinControl source): base(source)
{
this.Inherits = source.Inherits;
this.DefaultSize = source.DefaultSize;
this.MinimumSize = source.MinimumSize;
this.OriginMargins = source.OriginMargins;
this.ClientMargins = source.ClientMargins;
this.ResizerSize = source.ResizerSize;
this.Layers = new SkinList<SkinLayer>(source.Layers);
this.Attributes = new SkinList<SkinAttribute>(source.Attributes);
}
////////////////////////////////////////////////////////////////////////////
#endregion
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public class SkinAttribute: SkinBase
{
#region //// Fields ////////////
////////////////////////////////////////////////////////////////////////////
public string Value;
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Constructors //////
////////////////////////////////////////////////////////////////////////////
public SkinAttribute(): base()
{
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public SkinAttribute(SkinAttribute source): base(source)
{
this.Value = source.Value;
}
////////////////////////////////////////////////////////////////////////////
#endregion
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public class Skin: Component
{
#region //// Fields ////////////
////////////////////////////////////////////////////////////////////////////
SkinXmlDocument doc = null;
private string name = null;
private Version version = null;
private SkinInfo info;
private SkinList<SkinControl> controls = null;
private SkinList<SkinFont> fonts = null;
private SkinList<SkinCursor> cursors = null;
private SkinList<SkinImage> images = null;
private SkinList<SkinAttribute> attributes = null;
private ArchiveManager content = null;
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Properties ////////
////////////////////////////////////////////////////////////////////////////
public virtual string Name { get { return name; } }
public virtual Version Version { get { return version; } }
public virtual SkinInfo Info { get { return info; } }
public virtual SkinList<SkinControl> Controls { get { return controls; } }
public virtual SkinList<SkinFont> Fonts { get { return fonts; } }
public virtual SkinList<SkinCursor> Cursors { get { return cursors; } }
public virtual SkinList<SkinImage> Images { get { return images; } }
public virtual SkinList<SkinAttribute> Attributes { get { return attributes; } }
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Construstors //////
////////////////////////////////////////////////////////////////////////////
public Skin(Manager manager, string name): base(manager)
{
this.name = name;
content = new ArchiveManager(Manager.Game.Services, GetArchiveLocation(name + Manager.SkinExtension));
content.RootDirectory = GetFolder();
doc = new SkinXmlDocument();
controls = new SkinList<SkinControl>();
fonts = new SkinList<SkinFont>();
images = new SkinList<SkinImage>();
cursors = new SkinList<SkinCursor>();
attributes = new SkinList<SkinAttribute>();
LoadSkin(null, content.UseArchive);
string folder = GetAddonsFolder();
if (folder == "")
{
content.UseArchive = true;
folder = "Addons\\";
}
else
{
content.UseArchive = false;
}
string[] addons = content.GetDirectories(folder);
if (addons != null && addons.Length > 0)
{
for (int i = 0; i < addons.Length; i++)
{
DirectoryInfo d = new DirectoryInfo(GetAddonsFolder() + addons[i]);
if (!((d.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden) || content.UseArchive)
{
LoadSkin(addons[i].Replace("\\", ""), content.UseArchive);
}
}
}
}
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Destructors ///////
////////////////////////////////////////////////////////////////////////////
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (content != null)
{
content.Unload();
content.Dispose();
content = null;
}
}
base.Dispose(disposing);
}
////////////////////////////////////////////////////////////////////////////
#endregion
#region //// Methods ///////////
////////////////////////////////////////////////////////////////////////////
private string GetArchiveLocation(string name)
{
string path = Path.GetFullPath(Manager.SkinDirectory) + Path.GetFileNameWithoutExtension(name) + "\\";
if (!Directory.Exists(path) || !File.Exists(path + "Skin.xnb"))
{
path = Path.GetFullPath(Manager.SkinDirectory) + name;
return path;
}
return null;
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private string GetFolder()
{
string path = Path.GetFullPath(Manager.SkinDirectory) + name + "\\";
if (!Directory.Exists(path) || !File.Exists(path + "Skin.xnb"))
{
path = "";
}
return path;
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private string GetAddonsFolder()
{
string path = Path.GetFullPath(Manager.SkinDirectory) + name + "\\Addons\\";
if (!Directory.Exists(path))
{
path = Path.GetFullPath(".\\Content\\Skins\\") + name + "\\Addons\\";
if (!Directory.Exists(path))
{
path = Path.GetFullPath(".\\Skins\\") + name + "\\Addons\\";
}
}
return path;
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private string GetFolder(string type)
{
return GetFolder() + type + "\\";
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private string GetAsset(string type, string asset, string addon)
{
string ret = GetFolder(type) + asset;
if (addon != null && addon != "")
{
ret = GetAddonsFolder() + addon + "\\" + type + "\\" + asset;
}
return ret;
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
public override void Init()
{
base.Init();
for (int i = 0; i < fonts.Count; i++)
{
content.UseArchive = fonts[i].Archive;
string asset = GetAsset("Fonts", fonts[i].Asset, fonts[i].Addon);
asset = content.UseArchive ? asset : Path.GetFullPath(asset);
(fonts[i].Resource) = content.Load<SpriteFont>(asset);
}
#if (!XBOX && !XBOX_FAKE)
for (int i = 0; i < cursors.Count; i++)
{
content.UseArchive = cursors[i].Archive;
string asset = GetAsset("Cursors", cursors[i].Asset, cursors[i].Addon);
asset = content.UseArchive ? asset : Path.GetFullPath(asset);
cursors[i].Resource = content.Load<Cursor>(asset);
}
#endif
for (int i = 0; i < images.Count; i++)
{
content.UseArchive = images[i].Archive;
string asset = GetAsset("Images", images[i].Asset, images[i].Addon);
asset = content.UseArchive ? asset : Path.GetFullPath(asset);
images[i].Resource = content.Load<Texture2D>(asset);
}
for (int i = 0; i < controls.Count; i++)
{
for (int j = 0; j < controls[i].Layers.Count; j++)
{
if (controls[i].Layers[j].Image.Name != null)
{
controls[i].Layers[j].Image = images[controls[i].Layers[j].Image.Name];
}
else
{
controls[i].Layers[j].Image = images[0];
}
if (controls[i].Layers[j].Text.Name != null)
{
controls[i].Layers[j].Text.Font = fonts[controls[i].Layers[j].Text.Name];
}
else
{
controls[i].Layers[j].Text.Font = fonts[0];
}
}
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private string ReadAttribute(XmlElement element, string attrib, string defval, bool needed)
{
if (element != null && element.HasAttribute(attrib))
{
return element.Attributes[attrib].Value;
}
else if (needed)
{
throw new Exception("Missing required attribute \"" + attrib + "\" in the skin file.");
}
return defval;
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private void ReadAttribute(ref string retval, bool inherited, XmlElement element, string attrib, string defval, bool needed)
{
if (element != null && element.HasAttribute(attrib))
{
retval = element.Attributes[attrib].Value;
}
else if (inherited)
{
}
else if (needed)
{
throw new Exception("Missing required attribute \"" + attrib + "\" in the skin file.");
}
else
{
retval = defval;
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private int ReadAttributeInt(XmlElement element, string attrib, int defval, bool needed)
{
return int.Parse(ReadAttribute(element, attrib, defval.ToString(), needed));
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private void ReadAttributeInt(ref int retval, bool inherited, XmlElement element, string attrib, int defval, bool needed)
{
string tmp = retval.ToString();
ReadAttribute(ref tmp, inherited, element, attrib, defval.ToString(), needed);
retval = int.Parse(tmp);
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private bool ReadAttributeBool(XmlElement element, string attrib, bool defval, bool needed)
{
return bool.Parse(ReadAttribute(element, attrib, defval.ToString(), needed));
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private void ReadAttributeBool(ref bool retval, bool inherited, XmlElement element, string attrib, bool defval, bool needed)
{
string tmp = retval.ToString();
ReadAttribute(ref tmp, inherited, element, attrib, defval.ToString(), needed);
retval = bool.Parse(tmp);
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private byte ReadAttributeByte(XmlElement element, string attrib, byte defval, bool needed)
{
return byte.Parse(ReadAttribute(element, attrib, defval.ToString(), needed));
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private void ReadAttributeByte(ref byte retval, bool inherited, XmlElement element, string attrib, byte defval, bool needed)
{
string tmp = retval.ToString();
ReadAttribute(ref tmp, inherited, element, attrib, defval.ToString(), needed);
retval = byte.Parse(tmp);
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private string ColorToString(Color c)
{
return string.Format("{0};{1};{2};{3}", c.R, c.G, c.B, c.A);
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private void ReadAttributeColor(ref Color retval, bool inherited, XmlElement element, string attrib, Color defval, bool needed)
{
string tmp = ColorToString(retval);
ReadAttribute(ref tmp, inherited, element, attrib, ColorToString(defval), needed);
retval = Utilities.ParseColor(tmp);
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private void LoadSkin(string addon, bool archive)
{
try
{
bool isaddon = addon != null && addon != "";
string file = GetFolder();
if (isaddon)
{
file = GetAddonsFolder() + addon + "\\";
}
file += "Skin";
file = archive ? file : Path.GetFullPath(file);
doc = content.Load<SkinXmlDocument>(file);
XmlElement e = doc["Skin"];
if (e != null)
{
string xname = ReadAttribute(e, "Name", null, true);
if (!isaddon)
{
if (name.ToLower() != xname.ToLower())
{
throw new Exception("Skin name defined in the skin file doesn't match requested skin.");
}
else
{
name = xname;
}
}
else
{
if (addon.ToLower() != xname.ToLower())
{
throw new Exception("Skin name defined in the skin file doesn't match addon name.");
}
}
Version xversion = null;
try
{
xversion = new Version(ReadAttribute(e, "Version", "0.0.0.0", false));
}
catch (Exception x)
{
throw new Exception("Unable to resolve skin file version. " + x.Message);
}
if (xversion != Manager._SkinVersion)
{
throw new Exception("This version of Neoforce Controls can only read skin files in version of " + Manager._SkinVersion.ToString() + ".");
}
else if (!isaddon)
{
version = xversion;
}
if (!isaddon)
{
XmlElement ei = e["Info"];
if (ei != null)
{
if (ei["Name"] != null) info.Name = ei["Name"].InnerText;
if (ei["Description"] != null) info.Description = ei["Description"].InnerText;
if (ei["Author"] != null) info.Author = ei["Author"].InnerText;
if (ei["Version"] != null) info.Version = ei["Version"].InnerText;
}
}
LoadImages(addon, archive);
LoadFonts(addon, archive);
LoadCursors(addon, archive);
LoadSkinAttributes();
LoadControls();
}
}
catch(Exception x)
{
throw new Exception("Unable to load skin file. " + x.Message);
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private void LoadSkinAttributes()
{
if (doc["Skin"]["Attributes"] == null) return;
XmlNodeList l = doc["Skin"]["Attributes"].GetElementsByTagName("Attribute");
if (l != null && l.Count > 0)
{
foreach (XmlElement e in l)
{
SkinAttribute sa = new SkinAttribute();
sa.Name = ReadAttribute(e, "Name", null, true);
sa.Value = ReadAttribute(e, "Value", null, true);
attributes.Add(sa);
}
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private void LoadControls()
{
if (doc["Skin"]["Controls"] == null) return;
XmlNodeList l = doc["Skin"]["Controls"].GetElementsByTagName("Control");
if (l != null && l.Count > 0)
{
foreach (XmlElement e in l)
{
SkinControl sc = null;
string parent = ReadAttribute(e, "Inherits", null, false);
bool inh = false;
if (parent != null)
{
sc = new SkinControl(controls[parent]);
sc.Inherits = parent;
inh = true;
}
else
{
sc = new SkinControl();
}
ReadAttribute(ref sc.Name, inh, e, "Name", null, true);
ReadAttributeInt(ref sc.DefaultSize.Width, inh, e["DefaultSize"], "Width", 0, false);
ReadAttributeInt(ref sc.DefaultSize.Height, inh, e["DefaultSize"], "Height", 0, false);
ReadAttributeInt(ref sc.MinimumSize.Width, inh, e["MinimumSize"], "Width", 0, false);
ReadAttributeInt(ref sc.MinimumSize.Height, inh, e["MinimumSize"], "Height", 0, false);
ReadAttributeInt(ref sc.OriginMargins.Left, inh, e["OriginMargins"], "Left", 0, false);
ReadAttributeInt(ref sc.OriginMargins.Top, inh, e["OriginMargins"], "Top", 0, false);
ReadAttributeInt(ref sc.OriginMargins.Right, inh, e["OriginMargins"], "Right", 0, false);
ReadAttributeInt(ref sc.OriginMargins.Bottom,inh, e["OriginMargins"], "Bottom", 0, false);
ReadAttributeInt(ref sc.ClientMargins.Left, inh, e["ClientMargins"], "Left", 0, false);
ReadAttributeInt(ref sc.ClientMargins.Top, inh, e["ClientMargins"], "Top", 0, false);
ReadAttributeInt(ref sc.ClientMargins.Right, inh, e["ClientMargins"], "Right", 0, false);
ReadAttributeInt(ref sc.ClientMargins.Bottom, inh, e["ClientMargins"], "Bottom", 0, false);
ReadAttributeInt(ref sc.ResizerSize, inh, e["ResizerSize"], "Value", 0, false);
if (e["Layers"] != null)
{
XmlNodeList l2 = e["Layers"].GetElementsByTagName("Layer");
if (l2 != null && l2.Count > 0)
{
LoadLayers(sc, l2);
}
}
if (e["Attributes"] != null)
{
XmlNodeList l3 = e["Attributes"].GetElementsByTagName("Attribute");
if (l3 != null && l3.Count > 0)
{
LoadControlAttributes(sc, l3);
}
}
controls.Add(sc);
}
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private void LoadFonts(string addon, bool archive)
{
if (doc["Skin"]["Fonts"] == null) return;
XmlNodeList l = doc["Skin"]["Fonts"].GetElementsByTagName("Font");
if (l != null && l.Count > 0)
{
foreach (XmlElement e in l)
{
SkinFont sf = new SkinFont();
sf.Name = ReadAttribute(e, "Name", null, true);
sf.Archive = archive;
sf.Asset = ReadAttribute(e, "Asset", null, true);
sf.Addon = addon;
fonts.Add(sf);
}
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private void LoadCursors(string addon, bool archive)
{
if (doc["Skin"]["Cursors"] == null) return;
XmlNodeList l = doc["Skin"]["Cursors"].GetElementsByTagName("Cursor");
if (l != null && l.Count > 0)
{
foreach (XmlElement e in l)
{
SkinCursor sc = new SkinCursor();
sc.Name = ReadAttribute(e, "Name", null, true);
sc.Archive = archive;
sc.Asset = ReadAttribute(e, "Asset", null, true);
sc.Addon = addon;
cursors.Add(sc);
}
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private void LoadImages(string addon, bool archive)
{
if (doc["Skin"]["Images"] == null) return;
XmlNodeList l = doc["Skin"]["Images"].GetElementsByTagName("Image");
if (l != null && l.Count > 0)
{
foreach (XmlElement e in l)
{
SkinImage si = new SkinImage();
si.Name = ReadAttribute(e, "Name", null, true);
si.Archive = archive;
si.Asset = ReadAttribute(e, "Asset", null, true);
si.Addon = addon;
images.Add(si);
}
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private void LoadLayers(SkinControl sc, XmlNodeList l)
{
foreach (XmlElement e in l)
{
string name = ReadAttribute(e, "Name", null, true);
bool over = ReadAttributeBool(e, "Override", false, false);
SkinLayer sl = sc.Layers[name];
bool inh = true;
if (sl == null)
{
sl = new SkinLayer();
inh = false;
}
if (inh && over)
{
sl = new SkinLayer();
sc.Layers[name] = sl;
}
ReadAttribute(ref sl.Name, inh, e, "Name", null, true);
ReadAttribute(ref sl.Image.Name, inh, e, "Image", "Control", false);
ReadAttributeInt(ref sl.Width, inh, e, "Width", 0, false);
ReadAttributeInt(ref sl.Height, inh, e, "Height", 0, false);
string tmp = sl.Alignment.ToString();
ReadAttribute(ref tmp, inh, e, "Alignment", "MiddleCenter", false);
sl.Alignment = (Alignment)Enum.Parse(typeof(Alignment), tmp, true);
ReadAttributeInt(ref sl.OffsetX, inh, e, "OffsetX", 0, false);
ReadAttributeInt(ref sl.OffsetY, inh, e, "OffsetY", 0, false);
ReadAttributeInt(ref sl.SizingMargins.Left, inh, e["SizingMargins"], "Left", 0, false);
ReadAttributeInt(ref sl.SizingMargins.Top, inh, e["SizingMargins"], "Top", 0, false);
ReadAttributeInt(ref sl.SizingMargins.Right, inh, e["SizingMargins"], "Right", 0, false);
ReadAttributeInt(ref sl.SizingMargins.Bottom, inh, e["SizingMargins"], "Bottom", 0, false);
ReadAttributeInt(ref sl.ContentMargins.Left, inh, e["ContentMargins"], "Left", 0, false);
ReadAttributeInt(ref sl.ContentMargins.Top, inh, e["ContentMargins"], "Top", 0, false);
ReadAttributeInt(ref sl.ContentMargins.Right, inh, e["ContentMargins"], "Right", 0, false);
ReadAttributeInt(ref sl.ContentMargins.Bottom, inh, e["ContentMargins"], "Bottom", 0, false);
if (e["States"] != null)
{
ReadAttributeInt(ref sl.States.Enabled.Index, inh, e["States"]["Enabled"], "Index", 0, false);
int di = sl.States.Enabled.Index;
ReadAttributeInt(ref sl.States.Hovered.Index, inh, e["States"]["Hovered"], "Index", di, false);
ReadAttributeInt(ref sl.States.Pressed.Index, inh, e["States"]["Pressed"], "Index", di, false);
ReadAttributeInt(ref sl.States.Focused.Index, inh, e["States"]["Focused"], "Index", di, false);
ReadAttributeInt(ref sl.States.Disabled.Index, inh, e["States"]["Disabled"], "Index", di, false);
ReadAttributeColor(ref sl.States.Enabled.Color, inh, e["States"]["Enabled"], "Color", Color.White, false);
Color dc = sl.States.Enabled.Color;
ReadAttributeColor(ref sl.States.Hovered.Color, inh, e["States"]["Hovered"], "Color", dc, false);
ReadAttributeColor(ref sl.States.Pressed.Color, inh, e["States"]["Pressed"], "Color", dc, false);
ReadAttributeColor(ref sl.States.Focused.Color, inh, e["States"]["Focused"], "Color", dc, false);
ReadAttributeColor(ref sl.States.Disabled.Color, inh, e["States"]["Disabled"], "Color", dc, false);
ReadAttributeBool(ref sl.States.Enabled.Overlay, inh, e["States"]["Enabled"], "Overlay", false, false);
bool dv = sl.States.Enabled.Overlay;
ReadAttributeBool(ref sl.States.Hovered.Overlay, inh, e["States"]["Hovered"], "Overlay", dv, false);
ReadAttributeBool(ref sl.States.Pressed.Overlay, inh, e["States"]["Pressed"], "Overlay", dv, false);
ReadAttributeBool(ref sl.States.Focused.Overlay, inh, e["States"]["Focused"], "Overlay", dv, false);
ReadAttributeBool(ref sl.States.Disabled.Overlay, inh, e["States"]["Disabled"], "Overlay", dv, false);
}
if (e["Overlays"] != null)
{
ReadAttributeInt(ref sl.Overlays.Enabled.Index, inh, e["Overlays"]["Enabled"], "Index", 0, false);
int di = sl.Overlays.Enabled.Index;
ReadAttributeInt(ref sl.Overlays.Hovered.Index, inh, e["Overlays"]["Hovered"], "Index", di, false);
ReadAttributeInt(ref sl.Overlays.Pressed.Index, inh, e["Overlays"]["Pressed"], "Index", di, false);
ReadAttributeInt(ref sl.Overlays.Focused.Index, inh, e["Overlays"]["Focused"], "Index", di, false);
ReadAttributeInt(ref sl.Overlays.Disabled.Index, inh, e["Overlays"]["Disabled"], "Index", di, false);
ReadAttributeColor(ref sl.Overlays.Enabled.Color, inh, e["Overlays"]["Enabled"], "Color", Color.White, false);
Color dc = sl.Overlays.Enabled.Color;
ReadAttributeColor(ref sl.Overlays.Hovered.Color, inh, e["Overlays"]["Hovered"], "Color", dc, false);
ReadAttributeColor(ref sl.Overlays.Pressed.Color, inh, e["Overlays"]["Pressed"], "Color", dc, false);
ReadAttributeColor(ref sl.Overlays.Focused.Color, inh, e["Overlays"]["Focused"], "Color", dc, false);
ReadAttributeColor(ref sl.Overlays.Disabled.Color, inh, e["Overlays"]["Disabled"], "Color", dc, false);
}
if (e["Text"] != null)
{
ReadAttribute(ref sl.Text.Name, inh, e["Text"], "Font", null, true);
ReadAttributeInt(ref sl.Text.OffsetX, inh, e["Text"], "OffsetX", 0, false);
ReadAttributeInt(ref sl.Text.OffsetY , inh, e["Text"], "OffsetY", 0, false);
tmp = sl.Text.Alignment.ToString();
ReadAttribute(ref tmp, inh, e["Text"], "Alignment", "MiddleCenter", false);
sl.Text.Alignment = (Alignment)Enum.Parse(typeof(Alignment), tmp, true);
LoadColors(inh, e["Text"], ref sl.Text.Colors);
}
if (e["Attributes"] != null)
{
XmlNodeList l2 = e["Attributes"].GetElementsByTagName("Attribute");
if (l2 != null && l2.Count > 0)
{
LoadLayerAttributes(sl, l2);
}
}
if (!inh) sc.Layers.Add(sl);
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private void LoadColors(bool inherited, XmlElement e, ref SkinStates<Color> colors)
{
if (e != null)
{
ReadAttributeColor(ref colors.Enabled, inherited, e["Colors"]["Enabled"], "Color", Color.White, false);
ReadAttributeColor(ref colors.Hovered, inherited, e["Colors"]["Hovered"], "Color", colors.Enabled, false);
ReadAttributeColor(ref colors.Pressed, inherited, e["Colors"]["Pressed"], "Color", colors.Enabled, false);
ReadAttributeColor(ref colors.Focused, inherited, e["Colors"]["Focused"], "Color", colors.Enabled, false);
ReadAttributeColor(ref colors.Disabled, inherited, e["Colors"]["Disabled"], "Color", colors.Enabled, false);
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private void LoadControlAttributes(SkinControl sc, XmlNodeList l)
{
foreach (XmlElement e in l)
{
string name = ReadAttribute(e, "Name", null, true);
SkinAttribute sa = sc.Attributes[name];
bool inh = true;
if (sa == null)
{
sa = new SkinAttribute();
inh = false;
}
sa.Name = name;
ReadAttribute(ref sa.Value, inh, e, "Value", null, true);
if (!inh) sc.Attributes.Add(sa);
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
private void LoadLayerAttributes(SkinLayer sl, XmlNodeList l)
{
foreach (XmlElement e in l)
{
string name = ReadAttribute(e, "Name", null, true);
SkinAttribute sa = sl.Attributes[name];
bool inh = true;
if (sa == null)
{
sa = new SkinAttribute();
inh = false;
}
sa.Name = name;
ReadAttribute(ref sa.Value, inh, e, "Value", null, true);
if (!inh) sl.Attributes.Add(sa);
}
}
////////////////////////////////////////////////////////////////////////////
#endregion
}
////////////////////////////////////////////////////////////////////////////
#endregion
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Text;
using Microsoft.PowerShell.Commands;
namespace System.Management.Automation
{
/// <summary>
/// Defines the types of commands that MSH can execute.
/// </summary>
[Flags]
public enum CommandTypes
{
/// <summary>
/// Aliases create a name that refers to other command types.
/// </summary>
/// <remarks>
/// Aliases are only persisted within the execution of a single engine.
/// </remarks>
Alias = 0x0001,
/// <summary>
/// Script functions that are defined by a script block.
/// </summary>
/// <remarks>
/// Functions are only persisted within the execution of a single engine.
/// </remarks>
Function = 0x0002,
/// <summary>
/// Script filters that are defined by a script block.
/// </summary>
/// <remarks>
/// Filters are only persisted within the execution of a single engine.
/// </remarks>
Filter = 0x0004,
/// <summary>
/// A cmdlet.
/// </summary>
Cmdlet = 0x0008,
/// <summary>
/// An MSH script (*.ps1 file)
/// </summary>
ExternalScript = 0x0010,
/// <summary>
/// Any existing application (can be console or GUI).
/// </summary>
/// <remarks>
/// An application can have any extension that can be executed either directly through CreateProcess
/// or indirectly through ShellExecute.
/// </remarks>
Application = 0x0020,
/// <summary>
/// A script that is built into the runspace configuration.
/// </summary>
Script = 0x0040,
/// <summary>
/// A Configuration.
/// </summary>
Configuration = 0x0100,
/// <summary>
/// All possible command types.
/// </summary>
/// <remarks>
/// Note, a CommandInfo instance will never specify
/// All as its CommandType but All can be used when filtering the CommandTypes.
/// </remarks>
All = Alias | Function | Filter | Cmdlet | Script | ExternalScript | Application | Configuration,
}
/// <summary>
/// The base class for the information about commands. Contains the basic information about
/// the command, like name and type.
/// </summary>
public abstract class CommandInfo : IHasSessionStateEntryVisibility
{
#region ctor
/// <summary>
/// Creates an instance of the CommandInfo class with the specified name and type.
/// </summary>
/// <param name="name">
/// The name of the command.
/// </param>
/// <param name="type">
/// The type of the command.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="name"/> is null.
/// </exception>
internal CommandInfo(string name, CommandTypes type)
{
// The name can be empty for functions and filters but it
// can't be null
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
Name = name;
CommandType = type;
}
/// <summary>
/// Creates an instance of the CommandInfo class with the specified name and type.
/// </summary>
/// <param name="name">
/// The name of the command.
/// </param>
/// <param name="type">
/// The type of the command.
/// </param>
/// <param name="context">
/// The execution context for the command.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="name"/> is null.
/// </exception>
internal CommandInfo(string name, CommandTypes type, ExecutionContext context)
: this(name, type)
{
this.Context = context;
}
/// <summary>
/// This is a copy constructor, used primarily for get-command.
/// </summary>
internal CommandInfo(CommandInfo other)
{
// Computed fields not copied:
// this._externalCommandMetadata = other._externalCommandMetadata;
// this._moduleName = other._moduleName;
// this.parameterSets = other.parameterSets;
this.Module = other.Module;
_visibility = other._visibility;
Arguments = other.Arguments;
this.Context = other.Context;
Name = other.Name;
CommandType = other.CommandType;
CopiedCommand = other;
this.DefiningLanguageMode = other.DefiningLanguageMode;
}
/// <summary>
/// This is a copy constructor, used primarily for get-command.
/// </summary>
internal CommandInfo(string name, CommandInfo other)
: this(other)
{
Name = name;
}
#endregion ctor
/// <summary>
/// Gets the name of the command.
/// </summary>
public string Name { get; private set; } = string.Empty;
// Name
/// <summary>
/// Gets the type of the command.
/// </summary>
public CommandTypes CommandType { get; private set; } = CommandTypes.Application;
// CommandType
/// <summary>
/// Gets the source of the command (shown by default in Get-Command)
/// </summary>
public virtual string Source { get { return this.ModuleName; } }
/// <summary>
/// Gets the source version (shown by default in Get-Command)
/// </summary>
public virtual Version Version
{
get
{
if (_version == null)
{
if (Module != null)
{
if (Module.Version.Equals(new Version(0, 0)))
{
if (Module.Path.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
{
// Manifest module (.psd1)
Module.SetVersion(ModuleIntrinsics.GetManifestModuleVersion(Module.Path));
}
else if (Module.Path.EndsWith(StringLiterals.PowerShellILAssemblyExtension, StringComparison.OrdinalIgnoreCase) ||
Module.Path.EndsWith(StringLiterals.PowerShellILExecutableExtension, StringComparison.OrdinalIgnoreCase))
{
// Binary module (.dll or .exe)
Module.SetVersion(AssemblyName.GetAssemblyName(Module.Path).Version);
}
}
_version = Module.Version;
}
}
return _version;
}
}
private Version _version;
/// <summary>
/// The execution context this command will run in.
/// </summary>
internal ExecutionContext Context
{
get
{
return _context;
}
set
{
_context = value;
if ((value != null) && !this.DefiningLanguageMode.HasValue)
{
this.DefiningLanguageMode = value.LanguageMode;
}
}
}
private ExecutionContext _context;
/// <summary>
/// The language mode that was in effect when this alias was defined.
/// </summary>
internal PSLanguageMode? DefiningLanguageMode { get; set; }
internal virtual HelpCategory HelpCategory
{
get { return HelpCategory.None; }
}
internal CommandInfo CopiedCommand { get; set; }
/// <summary>
/// Internal interface to change the type of a CommandInfo object.
/// </summary>
/// <param name="newType"></param>
internal void SetCommandType(CommandTypes newType)
{
CommandType = newType;
}
/// <summary>
/// A string representing the definition of the command.
/// </summary>
/// <remarks>
/// This is overridden by derived classes to return specific
/// information for the command type.
/// </remarks>
public abstract string Definition { get; }
/// <summary>
/// This is required for renaming aliases, functions, and filters.
/// </summary>
/// <param name="newName">
/// The new name for the command.
/// </param>
/// <exception cref="ArgumentException">
/// If <paramref name="newName"/> is null or empty.
/// </exception>
internal void Rename(string newName)
{
if (string.IsNullOrEmpty(newName))
{
throw new ArgumentNullException(nameof(newName));
}
Name = newName;
}
/// <summary>
/// For diagnostic purposes.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return ModuleCmdletBase.AddPrefixToCommandName(Name, Prefix);
}
/// <summary>
/// Indicates if the command is to be allowed to be executed by a request
/// external to the runspace.
/// </summary>
public virtual SessionStateEntryVisibility Visibility
{
get
{
return CopiedCommand == null ? _visibility : CopiedCommand.Visibility;
}
set
{
if (CopiedCommand == null)
{
_visibility = value;
}
else
{
CopiedCommand.Visibility = value;
}
if (value == SessionStateEntryVisibility.Private && Module != null)
{
Module.ModuleHasPrivateMembers = true;
}
}
}
private SessionStateEntryVisibility _visibility = SessionStateEntryVisibility.Public;
/// <summary>
/// Return a CommandMetadata instance that is never exposed publicly.
/// </summary>
internal virtual CommandMetadata CommandMetadata
{
get
{
throw new InvalidOperationException();
}
}
/// <summary>
/// Returns the syntax of a command.
/// </summary>
internal virtual string Syntax
{
get { return Definition; }
}
/// <summary>
/// The module name of this command. It will be empty for commands
/// not imported from either a module or snapin.
/// </summary>
public string ModuleName
{
get
{
string moduleName = null;
if (Module != null && !string.IsNullOrEmpty(Module.Name))
{
moduleName = Module.Name;
}
else
{
CmdletInfo cmdlet = this as CmdletInfo;
if (cmdlet != null && cmdlet.PSSnapIn != null)
{
moduleName = cmdlet.PSSnapInName;
}
}
if (moduleName == null)
return string.Empty;
return moduleName;
}
}
/// <summary>
/// The module that defines this cmdlet. This will be null for commands
/// that are not defined in the context of a module.
/// </summary>
public PSModuleInfo Module { get; internal set; }
/// <summary>
/// The remoting capabilities of this cmdlet, when exposed in a context
/// with ambient remoting.
/// </summary>
public RemotingCapability RemotingCapability
{
get
{
try
{
return ExternalCommandMetadata.RemotingCapability;
}
catch (PSNotSupportedException)
{
// Thrown on an alias that hasn't been resolved yet (i.e.: in a module that
// hasn't been loaded.) Assume the default.
return RemotingCapability.PowerShell;
}
}
}
/// <summary>
/// True if the command has dynamic parameters, false otherwise.
/// </summary>
internal virtual bool ImplementsDynamicParameters
{
get { return false; }
}
/// <summary>
/// Constructs the MergedCommandParameterMetadata, using any arguments that
/// may have been specified so that dynamic parameters can be determined, if any.
/// </summary>
/// <returns></returns>
private MergedCommandParameterMetadata GetMergedCommandParameterMetadataSafely()
{
if (_context == null)
return null;
MergedCommandParameterMetadata result;
if (_context != LocalPipeline.GetExecutionContextFromTLS())
{
// In the normal case, _context is from the thread we're on, and we won't get here.
// But, if it's not, we can't safely get the parameter metadata without running on
// on the correct thread, because that thread may be busy doing something else.
// One of the things we do here is change the current scope in execution context,
// that can mess up the runspace our CommandInfo object came from.
var runspace = (RunspaceBase)_context.CurrentRunspace;
if (runspace.CanRunActionInCurrentPipeline())
{
GetMergedCommandParameterMetadata(out result);
}
else
{
_context.Events.SubscribeEvent(
source: null,
eventName: PSEngineEvent.GetCommandInfoParameterMetadata,
sourceIdentifier: PSEngineEvent.GetCommandInfoParameterMetadata,
data: null,
handlerDelegate: new PSEventReceivedEventHandler(OnGetMergedCommandParameterMetadataSafelyEventHandler),
supportEvent: true,
forwardEvent: false,
shouldQueueAndProcessInExecutionThread: true,
maxTriggerCount: 1);
var eventArgs = new GetMergedCommandParameterMetadataSafelyEventArgs();
_context.Events.GenerateEvent(
sourceIdentifier: PSEngineEvent.GetCommandInfoParameterMetadata,
sender: null,
args: new[] { eventArgs },
extraData: null,
processInCurrentThread: true,
waitForCompletionInCurrentThread: true);
if (eventArgs.Exception != null)
{
// An exception happened on a different thread, rethrow it here on the correct thread.
eventArgs.Exception.Throw();
}
return eventArgs.Result;
}
}
GetMergedCommandParameterMetadata(out result);
return result;
}
private sealed class GetMergedCommandParameterMetadataSafelyEventArgs : EventArgs
{
public MergedCommandParameterMetadata Result;
public ExceptionDispatchInfo Exception;
}
private void OnGetMergedCommandParameterMetadataSafelyEventHandler(object sender, PSEventArgs args)
{
var eventArgs = args.SourceEventArgs as GetMergedCommandParameterMetadataSafelyEventArgs;
if (eventArgs != null)
{
try
{
// Save the result in our event args as the return value.
GetMergedCommandParameterMetadata(out eventArgs.Result);
}
catch (Exception e)
{
// Save the exception so we can throw it on the correct thread.
eventArgs.Exception = ExceptionDispatchInfo.Capture(e);
}
}
}
private void GetMergedCommandParameterMetadata(out MergedCommandParameterMetadata result)
{
// MSFT:652277 - When invoking cmdlets or advanced functions, MyInvocation.MyCommand.Parameters do not contain the dynamic parameters
// When trying to get parameter metadata for a CommandInfo that has dynamic parameters, a new CommandProcessor will be
// created out of this CommandInfo and the parameter binding algorithm will be invoked. However, when this happens via
// 'MyInvocation.MyCommand.Parameter', it's actually retrieving the parameter metadata of the same cmdlet that is currently
// running. In this case, information about the specified parameters are not kept around in 'MyInvocation.MyCommand', so
// going through the binding algorithm again won't give us the metadata about the dynamic parameters that should have been
// discovered already.
// The fix is to check if the CommandInfo is actually representing the currently running cmdlet. If so, the retrieval of parameter
// metadata actually stems from the running of the same cmdlet. In this case, we can just use the current CommandProcessor to
// retrieve all bindable parameters, which should include the dynamic parameters that have been discovered already.
CommandProcessor processor;
if (Context.CurrentCommandProcessor != null && Context.CurrentCommandProcessor.CommandInfo == this)
{
// Accessing the parameters within the invocation of the same cmdlet/advanced function.
processor = (CommandProcessor)Context.CurrentCommandProcessor;
}
else
{
IScriptCommandInfo scriptCommand = this as IScriptCommandInfo;
processor = scriptCommand != null
? new CommandProcessor(scriptCommand, _context, useLocalScope: true, fromScriptFile: false,
sessionState: scriptCommand.ScriptBlock.SessionStateInternal ?? Context.EngineSessionState)
: new CommandProcessor((CmdletInfo)this, _context);
ParameterBinderController.AddArgumentsToCommandProcessor(processor, Arguments);
CommandProcessorBase oldCurrentCommandProcessor = Context.CurrentCommandProcessor;
try
{
Context.CurrentCommandProcessor = processor;
processor.SetCurrentScopeToExecutionScope();
processor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(processor.arguments);
}
catch (ParameterBindingException)
{
// Ignore the binding exception if no argument is specified
if (processor.arguments.Count > 0)
{
throw;
}
}
finally
{
Context.CurrentCommandProcessor = oldCurrentCommandProcessor;
processor.RestorePreviousScope();
}
}
result = processor.CmdletParameterBinderController.BindableParameters;
}
/// <summary>
/// Return the parameters for this command.
/// </summary>
public virtual Dictionary<string, ParameterMetadata> Parameters
{
get
{
Dictionary<string, ParameterMetadata> result = new Dictionary<string, ParameterMetadata>(StringComparer.OrdinalIgnoreCase);
if (ImplementsDynamicParameters && Context != null)
{
MergedCommandParameterMetadata merged = GetMergedCommandParameterMetadataSafely();
foreach (KeyValuePair<string, MergedCompiledCommandParameter> pair in merged.BindableParameters)
{
result.Add(pair.Key, new ParameterMetadata(pair.Value.Parameter));
}
// Don't cache this data...
return result;
}
return ExternalCommandMetadata.Parameters;
}
}
internal CommandMetadata ExternalCommandMetadata
{
get { return _externalCommandMetadata ??= new CommandMetadata(this, true); }
set { _externalCommandMetadata = value; }
}
private CommandMetadata _externalCommandMetadata;
/// <summary>
/// Resolves a full, shortened, or aliased parameter name to the actual
/// cmdlet parameter name, using PowerShell's standard parameter resolution
/// algorithm.
/// </summary>
/// <param name="name">The name of the parameter to resolve.</param>
/// <returns>The parameter that matches this name.</returns>
public ParameterMetadata ResolveParameter(string name)
{
MergedCommandParameterMetadata merged = GetMergedCommandParameterMetadataSafely();
MergedCompiledCommandParameter result = merged.GetMatchingParameter(name, true, true, null);
return this.Parameters[result.Parameter.Name];
}
/// <summary>
/// Gets the information about the parameters and parameter sets for
/// this command.
/// </summary>
public ReadOnlyCollection<CommandParameterSetInfo> ParameterSets
{
get
{
if (_parameterSets == null)
{
Collection<CommandParameterSetInfo> parameterSetInfo =
GenerateCommandParameterSetInfo();
_parameterSets = new ReadOnlyCollection<CommandParameterSetInfo>(parameterSetInfo);
}
return _parameterSets;
}
}
internal ReadOnlyCollection<CommandParameterSetInfo> _parameterSets;
/// <summary>
/// A possibly incomplete or even incorrect list of types the command could return.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public abstract ReadOnlyCollection<PSTypeName> OutputType { get; }
/// <summary>
/// Specifies whether this command was imported from a module or not.
/// This is used in Get-Command to figure out which of the commands in module session state were imported.
/// </summary>
internal bool IsImported { get; set; } = false;
/// <summary>
/// The prefix that was used when importing this command.
/// </summary>
internal string Prefix { get; set; } = string.Empty;
/// <summary>
/// Create a copy of commandInfo for GetCommandCommand so that we can generate parameter
/// sets based on an argument list (so we can get the dynamic parameters.)
/// </summary>
internal virtual CommandInfo CreateGetCommandCopy(object[] argumentList)
{
throw new InvalidOperationException();
}
/// <summary>
/// Generates the parameter and parameter set info from the cmdlet metadata.
/// </summary>
/// <returns>
/// A collection of CommandParameterSetInfo representing the cmdlet metadata.
/// </returns>
/// <exception cref="ArgumentException">
/// The type name is invalid or the length of the type name
/// exceeds 1024 characters.
/// </exception>
/// <exception cref="System.Security.SecurityException">
/// The caller does not have the required permission to load the assembly
/// or create the type.
/// </exception>
/// <exception cref="ParsingMetadataException">
/// If more than int.MaxValue parameter-sets are defined for the command.
/// </exception>
/// <exception cref="MetadataException">
/// If a parameter defines the same parameter-set name multiple times.
/// If the attributes could not be read from a property or field.
/// </exception>
internal Collection<CommandParameterSetInfo> GenerateCommandParameterSetInfo()
{
Collection<CommandParameterSetInfo> result;
if (IsGetCommandCopy && ImplementsDynamicParameters)
{
result = GetParameterMetadata(CommandMetadata, GetMergedCommandParameterMetadataSafely());
}
else
{
result = GetCacheableMetadata(CommandMetadata);
}
return result;
}
/// <summary>
/// Gets or sets whether this CmdletInfo instance is a copy used for get-command.
/// If true, and the cmdlet supports dynamic parameters, it means that the dynamic
/// parameter metadata will be merged into the parameter set information.
/// </summary>
internal bool IsGetCommandCopy { get; set; }
/// <summary>
/// Gets or sets the command line arguments/parameters that were specified
/// which will allow for the dynamic parameters to be retrieved and their
/// metadata merged into the parameter set information.
/// </summary>
internal object[] Arguments { get; set; }
internal static Collection<CommandParameterSetInfo> GetCacheableMetadata(CommandMetadata metadata)
{
return GetParameterMetadata(metadata, metadata.StaticCommandParameterMetadata);
}
internal static Collection<CommandParameterSetInfo> GetParameterMetadata(CommandMetadata metadata, MergedCommandParameterMetadata parameterMetadata)
{
Collection<CommandParameterSetInfo> result = new Collection<CommandParameterSetInfo>();
if (parameterMetadata != null)
{
if (parameterMetadata.ParameterSetCount == 0)
{
const string parameterSetName = ParameterAttribute.AllParameterSets;
result.Add(
new CommandParameterSetInfo(
parameterSetName,
false,
uint.MaxValue,
parameterMetadata));
}
else
{
int parameterSetCount = parameterMetadata.ParameterSetCount;
for (int index = 0; index < parameterSetCount; ++index)
{
uint currentFlagPosition = (uint)0x1 << index;
// Get the parameter set name
string parameterSetName = parameterMetadata.GetParameterSetName(currentFlagPosition);
// Is the parameter set the default?
bool isDefaultParameterSet = (currentFlagPosition & metadata.DefaultParameterSetFlag) != 0;
result.Add(
new CommandParameterSetInfo(
parameterSetName,
isDefaultParameterSet,
currentFlagPosition,
parameterMetadata));
}
}
}
return result;
}
}
/// <summary>
/// Represents <see cref="System.Type"/>, but can be used where a real type
/// might not be available, in which case the name of the type can be used.
/// </summary>
public class PSTypeName
{
/// <summary>
/// This constructor is used when the type exists and is currently loaded.
/// </summary>
/// <param name="type">The type.</param>
public PSTypeName(Type type)
{
_type = type;
if (_type != null)
{
Name = _type.FullName;
}
}
/// <summary>
/// This constructor is used when the type may not exist, or is not loaded.
/// </summary>
/// <param name="name">The name of the type.</param>
public PSTypeName(string name)
{
Name = name;
_type = null;
}
/// <summary>
/// This constructor is used when the creating a PSObject with a custom typename.
/// </summary>
/// <param name="name">The name of the type.</param>
/// <param name="type">The real type.</param>
public PSTypeName(string name, Type type)
{
Name = name;
_type = type;
}
/// <summary>
/// This constructor is used when the type is defined in PowerShell.
/// </summary>
/// <param name="typeDefinitionAst">The type definition from the ast.</param>
public PSTypeName(TypeDefinitionAst typeDefinitionAst)
{
if (typeDefinitionAst == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(typeDefinitionAst));
}
TypeDefinitionAst = typeDefinitionAst;
Name = typeDefinitionAst.Name;
}
/// <summary>
/// This constructor creates a type from a ITypeName.
/// </summary>
public PSTypeName(ITypeName typeName)
{
if (typeName == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(typeName));
}
_type = typeName.GetReflectionType();
if (_type != null)
{
Name = _type.FullName;
}
else
{
var t = typeName as TypeName;
if (t != null && t._typeDefinitionAst != null)
{
TypeDefinitionAst = t._typeDefinitionAst;
Name = TypeDefinitionAst.Name;
}
else
{
_type = null;
Name = typeName.FullName;
}
}
}
/// <summary>
/// Return the name of the type.
/// </summary>
public string Name { get; }
/// <summary>
/// Return the type with metadata, or null if the type is not loaded.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
public Type Type
{
get
{
if (!_typeWasCalculated)
{
if (_type == null)
{
if (TypeDefinitionAst != null)
{
_type = TypeDefinitionAst.Type;
}
else
{
TypeResolver.TryResolveType(Name, out _type);
}
}
if (_type == null)
{
// We ignore the exception.
if (Name != null &&
Name.StartsWith('[') &&
Name.EndsWith(']'))
{
string tmp = Name.Substring(1, Name.Length - 2);
TypeResolver.TryResolveType(tmp, out _type);
}
}
_typeWasCalculated = true;
}
return _type;
}
}
private Type _type;
/// <summary>
/// When a type is defined by PowerShell, the ast for that type.
/// </summary>
public TypeDefinitionAst TypeDefinitionAst { get; }
private bool _typeWasCalculated;
/// <summary>
/// Returns a String that represents the current PSTypeName.
/// </summary>
/// <returns>String that represents the current PSTypeName.</returns>
public override string ToString()
{
return Name ?? string.Empty;
}
}
[DebuggerDisplay("{PSTypeName} {Name}")]
internal readonly struct PSMemberNameAndType
{
public readonly string Name;
public readonly PSTypeName PSTypeName;
public readonly object Value;
public PSMemberNameAndType(string name, PSTypeName typeName, object value = null)
{
Name = name;
PSTypeName = typeName;
Value = value;
}
}
/// <summary>
/// Represents dynamic types such as <see cref="System.Management.Automation.PSObject"/>,
/// but can be used where a real type might not be available, in which case the name of the type can be used.
/// The type encodes the members of dynamic objects in the type name.
/// </summary>
internal sealed class PSSyntheticTypeName : PSTypeName
{
internal static PSSyntheticTypeName Create(string typename, IList<PSMemberNameAndType> membersTypes) => Create(new PSTypeName(typename), membersTypes);
internal static PSSyntheticTypeName Create(Type type, IList<PSMemberNameAndType> membersTypes) => Create(new PSTypeName(type), membersTypes);
internal static PSSyntheticTypeName Create(PSTypeName typename, IList<PSMemberNameAndType> membersTypes)
{
var typeName = GetMemberTypeProjection(typename.Name, membersTypes);
var members = new List<PSMemberNameAndType>();
members.AddRange(membersTypes);
members.Sort(static (c1, c2) => string.Compare(c1.Name, c2.Name, StringComparison.OrdinalIgnoreCase));
return new PSSyntheticTypeName(typeName, typename.Type, members);
}
private PSSyntheticTypeName(string typeName, Type type, IList<PSMemberNameAndType> membersTypes)
: base(typeName, type)
{
Members = membersTypes;
if (type != typeof(PSObject))
{
return;
}
for (int i = 0; i < Members.Count; i++)
{
var psMemberNameAndType = Members[i];
if (IsPSTypeName(psMemberNameAndType))
{
Members.RemoveAt(i);
break;
}
}
}
private static bool IsPSTypeName(in PSMemberNameAndType member) => member.Name.Equals(nameof(PSTypeName), StringComparison.OrdinalIgnoreCase);
private static string GetMemberTypeProjection(string typename, IList<PSMemberNameAndType> members)
{
if (typename == typeof(PSObject).FullName)
{
foreach (var mem in members)
{
if (IsPSTypeName(mem))
{
typename = mem.Value.ToString();
}
}
}
var builder = new StringBuilder(typename, members.Count * 7);
builder.Append('#');
foreach (var m in members.OrderBy(static m => m.Name))
{
if (!IsPSTypeName(m))
{
builder.Append(m.Name).Append(':');
}
}
builder.Length--;
return builder.ToString();
}
public IList<PSMemberNameAndType> Members { get; }
}
#nullable enable
internal interface IScriptCommandInfo
{
ScriptBlock ScriptBlock { get; }
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace ODataValidator.Rule
{
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Net;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using ODataValidator.Rule.Helper;
using ODataValidator.RuleEngine;
using ODataValidator.RuleEngine.Common;
/// <summary>
/// Class of extension rule for Entry.Core.2018
/// </summary>
[Export(typeof(ExtensionRule))]
public class EntryCore2018 : ExtensionRule
{
/// <summary>
/// Gets Category property
/// </summary>
public override string Category
{
get
{
return "core";
}
}
/// <summary>
/// Gets rule name
/// </summary>
public override string Name
{
get
{
return "Entry.Core.2018";
}
}
/// <summary>
/// Gets rule description
/// </summary>
public override string Description
{
get
{
return "A ComplexType property on an EntityType MUST be serialized within the <m:properties> element of an <atom:content> element or <atom:entry> element, as specified in Entity Type (as an Atom Entry Element) (section 2.2.6.2.2).";
}
}
/// <summary>
/// Gets rule specification in OData document
/// </summary>
public override string SpecificationSection
{
get
{
return "2.2.6.2.3";
}
}
/// <summary>
/// Gets rule specification section in OData Atom
/// </summary>
public override string V4SpecificationSection
{
get
{
return "9.1";
}
}
/// <summary>
/// Gets rule specification name in OData Atom
/// </summary>
public override string V4Specification
{
get
{
return "odatacsdl";
}
}
/// <summary>
/// Gets location of help information of the rule
/// </summary>
public override string HelpLink
{
get
{
return null;
}
}
/// <summary>
/// Gets the error message for validation failure
/// </summary>
public override string ErrorMessage
{
get
{
return this.Description;
}
}
/// <summary>
/// Gets the requirement level.
/// </summary>
public override RequirementLevel RequirementLevel
{
get
{
return RequirementLevel.Must;
}
}
/// <summary>
/// Gets the version.
/// </summary>
public override ODataVersion? Version
{
get
{
return ODataVersion.V1_V2;
}
}
/// <summary>
/// Gets the payload type to which the rule applies.
/// </summary>
public override PayloadType? PayloadType
{
get
{
return RuleEngine.PayloadType.Entry;
}
}
/// <summary>
/// Gets the flag whether the rule requires metadata document
/// </summary>
public override bool? RequireMetadata
{
get
{
return true;
}
}
/// <summary>
/// Gets the offline context to which the rule applies
/// </summary>
public override bool? IsOfflineContext
{
get
{
return false;
}
}
/// <summary>
/// Gets the flag whether this rule applies to proected response or not
/// </summary>
public override bool? Projection
{
get
{
return false; ;
}
}
/// <summary>
/// Gets the payload format to which the rule applies.
/// </summary>
public override PayloadFormat? PayloadFormat
{
get
{
return RuleEngine.PayloadFormat.Atom;
}
}
/// <summary>
/// Verify Entry.Core.2018
/// </summary>
/// <param name="context">Service context</param>
/// <param name="info">out parameter to return violation information when rule fail</param>
/// <returns>true if rule passes; false otherwise</returns>
public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
bool? passed = null;
info = null;
// Load MetadataDocument into XMLDOM
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(context.MetadataDocument);
// Get all the properties
XmlNodeList propertyNodeList = xmlDoc.SelectNodes("//*[local-name()='EntityType' and @Name = '" + context.EntityTypeShortName + "']/*[local-name()='Property']");
List<string> complexTypeProperties = new List<string>();
// Get all Complex Type properties
foreach (XmlNode node in propertyNodeList)
{
if (!EdmTypeManager.IsEdmSimpleType(node.Attributes["Type"].Value))
{
complexTypeProperties.Add(node.Attributes["Type"].Value);
}
}
if (complexTypeProperties.Count > 0)
{
var complexTypePropertyList = complexTypeProperties.GroupBy(c => c);
XmlDocument xmlDoc2 = new XmlDocument();
xmlDoc2.LoadXml(context.ResponsePayload);
XmlNodeList nodeList;
// Verify that all Complex Type properties are under m:properties
foreach (var complexTypeProperty in complexTypePropertyList)
{
nodeList = xmlDoc2.SelectNodes("//*[@*[local-name()='type'] = '" + complexTypeProperty.Key + "']");
foreach (XmlNode node in nodeList)
{
if (node.ParentNode.Name.Equals("m:properties", StringComparison.Ordinal))
{
passed = true;
}
else
{
passed = false;
break;
}
}
if (passed.HasValue && !passed.Value)
{
break;
}
}
}
info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
return passed;
}
}
}
| |
#define MCG_WINRT_SUPPORTED
using Mcg.System;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
// -----------------------------------------------------------------------------------------------------------
//
// WARNING: THIS SOURCE FILE IS FOR 32-BIT BUILDS ONLY!
//
// MCG GENERATED CODE
//
// This C# source file is generated by MCG and is added into the application at compile time to support interop features.
//
// It has three primary components:
//
// 1. Public type definitions with interop implementation used by this application including WinRT & COM data structures and P/Invokes.
//
// 2. The 'McgInterop' class containing marshaling code that acts as a bridge from managed code to native code.
//
// 3. The 'McgNative' class containing marshaling code and native type definitions that call into native code and are called by native code.
//
// -----------------------------------------------------------------------------------------------------------
//
// warning CS0067: The event 'event' is never used
#pragma warning disable 67
// warning CS0169: The field 'field' is never used
#pragma warning disable 169
// warning CS0649: Field 'field' is never assigned to, and will always have its default value 0
#pragma warning disable 414
// warning CS0414: The private field 'field' is assigned but its value is never used
#pragma warning disable 649
// warning CS1591: Missing XML comment for publicly visible type or member 'Type_or_Member'
#pragma warning disable 1591
// warning CS0108 'member1' hides inherited member 'member2'. Use the new keyword if hiding was intended.
#pragma warning disable 108
// warning CS0114 'member1' hides inherited member 'member2'. To make the current method override that implementation, add the override keyword. Otherwise add the new keyword.
#pragma warning disable 114
// warning CS0659 'type' overrides Object.Equals but does not override GetHashCode.
#pragma warning disable 659
// warning CS0465 Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?
#pragma warning disable 465
// warning CS0028 'function declaration' has the wrong signature to be an entry point
#pragma warning disable 28
// warning CS0162 Unreachable code Detected
#pragma warning disable 162
// warning CS0628 new protected member declared in sealed class
#pragma warning disable 628
namespace McgInterop
{
/// <summary>
/// P/Invoke class for module 'sqlite3'
/// </summary>
public unsafe static partial class sqlite3
{
// Signature, Open, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.AnsiStringMarshaller] string__unsigned char *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Open")]
public static global::SQLite.Net.Interop.Result__SQLite_Net Open(
string filename,
out global::System.IntPtr db)
{
// Setup
byte* unsafe_filename = default(byte*);
global::System.IntPtr unsafe_db;
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
try
{
// Marshalling
unsafe_filename = global::System.Runtime.InteropServices.McgMarshal.StringToAnsiString(filename, true, false);
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Open(
unsafe_filename,
&(unsafe_db)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
db = unsafe_db;
// Return
return unsafe___value;
}
finally
{
// Cleanup
global::System.Runtime.InteropServices.ExternalInterop.SafeCoTaskMemFree(unsafe_filename);
}
}
// Signature, Open__0, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.AnsiStringMarshaller] string__unsigned char *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Open")]
public static global::SQLite.Net.Interop.Result__SQLite_Net Open__0(
string filename,
out global::System.IntPtr db,
int flags,
global::System.IntPtr zvfs)
{
// Setup
byte* unsafe_filename = default(byte*);
global::System.IntPtr unsafe_db;
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
try
{
// Marshalling
unsafe_filename = global::System.Runtime.InteropServices.McgMarshal.StringToAnsiString(filename, true, false);
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Open__0(
unsafe_filename,
&(unsafe_db),
flags,
zvfs
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
db = unsafe_db;
// Return
return unsafe___value;
}
finally
{
// Cleanup
global::System.Runtime.InteropServices.ExternalInterop.SafeCoTaskMemFree(unsafe_filename);
}
}
// Signature, Open__1, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableArrayMarshaller] rg_byte__unsigned char *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Open")]
public static global::SQLite.Net.Interop.Result__SQLite_Net Open__1(
byte[] filename,
out global::System.IntPtr db,
int flags,
global::System.IntPtr zvfs)
{
// Setup
byte* unsafe_filename;
global::System.IntPtr unsafe_db;
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
// Marshalling
fixed (byte* pinned_filename = global::McgInterop.McgCoreHelpers.GetArrayForCompat(filename))
{
unsafe_filename = (byte*)pinned_filename;
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Open__1(
unsafe_filename,
&(unsafe_db),
flags,
zvfs
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
db = unsafe_db;
}
// Return
return unsafe___value;
}
// Signature, Open16, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.UnicodeStringMarshaller] string__wchar_t *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Open16")]
public static global::SQLite.Net.Interop.Result__SQLite_Net Open16(
string filename,
out global::System.IntPtr db)
{
// Setup
ushort* unsafe_filename = default(ushort*);
global::System.IntPtr unsafe_db;
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
// Marshalling
fixed (char* pinned_filename = filename)
{
unsafe_filename = (ushort*)pinned_filename;
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Open16(
unsafe_filename,
&(unsafe_db)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
db = unsafe_db;
}
// Return
return unsafe___value;
}
// Signature, Close, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Close")]
public static global::SQLite.Net.Interop.Result__SQLite_Net Close(global::System.IntPtr db)
{
// Setup
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Close(db);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, Config, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_ConfigOption__SQLite_Net__ConfigOption__SQLite_Net,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Config")]
public static global::SQLite.Net.Interop.Result__SQLite_Net Config(global::SQLite.Net.Interop.ConfigOption__SQLite_Net option)
{
// Setup
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Config(option);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, SetDirectory, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.UnicodeStringMarshaller] string__wchar_t *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "SetDirectory")]
public static int SetDirectory(
uint directoryType,
string directoryPath)
{
// Setup
ushort* unsafe_directoryPath = default(ushort*);
int unsafe___value;
// Marshalling
fixed (char* pinned_directoryPath = directoryPath)
{
unsafe_directoryPath = (ushort*)pinned_directoryPath;
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.SetDirectory(
directoryType,
unsafe_directoryPath
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
}
// Return
return unsafe___value;
}
// Signature, BusyTimeout, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BusyTimeout")]
public static global::SQLite.Net.Interop.Result__SQLite_Net BusyTimeout(
global::System.IntPtr db,
int milliseconds)
{
// Setup
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.BusyTimeout(
db,
milliseconds
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, Changes, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Changes")]
public static int Changes(global::System.IntPtr db)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Changes(db);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, Prepare2, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.AnsiStringMarshaller] string__unsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Prepare2")]
public static global::SQLite.Net.Interop.Result__SQLite_Net Prepare2(
global::System.IntPtr db,
string sql,
int numBytes,
out global::System.IntPtr stmt,
global::System.IntPtr pzTail)
{
// Setup
byte* unsafe_sql = default(byte*);
global::System.IntPtr unsafe_stmt;
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
try
{
// Marshalling
unsafe_sql = global::System.Runtime.InteropServices.McgMarshal.StringToAnsiString(sql, true, false);
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Prepare2(
db,
unsafe_sql,
numBytes,
&(unsafe_stmt),
pzTail
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
stmt = unsafe_stmt;
// Return
return unsafe___value;
}
finally
{
// Cleanup
global::System.Runtime.InteropServices.ExternalInterop.SafeCoTaskMemFree(unsafe_sql);
}
}
// Signature, Step, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Step")]
public static global::SQLite.Net.Interop.Result__SQLite_Net Step(global::System.IntPtr stmt)
{
// Setup
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Step(stmt);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, Reset, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Reset")]
public static global::SQLite.Net.Interop.Result__SQLite_Net Reset(global::System.IntPtr stmt)
{
// Setup
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Reset(stmt);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, Finalize, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Finalize")]
public static global::SQLite.Net.Interop.Result__SQLite_Net Finalize(global::System.IntPtr stmt)
{
// Setup
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Finalize(stmt);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, LastInsertRowid, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] long____int64, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "LastInsertRowid")]
public static long LastInsertRowid(global::System.IntPtr db)
{
// Setup
long unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.LastInsertRowid(db);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, Errmsg, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Errmsg")]
public static global::System.IntPtr Errmsg(global::System.IntPtr db)
{
// Setup
global::System.IntPtr unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.Errmsg(db);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, BindParameterIndex, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.AnsiStringMarshaller] string__unsigned char *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BindParameterIndex")]
public static int BindParameterIndex(
global::System.IntPtr stmt,
string name)
{
// Setup
byte* unsafe_name = default(byte*);
int unsafe___value;
try
{
// Marshalling
unsafe_name = global::System.Runtime.InteropServices.McgMarshal.StringToAnsiString(name, true, false);
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.BindParameterIndex(
stmt,
unsafe_name
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
finally
{
// Cleanup
global::System.Runtime.InteropServices.ExternalInterop.SafeCoTaskMemFree(unsafe_name);
}
}
// Signature, BindNull, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BindNull")]
public static int BindNull(
global::System.IntPtr stmt,
int index)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.BindNull(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, BindInt, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BindInt")]
public static int BindInt(
global::System.IntPtr stmt,
int index,
int val)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.BindInt(
stmt,
index,
val
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, BindInt64, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] long____int64,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BindInt64")]
public static int BindInt64(
global::System.IntPtr stmt,
int index,
long val)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.BindInt64(
stmt,
index,
val
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, BindDouble, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] double__double,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BindDouble")]
public static int BindDouble(
global::System.IntPtr stmt,
int index,
double val)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.BindDouble(
stmt,
index,
val
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, BindText, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.UnicodeStringMarshaller] string__wchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BindText")]
public static int BindText(
global::System.IntPtr stmt,
int index,
string val,
int n,
global::System.IntPtr free)
{
// Setup
ushort* unsafe_val = default(ushort*);
int unsafe___value;
// Marshalling
fixed (char* pinned_val = val)
{
unsafe_val = (ushort*)pinned_val;
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.BindText(
stmt,
index,
unsafe_val,
n,
free
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
}
// Return
return unsafe___value;
}
// Signature, BindBlob, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableArrayMarshaller] rg_byte__unsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BindBlob")]
public static int BindBlob(
global::System.IntPtr stmt,
int index,
byte[] val,
int n,
global::System.IntPtr free)
{
// Setup
byte* unsafe_val;
int unsafe___value;
// Marshalling
fixed (byte* pinned_val = global::McgInterop.McgCoreHelpers.GetArrayForCompat(val))
{
unsafe_val = (byte*)pinned_val;
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.BindBlob(
stmt,
index,
unsafe_val,
n,
free
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
}
// Return
return unsafe___value;
}
// Signature, ColumnCount, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnCount")]
public static int ColumnCount(global::System.IntPtr stmt)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnCount(stmt);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ColumnName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnName")]
public static global::System.IntPtr ColumnName(
global::System.IntPtr stmt,
int index)
{
// Setup
global::System.IntPtr unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnName(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ColumnName16Internal, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnName16Internal")]
public static global::System.IntPtr ColumnName16Internal(
global::System.IntPtr stmt,
int index)
{
// Setup
global::System.IntPtr unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnName16Internal(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ColumnType, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_ColType__SQLite_Net__ColType__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnType")]
public static global::SQLite.Net.Interop.ColType__SQLite_Net ColumnType(
global::System.IntPtr stmt,
int index)
{
// Setup
global::SQLite.Net.Interop.ColType__SQLite_Net unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnType(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ColumnInt, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnInt")]
public static int ColumnInt(
global::System.IntPtr stmt,
int index)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnInt(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ColumnInt64, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] long____int64, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnInt64")]
public static long ColumnInt64(
global::System.IntPtr stmt,
int index)
{
// Setup
long unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnInt64(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ColumnDouble, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] double__double, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnDouble")]
public static double ColumnDouble(
global::System.IntPtr stmt,
int index)
{
// Setup
double unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnDouble(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ColumnText, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnText")]
public static global::System.IntPtr ColumnText(
global::System.IntPtr stmt,
int index)
{
// Setup
global::System.IntPtr unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnText(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ColumnText16, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnText16")]
public static global::System.IntPtr ColumnText16(
global::System.IntPtr stmt,
int index)
{
// Setup
global::System.IntPtr unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnText16(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ColumnBlob, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnBlob")]
public static global::System.IntPtr ColumnBlob(
global::System.IntPtr stmt,
int index)
{
// Setup
global::System.IntPtr unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnBlob(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ColumnBytes, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnBytes")]
public static int ColumnBytes(
global::System.IntPtr stmt,
int index)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnBytes(
stmt,
index
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, sqlite3_extended_errcode, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_ExtendedResult__SQLite_Net__ExtendedResult__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_extended_errcode")]
public static global::SQLite.Net.Interop.ExtendedResult__SQLite_Net sqlite3_extended_errcode(global::System.IntPtr db)
{
// Setup
global::SQLite.Net.Interop.ExtendedResult__SQLite_Net unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_extended_errcode(db);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, sqlite3_libversion_number, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_libversion_number")]
public static int sqlite3_libversion_number()
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_libversion_number();
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, sqlite3_sourceid, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_sourceid")]
public static global::System.IntPtr sqlite3_sourceid()
{
// Setup
global::System.IntPtr unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_sourceid();
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, sqlite3_backup_init, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.AnsiStringMarshaller] string__unsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.AnsiStringMarshaller] string__unsigned char *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_backup_init")]
public static global::System.IntPtr sqlite3_backup_init(
global::System.IntPtr destDB,
string destName,
global::System.IntPtr srcDB,
string srcName)
{
// Setup
byte* unsafe_destName = default(byte*);
byte* unsafe_srcName = default(byte*);
global::System.IntPtr unsafe___value;
try
{
// Marshalling
unsafe_destName = global::System.Runtime.InteropServices.McgMarshal.StringToAnsiString(destName, true, false);
unsafe_srcName = global::System.Runtime.InteropServices.McgMarshal.StringToAnsiString(srcName, true, false);
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_backup_init(
destDB,
unsafe_destName,
srcDB,
unsafe_srcName
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
finally
{
// Cleanup
global::System.Runtime.InteropServices.ExternalInterop.SafeCoTaskMemFree(unsafe_destName);
global::System.Runtime.InteropServices.ExternalInterop.SafeCoTaskMemFree(unsafe_srcName);
}
}
// Signature, sqlite3_backup_step, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_backup_step")]
public static global::SQLite.Net.Interop.Result__SQLite_Net sqlite3_backup_step(
global::System.IntPtr backup,
int pageCount)
{
// Setup
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_backup_step(
backup,
pageCount
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, sqlite3_backup_finish, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_backup_finish")]
public static global::SQLite.Net.Interop.Result__SQLite_Net sqlite3_backup_finish(global::System.IntPtr backup)
{
// Setup
global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_backup_finish(backup);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, sqlite3_backup_remaining, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_backup_remaining")]
public static int sqlite3_backup_remaining(global::System.IntPtr backup)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_backup_remaining(backup);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, sqlite3_backup_pagecount, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_backup_pagecount")]
public static int sqlite3_backup_pagecount(global::System.IntPtr backup)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_backup_pagecount(backup);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, sqlite3_sleep, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_sleep")]
public static int sqlite3_sleep(int millis)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_sleep(millis);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module '[MRT]'
/// </summary>
public unsafe static partial class _MRT_
{
// Signature, RhWaitForPendingFinalizers, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "RhWaitForPendingFinalizers")]
public static void RhWaitForPendingFinalizers(int allowReentrantWait)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes.RhWaitForPendingFinalizers(allowReentrantWait);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
// Signature, RhCompatibleReentrantWaitAny, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr___ptr__w64 int *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "RhCompatibleReentrantWaitAny")]
public static int RhCompatibleReentrantWaitAny(
int alertable,
int timeout,
int count,
global::System.IntPtr* handles)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop._MRT__PInvokes.RhCompatibleReentrantWaitAny(
alertable,
timeout,
count,
((global::System.IntPtr*)handles)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, _ecvt_s, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] double__double, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int___ptrint *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int___ptrint *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "_ecvt_s")]
public static void _ecvt_s(
byte* buffer,
int sizeInBytes,
double value,
int count,
int* dec,
int* sign)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes._ecvt_s(
((byte*)buffer),
sizeInBytes,
value,
count,
((int*)dec),
((int*)sign)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
// Signature, memmove, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "memmove")]
public static void memmove(
byte* dmem,
byte* smem,
uint size)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes.memmove(
((byte*)dmem),
((byte*)smem),
size
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
}
/// <summary>
/// P/Invoke class for module '*'
/// </summary>
public unsafe static partial class _
{
// Signature, CallingConventionConverter_GetStubs, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.TypeLoader, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.Runtime.TypeLoader.CallConverterThunk", "CallingConventionConverter_GetStubs")]
public static void CallingConventionConverter_GetStubs(
out global::System.IntPtr returnVoidStub,
out global::System.IntPtr returnIntegerStub,
out global::System.IntPtr commonStub)
{
// Setup
global::System.IntPtr unsafe_returnVoidStub;
global::System.IntPtr unsafe_returnIntegerStub;
global::System.IntPtr unsafe_commonStub;
// Marshalling
// Call to native method
global::McgInterop.__PInvokes.CallingConventionConverter_GetStubs(
&(unsafe_returnVoidStub),
&(unsafe_returnIntegerStub),
&(unsafe_commonStub)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
commonStub = unsafe_commonStub;
returnIntegerStub = unsafe_returnIntegerStub;
returnVoidStub = unsafe_returnVoidStub;
// Return
}
// Signature, CallingConventionConverter_SpecifyCommonStubData, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.TypeLoader, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.Runtime.TypeLoader.CallConverterThunk", "CallingConventionConverter_SpecifyCommonStubData")]
public static void CallingConventionConverter_SpecifyCommonStubData(global::System.IntPtr commonStubData)
{
// Marshalling
// Call to native method
global::McgInterop.__PInvokes.CallingConventionConverter_SpecifyCommonStubData(commonStubData);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-errorhandling-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_errorhandling_l1_1_0_dll
{
// Signature, GetLastError, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Runtime.Extensions, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetLastError")]
public static int GetLastError()
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_errorhandling_l1_1_0_dll_PInvokes.GetLastError();
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-winrt-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_winrt_l1_1_0_dll
{
// Signature, RoInitialize, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "RoInitialize")]
public static int RoInitialize(uint initType)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_winrt_l1_1_0_dll_PInvokes.RoInitialize(initType);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-localization-l1-2-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_localization_l1_2_0_dll
{
// Signature, IsValidLocaleName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "IsValidLocaleName")]
public static int IsValidLocaleName(char* lpLocaleName)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.IsValidLocaleName(((ushort*)lpLocaleName));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ResolveLocaleName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "ResolveLocaleName")]
public static int ResolveLocaleName(
char* lpNameToResolve,
char* lpLocaleName,
int cchLocaleName)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.ResolveLocaleName(
((ushort*)lpNameToResolve),
((ushort*)lpLocaleName),
cchLocaleName
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, GetCPInfoExW, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages___ptr__Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Text.Encoding.CodePages, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetCPInfoExW")]
public static int GetCPInfoExW(
uint CodePage,
uint dwFlags,
global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages* lpCPInfoEx)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.GetCPInfoExW(
CodePage,
dwFlags,
((global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages*)lpCPInfoEx)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-com-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_com_l1_1_0_dll
{
// Signature, CoCreateInstance, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.StackTraceGenerator, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.StackTraceGenerator.StackTraceGenerator", "CoCreateInstance")]
public static int CoCreateInstance(
byte* rclsid,
global::System.IntPtr pUnkOuter,
int dwClsContext,
byte* riid,
out global::System.IntPtr ppv)
{
// Setup
global::System.IntPtr unsafe_ppv;
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_com_l1_1_0_dll_PInvokes.CoCreateInstance(
((byte*)rclsid),
pUnkOuter,
dwClsContext,
((byte*)riid),
&(unsafe_ppv)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
ppv = unsafe_ppv;
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'OleAut32'
/// </summary>
public unsafe static partial class OleAut32
{
// Signature, SysFreeString, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.StackTraceGenerator, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.LightweightInterop.MarshalExtensions", "SysFreeString")]
public static void SysFreeString(global::System.IntPtr bstr)
{
// Marshalling
// Call to native method
global::McgInterop.OleAut32_PInvokes.SysFreeString(bstr);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-winrt-robuffer-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_winrt_robuffer_l1_1_0_dll
{
// Signature, RoGetBufferMarshaler, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.ComInterfaceMarshaller] System_Runtime_InteropServices_IMarshal__System_Runtime_WindowsRuntime__System_Runtime_InteropServices__IMarshal__System_Runtime_WindowsRuntime *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Runtime.WindowsRuntime, Version=4.0.11.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop+mincore", "RoGetBufferMarshaler")]
public static int RoGetBufferMarshaler(out global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime bufferMarshalerPtr)
{
// Setup
global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl** unsafe_bufferMarshalerPtr = default(global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl**);
int unsafe___value;
try
{
// Marshalling
unsafe_bufferMarshalerPtr = null;
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_winrt_robuffer_l1_1_0_dll_PInvokes.RoGetBufferMarshaler(&(unsafe_bufferMarshalerPtr));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
bufferMarshalerPtr = (global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime)global::System.Runtime.InteropServices.McgModuleManager.ComInterfaceToObject(
((global::System.IntPtr)unsafe_bufferMarshalerPtr),
global::System.Runtime.InteropServices.TypeOfHelper.RuntimeTypeHandleOf("System.Runtime.InteropServices.IMarshal,System.Runtime.WindowsRuntime, Version=4.0.11.0, Culture=neutral, Public" +
"KeyToken=b77a5c561934e089")
);
// Return
return unsafe___value;
}
finally
{
// Cleanup
global::System.Runtime.InteropServices.McgMarshal.ComSafeRelease(new global::System.IntPtr(((void*)unsafe_bufferMarshalerPtr)));
}
}
}
public unsafe static partial class sqlite3_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_open", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net Open(
byte* filename,
global::System.IntPtr* db);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_open_v2", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net Open__0(
byte* filename,
global::System.IntPtr* db,
int flags,
global::System.IntPtr zvfs);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_open_v2", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net Open__1(
byte* filename,
global::System.IntPtr* db,
int flags,
global::System.IntPtr zvfs);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_open16", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net Open16(
ushort* filename,
global::System.IntPtr* db);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_close", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net Close(global::System.IntPtr db);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_config", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net Config(global::SQLite.Net.Interop.ConfigOption__SQLite_Net option);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_win32_set_directory", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int SetDirectory(
uint directoryType,
ushort* directoryPath);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_busy_timeout", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net BusyTimeout(
global::System.IntPtr db,
int milliseconds);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_changes", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int Changes(global::System.IntPtr db);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_prepare_v2", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net Prepare2(
global::System.IntPtr db,
byte* sql,
int numBytes,
global::System.IntPtr* stmt,
global::System.IntPtr pzTail);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_step", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net Step(global::System.IntPtr stmt);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_reset", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net Reset(global::System.IntPtr stmt);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_finalize", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net Finalize(global::System.IntPtr stmt);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_last_insert_rowid", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static long LastInsertRowid(global::System.IntPtr db);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_errmsg16", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::System.IntPtr Errmsg(global::System.IntPtr db);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_bind_parameter_index", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int BindParameterIndex(
global::System.IntPtr stmt,
byte* name);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_bind_null", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int BindNull(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_bind_int", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int BindInt(
global::System.IntPtr stmt,
int index,
int val);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_bind_int64", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int BindInt64(
global::System.IntPtr stmt,
int index,
long val);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_bind_double", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int BindDouble(
global::System.IntPtr stmt,
int index,
double val);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_bind_text16", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int BindText(
global::System.IntPtr stmt,
int index,
ushort* val,
int n,
global::System.IntPtr free);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_bind_blob", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int BindBlob(
global::System.IntPtr stmt,
int index,
byte* val,
int n,
global::System.IntPtr free);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_count", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int ColumnCount(global::System.IntPtr stmt);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_name", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::System.IntPtr ColumnName(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_name16", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::System.IntPtr ColumnName16Internal(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_type", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.ColType__SQLite_Net ColumnType(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_int", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int ColumnInt(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_int64", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static long ColumnInt64(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_double", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static double ColumnDouble(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_text", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::System.IntPtr ColumnText(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_text16", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::System.IntPtr ColumnText16(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_blob", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::System.IntPtr ColumnBlob(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_bytes", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int ColumnBytes(
global::System.IntPtr stmt,
int index);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.ExtendedResult__SQLite_Net sqlite3_extended_errcode(global::System.IntPtr db);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int sqlite3_libversion_number();
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::System.IntPtr sqlite3_sourceid();
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::System.IntPtr sqlite3_backup_init(
global::System.IntPtr destDB,
byte* destName,
global::System.IntPtr srcDB,
byte* srcName);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net sqlite3_backup_step(
global::System.IntPtr backup,
int pageCount);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static global::SQLite.Net.Interop.Result__SQLite_Net sqlite3_backup_finish(global::System.IntPtr backup);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int sqlite3_backup_remaining(global::System.IntPtr backup);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int sqlite3_backup_pagecount(global::System.IntPtr backup);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)]
public extern static int sqlite3_sleep(int millis);
}
public unsafe static partial class _MRT__PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void RhWaitForPendingFinalizers(int allowReentrantWait);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int RhCompatibleReentrantWaitAny(
int alertable,
int timeout,
int count,
global::System.IntPtr* handles);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void _ecvt_s(
byte* buffer,
int sizeInBytes,
double value,
int count,
int* dec,
int* sign);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void memmove(
byte* dmem,
byte* smem,
uint size);
}
public unsafe static partial class __PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("*", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void CallingConventionConverter_GetStubs(
global::System.IntPtr* returnVoidStub,
global::System.IntPtr* returnIntegerStub,
global::System.IntPtr* commonStub);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("*", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void CallingConventionConverter_SpecifyCommonStubData(global::System.IntPtr commonStubData);
}
public unsafe static partial class api_ms_win_core_errorhandling_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-errorhandling-l1-1-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetLastError();
}
public unsafe static partial class api_ms_win_core_winrt_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-winrt-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int RoInitialize(uint initType);
}
public unsafe static partial class api_ms_win_core_localization_l1_2_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int IsValidLocaleName(ushort* lpLocaleName);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int ResolveLocaleName(
ushort* lpNameToResolve,
ushort* lpLocaleName,
int cchLocaleName);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetCPInfoExW(
uint CodePage,
uint dwFlags,
global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages* lpCPInfoEx);
}
public unsafe static partial class api_ms_win_core_com_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-com-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int CoCreateInstance(
byte* rclsid,
global::System.IntPtr pUnkOuter,
int dwClsContext,
byte* riid,
global::System.IntPtr* ppv);
}
public unsafe static partial class OleAut32_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("oleaut32.dll", EntryPoint="#6", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void SysFreeString(global::System.IntPtr bstr);
}
public unsafe static partial class api_ms_win_core_winrt_robuffer_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-winrt-robuffer-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.StdCall)]
public extern static int RoGetBufferMarshaler(global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl*** bufferMarshalerPtr);
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Reflection;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
/// <summary>
/// A synthesized instance method used for binding
/// expressions outside of a method - specifically, binding
/// DebuggerDisplayAttribute expressions.
/// </summary>
internal sealed class SynthesizedContextMethodSymbol : SynthesizedInstanceMethodSymbol
{
private readonly NamedTypeSymbol _container;
public SynthesizedContextMethodSymbol(NamedTypeSymbol container)
{
_container = container;
}
public override int Arity
{
get { return 0; }
}
public override Symbol AssociatedSymbol
{
get { return null; }
}
public override Symbol ContainingSymbol
{
get { return _container; }
}
public override Accessibility DeclaredAccessibility
{
get { return Accessibility.NotApplicable; }
}
public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations
{
get { return ImmutableArray<MethodSymbol>.Empty; }
}
public override bool HidesBaseMethodsByName
{
get { return false; }
}
public override bool IsAbstract
{
get { return false; }
}
public override bool IsAsync
{
get { return false; }
}
public override bool IsExtensionMethod
{
get { return false; }
}
public override bool IsExtern
{
get { return false; }
}
public override bool IsOverride
{
get { return false; }
}
public override bool IsSealed
{
get { return true; }
}
public override bool IsStatic
{
get { return false; }
}
public override bool IsVararg
{
get { return false; }
}
public override bool IsVirtual
{
get { return false; }
}
public override ImmutableArray<Location> Locations
{
get { throw ExceptionUtilities.Unreachable; }
}
public override MethodKind MethodKind
{
get { return MethodKind.Ordinary; }
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get { return ImmutableArray<ParameterSymbol>.Empty; }
}
public override bool ReturnsVoid
{
get { return true; }
}
internal override RefKind RefKind
{
get { return RefKind.None; }
}
public override TypeSymbol ReturnType
{
get { throw ExceptionUtilities.Unreachable; }
}
public override ImmutableArray<CustomModifier> ReturnTypeCustomModifiers
{
get { throw ExceptionUtilities.Unreachable; }
}
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get { throw ExceptionUtilities.Unreachable; }
}
public override ImmutableArray<TypeSymbol> TypeArguments
{
get { return ImmutableArray<TypeSymbol>.Empty; }
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return ImmutableArray<TypeParameterSymbol>.Empty; }
}
internal override Microsoft.Cci.CallingConvention CallingConvention
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool GenerateDebugInfo
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool HasDeclarativeSecurity
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool HasSpecialName
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override MethodImplAttributes ImplementationAttributes
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool RequiresSecurityObject
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation
{
get { throw ExceptionUtilities.Unreachable; }
}
public override DllImportData GetDllImportData()
{
throw ExceptionUtilities.Unreachable;
}
internal override ImmutableArray<string> GetAppliedConditionalSymbols()
{
throw ExceptionUtilities.Unreachable;
}
internal override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation()
{
throw ExceptionUtilities.Unreachable;
}
internal override bool IsMetadataFinal
{
get
{
return false;
}
}
internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false)
{
throw ExceptionUtilities.Unreachable;
}
internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false)
{
throw ExceptionUtilities.Unreachable;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace System.Runtime.CompilerServices.Tests
{
public class ConditionalWeakTableTests
{
[Fact]
public static void InvalidArgs_Throws()
{
var cwt = new ConditionalWeakTable<object, object>();
object ignored;
AssertExtensions.Throws<ArgumentNullException>("key", () => cwt.Add(null, new object())); // null key
AssertExtensions.Throws<ArgumentNullException>("key", () => cwt.TryGetValue(null, out ignored)); // null key
AssertExtensions.Throws<ArgumentNullException>("key", () => cwt.Remove(null)); // null key
AssertExtensions.Throws<ArgumentNullException>("createValueCallback", () => cwt.GetValue(new object(), null)); // null delegate
object key = new object();
cwt.Add(key, key);
AssertExtensions.Throws<ArgumentException>(null, () => cwt.Add(key, key)); // duplicate key
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))]
[InlineData(1)]
[InlineData(100)]
public static void Add(int numObjects)
{
// Isolated to ensure we drop all references even in debug builds where lifetime is extended by the JIT to the end of the method
Func<int, Tuple<ConditionalWeakTable<object, object>, WeakReference[], WeakReference[]>> body = count =>
{
object[] keys = Enumerable.Range(0, count).Select(_ => new object()).ToArray();
object[] values = Enumerable.Range(0, count).Select(_ => new object()).ToArray();
var cwt = new ConditionalWeakTable<object, object>();
for (int i = 0; i < count; i++)
{
cwt.Add(keys[i], values[i]);
}
for (int i = 0; i < count; i++)
{
object value;
Assert.True(cwt.TryGetValue(keys[i], out value));
Assert.Same(values[i], value);
Assert.Same(value, cwt.GetOrCreateValue(keys[i]));
Assert.Same(value, cwt.GetValue(keys[i], _ => new object()));
}
return Tuple.Create(cwt, keys.Select(k => new WeakReference(k)).ToArray(), values.Select(v => new WeakReference(v)).ToArray());
};
Tuple<ConditionalWeakTable<object, object>, WeakReference[], WeakReference[]> result = body(numObjects);
GC.Collect();
Assert.NotNull(result.Item1);
for (int i = 0; i < numObjects; i++)
{
Assert.False(result.Item2[i].IsAlive, $"Expected not to find key #{i}");
Assert.False(result.Item3[i].IsAlive, $"Expected not to find value #{i}");
}
}
[Theory]
[InlineData(1)]
[InlineData(100)]
public static void AddMany_ThenRemoveAll(int numObjects)
{
object[] keys = Enumerable.Range(0, numObjects).Select(_ => new object()).ToArray();
object[] values = Enumerable.Range(0, numObjects).Select(_ => new object()).ToArray();
var cwt = new ConditionalWeakTable<object, object>();
for (int i = 0; i < numObjects; i++)
{
cwt.Add(keys[i], values[i]);
}
for (int i = 0; i < numObjects; i++)
{
Assert.Same(values[i], cwt.GetValue(keys[i], _ => new object()));
}
for (int i = 0; i < numObjects; i++)
{
Assert.True(cwt.Remove(keys[i]));
Assert.False(cwt.Remove(keys[i]));
}
for (int i = 0; i < numObjects; i++)
{
object ignored;
Assert.False(cwt.TryGetValue(keys[i], out ignored));
}
}
[Theory]
[InlineData(100)]
public static void AddRemoveIteratively(int numObjects)
{
object[] keys = Enumerable.Range(0, numObjects).Select(_ => new object()).ToArray();
object[] values = Enumerable.Range(0, numObjects).Select(_ => new object()).ToArray();
var cwt = new ConditionalWeakTable<object, object>();
for (int i = 0; i < numObjects; i++)
{
cwt.Add(keys[i], values[i]);
Assert.Same(values[i], cwt.GetValue(keys[i], _ => new object()));
Assert.True(cwt.Remove(keys[i]));
Assert.False(cwt.Remove(keys[i]));
}
}
[Fact]
public static void Concurrent_AddMany_DropReferences() // no asserts, just making nothing throws
{
var cwt = new ConditionalWeakTable<object, object>();
for (int i = 0; i < 10000; i++)
{
cwt.Add(i.ToString(), i.ToString());
if (i % 1000 == 0) GC.Collect();
}
}
[Fact]
public static void Concurrent_Add_Read_Remove_DifferentObjects()
{
var cwt = new ConditionalWeakTable<object, object>();
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(0.25);
Parallel.For(0, Environment.ProcessorCount, i =>
{
while (DateTime.UtcNow < end)
{
object key = new object();
object value = new object();
cwt.Add(key, value);
Assert.Same(value, cwt.GetValue(key, _ => new object()));
Assert.True(cwt.Remove(key));
Assert.False(cwt.Remove(key));
}
});
}
[Fact]
public static void Concurrent_GetValue_Read_Remove_DifferentObjects()
{
var cwt = new ConditionalWeakTable<object, object>();
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(0.25);
Parallel.For(0, Environment.ProcessorCount, i =>
{
while (DateTime.UtcNow < end)
{
object key = new object();
object value = new object();
Assert.Same(value, cwt.GetValue(key, _ => value));
Assert.True(cwt.Remove(key));
Assert.False(cwt.Remove(key));
}
});
}
[Fact]
public static void Concurrent_GetValue_Read_Remove_SameObject()
{
object key = new object();
object value = new object();
var cwt = new ConditionalWeakTable<object, object>();
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(0.25);
Parallel.For(0, Environment.ProcessorCount, i =>
{
while (DateTime.UtcNow < end)
{
Assert.Same(value, cwt.GetValue(key, _ => value));
cwt.Remove(key);
}
});
}
[System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
static WeakReference GetWeakCondTabRef(out ConditionalWeakTable<object, object> cwt_out, out object key_out)
{
var key = new object();
var value = new object();
var cwt = new ConditionalWeakTable<object, object>();
cwt.Add(key, value);
cwt.Remove(key);
// Return 3 values to the caller, drop everything else on the floor.
cwt_out = cwt;
key_out = key;
return new WeakReference(value);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))]
public static void AddRemove_DropValue()
{
// Verify that the removed entry is not keeping the value alive
ConditionalWeakTable<object, object> cwt;
object key;
var wrValue = GetWeakCondTabRef(out cwt, out key);
GC.Collect();
Assert.False(wrValue.IsAlive);
GC.KeepAlive(cwt);
GC.KeepAlive(key);
}
[System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
static void GetWeakRefPair(out WeakReference<object> key_out, out WeakReference<object> val_out)
{
var cwt = new ConditionalWeakTable<object, object>();
var key = new object();
object value = cwt.GetOrCreateValue(key);
Assert.True(cwt.TryGetValue(key, out value));
Assert.Equal(value, cwt.GetValue(key, k => new object()));
val_out = new WeakReference<object>(value, false);
key_out = new WeakReference<object>(key, false);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))]
public static void GetOrCreateValue()
{
WeakReference<object> wrValue;
WeakReference<object> wrKey;
GetWeakRefPair(out wrKey, out wrValue);
GC.Collect();
// key and value must be collected
object obj;
Assert.False(wrValue.TryGetTarget(out obj));
Assert.False(wrKey.TryGetTarget(out obj));
}
[System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
static void GetWeakRefValPair(out WeakReference<object> key_out, out WeakReference<object> val_out)
{
var cwt = new ConditionalWeakTable<object, object>();
var key = new object();
object value = cwt.GetValue(key, k => new object());
Assert.True(cwt.TryGetValue(key, out value));
Assert.Equal(value, cwt.GetOrCreateValue(key));
val_out = new WeakReference<object>(value, false);
key_out = new WeakReference<object>(key, false);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))]
public static void GetValue()
{
WeakReference<object> wrValue;
WeakReference<object> wrKey;
GetWeakRefValPair(out wrKey, out wrValue);
GC.Collect();
// key and value must be collected
object obj;
Assert.False(wrValue.TryGetTarget(out obj));
Assert.False(wrKey.TryGetTarget(out obj));
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
public static void Clear_AllValuesRemoved(int numObjects)
{
var cwt = new ConditionalWeakTable<object, object>();
MethodInfo clear = cwt.GetType().GetMethod("Clear", BindingFlags.NonPublic | BindingFlags.Instance);
if (clear == null)
{
// Couldn't access the Clear method; skip the test.
return;
}
object[] keys = Enumerable.Range(0, numObjects).Select(_ => new object()).ToArray();
object[] values = Enumerable.Range(0, numObjects).Select(_ => new object()).ToArray();
for (int iter = 0; iter < 2; iter++)
{
// Add the objects
for (int i = 0; i < numObjects; i++)
{
cwt.Add(keys[i], values[i]);
Assert.Same(values[i], cwt.GetValue(keys[i], _ => new object()));
}
// Clear the table
clear.Invoke(cwt, null);
// Verify the objects are removed
for (int i = 0; i < numObjects; i++)
{
object ignored;
Assert.False(cwt.TryGetValue(keys[i], out ignored));
}
// Do it a couple of times, to make sure the table is still usable after a clear.
}
}
[Fact]
public static void AddOrUpdateDataTest()
{
var cwt = new ConditionalWeakTable<string, string>();
string key = "key1";
cwt.AddOrUpdate(key, "value1");
string value;
Assert.True(cwt.TryGetValue(key, out value));
Assert.Equal("value1", value);
Assert.Equal(value, cwt.GetOrCreateValue(key));
Assert.Equal(value, cwt.GetValue(key, k => "value1"));
Assert.Throws<ArgumentNullException>(() => cwt.AddOrUpdate(null, "value2"));
cwt.AddOrUpdate(key, "value2");
Assert.True(cwt.TryGetValue(key, out value));
Assert.Equal("value2", value);
Assert.Equal(value, cwt.GetOrCreateValue(key));
Assert.Equal(value, cwt.GetValue(key, k => "value1"));
}
[Fact]
public static void Clear_EmptyTable()
{
var cwt = new ConditionalWeakTable<object, object>();
cwt.Clear(); // no exception
cwt.Clear();
}
[Fact]
public static void Clear_AddThenEmptyRepeatedly_ItemsRemoved()
{
var cwt = new ConditionalWeakTable<object, object>();
object key = new object(), value = new object();
object result;
for (int i = 0; i < 3; i++)
{
cwt.Add(key, value);
Assert.True(cwt.TryGetValue(key, out result));
Assert.Same(value, result);
cwt.Clear();
Assert.False(cwt.TryGetValue(key, out result));
Assert.Null(result);
}
}
[Fact]
public static void Clear_AddMany_Clear_AllItemsRemoved()
{
var cwt = new ConditionalWeakTable<object, object>();
object[] keys = Enumerable.Range(0, 33).Select(_ => new object()).ToArray();
object[] values = Enumerable.Range(0, keys.Length).Select(_ => new object()).ToArray();
for (int i = 0; i < keys.Length; i++)
{
cwt.Add(keys[i], values[i]);
}
Assert.Equal(keys.Length, ((IEnumerable<KeyValuePair<object, object>>)cwt).Count());
cwt.Clear();
Assert.Equal(0, ((IEnumerable<KeyValuePair<object, object>>)cwt).Count());
GC.KeepAlive(keys);
GC.KeepAlive(values);
}
[Fact]
public static void GetEnumerator_Empty_ReturnsEmptyEnumerator()
{
var cwt = new ConditionalWeakTable<object, object>();
var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt;
Assert.Equal(0, enumerable.Count());
}
[Fact]
public static void GetEnumerator_AddedAndRemovedItems_AppropriatelyShowUpInEnumeration()
{
var cwt = new ConditionalWeakTable<object, object>();
var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt;
object key1 = new object(), value1 = new object();
for (int i = 0; i < 20; i++) // adding and removing multiple times, across internal container boundary
{
cwt.Add(key1, value1);
Assert.Equal(1, enumerable.Count());
Assert.Equal(new KeyValuePair<object, object>(key1, value1), enumerable.First());
Assert.True(cwt.Remove(key1));
Assert.Equal(0, enumerable.Count());
}
GC.KeepAlive(key1);
GC.KeepAlive(value1);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))]
public static void GetEnumerator_CollectedItemsNotEnumerated()
{
var cwt = new ConditionalWeakTable<object, object>();
var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt;
// Delegate to add collectible items to the table, separated out
// to avoid the JIT extending the lifetimes of the temporaries
Action<ConditionalWeakTable<object, object>> addItem =
t => t.Add(new object(), new object());
for (int i = 0; i < 10; i++) addItem(cwt);
GC.Collect();
Assert.Equal(0, enumerable.Count());
}
[Fact]
public static void GetEnumerator_MultipleEnumeratorsReturnSameResults()
{
var cwt = new ConditionalWeakTable<object, object>();
var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt;
object[] keys = Enumerable.Range(0, 33).Select(_ => new object()).ToArray();
object[] values = Enumerable.Range(0, keys.Length).Select(_ => new object()).ToArray();
for (int i = 0; i < keys.Length; i++)
{
cwt.Add(keys[i], values[i]);
}
using (IEnumerator<KeyValuePair<object, object>> enumerator1 = enumerable.GetEnumerator())
using (IEnumerator<KeyValuePair<object, object>> enumerator2 = enumerable.GetEnumerator())
{
while (enumerator1.MoveNext())
{
Assert.True(enumerator2.MoveNext());
Assert.Equal(enumerator1.Current, enumerator2.Current);
}
Assert.False(enumerator2.MoveNext());
}
GC.KeepAlive(keys);
GC.KeepAlive(values);
}
[Fact]
public static void GetEnumerator_RemovedItems_RemovedFromResults()
{
var cwt = new ConditionalWeakTable<object, object>();
var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt;
object[] keys = Enumerable.Range(0, 33).Select(_ => new object()).ToArray();
object[] values = Enumerable.Range(0, keys.Length).Select(_ => new object()).ToArray();
for (int i = 0; i < keys.Length; i++)
{
cwt.Add(keys[i], values[i]);
}
for (int i = 0; i < keys.Length; i++)
{
Assert.Equal(keys.Length - i, enumerable.Count());
Assert.Equal(
Enumerable.Range(i, keys.Length - i).Select(j => new KeyValuePair<object, object>(keys[j], values[j])),
enumerable);
cwt.Remove(keys[i]);
}
Assert.Equal(0, enumerable.Count());
GC.KeepAlive(keys);
GC.KeepAlive(values);
}
[Fact]
public static void GetEnumerator_ItemsAddedAfterGetEnumeratorNotIncluded()
{
var cwt = new ConditionalWeakTable<object, object>();
var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt;
object key1 = new object(), key2 = new object(), value1 = new object(), value2 = new object();
cwt.Add(key1, value1);
IEnumerator<KeyValuePair<object, object>> enumerator1 = enumerable.GetEnumerator();
cwt.Add(key2, value2);
IEnumerator<KeyValuePair<object, object>> enumerator2 = enumerable.GetEnumerator();
Assert.True(enumerator1.MoveNext());
Assert.Equal(new KeyValuePair<object, object>(key1, value1), enumerator1.Current);
Assert.False(enumerator1.MoveNext());
Assert.True(enumerator2.MoveNext());
Assert.Equal(new KeyValuePair<object, object>(key1, value1), enumerator2.Current);
Assert.True(enumerator2.MoveNext());
Assert.Equal(new KeyValuePair<object, object>(key2, value2), enumerator2.Current);
Assert.False(enumerator2.MoveNext());
enumerator1.Dispose();
enumerator2.Dispose();
GC.KeepAlive(key1);
GC.KeepAlive(key2);
GC.KeepAlive(value1);
GC.KeepAlive(value2);
}
[Fact]
public static void GetEnumerator_ItemsRemovedAfterGetEnumeratorNotIncluded()
{
var cwt = new ConditionalWeakTable<object, object>();
var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt;
object key1 = new object(), key2 = new object(), value1 = new object(), value2 = new object();
cwt.Add(key1, value1);
cwt.Add(key2, value2);
IEnumerator<KeyValuePair<object, object>> enumerator1 = enumerable.GetEnumerator();
cwt.Remove(key1);
IEnumerator<KeyValuePair<object, object>> enumerator2 = enumerable.GetEnumerator();
Assert.True(enumerator1.MoveNext());
Assert.Equal(new KeyValuePair<object, object>(key2, value2), enumerator1.Current);
Assert.False(enumerator1.MoveNext());
Assert.True(enumerator2.MoveNext());
Assert.Equal(new KeyValuePair<object, object>(key2, value2), enumerator2.Current);
Assert.False(enumerator2.MoveNext());
enumerator1.Dispose();
enumerator2.Dispose();
GC.KeepAlive(key1);
GC.KeepAlive(key2);
GC.KeepAlive(value1);
GC.KeepAlive(value2);
}
[Fact]
public static void GetEnumerator_ItemsClearedAfterGetEnumeratorNotIncluded()
{
var cwt = new ConditionalWeakTable<object, object>();
var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt;
object key1 = new object(), key2 = new object(), value1 = new object(), value2 = new object();
cwt.Add(key1, value1);
cwt.Add(key2, value2);
IEnumerator<KeyValuePair<object, object>> enumerator1 = enumerable.GetEnumerator();
cwt.Clear();
IEnumerator<KeyValuePair<object, object>> enumerator2 = enumerable.GetEnumerator();
Assert.False(enumerator1.MoveNext());
Assert.False(enumerator2.MoveNext());
enumerator1.Dispose();
enumerator2.Dispose();
GC.KeepAlive(key1);
GC.KeepAlive(key2);
GC.KeepAlive(value1);
GC.KeepAlive(value2);
}
[Fact]
public static void GetEnumerator_Current_ThrowsOnInvalidUse()
{
var cwt = new ConditionalWeakTable<object, object>();
var enumerable = (IEnumerable<KeyValuePair<object, object>>)cwt;
object key1 = new object(), value1 = new object();
cwt.Add(key1, value1);
using (IEnumerator<KeyValuePair<object, object>> enumerator = enumerable.GetEnumerator())
{
Assert.Throws<InvalidOperationException>(() => enumerator.Current); // before first MoveNext
}
GC.KeepAlive(key1);
GC.KeepAlive(value1);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using Legacy.Support;
using Xunit;
using ThreadState = System.Threading.ThreadState;
namespace System.IO.Ports.Tests
{
public class Write_str_Generic : PortsTest
{
//Set bounds fore random timeout values.
//If the min is to low write will not timeout accurately and the testcase will fail
private const int minRandomTimeout = 250;
//If the max is to large then the testcase will take forever to run
private const int maxRandomTimeout = 2000;
//If the percentage difference between the expected timeout and the actual timeout
//found through Stopwatch is greater then 10% then the timeout value was not correctly
//to the write method and the testcase fails.
private const double maxPercentageDifference = .15;
//The string used when we expect the ReadCall to throw an exception for something other
//then the contents of the string itself
private const string DEFAULT_STRING = "DEFAULT_STRING";
//The string size used when verifying BytesToWrite
private static readonly int s_STRING_SIZE_BYTES_TO_WRITE = 2 * TCSupport.MinimumBlockingByteCount;
//The string size used when verifying Handshake
private const int STRING_SIZE_HANDSHAKE = 8;
private const int NUM_TRYS = 5;
#region Test Cases
[Fact]
public void WriteWithoutOpen()
{
using (SerialPort com = new SerialPort())
{
Debug.WriteLine("Verifying write method throws exception without a call to Open()");
VerifyWriteException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteAfterFailedOpen()
{
using (SerialPort com = new SerialPort("BAD_PORT_NAME"))
{
Debug.WriteLine("Verifying write method throws exception with a failed call to Open()");
//Since the PortName is set to a bad port name Open will thrown an exception
//however we don't care what it is since we are verifying a write method
Assert.ThrowsAny<Exception>(() => com.Open());
VerifyWriteException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteAfterClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying write method throws exception after a call to Cloes()");
com.Open();
com.Close();
VerifyWriteException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasNullModem))]
public void Timeout()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] XOffBuffer = new byte[1];
XOffBuffer[0] = 19;
com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Handshake = Handshake.XOnXOff;
Debug.WriteLine("Verifying WriteTimeout={0}", com1.WriteTimeout);
com1.Open();
com2.Open();
com2.Write(XOffBuffer, 0, 1);
Thread.Sleep(250);
com2.Close();
VerifyTimeout(com1);
}
}
[OuterLoop("Slow test")]
[ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))]
public void SuccessiveReadTimeout()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com.Handshake = Handshake.RequestToSendXOnXOff;
// com.Encoding = new System.Text.UTF7Encoding();
com.Encoding = Encoding.Unicode;
Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout);
com.Open();
try
{
com.Write(DEFAULT_STRING);
}
catch (TimeoutException)
{
}
VerifyTimeout(com);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void SuccessiveReadTimeoutWithWriteSucceeding()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
AsyncEnableRts asyncEnableRts = new AsyncEnableRts();
Thread t = new Thread(asyncEnableRts.EnableRTS);
int waitTime;
com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Handshake = Handshake.RequestToSend;
com1.Encoding = new UTF8Encoding();
Debug.WriteLine(
"Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before its timeout",
com1.WriteTimeout);
com1.Open();
//Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed
//before the timeout is reached
t.Start();
waitTime = 0;
while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{
//Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
try
{
com1.Write(DEFAULT_STRING);
}
catch (TimeoutException)
{
}
asyncEnableRts.Stop();
while (t.IsAlive)
Thread.Sleep(100);
VerifyTimeout(com1);
}
}
[ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))]
public void BytesToWrite()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, s_STRING_SIZE_BYTES_TO_WRITE);
Thread t = new Thread(asyncWriteRndStr.WriteRndStr);
int waitTime;
Debug.WriteLine("Verifying BytesToWrite with one call to Write");
com.Handshake = Handshake.RequestToSend;
com.Open();
com.WriteTimeout = 500;
//Write a random string asynchronously so we can verify some things while the write call is blocking
t.Start();
waitTime = 0;
while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{
//Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
TCSupport.WaitForWriteBufferToLoad(com, s_STRING_SIZE_BYTES_TO_WRITE);
//Wait for write method to timeout
while (t.IsAlive)
Thread.Sleep(100);
}
}
[ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))]
public void BytesToWriteSuccessive()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, s_STRING_SIZE_BYTES_TO_WRITE);
var t1 = new Thread(asyncWriteRndStr.WriteRndStr);
var t2 = new Thread(asyncWriteRndStr.WriteRndStr);
int waitTime;
Debug.WriteLine("Verifying BytesToWrite with successive calls to Write");
com.Handshake = Handshake.RequestToSend;
com.Open();
com.WriteTimeout = 1000;
//Write a random string asynchronously so we can verify some things while the write call is blocking
t1.Start();
waitTime = 0;
while (t1.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{
//Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
TCSupport.WaitForWriteBufferToLoad(com, s_STRING_SIZE_BYTES_TO_WRITE);
//Write a random string asynchronously so we can verify some things while the write call is blocking
t2.Start();
waitTime = 0;
while (t2.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{
//Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
TCSupport.WaitForWriteBufferToLoad(com, s_STRING_SIZE_BYTES_TO_WRITE * 2);
//Wait for both write methods to timeout
while (t1.IsAlive || t2.IsAlive)
Thread.Sleep(100);
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Handshake_None()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, STRING_SIZE_HANDSHAKE);
Thread t = new Thread(asyncWriteRndStr.WriteRndStr);
int waitTime;
//Write a random string asynchronously so we can verify some things while the write call is blocking
Debug.WriteLine("Verifying Handshake=None");
com.Open();
t.Start();
waitTime = 0;
while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{ //Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
//Wait for both write methods to timeout
while (t.IsAlive)
Thread.Sleep(100);
Assert.Equal(0, com.BytesToWrite);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_RequestToSend()
{
Verify_Handshake(Handshake.RequestToSend);
}
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_XOnXOff()
{
Verify_Handshake(Handshake.XOnXOff);
}
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_RequestToSendXOnXOff()
{
Verify_Handshake(Handshake.RequestToSendXOnXOff);
}
private class AsyncEnableRts
{
private bool _stop;
public void EnableRTS()
{
lock (this)
{
SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName);
Random rndGen = new Random(-55);
int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2);
//Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1
Thread.Sleep(sleepPeriod);
com2.Open();
com2.RtsEnable = true;
while (!_stop)
Monitor.Wait(this);
com2.RtsEnable = false;
if (com2.IsOpen)
com2.Close();
}
}
public void Stop()
{
lock (this)
{
_stop = true;
Monitor.Pulse(this);
}
}
}
public class AsyncWriteRndStr
{
private readonly SerialPort _com;
private readonly int _strSize;
public AsyncWriteRndStr(SerialPort com, int strSize)
{
_com = com;
_strSize = strSize;
}
public void WriteRndStr()
{
string stringToWrite = TCSupport.GetRandomString(_strSize, TCSupport.CharacterOptions.Surrogates);
try
{
_com.Write(stringToWrite);
}
catch (TimeoutException)
{
}
}
}
#endregion
#region Verification for Test Cases
public static void VerifyWriteException(SerialPort com, Type expectedException)
{
Assert.Throws(expectedException, () => com.Write(DEFAULT_STRING));
}
private void VerifyTimeout(SerialPort com)
{
Stopwatch timer = new Stopwatch();
int expectedTime = com.WriteTimeout;
int actualTime = 0;
double percentageDifference;
try
{
com.Write(DEFAULT_STRING); //Warm up write method
}
catch (TimeoutException) { }
Thread.CurrentThread.Priority = ThreadPriority.Highest;
for (int i = 0; i < NUM_TRYS; i++)
{
timer.Start();
try
{
com.Write(DEFAULT_STRING);
}
catch (TimeoutException) { }
timer.Stop();
actualTime += (int)timer.ElapsedMilliseconds;
timer.Reset();
}
Thread.CurrentThread.Priority = ThreadPriority.Normal;
actualTime /= NUM_TRYS;
percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime);
//Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference
if (maxPercentageDifference < percentageDifference)
{
Fail("ERROR!!!: The write method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference);
}
}
private void Verify_Handshake(Handshake handshake)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com1, STRING_SIZE_HANDSHAKE);
Thread t = new Thread(asyncWriteRndStr.WriteRndStr);
byte[] XOffBuffer = new byte[1];
byte[] XOnBuffer = new byte[1];
int waitTime;
XOffBuffer[0] = 19;
XOnBuffer[0] = 17;
Debug.WriteLine("Verifying Handshake={0}", handshake);
com1.Handshake = handshake;
com1.Open();
com2.Open();
//Setup to ensure write will bock with type of handshake method being used
if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.RtsEnable = false;
}
if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.Write(XOffBuffer, 0, 1);
Thread.Sleep(250);
}
//Write a random string asynchronously so we can verify some things while the write call is blocking
t.Start();
waitTime = 0;
while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000)
{
//Wait for the thread to start
Thread.Sleep(50);
waitTime += 50;
}
TCSupport.WaitForExactWriteBufferLoad(com1, STRING_SIZE_HANDSHAKE);
//Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used
if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && com1.CtsHolding)
{
Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", false, com1.CtsHolding);
}
//Setup to ensure write will succeed
if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.RtsEnable = true;
}
if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake)
{
com2.Write(XOnBuffer, 0, 1);
}
//Wait till write finishes
while (t.IsAlive)
Thread.Sleep(100);
//Verify that the correct number of bytes are in the buffer
if (0 != com1.BytesToWrite)
{
Fail("ERROR!!! Expcted BytesToWrite=0 actual {0}", com1.BytesToWrite);
}
//Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used
if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) &&
!com1.CtsHolding)
{
Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", true, com1.CtsHolding);
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Media3D;
namespace WPF.JoshSmith.Controls
{
/// <summary>
/// A Canvas which manages dragging of the UIElements it contains.
/// </summary>
public class DragCanvas : Canvas
{
#region Data
// Stores a reference to the UIElement currently being dragged by the user.
private UIElement elementBeingDragged;
// Keeps track of where the mouse cursor was when a drag operation began.
private Point origCursorLocation;
// The offsets from the DragCanvas' edges when the drag operation began.
private double origHorizOffset, origVertOffset;
// Keeps track of which horizontal and vertical offset should be modified for the drag element.
private bool modifyLeftOffset, modifyTopOffset;
// True if a drag operation is underway, else false.
private bool isDragInProgress;
#endregion // Data
#region Attached Properties
#region CanBeDragged
public static readonly DependencyProperty CanBeDraggedProperty;
public static bool GetCanBeDragged( UIElement uiElement )
{
if( uiElement == null )
return false;
return (bool)uiElement.GetValue( CanBeDraggedProperty );
}
public static void SetCanBeDragged( UIElement uiElement, bool value )
{
if( uiElement != null )
uiElement.SetValue( CanBeDraggedProperty, value );
}
#endregion // CanBeDragged
#endregion // Attached Properties
#region Dependency Properties
public static readonly DependencyProperty AllowDraggingProperty;
public static readonly DependencyProperty AllowDragOutOfViewProperty;
#endregion // Dependency Properties
#region Static Constructor
static DragCanvas()
{
AllowDraggingProperty = DependencyProperty.Register(
"AllowDragging",
typeof( bool ),
typeof( DragCanvas ),
new PropertyMetadata( true ) );
AllowDragOutOfViewProperty = DependencyProperty.Register(
"AllowDragOutOfView",
typeof( bool ),
typeof( DragCanvas ),
new UIPropertyMetadata( false ) );
CanBeDraggedProperty = DependencyProperty.RegisterAttached(
"CanBeDragged",
typeof( bool ),
typeof( DragCanvas ),
new UIPropertyMetadata( true ) );
}
#endregion // Static Constructor
#region Constructor
/// <summary>
/// Initializes a new instance of DragCanvas. UIElements in
/// the DragCanvas will immediately be draggable by the user.
/// </summary>
public DragCanvas()
{
}
#endregion // Constructor
#region Interface
#region AllowDragging
/// <summary>
/// Gets/sets whether elements in the DragCanvas should be draggable by the user.
/// The default value is true. This is a dependency property.
/// </summary>
public bool AllowDragging
{
get { return (bool)base.GetValue( AllowDraggingProperty ); }
set { base.SetValue( AllowDraggingProperty, value ); }
}
#endregion // AllowDragging
#region AllowDragOutOfView
/// <summary>
/// Gets/sets whether the user should be able to drag elements in the DragCanvas out of
/// the viewable area. The default value is false. This is a dependency property.
/// </summary>
public bool AllowDragOutOfView
{
get { return (bool)GetValue( AllowDragOutOfViewProperty ); }
set { SetValue( AllowDragOutOfViewProperty, value ); }
}
#endregion // AllowDragOutOfView
#region BringToFront / SendToBack
/// <summary>
/// Assigns the element a z-index which will ensure that
/// it is in front of every other element in the Canvas.
/// The z-index of every element whose z-index is between
/// the element's old and new z-index will have its z-index
/// decremented by one.
/// </summary>
/// <param name="targetElement">
/// The element to be sent to the front of the z-order.
/// </param>
public void BringToFront( UIElement element )
{
this.UpdateZOrder( element, true );
}
/// <summary>
/// Assigns the element a z-index which will ensure that
/// it is behind every other element in the Canvas.
/// The z-index of every element whose z-index is between
/// the element's old and new z-index will have its z-index
/// incremented by one.
/// </summary>
/// <param name="targetElement">
/// The element to be sent to the back of the z-order.
/// </param>
public void SendToBack( UIElement element )
{
this.UpdateZOrder( element, false );
}
#endregion // BringToFront / SendToBack
#region ElementBeingDragged
/// <summary>
/// Returns the UIElement currently being dragged, or null.
/// </summary>
/// <remarks>
/// Note to inheritors: This property exposes a protected
/// setter which should be used to modify the drag element.
/// </remarks>
public UIElement ElementBeingDragged
{
get
{
if( !this.AllowDragging )
return null;
else
return this.elementBeingDragged;
}
protected set
{
if( this.elementBeingDragged != null )
this.elementBeingDragged.ReleaseMouseCapture();
if( !this.AllowDragging )
this.elementBeingDragged = null;
else
{
if( DragCanvas.GetCanBeDragged( value ) )
{
this.elementBeingDragged = value;
this.elementBeingDragged.CaptureMouse();
}
else
this.elementBeingDragged = null;
}
}
}
#endregion // ElementBeingDragged
#region FindCanvasChild
/// <summary>
/// Walks up the visual tree starting with the specified DependencyObject,
/// looking for a UIElement which is a child of the Canvas. If a suitable
/// element is not found, null is returned. If the 'depObj' object is a
/// UIElement in the Canvas's Children collection, it will be returned.
/// </summary>
/// <param name="depObj">
/// A DependencyObject from which the search begins.
/// </param>
public UIElement FindCanvasChild( DependencyObject depObj )
{
while( depObj != null )
{
// If the current object is a UIElement which is a child of the
// Canvas, exit the loop and return it.
UIElement elem = depObj as UIElement;
if( elem != null && base.Children.Contains( elem ) )
break;
// VisualTreeHelper works with objects of type Visual or Visual3D.
// If the current object is not derived from Visual or Visual3D,
// then use the LogicalTreeHelper to find the parent element.
if( depObj is Visual || depObj is Visual3D )
depObj = VisualTreeHelper.GetParent( depObj );
else
depObj = LogicalTreeHelper.GetParent( depObj );
}
return depObj as UIElement;
}
#endregion // FindCanvasChild
#endregion // Interface
#region Overrides
#region OnPreviewMouseLeftButtonDown
protected override void OnPreviewMouseLeftButtonDown( MouseButtonEventArgs e )
{
base.OnPreviewMouseLeftButtonDown( e );
this.isDragInProgress = false;
// Cache the mouse cursor location.
this.origCursorLocation = e.GetPosition( this );
// Walk up the visual tree from the element that was clicked,
// looking for an element that is a direct child of the Canvas.
this.ElementBeingDragged = this.FindCanvasChild( e.Source as DependencyObject );
if( this.ElementBeingDragged == null )
return;
// Get the element's offsets from the four sides of the Canvas.
double left = Canvas.GetLeft( this.ElementBeingDragged );
double right = Canvas.GetRight( this.ElementBeingDragged );
double top = Canvas.GetTop( this.ElementBeingDragged );
double bottom = Canvas.GetBottom( this.ElementBeingDragged );
// Calculate the offset deltas and determine for which sides
// of the Canvas to adjust the offsets.
this.origHorizOffset = ResolveOffset( left, right, out this.modifyLeftOffset );
this.origVertOffset = ResolveOffset( top, bottom, out this.modifyTopOffset );
// Set the Handled flag so that a control being dragged
// does not react to the mouse input.
//e.Handled = true;
this.isDragInProgress = true;
}
#endregion // OnPreviewMouseLeftButtonDown
#region OnPreviewMouseMove
protected override void OnPreviewMouseMove( MouseEventArgs e )
{
base.OnPreviewMouseMove( e );
// If no element is being dragged, there is nothing to do.
if( this.ElementBeingDragged == null || !this.isDragInProgress )
return;
// Get the position of the mouse cursor, relative to the Canvas.
Point cursorLocation = e.GetPosition( this );
// These values will store the new offsets of the drag element.
double newHorizontalOffset, newVerticalOffset;
#region Calculate Offsets
// Determine the horizontal offset.
if( this.modifyLeftOffset )
newHorizontalOffset = this.origHorizOffset + (cursorLocation.X - this.origCursorLocation.X);
else
newHorizontalOffset = this.origHorizOffset - (cursorLocation.X - this.origCursorLocation.X);
// Determine the vertical offset.
if( this.modifyTopOffset )
newVerticalOffset = this.origVertOffset + (cursorLocation.Y - this.origCursorLocation.Y);
else
newVerticalOffset = this.origVertOffset - (cursorLocation.Y - this.origCursorLocation.Y);
#endregion // Calculate Offsets
if( ! this.AllowDragOutOfView )
{
#region Verify Drag Element Location
// Get the bounding rect of the drag element.
Rect elemRect = this.CalculateDragElementRect( newHorizontalOffset, newVerticalOffset );
//
// If the element is being dragged out of the viewable area,
// determine the ideal rect location, so that the element is
// within the edge(s) of the canvas.
//
bool leftAlign = elemRect.Left < 0;
bool rightAlign = elemRect.Right > this.ActualWidth;
if( leftAlign )
newHorizontalOffset = modifyLeftOffset ? 0 : this.ActualWidth - elemRect.Width;
else if( rightAlign )
newHorizontalOffset = modifyLeftOffset ? this.ActualWidth - elemRect.Width : 0;
bool topAlign = elemRect.Top < 0;
bool bottomAlign = elemRect.Bottom > this.ActualHeight;
if( topAlign )
newVerticalOffset = modifyTopOffset ? 0 : this.ActualHeight - elemRect.Height;
else if( bottomAlign )
newVerticalOffset = modifyTopOffset ? this.ActualHeight - elemRect.Height : 0;
#endregion // Verify Drag Element Location
}
#region Move Drag Element
if( this.modifyLeftOffset )
Canvas.SetLeft( this.ElementBeingDragged, newHorizontalOffset );
else
Canvas.SetRight( this.ElementBeingDragged, newHorizontalOffset );
if( this.modifyTopOffset )
Canvas.SetTop( this.ElementBeingDragged, newVerticalOffset );
else
Canvas.SetBottom( this.ElementBeingDragged, newVerticalOffset );
#endregion // Move Drag Element
}
#endregion // OnPreviewMouseMove
#region OnHostPreviewMouseUp
protected override void OnPreviewMouseUp( MouseButtonEventArgs e )
{
base.OnPreviewMouseUp( e );
// Reset the field whether the left or right mouse button was
// released, in case a context menu was opened on the drag element.
this.ElementBeingDragged = null;
}
#endregion // OnHostPreviewMouseUp
#endregion // Host Event Handlers
#region Private Helpers
#region CalculateDragElementRect
/// <summary>
/// Returns a Rect which describes the bounds of the element being dragged.
/// </summary>
private Rect CalculateDragElementRect( double newHorizOffset, double newVertOffset )
{
if( this.ElementBeingDragged == null )
throw new InvalidOperationException( "ElementBeingDragged is null." );
Size elemSize = this.ElementBeingDragged.RenderSize;
double x, y;
if( this.modifyLeftOffset )
x = newHorizOffset;
else
x = this.ActualWidth - newHorizOffset - elemSize.Width;
if( this.modifyTopOffset )
y = newVertOffset;
else
y = this.ActualHeight - newVertOffset - elemSize.Height;
Point elemLoc = new Point( x, y );
return new Rect( elemLoc, elemSize );
}
#endregion // CalculateDragElementRect
#region ResolveOffset
/// <summary>
/// Determines one component of a UIElement's location
/// within a Canvas (either the horizontal or vertical offset).
/// </summary>
/// <param name="side1">
/// The value of an offset relative to a default side of the
/// Canvas (i.e. top or left).
/// </param>
/// <param name="side2">
/// The value of the offset relative to the other side of the
/// Canvas (i.e. bottom or right).
/// </param>
/// <param name="useSide1">
/// Will be set to true if the returned value should be used
/// for the offset from the side represented by the 'side1'
/// parameter. Otherwise, it will be set to false.
/// </param>
private static double ResolveOffset( double side1, double side2, out bool useSide1 )
{
// If the Canvas.Left and Canvas.Right attached properties
// are specified for an element, the 'Left' value is honored.
// The 'Top' value is honored if both Canvas.Top and
// Canvas.Bottom are set on the same element. If one
// of those attached properties is not set on an element,
// the default value is Double.NaN.
useSide1 = true;
double result;
if( Double.IsNaN( side1 ) )
{
if( Double.IsNaN( side2 ) )
{
// Both sides have no value, so set the
// first side to a value of zero.
result = 0;
}
else
{
result = side2;
useSide1 = false;
}
}
else
{
result = side1;
}
return result;
}
#endregion // ResolveOffset
#region UpdateZOrder
/// <summary>
/// Helper method used by the BringToFront and SendToBack methods.
/// </summary>
/// <param name="element">
/// The element to bring to the front or send to the back.
/// </param>
/// <param name="bringToFront">
/// Pass true if calling from BringToFront, else false.
/// </param>
private void UpdateZOrder( UIElement element, bool bringToFront )
{
#region Safety Check
if( element == null )
throw new ArgumentNullException( "element" );
if( !base.Children.Contains( element ) )
throw new ArgumentException( "Must be a child element of the Canvas.", "element" );
#endregion // Safety Check
#region Calculate Z-Indici And Offset
// Determine the Z-Index for the target UIElement.
int elementNewZIndex = -1;
if( bringToFront )
{
foreach( UIElement elem in base.Children )
if( elem.Visibility != Visibility.Collapsed )
++elementNewZIndex;
}
else
{
elementNewZIndex = 0;
}
// Determine if the other UIElements' Z-Index
// should be raised or lowered by one.
int offset = (elementNewZIndex == 0) ? +1 : -1;
int elementCurrentZIndex = Canvas.GetZIndex( element );
#endregion // Calculate Z-Indici And Offset
#region Update Z-Indici
// Update the Z-Index of every UIElement in the Canvas.
foreach( UIElement childElement in base.Children )
{
if( childElement == element )
Canvas.SetZIndex( element, elementNewZIndex );
else
{
int zIndex = Canvas.GetZIndex( childElement );
// Only modify the z-index of an element if it is
// in between the target element's old and new z-index.
if( bringToFront && elementCurrentZIndex < zIndex ||
!bringToFront && zIndex < elementCurrentZIndex )
{
Canvas.SetZIndex( childElement, zIndex + offset );
}
}
}
#endregion // Update Z-Indici
}
#endregion // UpdateZOrder
#endregion // Private Helpers
}
}
| |
// Copyright 2010 xUnit.BDDExtensions
//
// 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.ComponentModel.Design;
using Xunit.Sdk;
namespace Xunit.BDDExtensionsSpecs
{
public abstract class Concern_for_BDDExtensions : StaticContextSpecification
{
protected Action TheAssertion;
}
[Concern(typeof (BDDExtensions))]
public class When_an__Exception__is_expected_to_be_thrown_and_is_actually_thrown :
Concern_for_BDDExtensions
{
private Action _operationThatThrows;
protected override void EstablishContext()
{
_operationThatThrows = () => { throw new InvalidOperationException(); };
}
protected override void Because()
{
TheAssertion = () => _operationThatThrows.ShouldThrowAn<InvalidOperationException>();
}
[Observation]
public void Should_not_throw_an__Exception__()
{
TheAssertion.ShouldNotThrowAnyExceptions();
}
}
[Concern(typeof (BDDExtensions))]
public class When_an_instance_is_expected_to_be__null__and_is_actually__null__ : Concern_for_BDDExtensions
{
private object _existingObject;
protected override void EstablishContext()
{
_existingObject = null;
}
protected override void Because()
{
TheAssertion = () => _existingObject.ShouldBeNull();
}
[Observation]
public void Should_not_throw_an__Exception__()
{
TheAssertion.ShouldNotThrowAnyExceptions();
}
}
[Concern(typeof (BDDExtensions))]
public class When_an_instance_is_expected_to_be__null__but_it_is_not : Concern_for_BDDExtensions
{
private object _existingObject;
protected override void EstablishContext()
{
_existingObject = new object();
}
protected override void Because()
{
TheAssertion = () => _existingObject.ShouldBeNull();
}
[Observation]
public void Should_throw_a__NullException__()
{
TheAssertion.ShouldThrowAn<NullException>();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting_null_to_be_not__null__ : Concern_for_BDDExtensions
{
private object _existingObject;
protected override void EstablishContext()
{
_existingObject = null;
}
protected override void Because()
{
TheAssertion = () => _existingObject.ShouldNotBeNull();
}
[Observation]
public void Should_throw_an__NotNullException__()
{
TheAssertion.ShouldThrowAn<NotNullException>();
}
}
[Concern(typeof (BDDExtensions))]
public class When_an_instance_is_expected_to_be_not__null__ : Concern_for_BDDExtensions
{
private object _existingObject;
protected override void EstablishContext()
{
_existingObject = new object();
}
protected override void Because()
{
TheAssertion = () => _existingObject.ShouldNotBeNull();
}
[Observation]
public void Should_not_throw_an__Exception__()
{
TheAssertion.ShouldNotThrowAnyExceptions();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting_a_particular__Exception__to_be_thrown_and_no__Exception__was_thrown :
Concern_for_BDDExtensions
{
private Action _operationNotThrowingAnException;
protected override void EstablishContext()
{
_operationNotThrowingAnException = () => { };
}
protected override void Because()
{
TheAssertion = () => _operationNotThrowingAnException.ShouldThrowAn<ArgumentNullException>();
}
[Observation]
public void Should_throw_a__ThrowsException__()
{
TheAssertion.ShouldThrowAn<ThrowsException>();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting_a_particular__Exception__to_be_thrown_and_a_different__Exception__was_thrown :
Concern_for_BDDExtensions
{
private Action _operationThatThrowsADifferentException;
protected override void EstablishContext()
{
_operationThatThrowsADifferentException = () => { throw new InvalidOperationException(); };
}
protected override void Because()
{
TheAssertion = () => _operationThatThrowsADifferentException.ShouldThrowAn<ArgumentNullException>();
}
[Observation]
public void Should_throw_a__ThrowsException__()
{
TheAssertion.ShouldThrowAn<ThrowsException>();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting__False__to_be__False__ : Concern_for_BDDExtensions
{
protected override void Because()
{
TheAssertion = () => false.ShouldBeFalse();
}
[Observation]
public void Should_not_throw_an__Exception__()
{
TheAssertion.ShouldNotThrowAnyExceptions();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting__True__to_be__True__ : Concern_for_BDDExtensions
{
protected override void Because()
{
TheAssertion = () => true.ShouldBeTrue();
}
[Observation]
public void Should_not_throw_an__Exception__()
{
TheAssertion.ShouldNotThrowAnyExceptions();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting__True__to_be__False__ : Concern_for_BDDExtensions
{
protected override void Because()
{
TheAssertion = () => true.ShouldBeFalse();
}
[Observation]
public void Should_throw_a__FalseException__()
{
TheAssertion.ShouldThrowAn<FalseException>();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting__False__to_be__True__ : Concern_for_BDDExtensions
{
protected override void Because()
{
TheAssertion = () => false.ShouldBeTrue();
}
[Observation]
public void Should_throw_a__TrueException__()
{
TheAssertion.ShouldThrowAn<TrueException>();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting_a_collection_to_contain_only_a_particular_set_of_items_and_a_different_set_is_present :
Concern_for_BDDExtensions
{
private string _bar;
private List<string> _collectionToTest;
private string _foo;
protected override void EstablishContext()
{
_foo = "foo";
_bar = "bar";
_collectionToTest = new List<string>
{
_foo,
_bar
};
}
protected override void Because()
{
TheAssertion = () => _collectionToTest.ShouldOnlyContain("SomethingDifferent");
}
[Observation]
public void Should_throw_an__AssertException__()
{
TheAssertion.ShouldThrowAn<AssertException>();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting_a_collection_to_contain_only_a_particular_set_of_items_and_more_are_present :
Concern_for_BDDExtensions
{
private string _bar;
private List<string> _collectionToTest;
private string _foo;
private string _unexpected;
protected override void EstablishContext()
{
_foo = "foo";
_bar = "bar";
_unexpected = "unexpected";
_collectionToTest = new List<string>
{
_foo,
_bar,
_unexpected
};
}
protected override void Because()
{
TheAssertion = () => _collectionToTest.ShouldOnlyContain(_foo, _bar);
}
[Observation]
public void Should_throw_an__AssertException__()
{
TheAssertion.ShouldThrowAn<AssertException>();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting_a_collection_to_contain_only_the_items_it_actually_contains :
Concern_for_BDDExtensions
{
private string _bar;
private List<string> _collectionToTest;
private string _foo;
protected override void EstablishContext()
{
_foo = "foo";
_bar = "bar";
_collectionToTest = new List<string>
{
_foo,
_bar
};
}
protected override void Because()
{
TheAssertion = () => _collectionToTest.ShouldOnlyContain(_foo, _bar);
}
[Observation]
public void Should_not_throw_an__Exception__()
{
TheAssertion.ShouldNotThrowAnyExceptions();
}
}
[Concern(typeof (BDDExtensions))]
public class
When_expecting_a_collection_to_contain_only_a_particular_set_in_a_particular_order_and_different_set_is_present :
Concern_for_BDDExtensions
{
private string _bar;
private List<string> _collectionToTest;
private string _foo;
protected override void EstablishContext()
{
_foo = "foo";
_bar = "bar";
_collectionToTest = new List<string>
{
_foo,
_bar
};
}
protected override void Because()
{
TheAssertion = () => _collectionToTest.ShouldOnlyContainInOrder("SomethingDifferent");
}
[Observation]
public void Should_throw_an__AssertException__()
{
TheAssertion.ShouldThrowAn<AssertException>();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting_a_collection_to_contain_only_a_particular_ordered_set_of_items_and_more_are_present :
Concern_for_BDDExtensions
{
private string _bar;
private List<string> _collectionToTest;
private string _foo;
private string _unexpected;
protected override void EstablishContext()
{
_foo = "foo";
_bar = "bar";
_unexpected = "unexpected";
_collectionToTest = new List<string>
{
_foo,
_bar,
_unexpected
};
}
protected override void Because()
{
TheAssertion = () => _collectionToTest.ShouldOnlyContainInOrder(_foo, _bar);
}
[Observation]
public void Should_throw_an__AssertException__()
{
TheAssertion.ShouldThrowAn<AssertException>();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting_a_collection_to_contain_only_a_particular_ordered_set_of_items_ordering_does_not_match :
Concern_for_BDDExtensions
{
private string _bar;
private List<string> _collectionToTest;
private string _foo;
protected override void EstablishContext()
{
_foo = "foo";
_bar = "bar";
_collectionToTest = new List<string>
{
_foo,
_bar
};
}
protected override void Because()
{
TheAssertion = () => _collectionToTest.ShouldOnlyContainInOrder(_bar, _foo);
}
[Observation]
public void Should_throw_an__AssertException__()
{
TheAssertion.ShouldThrowAn<AssertException>();
}
}
[Concern(typeof (BDDExtensions))]
public class
When_expecting_a_collection_to_contain_only_a_particular_ordered_set_of_items_on_a_set_that_matches_the_criteria :
Concern_for_BDDExtensions
{
private string _bar;
private List<string> _collectionToTest;
private string _foo;
protected override void EstablishContext()
{
_foo = "foo";
_bar = "bar";
_collectionToTest = new List<string>
{
_foo,
_bar
};
}
protected override void Because()
{
TheAssertion = () => _collectionToTest.ShouldOnlyContainInOrder(_foo, _bar);
}
[Observation]
public void Should_not_throw_an__Exception__()
{
TheAssertion.ShouldNotThrowAnyExceptions();
}
}
[Concern(typeof (BDDExtensions))]
public class When_an_instance_is_expected_to_be_of_an_unrelated__Type__ :
Concern_for_BDDExtensions
{
private ServiceContainer _serviceContainer;
protected override void EstablishContext()
{
_serviceContainer = new ServiceContainer();
}
protected override void Because()
{
TheAssertion = () => _serviceContainer.ShouldBeAnInstanceOf<bool>();
}
[Observation]
public void Should_throw_a__IsAssignableFromException__()
{
TheAssertion.ShouldThrowAn<IsAssignableFromException>();
}
}
[Concern(typeof (BDDExtensions))]
public class When_an_instance_is_expected_to_assignable_to_a_related__Type__ :
Concern_for_BDDExtensions
{
private ServiceContainer _serviceContainer;
protected override void EstablishContext()
{
_serviceContainer = new ServiceContainer();
}
protected override void Because()
{
TheAssertion = () => _serviceContainer.ShouldBeAnInstanceOf<IServiceProvider>();
}
[Observation]
public void Should_not_throw_an__Exception__()
{
TheAssertion.ShouldNotThrowAnyExceptions();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting_an_instance_to_be_of_its_own__Type__ :
Concern_for_BDDExtensions
{
private ServiceContainer _serviceContainer;
protected override void EstablishContext()
{
_serviceContainer = new ServiceContainer();
}
protected override void Because()
{
TheAssertion = () => _serviceContainer.ShouldBeAnInstanceOf<ServiceContainer>();
}
[Observation]
public void Should_not_throw_an__Exception__()
{
TheAssertion.ShouldNotThrowAnyExceptions();
}
}
[Concern(typeof (BDDExtensions))]
public class When_a__Comparable__is_expected_to_be_greater_than_a_second_one_and_it_actually_is_not :
Concern_for_BDDExtensions
{
protected override void Because()
{
TheAssertion = () => 1.ShouldBeGreaterThan(2);
}
[Observation]
public void Should_throw_a__AssertException__()
{
TheAssertion.ShouldThrowAn<AssertException>();
}
}
[Concern(typeof (BDDExtensions))]
public class When_a__Comparable__is_expected_to_be_greater_than_a_smaller_second_one : Concern_for_BDDExtensions
{
protected override void Because()
{
TheAssertion = () => 2.ShouldBeGreaterThan(1);
}
[Observation]
public void Should_not_throw_an__Exception__()
{
TheAssertion.ShouldNotThrowAnyExceptions();
}
}
[Concern(typeof (BDDExtensions))]
public class When_a__Comparable__is_expected_to_be_greater_than_itself : Concern_for_BDDExtensions
{
protected override void Because()
{
TheAssertion = () => 2.ShouldBeGreaterThan(2);
}
[Observation]
public void Should_throw_an__AssertException__()
{
TheAssertion.ShouldThrowAn<AssertException>();
}
}
[Concern(typeof (BDDExtensions))]
public class When_an_instance_is_expected_to_be_contained_in_a_collection_and_it_actually_is :
Concern_for_BDDExtensions
{
private List<string> _collection;
private string _item;
protected override void EstablishContext()
{
_item = "Foo";
_collection = new List<string>
{
_item
};
}
protected override void Because()
{
TheAssertion = () => _collection.ShouldContain(_item);
}
[Observation]
public void Should_not_throw_an__Exception__()
{
TheAssertion.ShouldNotThrowAnyExceptions();
}
}
[Concern(typeof (BDDExtensions))]
public class When_an_instance_is_expected_to_be_contained_in_a_collection_and_it_actually_is_not :
Concern_for_BDDExtensions
{
private List<string> _collection;
private string _item;
protected override void EstablishContext()
{
_item = "Foo";
_collection = new List<string>();
}
protected override void Because()
{
TheAssertion = () => _collection.ShouldContain(_item);
}
[Observation]
public void Should_throw_a__ContainsException__()
{
TheAssertion.ShouldThrowAn<ContainsException>();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting_two_different_instances_to_be_equal :
Concern_for_BDDExtensions
{
private ServiceContainer _otherObject;
private object _someObject;
protected override void EstablishContext()
{
_someObject = new ServiceContainer();
_otherObject = new ServiceContainer();
}
protected override void Because()
{
TheAssertion = () => _someObject.ShouldBeEqualTo(_otherObject);
}
[Observation]
public void Should_throw_an__EqualException__()
{
TheAssertion.ShouldThrowAn<EqualException>();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting_an_instance_to_be_equal_to_itself : Concern_for_BDDExtensions
{
private object _someObject;
protected override void EstablishContext()
{
_someObject = new ServiceContainer();
}
protected override void Because()
{
TheAssertion = () => _someObject.ShouldBeEqualTo(_someObject);
}
[Observation]
public void Should_not_throw_an__Exception__()
{
TheAssertion.ShouldNotThrowAnyExceptions();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting_to_differnt_instances_not_to_be_equal :
Concern_for_BDDExtensions
{
private ServiceContainer _otherObject;
private object _someObject;
protected override void EstablishContext()
{
_someObject = new ServiceContainer();
_otherObject = new ServiceContainer();
}
protected override void Because()
{
TheAssertion = () => _someObject.ShouldNotBeEqualTo(_otherObject);
}
[Observation]
public void Should_not_throw_and__Exception__()
{
TheAssertion.ShouldNotThrowAnyExceptions();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting_an_instance_not_to_be_equal_to_itself : Concern_for_BDDExtensions
{
private object _someObject;
protected override void EstablishContext()
{
_someObject = new ServiceContainer();
}
protected override void Because()
{
TheAssertion = () => _someObject.ShouldNotBeEqualTo(_someObject);
}
[Observation]
public void Should_throw_an__NotEqualException__()
{
TheAssertion.ShouldThrowAn<NotEqualException>();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting_two_differnt__strings__to_be_equal_ignoring_the_casing :
Concern_for_BDDExtensions
{
protected override void Because()
{
TheAssertion = () => "Foo".ShouldBeEqualIgnoringCase("Bar");
}
[Observation]
public void Should_throw_an__EqualException__()
{
TheAssertion.ShouldThrowAn<EqualException>();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting_a__string___to_be_equal_to_itself_ignoring_the_casing :
Concern_for_BDDExtensions
{
protected override void Because()
{
TheAssertion = () => "Foo".ShouldBeEqualIgnoringCase("Foo");
}
[Observation]
public void Should_not_throw_an__Exception__()
{
TheAssertion.ShouldNotThrowAnyExceptions();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting_a_non_empty_collection_to_be_empty : Concern_for_BDDExtensions
{
private ICollection<string> _nonEmptyCollection;
protected override void EstablishContext()
{
_nonEmptyCollection = new List<string>
{
"Foo",
"Bar"
};
}
protected override void Because()
{
TheAssertion = () => _nonEmptyCollection.ShouldBeEmpty();
}
[Observation]
public void Should_throw_an__EmptyException__()
{
TheAssertion.ShouldThrowAn<EmptyException>();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting_an_empty_collection_to_be_empty : Concern_for_BDDExtensions
{
private ICollection<string> _collection;
protected override void EstablishContext()
{
_collection = new List<string>();
}
protected override void Because()
{
TheAssertion = () => _collection.ShouldBeEmpty();
}
[Observation]
public void Should_not_throw_an__Exception__()
{
TheAssertion.ShouldNotThrowAnyExceptions();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting_a_non_empty_collection_to_contain_items : Concern_for_BDDExtensions
{
private ICollection<string> _collection;
protected override void EstablishContext()
{
_collection = new List<string>
{
"Foo",
"Bar"
};
}
protected override void Because()
{
TheAssertion = () => _collection.ShouldNotBeEmpty();
}
[Observation]
public void Should_not_throw_an__Exception__()
{
TheAssertion.ShouldNotThrowAnyExceptions();
}
}
[Concern(typeof (BDDExtensions))]
public class When_expecting_an_empty_collection_not_to_be_empty : Concern_for_BDDExtensions
{
private ICollection<string> _collection;
protected override void EstablishContext()
{
_collection = new List<string>();
}
protected override void Because()
{
TheAssertion = () => _collection.ShouldNotBeEmpty();
}
[Observation]
public void Should_throw_a__NotEmptyException__()
{
TheAssertion.ShouldThrowAn<NotEmptyException>();
}
}
[Concern(typeof (BDDExtensions))]
public class When_a_string_should_be_equal_to_a_differently_cased_string_and_casing_is_ignored :
Concern_for_BDDExtensions
{
protected override void Because()
{
TheAssertion = () => "Foo".ShouldBeEqualIgnoringCase("fOO");
}
[Observation]
public void Should_not_throw_an__Exception__()
{
TheAssertion.ShouldNotThrowAnyExceptions();
}
}
}
| |
using UnityEngine;
namespace UnityStandardAssets.Characters.ThirdPerson
{
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]
[RequireComponent(typeof(Animator))]
public class ThirdPersonCharacter : MonoBehaviour
{
[SerializeField] float m_MovingTurnSpeed = 0;
[SerializeField] float m_StationaryTurnSpeed = 0;
[SerializeField] float m_JumpPower = 12f;
[Range(1f, 4f)][SerializeField] float m_GravityMultiplier = 2f;
[SerializeField] float m_RunCycleLegOffset = 0.2f; //specific to the character in sample assets, will need to be modified to work with others
[SerializeField] float m_MoveSpeedMultiplier = 1f;
[SerializeField] float m_AnimSpeedMultiplier = 1f;
[SerializeField] float m_GroundCheckDistance = 0.1f;
Rigidbody m_Rigidbody;
Animator m_Animator;
bool m_IsGrounded;
float m_OrigGroundCheckDistance;
const float k_Half = 0.5f;
float m_TurnAmount;
float m_ForwardAmount;
Vector3 m_GroundNormal;
float m_CapsuleHeight;
Vector3 m_CapsuleCenter;
CapsuleCollider m_Capsule;
bool m_Crouching;
void Start()
{
m_Animator = GetComponent<Animator>();
m_Rigidbody = GetComponent<Rigidbody>();
m_Capsule = GetComponent<CapsuleCollider>();
m_CapsuleHeight = m_Capsule.height;
m_CapsuleCenter = m_Capsule.center;
m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ;
m_OrigGroundCheckDistance = m_GroundCheckDistance;
}
public void Move(Vector3 move, bool crouch, bool jump)
{
// convert the world relative moveInput vector into a local-relative
// turn amount and forward amount required to head in the desired
// direction.
if (move.magnitude > 1f) move.Normalize();
move = transform.InverseTransformDirection(move);
CheckGroundStatus();
move = Vector3.ProjectOnPlane(move, m_GroundNormal);
m_TurnAmount = Mathf.Atan2(move.x, move.z);
m_ForwardAmount = move.z;
ApplyExtraTurnRotation();
// control and velocity handling is different when grounded and airborne:
if (m_IsGrounded)
{
HandleGroundedMovement(crouch, jump);
}
else
{
HandleAirborneMovement();
}
ScaleCapsuleForCrouching(crouch);
PreventStandingInLowHeadroom();
// send input and other state parameters to the animator
UpdateAnimator(move);
}
void ScaleCapsuleForCrouching(bool crouch)
{
if (m_IsGrounded && crouch)
{
if (m_Crouching) return;
m_Capsule.height = m_Capsule.height / 2f;
m_Capsule.center = m_Capsule.center / 2f;
m_Crouching = true;
}
else
{
Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half;
if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength))
{
m_Crouching = true;
return;
}
m_Capsule.height = m_CapsuleHeight;
m_Capsule.center = m_CapsuleCenter;
m_Crouching = false;
}
}
void PreventStandingInLowHeadroom()
{
// prevent standing up in crouch-only zones
if (!m_Crouching)
{
Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half;
if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength))
{
m_Crouching = true;
}
}
}
void UpdateAnimator(Vector3 move)
{
// update the animator parameters
m_Animator.SetFloat("Forward", m_ForwardAmount, 0.1f, Time.deltaTime);
m_Animator.SetFloat("Turn", m_TurnAmount, 0.1f, Time.deltaTime);
m_Animator.SetBool("Crouch", m_Crouching);
m_Animator.SetBool("OnGround", m_IsGrounded);
if (!m_IsGrounded)
{
m_Animator.SetFloat("Jump", m_Rigidbody.velocity.y);
}
// calculate which leg is behind, so as to leave that leg trailing in the jump animation
// (This code is reliant on the specific run cycle offset in our animations,
// and assumes one leg passes the other at the normalized clip times of 0.0 and 0.5)
float runCycle =
Mathf.Repeat(
m_Animator.GetCurrentAnimatorStateInfo(0).normalizedTime + m_RunCycleLegOffset, 1);
float jumpLeg = (runCycle < k_Half ? 1 : -1) * m_ForwardAmount;
if (m_IsGrounded)
{
m_Animator.SetFloat("JumpLeg", jumpLeg);
}
// the anim speed multiplier allows the overall speed of walking/running to be tweaked in the inspector,
// which affects the movement speed because of the root motion.
if (m_IsGrounded && move.magnitude > 0)
{
m_Animator.speed = m_AnimSpeedMultiplier;
}
else
{
// don't use that while airborne
m_Animator.speed = 1;
}
}
void HandleAirborneMovement()
{
// apply extra gravity from multiplier:
Vector3 extraGravityForce = (Physics.gravity * m_GravityMultiplier) - Physics.gravity;
m_Rigidbody.AddForce(extraGravityForce);
m_GroundCheckDistance = m_Rigidbody.velocity.y < 0 ? m_OrigGroundCheckDistance : 0.01f;
}
void HandleGroundedMovement(bool crouch, bool jump)
{
// check whether conditions are right to allow a jump:
if (jump && !crouch && m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Grounded"))
{
// jump!
m_Rigidbody.velocity = new Vector3(m_Rigidbody.velocity.x, m_JumpPower, m_Rigidbody.velocity.z);
m_IsGrounded = false;
m_Animator.applyRootMotion = false;
m_GroundCheckDistance = 0.1f;
}
}
void ApplyExtraTurnRotation()
{
// help the character turn faster (this is in addition to root rotation in the animation)
float turnSpeed = Mathf.Lerp(m_StationaryTurnSpeed, m_MovingTurnSpeed, m_ForwardAmount);
transform.Rotate(0, m_TurnAmount * turnSpeed * Time.deltaTime, 0);
}
public void OnAnimatorMove()
{
// we implement this function to override the default root motion.
// this allows us to modify the positional speed before it's applied.
if (m_IsGrounded && Time.deltaTime > 0)
{
Vector3 v = (m_Animator.deltaPosition * m_MoveSpeedMultiplier) / Time.deltaTime;
// we preserve the existing y part of the current velocity.
v.y = m_Rigidbody.velocity.y;
m_Rigidbody.velocity = v;
}
}
void CheckGroundStatus()
{
RaycastHit hitInfo;
#if UNITY_EDITOR
// helper to visualise the ground check ray in the scene view
Debug.DrawLine(transform.position + (Vector3.up * 0.1f), transform.position + (Vector3.up * 0.1f) + (Vector3.down * m_GroundCheckDistance));
#endif
// 0.1f is a small offset to start the ray from inside the character
// it is also good to note that the transform position in the sample assets is at the base of the character
if (Physics.Raycast(transform.position + (Vector3.up * 0.1f), Vector3.down, out hitInfo, m_GroundCheckDistance))
{
m_GroundNormal = hitInfo.normal;
m_IsGrounded = true;
m_Animator.applyRootMotion = true;
}
else
{
m_IsGrounded = false;
m_GroundNormal = Vector3.up;
m_Animator.applyRootMotion = false;
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Globalization;
namespace Eto.Drawing
{
/// <summary>
/// Enumeration of the different system fonts for a <see cref="Font"/>
/// </summary>
/// <remarks>
/// This is useful when you want to use a font that is the same as standard UI elements.
/// </remarks>
/// <copyright>(c) 2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
public enum SystemFont
{
/// <summary>
/// Default system font
/// </summary>
Default,
/// <summary>
/// Default system font in BOLD
/// </summary>
Bold,
/// <summary>
/// Default label font
/// </summary>
Label,
/// <summary>
/// Default title bar font (window title)
/// </summary>
TitleBar,
/// <summary>
/// Default tool top font
/// </summary>
ToolTip,
/// <summary>
/// Default menu bar font
/// </summary>
MenuBar,
/// <summary>
/// Default font for items in a menu
/// </summary>
Menu,
/// <summary>
/// Default font for message boxes
/// </summary>
Message,
/// <summary>
/// Default font for palette dialogs
/// </summary>
Palette,
/// <summary>
/// Default font for status bars
/// </summary>
StatusBar
}
/// <summary>
/// Syles for a <see cref="Font"/>
/// </summary>
/// <copyright>(c) 2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
[Flags]
public enum FontStyle
{
/// <summary>
/// No extra font style applied
/// </summary>
None = 0,
/// <summary>
/// Bold font style
/// </summary>
Bold = 1 << 0,
/// <summary>
/// Italic font style
/// </summary>
Italic = 1 << 1,
}
/// <summary>
/// Decorations for a <see cref="Font"/>
/// </summary>
/// <remarks>
/// These specify the different decorations to apply to a font, and are not related to the style.
/// </remarks>
/// <copyright>(c) 2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
[Flags]
public enum FontDecoration
{
/// <summary>
/// No decorations
/// </summary>
None = 0,
/// <summary>
/// Underline font decoration
/// </summary>
Underline = 1 << 0,
/// <summary>
/// Strikethrough font decoration
/// </summary>
Strikethrough = 1 << 1,
}
/// <summary>
/// Defines a format for text
/// </summary>
/// <remarks>
/// A font is typically defined with a specified font family, with a given typeface. Each typeface has certain characteristics
/// that define the variation of the font family, for example Bold, or Italic.
///
/// You can get a list of <see cref="FontFamily"/> objects available in the current system using
/// <see cref="Fonts.AvailableFontFamilies"/>, which can then be used to create an instance of a font.
/// </remarks>
/// <copyright>(c) 2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
[Handler(typeof(Font.IHandler))]
[TypeConverter(typeof(FontConverter))]
public class Font : Widget
{
new IHandler Handler { get { return (IHandler)base.Handler; } }
/// <summary>
/// Creates a new instance of the Font class with a specified <paramref name="family"/>, <paramref name="size"/>, and <paramref name="style"/>
/// </summary>
/// <param name="family">Family of font to use</param>
/// <param name="size">Size of the font, in points</param>
/// <param name="style">Style of the font</param>
/// <param name="decoration">Decorations to apply to the font</param>
public Font(string family, float size, FontStyle style = FontStyle.None, FontDecoration decoration = FontDecoration.None)
{
Handler.Create(new FontFamily(family), size, style, decoration);
Initialize();
}
/// <summary>
/// Creates a new instance of the Font class with a specified <paramref name="family"/>, <paramref name="size"/>, and <paramref name="style"/>
/// </summary>
/// <param name="family">Family of font to use</param>
/// <param name="size">Size of the font, in points</param>
/// <param name="style">Style of the font</param>
/// <param name="decoration">Decorations to apply to the font</param>
public Font(FontFamily family, float size, FontStyle style = FontStyle.None, FontDecoration decoration = FontDecoration.None)
{
Handler.Create(family, size, style, decoration);
Initialize();
}
/// <summary>
/// Creates a new instance of the Font class with a specified <paramref name="systemFont"/> and optional custom <paramref name="size"/>
/// </summary>
/// <remarks>
/// The system fonts are the same fonts that the standard UI of each platform use for particular areas
/// given the <see cref="SystemFont"/> enumeration.
/// </remarks>
/// <param name="systemFont">Type of system font to create</param>
/// <param name="size">Optional size of the font, in points. If not specified, the default size of the system font is used</param>
/// <param name="decoration">Decorations to apply to the font</param>
public Font(SystemFont systemFont, float? size = null, FontDecoration decoration = FontDecoration.None)
{
Handler.Create(systemFont, size, decoration);
Initialize();
}
/// <summary>
/// Initializes a new instance of the Font class with the specified <paramref name="typeface"/> and <paramref name="size"/>
/// </summary>
/// <param name="typeface">Typeface of the font to create</param>
/// <param name="size">Size of the font in points</param>
/// <param name="decoration">Decorations to apply to the font</param>
public Font(FontTypeface typeface, float size, FontDecoration decoration = FontDecoration.None)
{
Handler.Create(typeface, size, decoration);
Initialize();
}
/// <summary>
/// Initializes a new instance of the Font class with the specified font <paramref name="handler"/>
/// </summary>
/// <remarks>
/// Not intended to be used directly, this is used by each platform to pass back a font instance with a specific handler
/// </remarks>
/// <param name="handler">Handler for the font</param>
public Font(IHandler handler)
: base(handler)
{
}
/// <summary>
/// Gets the name of the family of this font
/// </summary>
public string FamilyName
{
get { return Handler.FamilyName; }
}
/// <summary>
/// Gets the style flags for this font
/// </summary>
/// <remarks>
/// This does not represent all of the style properties of the font. Each <see cref="Typeface"/>
/// has its own style relative to the font family.
/// </remarks>
public FontStyle FontStyle
{
get { return Handler.FontStyle; }
}
/// <summary>
/// Gets the decorations applied to the font
/// </summary>
/// <remarks>
/// Decorations can be applied to any typeface/style of font.
/// </remarks>
/// <value>The font decoration.</value>
public FontDecoration FontDecoration
{
get { return Handler.FontDecoration; }
}
/// <summary>
/// Gets the family information for this font
/// </summary>
public FontFamily Family
{
get { return Handler.Family; }
}
/// <summary>
/// Gets the typeface information for this font
/// </summary>
public FontTypeface Typeface
{
get { return Handler.Typeface; }
}
/// <summary>
/// Gets the height of the lower case 'x' character
/// </summary>
/// <value>The height of the x character</value>
public float XHeight
{
get { return Handler.XHeight; }
}
/// <summary>
/// Gets the top y co-ordinate from the baseline to the tallest character ascent
/// </summary>
/// <value>The tallest ascent of the font</value>
public float Ascent
{
get { return Handler.Ascent; }
}
/// <summary>
/// Gets the bottom y co-ordinate from the baseline to the longest character descent
/// </summary>
/// <value>The longest descent of the font</value>
public float Descent
{
get { return Handler.Descent; }
}
/// <summary>
/// Gets the height of a single line of the font
/// </summary>
/// <value>The height of a single line</value>
public float LineHeight
{
get { return Handler.LineHeight; }
}
/// <summary>
/// Gets the leading space between each line
/// </summary>
/// <value>The leading.</value>
public float Leading
{
get { return Handler.Leading; }
}
/// <summary>
/// Gets the offset of the baseline from the drawing point
/// </summary>
/// <value>The baseline offset from the drawing point</value>
public float Baseline
{
get { return Handler.Baseline; }
}
/// <summary>
/// Gets the size, in points, of this font
/// </summary>
public float Size
{
get { return Handler.Size; }
}
/// <summary>
/// Gets a value indicating that this font has a bold style
/// </summary>
public bool Bold
{
get { return FontStyle.HasFlag(FontStyle.Bold); }
}
/// <summary>
/// Gets a value indicating that this font has an italic style
/// </summary>
public bool Italic
{
get { return FontStyle.HasFlag(FontStyle.Italic); }
}
/// <summary>
/// Gets a value indicating that this font has an underline decoration
/// </summary>
public bool Underline
{
get { return FontDecoration.HasFlag(FontDecoration.Underline); }
}
/// <summary>
/// Gets a value indicating that this font has a strikethrough decoration
/// </summary>
public bool Strikethrough
{
get { return FontDecoration.HasFlag(FontDecoration.Strikethrough); }
}
/// <summary>
/// Gets a string representation of the font object
/// </summary>
/// <returns>String representation of the font object</returns>
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "Family={0}, Typeface={1}, Size={2}pt, Style={3}", Family, Typeface, Size, FontStyle);
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to the current <see cref="Eto.Drawing.Font"/>.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with the current <see cref="Eto.Drawing.Font"/>.</param>
/// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to the current <see cref="Eto.Drawing.Font"/>;
/// otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
var font = obj as Font;
return font != null
&& object.ReferenceEquals(Platform, font.Platform)
&& Family.Equals(font.Family)
&& Size.Equals(font.Size)
&& FontStyle.Equals(font.FontStyle);
}
/// <summary>
/// Serves as a hash function for a <see cref="Eto.Drawing.Font"/> object.
/// </summary>
/// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a hash table.</returns>
public override int GetHashCode()
{
return FamilyName.GetHashCode() ^ Platform.GetHashCode() ^ Size.GetHashCode() ^ FontStyle.GetHashCode();
}
#region Handler
/// <summary>
/// Platform handler for the <see cref="Font"/> class
/// </summary>
[AutoInitialize(false)]
public new interface IHandler : Widget.IHandler
{
/// <summary>
/// Creates a new font object
/// </summary>
/// <param name="family">Type of font family</param>
/// <param name="size">Size of the font (in points)</param>
/// <param name="style">Style of the font</param>
/// <param name="decoration">Decorations to apply to the font</param>
void Create(FontFamily family, float size, FontStyle style, FontDecoration decoration);
/// <summary>
/// Creates a new font object with the specified <paramref name="systemFont"/> and optional size
/// </summary>
/// <param name="systemFont">System font to create</param>
/// <param name="size">Size of font to use, or null to use the system font's default size</param>
/// <param name="decoration">Decorations to apply to the font</param>
void Create(SystemFont systemFont, float? size, FontDecoration decoration);
/// <summary>
/// Creates a new font object with the specified <paramref name="typeface"/> and <paramref name="size"/>
/// </summary>
/// <param name="typeface">Typeface to specify the style (and family) of the font</param>
/// <param name="size">Size of the font to create</param>
/// <param name="decoration">Decorations to apply to the font</param>
void Create(FontTypeface typeface, float size, FontDecoration decoration);
/// <summary>
/// Gets the height of the lower case 'x' character
/// </summary>
/// <value>The height of the x character</value>
float XHeight { get; }
/// <summary>
/// Gets the top y co-ordinate from the baseline to the tallest character ascent
/// </summary>
/// <value>The tallest ascent of the font</value>
float Ascent { get; }
/// <summary>
/// Gets the bottom y co-ordinate from the baseline to the longest character descent
/// </summary>
/// <value>The longest descent of the font</value>
float Descent { get; }
/// <summary>
/// Gets the height of a single line of the font
/// </summary>
/// <value>The height of a single line</value>
float LineHeight { get; }
/// <summary>
/// Gets the leading space between each line
/// </summary>
/// <value>The leading.</value>
float Leading { get; }
/// <summary>
/// Gets the offset of the baseline from the drawing point
/// </summary>
/// <value>The baseline offset from the drawing point</value>
float Baseline { get; }
/// <summary>
/// Gets the size of the font in points
/// </summary>
float Size { get; }
/// <summary>
/// Gets the name of the family of this font
/// </summary>
string FamilyName { get; }
/// <summary>
/// Gets the style flags for this font
/// </summary>
/// <remarks>
/// This does not necessarily represent all of the style properties of the font.
/// Each <see cref="Typeface"/> has its own style relative to the font family. This is meerely a
/// convenience to get the common properties of a font's typeface style
/// </remarks>
FontStyle FontStyle { get; }
/// <summary>
/// Gets the decorations applied to the font
/// </summary>
/// <remarks>
/// Decorations can be applied to any typeface/style of font.
/// </remarks>
/// <value>The font decoration.</value>
FontDecoration FontDecoration { get; }
/// <summary>
/// Gets the family information for this font
/// </summary>
/// <remarks>
/// This should always return an instance that represents the family of this font
/// </remarks>
FontFamily Family { get; }
/// <summary>
/// Gets the typeface information for this font
/// </summary>
/// <remarks>
/// This should always return an instance that represents the typeface of this font
/// </remarks>
FontTypeface Typeface { get; }
}
#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 Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Region.CoreModules.Avatar.Attachments;
using OpenSim.Region.CoreModules.Avatar.AvatarFactory;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.OptionalModules.World.NPC;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Tests.Common;
namespace OpenSim.Region.ScriptEngine.Shared.Tests
{
/// <summary>
/// Tests for OSSL NPC API
/// </summary>
[TestFixture]
public class OSSL_NpcApiAppearanceTest : OpenSimTestCase
{
protected Scene m_scene;
protected XEngine.XEngine m_engine;
[SetUp]
public override void SetUp()
{
base.SetUp();
IConfigSource initConfigSource = new IniConfigSource();
IConfig config = initConfigSource.AddConfig("XEngine");
config.Set("Enabled", "true");
config.Set("AllowOSFunctions", "true");
config.Set("OSFunctionThreatLevel", "Severe");
config = initConfigSource.AddConfig("NPC");
config.Set("Enabled", "true");
m_scene = new SceneHelpers().SetupScene();
SceneHelpers.SetupSceneModules(
m_scene, initConfigSource, new AvatarFactoryModule(), new AttachmentsModule(), new NPCModule());
m_engine = new XEngine.XEngine();
m_engine.Initialise(initConfigSource);
m_engine.AddRegion(m_scene);
}
/// <summary>
/// Test creation of an NPC where the appearance data comes from a notecard
/// </summary>
[Test]
public void TestOsNpcCreateUsingAppearanceFromNotecard()
{
TestHelpers.InMethod();
// Store an avatar with a different height from default in a notecard.
UUID userId = TestHelpers.ParseTail(0x1);
float newHeight = 1.9f;
ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, userId);
sp.Appearance.AvatarHeight = newHeight;
SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, userId, 0x10);
SceneObjectPart part = so.RootPart;
m_scene.AddSceneObject(so);
OSSL_Api osslApi = new OSSL_Api();
osslApi.Initialize(m_engine, part, null, null);
string notecardName = "appearanceNc";
osslApi.osOwnerSaveAppearance(notecardName);
// Try creating a bot using the appearance in the notecard.
string npcRaw = osslApi.osNpcCreate("Jane", "Doe", new LSL_Types.Vector3(128, 128, 128), notecardName);
Assert.That(npcRaw, Is.Not.Null);
UUID npcId = new UUID(npcRaw);
ScenePresence npc = m_scene.GetScenePresence(npcId);
Assert.That(npc, Is.Not.Null);
Assert.That(npc.Appearance.AvatarHeight, Is.EqualTo(newHeight));
}
[Test]
public void TestOsNpcCreateNotExistingNotecard()
{
TestHelpers.InMethod();
UUID userId = TestHelpers.ParseTail(0x1);
SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, userId, 0x10);
m_scene.AddSceneObject(so);
OSSL_Api osslApi = new OSSL_Api();
osslApi.Initialize(m_engine, so.RootPart, null, null);
bool gotExpectedException = false;
try
{
osslApi.osNpcCreate("Jane", "Doe", new LSL_Types.Vector3(128, 128, 128), "not existing notecard name");
}
catch (ScriptException)
{
gotExpectedException = true;
}
Assert.That(gotExpectedException, Is.True);
}
/// <summary>
/// Test creation of an NPC where the appearance data comes from an avatar already in the region.
/// </summary>
[Test]
public void TestOsNpcCreateUsingAppearanceFromAvatar()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
// Store an avatar with a different height from default in a notecard.
UUID userId = TestHelpers.ParseTail(0x1);
float newHeight = 1.9f;
ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, userId);
sp.Appearance.AvatarHeight = newHeight;
SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, userId, 0x10);
SceneObjectPart part = so.RootPart;
m_scene.AddSceneObject(so);
OSSL_Api osslApi = new OSSL_Api();
osslApi.Initialize(m_engine, part, null, null);
string notecardName = "appearanceNc";
osslApi.osOwnerSaveAppearance(notecardName);
// Try creating a bot using the existing avatar's appearance
string npcRaw = osslApi.osNpcCreate("Jane", "Doe", new LSL_Types.Vector3(128, 128, 128), sp.UUID.ToString());
Assert.That(npcRaw, Is.Not.Null);
UUID npcId = new UUID(npcRaw);
ScenePresence npc = m_scene.GetScenePresence(npcId);
Assert.That(npc, Is.Not.Null);
Assert.That(npc.Appearance.AvatarHeight, Is.EqualTo(newHeight));
}
[Test]
public void TestOsNpcLoadAppearance()
{
TestHelpers.InMethod();
//TestHelpers.EnableLogging();
// Store an avatar with a different height from default in a notecard.
UUID userId = TestHelpers.ParseTail(0x1);
float firstHeight = 1.9f;
float secondHeight = 2.1f;
string firstAppearanceNcName = "appearanceNc1";
string secondAppearanceNcName = "appearanceNc2";
ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, userId);
sp.Appearance.AvatarHeight = firstHeight;
SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, userId, 0x10);
SceneObjectPart part = so.RootPart;
m_scene.AddSceneObject(so);
OSSL_Api osslApi = new OSSL_Api();
osslApi.Initialize(m_engine, part, null, null);
osslApi.osOwnerSaveAppearance(firstAppearanceNcName);
string npcRaw
= osslApi.osNpcCreate("Jane", "Doe", new LSL_Types.Vector3(128, 128, 128), firstAppearanceNcName);
// Create a second appearance notecard with a different height
sp.Appearance.AvatarHeight = secondHeight;
osslApi.osOwnerSaveAppearance(secondAppearanceNcName);
osslApi.osNpcLoadAppearance(npcRaw, secondAppearanceNcName);
UUID npcId = new UUID(npcRaw);
ScenePresence npc = m_scene.GetScenePresence(npcId);
Assert.That(npc, Is.Not.Null);
Assert.That(npc.Appearance.AvatarHeight, Is.EqualTo(secondHeight));
}
[Test]
public void TestOsNpcLoadAppearanceNotExistingNotecard()
{
TestHelpers.InMethod();
// Store an avatar with a different height from default in a notecard.
UUID userId = TestHelpers.ParseTail(0x1);
float firstHeight = 1.9f;
// float secondHeight = 2.1f;
string firstAppearanceNcName = "appearanceNc1";
string secondAppearanceNcName = "appearanceNc2";
ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, userId);
sp.Appearance.AvatarHeight = firstHeight;
SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, userId, 0x10);
SceneObjectPart part = so.RootPart;
m_scene.AddSceneObject(so);
OSSL_Api osslApi = new OSSL_Api();
osslApi.Initialize(m_engine, part, null, null);
osslApi.osOwnerSaveAppearance(firstAppearanceNcName);
string npcRaw
= osslApi.osNpcCreate("Jane", "Doe", new LSL_Types.Vector3(128, 128, 128), firstAppearanceNcName);
bool gotExpectedException = false;
try
{
osslApi.osNpcLoadAppearance(npcRaw, secondAppearanceNcName);
}
catch (ScriptException)
{
gotExpectedException = true;
}
Assert.That(gotExpectedException, Is.True);
UUID npcId = new UUID(npcRaw);
ScenePresence npc = m_scene.GetScenePresence(npcId);
Assert.That(npc, Is.Not.Null);
Assert.That(npc.Appearance.AvatarHeight, Is.EqualTo(firstHeight));
}
/// <summary>
/// Test removal of an owned NPC.
/// </summary>
[Test]
public void TestOsNpcRemoveOwned()
{
TestHelpers.InMethod();
// Store an avatar with a different height from default in a notecard.
UUID userId = TestHelpers.ParseTail(0x1);
UUID otherUserId = TestHelpers.ParseTail(0x2);
float newHeight = 1.9f;
SceneHelpers.AddScenePresence(m_scene, otherUserId);
ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, userId);
sp.Appearance.AvatarHeight = newHeight;
SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, userId, 0x10);
SceneObjectPart part = so.RootPart;
m_scene.AddSceneObject(so);
SceneObjectGroup otherSo = SceneHelpers.CreateSceneObject(1, otherUserId, 0x20);
SceneObjectPart otherPart = otherSo.RootPart;
m_scene.AddSceneObject(otherSo);
OSSL_Api osslApi = new OSSL_Api();
osslApi.Initialize(m_engine, part, null, null);
OSSL_Api otherOsslApi = new OSSL_Api();
otherOsslApi.Initialize(m_engine, otherPart, null, null);
string notecardName = "appearanceNc";
osslApi.osOwnerSaveAppearance(notecardName);
string npcRaw
= osslApi.osNpcCreate(
"Jane", "Doe", new LSL_Types.Vector3(128, 128, 128), notecardName, ScriptBaseClass.OS_NPC_CREATOR_OWNED);
otherOsslApi.osNpcRemove(npcRaw);
// Should still be around
UUID npcId = new UUID(npcRaw);
ScenePresence npc = m_scene.GetScenePresence(npcId);
Assert.That(npc, Is.Not.Null);
osslApi.osNpcRemove(npcRaw);
npc = m_scene.GetScenePresence(npcId);
// Now the owner deleted it and it's gone
Assert.That(npc, Is.Null);
}
/// <summary>
/// Test removal of an unowned NPC.
/// </summary>
[Test]
public void TestOsNpcRemoveUnowned()
{
TestHelpers.InMethod();
// log4net.Config.XmlConfigurator.Configure();
// Store an avatar with a different height from default in a notecard.
UUID userId = TestHelpers.ParseTail(0x1);
float newHeight = 1.9f;
ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, userId);
sp.Appearance.AvatarHeight = newHeight;
SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, userId, 0x10);
SceneObjectPart part = so.RootPart;
m_scene.AddSceneObject(so);
OSSL_Api osslApi = new OSSL_Api();
osslApi.Initialize(m_engine, part, null, null);
string notecardName = "appearanceNc";
osslApi.osOwnerSaveAppearance(notecardName);
string npcRaw
= osslApi.osNpcCreate(
"Jane", "Doe", new LSL_Types.Vector3(128, 128, 128), notecardName, ScriptBaseClass.OS_NPC_NOT_OWNED);
osslApi.osNpcRemove(npcRaw);
UUID npcId = new UUID(npcRaw);
ScenePresence npc = m_scene.GetScenePresence(npcId);
Assert.That(npc, Is.Null);
}
}
}
| |
// Copyright 2014 Jacob Trimble
//
// 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.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Text.RegularExpressions;
using ModMaker.Lua.Runtime;
using ModMaker.Lua.Runtime.LuaValues;
namespace ModMaker.Lua {
/// <summary>
/// A static class that contains several helper methods.
/// </summary>
static class Helpers {
static readonly Action<Exception> _preserveStackTrace;
static Helpers() {
MethodInfo preserveStackTrace = typeof(Exception).GetMethod(
"InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic);
_preserveStackTrace =
(Action<Exception>)Delegate.CreateDelegate(typeof(Action<Exception>), preserveStackTrace);
}
/// <summary>
/// Helper class that calls a given method when Dispose is called.
/// </summary>
sealed class DisposableHelper : IDisposable {
readonly Action _act;
bool _disposed = false;
public DisposableHelper(Action act) {
_act = act;
}
public void Dispose() {
if (_disposed) {
return;
}
_disposed = true;
_act();
}
}
/// <summary>
/// Creates an IDisposable object that calls the given function when Dispose is called.
/// </summary>
/// <param name="act">The function to call on Dispose.</param>
/// <returns>An IDisposable object.</returns>
public static IDisposable Disposable(Action act) {
return new DisposableHelper(act);
}
/// <summary>
/// Parses the number in the given string.
/// </summary>
/// <param name="value">The string to parse.</param>
/// <returns>The double value that was parsed.</returns>
public static double ParseNumber(string value) {
value = value.ToLower();
string pattern;
NumberStyles style;
int @base;
int exponent;
if (value.StartsWith("0x")) {
pattern = @"^0x([0-9a-f]*)(?:\.([0-9a-f]*))?(?:p([-+])?(\d+))?$";
style = NumberStyles.AllowHexSpecifier;
@base = 16;
exponent = 2;
} else {
pattern = @"^(\d*)(?:\.(\d*))?(?:e([-+])?(\d+))?$";
style = NumberStyles.Integer;
@base = 10;
exponent = 10;
}
var match = Regex.Match(value, pattern);
if (match == null || !match.Success) {
throw new ArgumentException("Invalid number format");
}
double ret = match.Groups[1].Value == "" ? 0 : long.Parse(match.Groups[1].Value, style);
if (match.Groups[2].Value != "") {
double temp = long.Parse(match.Groups[2].Value, style);
ret += temp * Math.Pow(@base, -match.Groups[2].Value.Length);
}
if (match.Groups[4].Value != "") {
double temp = long.Parse(match.Groups[4].Value);
int mult = match.Groups[3].Value == "-" ? -1 : 1;
ret *= Math.Pow(exponent, mult * temp);
}
return ret;
}
/// <summary>
/// Retrieves a custom attribute applied to a member of a type. Parameters specify the member,
/// and the type of the custom attribute to search for.
/// </summary>
/// <param name="element">
/// An object derived from the System.Reflection.MemberInfo class that describes a constructor,
/// event, field, method, or property member of a class.
/// </param>
/// <returns>
/// A reference to the single custom attribute of type attributeType that is applied to element,
/// or null if there is no such attribute.
/// </returns>
public static T GetCustomAttribute<T>(this MemberInfo element) where T : Attribute {
return (T)Attribute.GetCustomAttribute(element, typeof(T));
}
/// <summary>
/// Retrieves a custom attribute applied to a member of a type. Parameters specify the member,
/// and the type of the custom attribute to search for.
/// </summary>
/// <param name="element">
/// An object derived from the System.Reflection.MemberInfo class that describes a constructor,
/// event, field, method, or property member of a class.
/// </param>
/// <returns>
/// A reference to the single custom attribute of type attributeType that is applied to element,
/// or null if there is no such attribute.
/// </returns>
public static T GetCustomAttribute<T>(this MemberInfo element, bool inherit) where T : Attribute {
return (T)Attribute.GetCustomAttribute(element, typeof(T), inherit);
}
/// <summary>
/// Invokes the given method while throwing the inner exception. This ensures that the
/// TargetInvocationException is not thrown an instead the inner exception is thrown.
/// </summary>
/// <param name="method">The method to invoke.</param>
/// <param name="target">The target of the invocation.</param>
/// <param name="args">The arguments to pass to the method.</param>
/// <returns>Any value returned from the method.</returns>
public static object DynamicInvoke(MethodBase method, object target, object[] args) {
try {
return method.Invoke(target, args);
} catch (TargetInvocationException e) {
Exception inner = e.InnerException;
if (inner == null) {
throw;
}
ExceptionDispatchInfo.Capture(inner).Throw();
throw inner; // Shouldn't happen.
}
}
/// <summary>
/// Gets or sets the given object to the given value. Also handles accessibility correctly.
/// </remarks>
/// <param name="targetType">The type of the target object.</param>
/// <param name="target">The target object.</param>
/// <param name="index">The indexing object.</param>
/// <param name="value">The value to set to.</param>
/// <returns>The value for get or null if setting.</returns>
public static ILuaValue GetSetMember(Type targetType, object target, ILuaValue index,
ILuaValue value = null) {
if (index.ValueType == LuaValueType.Number || index.ValueType == LuaValueType.Table) {
if (target == null) {
throw new InvalidOperationException(
"Attempt to call indexer on a static type.");
}
LuaMultiValue args;
if (index.ValueType == LuaValueType.Number) {
args = new LuaMultiValue(new[] { value });
} else {
int len = index.Length().As<int>();
object[] objArgs = new object[len];
for (int i = 1; i <= len; i++) {
ILuaValue item = index.GetIndex(LuaValueBase.CreateValue(i));
if (item.ValueType == LuaValueType.Table) {
throw new InvalidOperationException(
"Arguments to indexer cannot be a table.");
}
objArgs[i - 1] = item;
}
args = LuaMultiValue.CreateMultiValueFromObj(objArgs);
}
return _getSetIndex(targetType, target, args, value);
} else if (index.ValueType == LuaValueType.String) {
string name = index.As<string>();
// Find all visible members with the given name
var attr = targetType.GetCustomAttribute<LuaIgnoreAttribute>(true);
MemberInfo[] members = targetType.GetMember(name)
.Where(m => !m.IsDefined(typeof(LuaIgnoreAttribute), true) &&
(attr == null || attr.IsMemberVisible(targetType, m.Name)))
.ToArray();
// TODO: Implement accessibility.
//if (Base == null || Base.Length == 0 ||
// (userData != null && !userData.IsMemberVisible(name)) ||
// (ignAttr != null && !ignAttr.IsMemberVisible(type, name)))
// throw new InvalidOperationException(
// "'" + name + "' is not a visible member of type '" + type + "'.");
if (members.Length == 0 || typeof(MemberInfo).IsAssignableFrom(targetType) ||
name == "GetType") {
// Note that reflection types are always opaque to Lua.
// TODO: Consider how to get settings here to make this configurable.
if (value != null) {
Type t = targetType;
throw new InvalidOperationException(
$"The property '{name}' on '{t.FullName}' doesn't exist or isn't visible.");
}
return LuaNil.Nil;
}
return _getSetValue(members, target, value);
} else {
throw new InvalidOperationException(
"Indices of a User-Defined type must be a string, number, or table.");
}
}
static ILuaValue _getSetValue(MemberInfo[] members, object target, ILuaValue value = null) {
// Perform the action on the given member. Although this only checks the first member, the
// only type that can return more than one with the same name is a method and can only be
// other methods.
if (members[0] is FieldInfo field) {
if (value == null) {
return LuaValueBase.CreateValue(field.GetValue(target));
} else {
// Must try to convert the given type to the requested type. This will use both implicit
// and explicit casts for user-defined types by default, SetValue only works if the
// backing type is the same as or derived from the FieldType. It does not even support
// implicit numerical conversion
var convert =
typeof(ILuaValue).GetMethod(nameof(ILuaValue.As)).MakeGenericMethod(field.FieldType);
field.SetValue(target, DynamicInvoke(convert, value, null));
return null;
}
} else if (members[0] is PropertyInfo property) {
if (value == null) {
MethodInfo meth = property.GetGetMethod();
if (meth == null) {
throw new InvalidOperationException($"The property '{property.Name}' is write-only.");
}
// TODO: Implement accessibility.
/*if (meth.GetCustomAttributes(typeof(LuaIgnoreAttribute), true).Length > 0 ||
(userData != null && !userData.IsMemberVisible("get_" + name)) ||
(ignAttr != null && !ignAttr.IsMemberVisible(type, "get_" + name)))
throw new InvalidOperationException(
"The get method for property '" + name + "' is inaccessible to Lua.");*/
return LuaValueBase.CreateValue(DynamicInvoke(meth, target, null));
} else {
MethodInfo meth = property.GetSetMethod();
if (meth == null) {
throw new InvalidOperationException($"The property '{property.Name}' is read-only.");
}
// TODO: Implement accessibility.
/*if (meth.GetCustomAttributes(typeof(LuaIgnoreAttribute), true).Length > 0 ||
(userData != null && !userData.IsMemberVisible("set_" + name)) ||
(ignAttr != null && !ignAttr.IsMemberVisible(type, "set_" + name)))
throw new InvalidOperationException(
"The set method for property '" + name + "' is inaccessible to Lua.");*/
var convert = typeof(ILuaValue).GetMethod(nameof(ILuaValue.As))
.MakeGenericMethod(property.PropertyType);
property.SetValue(target, DynamicInvoke(meth, value, null), null);
return null;
}
} else if (members[0] is MethodInfo method) {
if (value != null) {
throw new InvalidOperationException("Cannot set the value of a method.");
}
if (method.IsSpecialName) {
throw new InvalidOperationException($"Cannot call special method '{method.Name}'.");
}
return new LuaOverloadFunction(method.Name, members.Cast<MethodInfo>(),
Enumerable.Repeat(target, members.Length));
} else {
throw new InvalidOperationException("Unrecognized member type " + members[0]);
}
}
/// <summary>
/// Gets or sets the given index to the given value.
/// </remarks>
/// <param name="targetType">The type of the target object.</param>
/// <param name="target">The target object, or null for static access.</param>
/// <param name="index">The indexing object.</param>
/// <param name="value">The value to set to.</param>
/// <returns>The value for get or value if setting.</returns>
static ILuaValue _getSetIndex(Type targetType, object target, LuaMultiValue indicies,
ILuaValue value = null) {
// Arrays do not actually define an 'Item' method so we need to access the indexer directly.
if (target is Array targetArray) {
// Convert the arguments to long.
int[] args = new int[indicies.Count];
for (int i = 0; i < indicies.Count; i++) {
if (indicies[i].ValueType == LuaValueType.Number) {
// TODO: Move to resources.
throw new InvalidOperationException(
"Arguments to indexer for an array can only be numbers.");
} else {
args[i] = indicies[i].As<int>();
}
}
if (value == null) {
return LuaValueBase.CreateValue(targetArray.GetValue(args));
} else {
// Convert to the array type.
Type arrayType = targetArray.GetType().GetElementType();
object valueObj = DynamicInvoke(
typeof(ILuaValue).GetMethod(nameof(ILuaValue.As)).MakeGenericMethod(arrayType),
value, null);
targetArray.SetValue(valueObj, args);
return value;
}
}
// Setting also requires the last arg be the 'value'
if (value != null) {
indicies = indicies.AdjustResults(indicies.Count + 1);
indicies[indicies.Count - 1] = value;
}
// Find the valid method
string name = targetType == typeof(string) ? "Chars" : "Item";
var methods = targetType.GetMethods()
.Where(m => m.Name == (value == null ? "get_" + name : "set_" + name) &&
!m.IsDefined(typeof(LuaIgnoreAttribute), true))
.ToArray();
var choices = methods.Select(m => new OverloadSelector.Choice(m)).ToArray();
int index = OverloadSelector.FindOverload(choices, indicies);
if (index < 0) {
throw new InvalidOperationException(
"Unable to find a visible indexer that matches the provided arguments for type '" +
target.GetType() + "'.");
}
object[] values = OverloadSelector.ConvertArguments(indicies, choices[index]);
if (value == null) {
return LuaValueBase.CreateValue(DynamicInvoke(methods[index], target, values));
} else {
DynamicInvoke(methods[index], target, values);
return value;
}
}
}
}
| |
// 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.
// ------------------------------------------------------------------------------
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.Serialization.InvalidDataContractException))]
namespace System.Runtime.Serialization
{
#if !netfx
public abstract partial class DataContractResolver
{
protected DataContractResolver() { }
public abstract System.Type ResolveName(string typeName, string typeNamespace, System.Type declaredType, System.Runtime.Serialization.DataContractResolver knownTypeResolver);
public abstract bool TryResolveType(System.Type type, System.Type declaredType, System.Runtime.Serialization.DataContractResolver knownTypeResolver, out System.Xml.XmlDictionaryString typeName, out System.Xml.XmlDictionaryString typeNamespace);
}
public sealed partial class DataContractSerializer : System.Runtime.Serialization.XmlObjectSerializer
{
public DataContractSerializer(System.Type type) { }
public DataContractSerializer(System.Type type, System.Collections.Generic.IEnumerable<System.Type> knownTypes) { }
public DataContractSerializer(System.Type type, System.Runtime.Serialization.DataContractSerializerSettings settings) { }
public DataContractSerializer(System.Type type, string rootName, string rootNamespace) { }
public DataContractSerializer(System.Type type, string rootName, string rootNamespace, System.Collections.Generic.IEnumerable<System.Type> knownTypes) { }
public DataContractSerializer(System.Type type, System.Xml.XmlDictionaryString rootName, System.Xml.XmlDictionaryString rootNamespace) { }
public DataContractSerializer(System.Type type, System.Xml.XmlDictionaryString rootName, System.Xml.XmlDictionaryString rootNamespace, System.Collections.Generic.IEnumerable<System.Type> knownTypes) { }
public System.Runtime.Serialization.DataContractResolver DataContractResolver { get { throw null; } }
public bool IgnoreExtensionDataObject { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyCollection<System.Type> KnownTypes { get { throw null; } }
public int MaxItemsInObjectGraph { get { throw null; } }
public bool PreserveObjectReferences { get { throw null; } }
public bool SerializeReadOnlyTypes { get { throw null; } }
public override bool IsStartObject(System.Xml.XmlDictionaryReader reader) { throw null; }
public override bool IsStartObject(System.Xml.XmlReader reader) { throw null; }
public override object ReadObject(System.Xml.XmlDictionaryReader reader, bool verifyObjectName) { throw null; }
public object ReadObject(System.Xml.XmlDictionaryReader reader, bool verifyObjectName, System.Runtime.Serialization.DataContractResolver dataContractResolver) { throw null; }
public override object ReadObject(System.Xml.XmlReader reader) { throw null; }
public override object ReadObject(System.Xml.XmlReader reader, bool verifyObjectName) { throw null; }
public override void WriteEndObject(System.Xml.XmlDictionaryWriter writer) { }
public override void WriteEndObject(System.Xml.XmlWriter writer) { }
public void WriteObject(System.Xml.XmlDictionaryWriter writer, object graph, System.Runtime.Serialization.DataContractResolver dataContractResolver) { }
public override void WriteObject(System.Xml.XmlWriter writer, object graph) { }
public override void WriteObjectContent(System.Xml.XmlDictionaryWriter writer, object graph) { }
public override void WriteObjectContent(System.Xml.XmlWriter writer, object graph) { }
public override void WriteStartObject(System.Xml.XmlDictionaryWriter writer, object graph) { }
public override void WriteStartObject(System.Xml.XmlWriter writer, object graph) { }
}
#endif // !netfx
public static partial class DataContractSerializerExtensions
{
public static System.Runtime.Serialization.ISerializationSurrogateProvider GetSerializationSurrogateProvider(this DataContractSerializer serializer) { throw null; }
public static void SetSerializationSurrogateProvider(this DataContractSerializer serializer, System.Runtime.Serialization.ISerializationSurrogateProvider provider) { }
}
#if !netfx
public partial class DataContractSerializerSettings
{
public DataContractSerializerSettings() { }
public System.Runtime.Serialization.DataContractResolver DataContractResolver { get { throw null; } set { } }
//CODEDOM public System.Runtime.Serialization.IDataContractSurrogate DataContractSurrogate { get { throw null; } set { } }
public bool IgnoreExtensionDataObject { get { throw null; } set { } }
public System.Collections.Generic.IEnumerable<System.Type> KnownTypes { get { throw null; } set { } }
public int MaxItemsInObjectGraph { get { throw null; } set { } }
public bool PreserveObjectReferences { get { throw null; } set { } }
public System.Xml.XmlDictionaryString RootName { get { throw null; } set { } }
public System.Xml.XmlDictionaryString RootNamespace { get { throw null; } set { } }
public bool SerializeReadOnlyTypes { get { throw null; } set { } }
}
public static partial class XmlSerializableServices
{
public static void AddDefaultSchema(System.Xml.Schema.XmlSchemaSet schemas, System.Xml.XmlQualifiedName typeQName) { }
public static System.Xml.XmlNode[] ReadNodes(System.Xml.XmlReader xmlReader) { throw null; }
public static void WriteNodes(System.Xml.XmlWriter xmlWriter, System.Xml.XmlNode[] nodes) { }
}
public static partial class XPathQueryGenerator
{
public static string CreateFromDataContractSerializer(System.Type type, System.Reflection.MemberInfo[] pathToMember, System.Text.StringBuilder rootElementXpath, out System.Xml.XmlNamespaceManager namespaces) { throw null; }
public static string CreateFromDataContractSerializer(System.Type type, System.Reflection.MemberInfo[] pathToMember, out System.Xml.XmlNamespaceManager namespaces) { throw null; }
}
public partial class XsdDataContractExporter
{
public XsdDataContractExporter() { }
public XsdDataContractExporter(System.Xml.Schema.XmlSchemaSet schemas) { }
public System.Runtime.Serialization.ExportOptions Options { get { throw null; } set { } }
public System.Xml.Schema.XmlSchemaSet Schemas { get { throw null; } }
public bool CanExport(System.Collections.Generic.ICollection<System.Reflection.Assembly> assemblies) { throw null; }
public bool CanExport(System.Collections.Generic.ICollection<System.Type> types) { throw null; }
public bool CanExport(System.Type type) { throw null; }
public void Export(System.Collections.Generic.ICollection<System.Reflection.Assembly> assemblies) { }
public void Export(System.Collections.Generic.ICollection<System.Type> types) { }
public void Export(System.Type type) { }
public System.Xml.XmlQualifiedName GetRootElementName(System.Type type) { throw null; }
public System.Xml.Schema.XmlSchemaType GetSchemaType(System.Type type) { throw null; }
public System.Xml.XmlQualifiedName GetSchemaTypeName(System.Type type) { throw null; }
}
public partial class ExportOptions
{
public ExportOptions() { }
//CODEDOM public System.Runtime.Serialization.IDataContractSurrogate DataContractSurrogate { get { throw null; } set { } }
public System.Collections.ObjectModel.Collection<System.Type> KnownTypes { get { throw null; } }
}
public sealed partial class ExtensionDataObject
{
internal ExtensionDataObject() { }
}
public partial interface IExtensibleDataObject
{
System.Runtime.Serialization.ExtensionDataObject ExtensionData { get; set; }
}
public abstract partial class XmlObjectSerializer
{
protected XmlObjectSerializer() { }
public abstract bool IsStartObject(System.Xml.XmlDictionaryReader reader);
public virtual bool IsStartObject(System.Xml.XmlReader reader) { throw null; }
public virtual object ReadObject(System.IO.Stream stream) { throw null; }
public virtual object ReadObject(System.Xml.XmlDictionaryReader reader) { throw null; }
public abstract object ReadObject(System.Xml.XmlDictionaryReader reader, bool verifyObjectName);
public virtual object ReadObject(System.Xml.XmlReader reader) { throw null; }
public virtual object ReadObject(System.Xml.XmlReader reader, bool verifyObjectName) { throw null; }
public abstract void WriteEndObject(System.Xml.XmlDictionaryWriter writer);
public virtual void WriteEndObject(System.Xml.XmlWriter writer) { }
public virtual void WriteObject(System.IO.Stream stream, object graph) { }
public virtual void WriteObject(System.Xml.XmlDictionaryWriter writer, object graph) { }
public virtual void WriteObject(System.Xml.XmlWriter writer, object graph) { }
public abstract void WriteObjectContent(System.Xml.XmlDictionaryWriter writer, object graph);
public virtual void WriteObjectContent(System.Xml.XmlWriter writer, object graph) { }
public abstract void WriteStartObject(System.Xml.XmlDictionaryWriter writer, object graph);
public virtual void WriteStartObject(System.Xml.XmlWriter writer, object graph) { }
}
}
namespace System.Xml
{
public partial interface IFragmentCapableXmlDictionaryWriter
{
bool CanFragment { get; }
void EndFragment();
void StartFragment(System.IO.Stream stream, bool generateSelfContainedTextFragment);
void WriteFragment(byte[] buffer, int offset, int count);
}
public partial interface IStreamProvider
{
System.IO.Stream GetStream();
void ReleaseStream(System.IO.Stream stream);
}
public partial interface IXmlBinaryReaderInitializer
{
void SetInput(byte[] buffer, int offset, int count, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session, System.Xml.OnXmlDictionaryReaderClose onClose);
void SetInput(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session, System.Xml.OnXmlDictionaryReaderClose onClose);
}
public partial interface IXmlBinaryWriterInitializer
{
void SetOutput(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlBinaryWriterSession session, bool ownsStream);
}
public partial interface IXmlDictionary
{
bool TryLookup(int key, out System.Xml.XmlDictionaryString result);
bool TryLookup(string value, out System.Xml.XmlDictionaryString result);
bool TryLookup(System.Xml.XmlDictionaryString value, out System.Xml.XmlDictionaryString result);
}
public partial interface IXmlTextReaderInitializer
{
void SetInput(byte[] buffer, int offset, int count, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose onClose);
void SetInput(System.IO.Stream stream, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose onClose);
}
public partial interface IXmlTextWriterInitializer
{
void SetOutput(System.IO.Stream stream, System.Text.Encoding encoding, bool ownsStream);
}
public delegate void OnXmlDictionaryReaderClose(System.Xml.XmlDictionaryReader reader);
public partial class UniqueId
{
public UniqueId() { }
public UniqueId(byte[] guid) { }
public UniqueId(byte[] guid, int offset) { }
public UniqueId(char[] chars, int offset, int count) { }
public UniqueId(System.Guid guid) { }
public UniqueId(string value) { }
public int CharArrayLength { get { throw null; } }
public bool IsGuid { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Xml.UniqueId id1, System.Xml.UniqueId id2) { throw null; }
public static bool operator !=(System.Xml.UniqueId id1, System.Xml.UniqueId id2) { throw null; }
public int ToCharArray(char[] chars, int offset) { throw null; }
public override string ToString() { throw null; }
public bool TryGetGuid(byte[] buffer, int offset) { throw null; }
public bool TryGetGuid(out System.Guid guid) { throw null; }
}
public partial class XmlBinaryReaderSession : System.Xml.IXmlDictionary
{
public XmlBinaryReaderSession() { }
public System.Xml.XmlDictionaryString Add(int id, string value) { throw null; }
public void Clear() { }
public bool TryLookup(int key, out System.Xml.XmlDictionaryString result) { throw null; }
public bool TryLookup(string value, out System.Xml.XmlDictionaryString result) { throw null; }
public bool TryLookup(System.Xml.XmlDictionaryString value, out System.Xml.XmlDictionaryString result) { throw null; }
}
public partial class XmlBinaryWriterSession
{
public XmlBinaryWriterSession() { }
public void Reset() { }
public virtual bool TryAdd(System.Xml.XmlDictionaryString value, out int key) { throw null; }
}
public partial class XmlDictionary : System.Xml.IXmlDictionary
{
public XmlDictionary() { }
public XmlDictionary(int capacity) { }
public static System.Xml.IXmlDictionary Empty { get { throw null; } }
public virtual System.Xml.XmlDictionaryString Add(string value) { throw null; }
public virtual bool TryLookup(int key, out System.Xml.XmlDictionaryString result) { throw null; }
public virtual bool TryLookup(string value, out System.Xml.XmlDictionaryString result) { throw null; }
public virtual bool TryLookup(System.Xml.XmlDictionaryString value, out System.Xml.XmlDictionaryString result) { throw null; }
}
public abstract partial class XmlDictionaryReader : System.Xml.XmlReader
{
protected XmlDictionaryReader() { }
public virtual bool CanCanonicalize { get { throw null; } }
public virtual System.Xml.XmlDictionaryReaderQuotas Quotas { get { throw null; } }
public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session) { throw null; }
public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; }
public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateBinaryReader(byte[] buffer, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateBinaryReader(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateBinaryReader(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session) { throw null; }
public static System.Xml.XmlDictionaryReader CreateBinaryReader(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.XmlBinaryReaderSession session, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; }
public static System.Xml.XmlDictionaryReader CreateBinaryReader(System.IO.Stream stream, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateDictionaryReader(System.Xml.XmlReader reader) { throw null; }
public static System.Xml.XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, System.Text.Encoding[] encodings, string contentType, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, System.Text.Encoding[] encodings, string contentType, System.Xml.XmlDictionaryReaderQuotas quotas, int maxBufferSize, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; }
public static System.Xml.XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, System.Text.Encoding[] encodings, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateMtomReader(System.IO.Stream stream, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateMtomReader(System.IO.Stream stream, System.Text.Encoding[] encodings, string contentType, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateMtomReader(System.IO.Stream stream, System.Text.Encoding[] encodings, string contentType, System.Xml.XmlDictionaryReaderQuotas quotas, int maxBufferSize, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; }
public static System.Xml.XmlDictionaryReader CreateMtomReader(System.IO.Stream stream, System.Text.Encoding[] encodings, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; }
public static System.Xml.XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateTextReader(byte[] buffer, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public static System.Xml.XmlDictionaryReader CreateTextReader(System.IO.Stream stream, System.Text.Encoding encoding, System.Xml.XmlDictionaryReaderQuotas quotas, System.Xml.OnXmlDictionaryReaderClose onClose) { throw null; }
public static System.Xml.XmlDictionaryReader CreateTextReader(System.IO.Stream stream, System.Xml.XmlDictionaryReaderQuotas quotas) { throw null; }
public virtual void EndCanonicalization() { }
public virtual string GetAttribute(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual void GetNonAtomizedNames(out string localName, out string namespaceUri) { throw null; }
public virtual int IndexOfLocalName(string[] localNames, string namespaceUri) { throw null; }
public virtual int IndexOfLocalName(System.Xml.XmlDictionaryString[] localNames, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual bool IsLocalName(string localName) { throw null; }
public virtual bool IsLocalName(System.Xml.XmlDictionaryString localName) { throw null; }
public virtual bool IsNamespaceUri(string namespaceUri) { throw null; }
public virtual bool IsNamespaceUri(System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual bool IsStartArray(out System.Type type) { throw null; }
public virtual bool IsStartElement(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
protected bool IsTextNode(System.Xml.XmlNodeType nodeType) { throw null; }
public virtual void MoveToStartElement() { }
public virtual void MoveToStartElement(string name) { }
public virtual void MoveToStartElement(string localName, string namespaceUri) { }
public virtual void MoveToStartElement(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { }
public virtual int ReadArray(string localName, string namespaceUri, bool[] array, int offset, int count) { throw null; }
public virtual int ReadArray(string localName, string namespaceUri, System.DateTime[] array, int offset, int count) { throw null; }
public virtual int ReadArray(string localName, string namespaceUri, decimal[] array, int offset, int count) { throw null; }
public virtual int ReadArray(string localName, string namespaceUri, double[] array, int offset, int count) { throw null; }
public virtual int ReadArray(string localName, string namespaceUri, System.Guid[] array, int offset, int count) { throw null; }
public virtual int ReadArray(string localName, string namespaceUri, short[] array, int offset, int count) { throw null; }
public virtual int ReadArray(string localName, string namespaceUri, int[] array, int offset, int count) { throw null; }
public virtual int ReadArray(string localName, string namespaceUri, long[] array, int offset, int count) { throw null; }
public virtual int ReadArray(string localName, string namespaceUri, float[] array, int offset, int count) { throw null; }
public virtual int ReadArray(string localName, string namespaceUri, System.TimeSpan[] array, int offset, int count) { throw null; }
public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { throw null; }
public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.DateTime[] array, int offset, int count) { throw null; }
public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { throw null; }
public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, double[] array, int offset, int count) { throw null; }
public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.Guid[] array, int offset, int count) { throw null; }
public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, short[] array, int offset, int count) { throw null; }
public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, int[] array, int offset, int count) { throw null; }
public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, long[] array, int offset, int count) { throw null; }
public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, float[] array, int offset, int count) { throw null; }
public virtual int ReadArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.TimeSpan[] array, int offset, int count) { throw null; }
public virtual bool[] ReadBooleanArray(string localName, string namespaceUri) { throw null; }
public virtual bool[] ReadBooleanArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public override object ReadContentAs(System.Type type, System.Xml.IXmlNamespaceResolver namespaceResolver) { throw null; }
public virtual byte[] ReadContentAsBase64() { throw null; }
public virtual byte[] ReadContentAsBinHex() { throw null; }
protected byte[] ReadContentAsBinHex(int maxByteArrayContentLength) { throw null; }
public virtual int ReadContentAsChars(char[] chars, int offset, int count) { throw null; }
public override decimal ReadContentAsDecimal() { throw null; }
public override float ReadContentAsFloat() { throw null; }
public virtual System.Guid ReadContentAsGuid() { throw null; }
public virtual void ReadContentAsQualifiedName(out string localName, out string namespaceUri) { throw null; }
public override string ReadContentAsString() { throw null; }
protected string ReadContentAsString(int maxStringContentLength) { throw null; }
public virtual string ReadContentAsString(string[] strings, out int index) { throw null; }
public virtual string ReadContentAsString(System.Xml.XmlDictionaryString[] strings, out int index) { throw null; }
public virtual System.TimeSpan ReadContentAsTimeSpan() { throw null; }
public virtual System.Xml.UniqueId ReadContentAsUniqueId() { throw null; }
public virtual System.DateTime[] ReadDateTimeArray(string localName, string namespaceUri) { throw null; }
public virtual System.DateTime[] ReadDateTimeArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual decimal[] ReadDecimalArray(string localName, string namespaceUri) { throw null; }
public virtual decimal[] ReadDecimalArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual double[] ReadDoubleArray(string localName, string namespaceUri) { throw null; }
public virtual double[] ReadDoubleArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual byte[] ReadElementContentAsBase64() { throw null; }
public virtual byte[] ReadElementContentAsBinHex() { throw null; }
public override bool ReadElementContentAsBoolean() { throw null; }
public override System.DateTime ReadElementContentAsDateTime() { throw null; }
public override decimal ReadElementContentAsDecimal() { throw null; }
public override double ReadElementContentAsDouble() { throw null; }
public override float ReadElementContentAsFloat() { throw null; }
public virtual System.Guid ReadElementContentAsGuid() { throw null; }
public override int ReadElementContentAsInt() { throw null; }
public override long ReadElementContentAsLong() { throw null; }
public override string ReadElementContentAsString() { throw null; }
public virtual System.TimeSpan ReadElementContentAsTimeSpan() { throw null; }
public virtual System.Xml.UniqueId ReadElementContentAsUniqueId() { throw null; }
public virtual void ReadFullStartElement() { }
public virtual void ReadFullStartElement(string name) { }
public virtual void ReadFullStartElement(string localName, string namespaceUri) { }
public virtual void ReadFullStartElement(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { }
public virtual System.Guid[] ReadGuidArray(string localName, string namespaceUri) { throw null; }
public virtual System.Guid[] ReadGuidArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual short[] ReadInt16Array(string localName, string namespaceUri) { throw null; }
public virtual short[] ReadInt16Array(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual int[] ReadInt32Array(string localName, string namespaceUri) { throw null; }
public virtual int[] ReadInt32Array(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual long[] ReadInt64Array(string localName, string namespaceUri) { throw null; }
public virtual long[] ReadInt64Array(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual float[] ReadSingleArray(string localName, string namespaceUri) { throw null; }
public virtual float[] ReadSingleArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual void ReadStartElement(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { }
public override string ReadString() { throw null; }
protected string ReadString(int maxStringContentLength) { throw null; }
public virtual System.TimeSpan[] ReadTimeSpanArray(string localName, string namespaceUri) { throw null; }
public virtual System.TimeSpan[] ReadTimeSpanArray(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual int ReadValueAsBase64(byte[] buffer, int offset, int count) { throw null; }
public virtual void StartCanonicalization(System.IO.Stream stream, bool includeComments, string[] inclusivePrefixes) { }
public virtual bool TryGetArrayLength(out int count) { throw null; }
public virtual bool TryGetBase64ContentLength(out int length) { throw null; }
public virtual bool TryGetLocalNameAsDictionaryString(out System.Xml.XmlDictionaryString localName) { throw null; }
public virtual bool TryGetNamespaceUriAsDictionaryString(out System.Xml.XmlDictionaryString namespaceUri) { throw null; }
public virtual bool TryGetValueAsDictionaryString(out System.Xml.XmlDictionaryString value) { throw null; }
}
public sealed partial class XmlDictionaryReaderQuotas
{
public XmlDictionaryReaderQuotas() { }
public static System.Xml.XmlDictionaryReaderQuotas Max { get { throw null; } }
[System.ComponentModel.DefaultValueAttribute(16384)]
public int MaxArrayLength { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute(4096)]
public int MaxBytesPerRead { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute(32)]
public int MaxDepth { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute(16384)]
public int MaxNameTableCharCount { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute(8192)]
public int MaxStringContentLength { get { throw null; } set { } }
public System.Xml.XmlDictionaryReaderQuotaTypes ModifiedQuotas { get { throw null; } }
public void CopyTo(System.Xml.XmlDictionaryReaderQuotas quotas) { }
}
[System.FlagsAttribute]
public enum XmlDictionaryReaderQuotaTypes
{
MaxArrayLength = 4,
MaxBytesPerRead = 8,
MaxDepth = 1,
MaxNameTableCharCount = 16,
MaxStringContentLength = 2,
}
public partial class XmlDictionaryString
{
public XmlDictionaryString(System.Xml.IXmlDictionary dictionary, string value, int key) { }
public System.Xml.IXmlDictionary Dictionary { get { throw null; } }
public static System.Xml.XmlDictionaryString Empty { get { throw null; } }
public int Key { get { throw null; } }
public string Value { get { throw null; } }
public override string ToString() { throw null; }
}
public abstract partial class XmlDictionaryWriter : System.Xml.XmlWriter
{
protected XmlDictionaryWriter() { }
public virtual bool CanCanonicalize { get { throw null; } }
public static System.Xml.XmlDictionaryWriter CreateBinaryWriter(System.IO.Stream stream) { throw null; }
public static System.Xml.XmlDictionaryWriter CreateBinaryWriter(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary) { throw null; }
public static System.Xml.XmlDictionaryWriter CreateBinaryWriter(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlBinaryWriterSession session) { throw null; }
public static System.Xml.XmlDictionaryWriter CreateBinaryWriter(System.IO.Stream stream, System.Xml.IXmlDictionary dictionary, System.Xml.XmlBinaryWriterSession session, bool ownsStream) { throw null; }
public static System.Xml.XmlDictionaryWriter CreateDictionaryWriter(System.Xml.XmlWriter writer) { throw null; }
public static System.Xml.XmlDictionaryWriter CreateMtomWriter(System.IO.Stream stream, System.Text.Encoding encoding, int maxSizeInBytes, string startInfo) { throw null; }
public static System.Xml.XmlDictionaryWriter CreateMtomWriter(System.IO.Stream stream, System.Text.Encoding encoding, int maxSizeInBytes, string startInfo, string boundary, string startUri, bool writeMessageHeaders, bool ownsStream) { throw null; }
public static System.Xml.XmlDictionaryWriter CreateTextWriter(System.IO.Stream stream) { throw null; }
public static System.Xml.XmlDictionaryWriter CreateTextWriter(System.IO.Stream stream, System.Text.Encoding encoding) { throw null; }
public static System.Xml.XmlDictionaryWriter CreateTextWriter(System.IO.Stream stream, System.Text.Encoding encoding, bool ownsStream) { throw null; }
public virtual void EndCanonicalization() { }
public virtual void StartCanonicalization(System.IO.Stream stream, bool includeComments, string[] inclusivePrefixes) { }
public virtual void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, string localName, string namespaceUri, System.DateTime[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, string localName, string namespaceUri, System.Guid[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, string localName, string namespaceUri, short[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, string localName, string namespaceUri, int[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, string localName, string namespaceUri, long[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, string localName, string namespaceUri, System.TimeSpan[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, bool[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.DateTime[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, double[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.Guid[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, short[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, int[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, long[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, float[] array, int offset, int count) { }
public virtual void WriteArray(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, System.TimeSpan[] array, int offset, int count) { }
public void WriteAttributeString(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, string value) { }
public void WriteAttributeString(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, string value) { }
public override System.Threading.Tasks.Task WriteBase64Async(byte[] buffer, int index, int count) { throw null; }
public void WriteElementString(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, string value) { }
public void WriteElementString(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri, string value) { }
public virtual void WriteNode(System.Xml.XmlDictionaryReader reader, bool defattr) { }
public override void WriteNode(System.Xml.XmlReader reader, bool defattr) { }
public virtual void WriteQualifiedName(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { }
public virtual void WriteStartAttribute(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { }
public void WriteStartAttribute(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { }
public virtual void WriteStartElement(string prefix, System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { }
public void WriteStartElement(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString namespaceUri) { }
public virtual void WriteString(System.Xml.XmlDictionaryString value) { }
protected virtual void WriteTextNode(System.Xml.XmlDictionaryReader reader, bool isAttribute) { }
public virtual void WriteValue(System.Guid value) { }
public virtual void WriteValue(System.TimeSpan value) { }
public virtual void WriteValue(System.Xml.IStreamProvider value) { }
public virtual void WriteValue(System.Xml.UniqueId value) { }
public virtual void WriteValue(System.Xml.XmlDictionaryString value) { }
public virtual System.Threading.Tasks.Task WriteValueAsync(System.Xml.IStreamProvider value) { throw null; }
public virtual void WriteXmlAttribute(string localName, string value) { }
public virtual void WriteXmlAttribute(System.Xml.XmlDictionaryString localName, System.Xml.XmlDictionaryString value) { }
public virtual void WriteXmlnsAttribute(string prefix, string namespaceUri) { }
public virtual void WriteXmlnsAttribute(string prefix, System.Xml.XmlDictionaryString namespaceUri) { }
}
#endif // !netfx
}
| |
using UnityEngine;
using System.Collections.Generic;
#if UNITY_EDITOR
#endif
namespace Pathfinding
{
[AddComponentMenu("Pathfinding/Link2")]
public class NodeLink2 : GraphModifier {
protected static Dictionary<GraphNode,NodeLink2> reference = new Dictionary<GraphNode,NodeLink2>();
public static NodeLink2 GetNodeLink (GraphNode node) {
NodeLink2 v;
reference.TryGetValue (node, out v);
return v;
}
/** End position of the link */
public Transform end;
/** The connection will be this times harder/slower to traverse.
* Note that values lower than one will not always make the pathfinder choose this path instead of another path even though this one should
* lead to a lower total cost unless you also adjust the Heuristic Scale in A* Inspector -> Settings -> Pathfinding or disable the heuristic altogether.
*/
public float costFactor = 1.0f;
/** Make a one-way connection */
public bool oneWay = false;
/* Delete existing connection instead of adding one */
//public bool deleteConnection = false;
//private bool createHiddenNodes = true;
public Transform StartTransform {
get { return transform; }
}
public Transform EndTransform {
get { return end; }
}
PointNode startNode;
PointNode endNode;
MeshNode connectedNode1, connectedNode2;
Vector3 clamped1, clamped2;
bool postScanCalled = false;
public GraphNode StartNode {
get { return startNode; }
}
public GraphNode EndNode {
get { return endNode; }
}
public override void OnPostScan () {
if (AstarPath.active.isScanning) {
InternalOnPostScan ();
} else {
AstarPath.active.AddWorkItem (new AstarPath.AstarWorkItem (delegate (bool force) {
InternalOnPostScan ();
return true;
}));
}
}
public void InternalOnPostScan () {
if ( AstarPath.active.astarData.pointGraph == null ) {
AstarPath.active.astarData.AddGraph ( new PointGraph () );
}
if ( startNode != null) {
NodeLink2 tmp;
if (reference.TryGetValue (startNode, out tmp) && tmp == this) reference.Remove (startNode);
}
if ( endNode != null) {
NodeLink2 tmp;
if (reference.TryGetValue (endNode, out tmp) && tmp == this) reference.Remove (endNode);
}
//Get nearest nodes from the first point graph, assuming both start and end transforms are nodes
startNode = AstarPath.active.astarData.pointGraph.AddNode ( (Int3)StartTransform.position );//AstarPath.active.astarData.pointGraph.GetNearest(StartTransform.position).node as PointNode;
endNode = AstarPath.active.astarData.pointGraph.AddNode ( (Int3)EndTransform.position ); //AstarPath.active.astarData.pointGraph.GetNearest(EndTransform.position).node as PointNode;
connectedNode1 = null;
connectedNode2 = null;
if (startNode == null || endNode == null) {
startNode = null;
endNode = null;
return;
}
postScanCalled = true;
reference[startNode] = this;
reference[endNode] = this;
Apply( true );
}
public override void OnGraphsPostUpdate () {
//if (connectedNode1 != null && connectedNode2 != null) {
if (!AstarPath.active.isScanning) {
if (connectedNode1 != null && connectedNode1.Destroyed) {
connectedNode1 = null;
}
if (connectedNode2 != null && connectedNode2.Destroyed) {
connectedNode2 = null;
}
if (!postScanCalled) {
OnPostScan();
} else {
//OnPostScan will also call this method
/** \todo Can mess up pathfinding, wrap in delegate */
Apply( false );
}
}
}
protected override void OnEnable () {
base.OnEnable();
if (AstarPath.active != null && AstarPath.active.astarData != null && AstarPath.active.astarData.pointGraph != null) {
OnGraphsPostUpdate ();
}
}
protected override void OnDisable () {
base.OnDisable();
postScanCalled = false;
if ( startNode != null) {
NodeLink2 tmp;
if (reference.TryGetValue (startNode, out tmp) && tmp == this) reference.Remove (startNode);
}
if ( endNode != null) {
NodeLink2 tmp;
if (reference.TryGetValue (endNode, out tmp) && tmp == this) reference.Remove (endNode);
}
if (startNode != null && endNode != null) {
startNode.RemoveConnection (endNode);
endNode.RemoveConnection (startNode);
if (connectedNode1 != null && connectedNode2 != null) {
startNode.RemoveConnection (connectedNode1);
connectedNode1.RemoveConnection (startNode);
endNode.RemoveConnection (connectedNode2);
connectedNode2.RemoveConnection (endNode);
}
}
}
void RemoveConnections (GraphNode node) {
//TODO, might be better to replace connection
node.ClearConnections (true);
}
[ContextMenu ("Recalculate neighbours")]
void ContextApplyForce () {
if (Application.isPlaying) {
Apply ( true );
if ( AstarPath.active != null ) {
AstarPath.active.FloodFill ();
}
}
}
public void Apply ( bool forceNewCheck ) {
//TODO
//This function assumes that connections from the n1,n2 nodes never need to be removed in the future (e.g because the nodes move or something)
NNConstraint nn = NNConstraint.None;
int graph = (int)startNode.GraphIndex;
//Search all graphs but the one which start and end nodes are on
nn.graphMask = ~(1 << graph);
startNode.SetPosition ( (Int3)StartTransform.position );
endNode.SetPosition ( (Int3)EndTransform.position );
RemoveConnections(startNode);
RemoveConnections(endNode);
uint cost = (uint)Mathf.RoundToInt(((Int3)(StartTransform.position-EndTransform.position)).costMagnitude*costFactor);
startNode.AddConnection (endNode, cost);
endNode.AddConnection(startNode, cost);
if (connectedNode1 == null || forceNewCheck) {
NNInfo n1 = AstarPath.active.GetNearest(StartTransform.position, nn);
connectedNode1 = n1.node as MeshNode;
clamped1 = n1.clampedPosition;
}
if (connectedNode2 == null || forceNewCheck) {
NNInfo n2 = AstarPath.active.GetNearest(EndTransform.position, nn);
connectedNode2 = n2.node as MeshNode;
clamped2 = n2.clampedPosition;
}
if (connectedNode2 == null || connectedNode1 == null) return;
//Add connections between nodes, or replace old connections if existing
connectedNode1.AddConnection(startNode, (uint)Mathf.RoundToInt (((Int3)(clamped1 - StartTransform.position)).costMagnitude*costFactor));
connectedNode2.AddConnection(endNode, (uint)Mathf.RoundToInt (((Int3)(clamped2 - EndTransform.position)).costMagnitude*costFactor));
startNode.AddConnection(connectedNode1, (uint)Mathf.RoundToInt (((Int3)(clamped1 - StartTransform.position)).costMagnitude*costFactor));
endNode.AddConnection(connectedNode2, (uint)Mathf.RoundToInt (((Int3)(clamped2 - EndTransform.position)).costMagnitude*costFactor));
}
void DrawCircle (Vector3 o, float r, int detail, Color col) {
Vector3 prev = new Vector3(Mathf.Cos(0)*r,0,Mathf.Sin(0)*r) + o;
Gizmos.color = col;
for (int i=0;i<=detail;i++) {
float t = (i*Mathf.PI*2f)/detail;
Vector3 c = new Vector3(Mathf.Cos(t)*r,0,Mathf.Sin(t)*r) + o;
Gizmos.DrawLine(prev,c);
prev = c;
}
}
private readonly static Color GizmosColor = new Color(206.0f/255.0f,136.0f/255.0f,48.0f/255.0f,0.5f);
private readonly static Color GizmosColorSelected = new Color(235.0f/255.0f,123.0f/255.0f,32.0f/255.0f,1.0f);
void DrawGizmoBezier (Vector3 p1, Vector3 p2) {
Vector3 dir = p2-p1;
if (dir == Vector3.zero) return;
Vector3 normal = Vector3.Cross (Vector3.up,dir);
Vector3 normalUp = Vector3.Cross (dir,normal);
normalUp = normalUp.normalized;
normalUp *= dir.magnitude*0.1f;
Vector3 p1c = p1+normalUp;
Vector3 p2c = p2+normalUp;
Vector3 prev = p1;
for (int i=1;i<=20;i++) {
float t = i/20.0f;
Vector3 p = AstarMath.CubicBezier (p1,p1c,p2c,p2,t);
Gizmos.DrawLine (prev,p);
prev = p;
}
}
public virtual void OnDrawGizmosSelected () {
OnDrawGizmos(true);
}
public void OnDrawGizmos () {
OnDrawGizmos (false);
}
public void OnDrawGizmos (bool selected) {
Color col = selected ? GizmosColorSelected : GizmosColor;
if (StartTransform != null) {
DrawCircle(StartTransform.position,0.4f,10,col);
}
if (EndTransform != null) {
DrawCircle(EndTransform.position,0.4f,10,col);
}
if (StartTransform != null && EndTransform != null) {
Gizmos.color = col;
DrawGizmoBezier (StartTransform.position,EndTransform.position);
if (selected) {
Vector3 cross = Vector3.Cross (Vector3.up, (EndTransform.position-StartTransform.position)).normalized;
DrawGizmoBezier (StartTransform.position+cross*0.1f,EndTransform.position+cross*0.1f);
DrawGizmoBezier (StartTransform.position-cross*0.1f,EndTransform.position-cross*0.1f);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Orleans.CodeGeneration;
using Orleans.Serialization;
using TestExtensions;
using UnitTests.GrainInterfaces;
using Xunit;
namespace UnitTests.Serialization
{
/// <summary>
/// Summary description for SerializationTests
/// </summary>
[Collection(TestEnvironmentFixture.DefaultCollection)]
public class SerializationTestsDifferentTypes
{
private readonly TestEnvironmentFixture fixture;
public SerializationTestsDifferentTypes(TestEnvironmentFixture fixture)
{
this.fixture = fixture;
}
[Fact, TestCategory("BVT"), TestCategory("Serialization")]
public void SerializationTests_DateTime()
{
// Local Kind
DateTime inputLocal = DateTime.Now;
DateTime outputLocal = this.fixture.SerializationManager.RoundTripSerializationForTesting(inputLocal);
Assert.Equal(inputLocal.ToString(CultureInfo.InvariantCulture), outputLocal.ToString(CultureInfo.InvariantCulture));
Assert.Equal(inputLocal.Kind, outputLocal.Kind);
// UTC Kind
DateTime inputUtc = DateTime.UtcNow;
DateTime outputUtc = this.fixture.SerializationManager.RoundTripSerializationForTesting(inputUtc);
Assert.Equal(inputUtc.ToString(CultureInfo.InvariantCulture), outputUtc.ToString(CultureInfo.InvariantCulture));
Assert.Equal(inputUtc.Kind, outputUtc.Kind);
// Unspecified Kind
DateTime inputUnspecified = new DateTime(0x08d27e2c0cc7dfb9);
DateTime outputUnspecified = this.fixture.SerializationManager.RoundTripSerializationForTesting(inputUnspecified);
Assert.Equal(inputUnspecified.ToString(CultureInfo.InvariantCulture), outputUnspecified.ToString(CultureInfo.InvariantCulture));
Assert.Equal(inputUnspecified.Kind, outputUnspecified.Kind);
}
[Fact, TestCategory("BVT"), TestCategory("Serialization")]
public void SerializationTests_DateTimeOffset()
{
// Local Kind
DateTime inputLocalDateTime = DateTime.Now;
DateTimeOffset inputLocal = new DateTimeOffset(inputLocalDateTime);
DateTimeOffset outputLocal = this.fixture.SerializationManager.RoundTripSerializationForTesting(inputLocal);
Assert.Equal(inputLocal, outputLocal);
Assert.Equal(
inputLocal.ToString(CultureInfo.InvariantCulture),
outputLocal.ToString(CultureInfo.InvariantCulture));
Assert.Equal(inputLocal.DateTime.Kind, outputLocal.DateTime.Kind);
// UTC Kind
DateTime inputUtcDateTime = DateTime.UtcNow;
DateTimeOffset inputUtc = new DateTimeOffset(inputUtcDateTime);
DateTimeOffset outputUtc = this.fixture.SerializationManager.RoundTripSerializationForTesting(inputUtc);
Assert.Equal(inputUtc, outputUtc);
Assert.Equal(
inputUtc.ToString(CultureInfo.InvariantCulture),
outputUtc.ToString(CultureInfo.InvariantCulture));
Assert.Equal(inputUtc.DateTime.Kind, outputUtc.DateTime.Kind);
// Unspecified Kind
DateTime inputUnspecifiedDateTime = new DateTime(0x08d27e2c0cc7dfb9);
DateTimeOffset inputUnspecified = new DateTimeOffset(inputUnspecifiedDateTime);
DateTimeOffset outputUnspecified = this.fixture.SerializationManager.RoundTripSerializationForTesting(inputUnspecified);
Assert.Equal(inputUnspecified, outputUnspecified);
Assert.Equal(
inputUnspecified.ToString(CultureInfo.InvariantCulture),
outputUnspecified.ToString(CultureInfo.InvariantCulture));
Assert.Equal(inputUnspecified.DateTime.Kind, outputUnspecified.DateTime.Kind);
}
[Serializer(typeof(TestTypeA))]
internal class TestTypeASerialization
{
[CopierMethod]
public static object DeepCopier(object original, ICopyContext context)
{
TestTypeA input = (TestTypeA)original;
TestTypeA result = new TestTypeA();
context.RecordCopy(original, result);
result.Collection = (ICollection<TestTypeA>)SerializationManager.DeepCopyInner(input.Collection, context);
return result;
}
[SerializerMethod]
public static void Serializer(object untypedInput, ISerializationContext context, Type expected)
{
TestTypeA input = (TestTypeA)untypedInput;
SerializationManager.SerializeInner(input.Collection, context, typeof(ICollection<TestTypeA>));
}
[DeserializerMethod]
public static object Deserializer(Type expected, IDeserializationContext context)
{
TestTypeA result = new TestTypeA();
context.RecordObject(result);
result.Collection = (ICollection<TestTypeA>)SerializationManager.DeserializeInner(typeof(ICollection<TestTypeA>), context);
return result;
}
}
[Fact, TestCategory("BVT"), TestCategory("Serialization")]
public void SerializationTests_RecursiveSerialization()
{
TestTypeA input = new TestTypeA();
input.Collection = new HashSet<TestTypeA>();
input.Collection.Add(input);
TestTypeA output1 = Orleans.TestingHost.Utils.TestingUtils.RoundTripDotNetSerializer(input, this.fixture.GrainFactory, this.fixture.SerializationManager);
TestTypeA output2 = this.fixture.SerializationManager.RoundTripSerializationForTesting(input);
}
[Fact, TestCategory("BVT"), TestCategory("Serialization")]
public void SerializationTests_CultureInfo()
{
var input = new List<CultureInfo> { CultureInfo.GetCultureInfo("en"), CultureInfo.GetCultureInfo("de") };
foreach (var cultureInfo in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(cultureInfo);
Assert.Equal(cultureInfo, output);
}
}
[Fact, TestCategory("BVT"), TestCategory("Serialization")]
public void SerializationTests_CultureInfoList()
{
var input = new List<CultureInfo> { CultureInfo.GetCultureInfo("en"), CultureInfo.GetCultureInfo("de") };
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(input);
Assert.True(input.SequenceEqual(output));
}
[Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple()
{
var input = new List<ValueTuple<int>> { ValueTuple.Create(1), ValueTuple.Create(100) };
foreach (var valueTuple in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
[Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple2()
{
var input = new List<ValueTuple<int, int>> { ValueTuple.Create(1, 2), ValueTuple.Create(100, 200) };
foreach (var valueTuple in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
[Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple3()
{
var input = new List<ValueTuple<int, int, int>>
{
ValueTuple.Create(1, 2, 3),
ValueTuple.Create(100, 200, 300)
};
foreach (var valueTuple in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
[Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple4()
{
var input = new List<ValueTuple<int, int, int, int>>
{
ValueTuple.Create(1, 2, 3, 4),
ValueTuple.Create(100, 200, 300, 400)
};
foreach (var valueTuple in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
[Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple5()
{
var input = new List<ValueTuple<int, int, int, int, int>>
{
ValueTuple.Create(1, 2, 3, 4, 5),
ValueTuple.Create(100, 200, 300, 400, 500)
};
foreach (var valueTuple in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
[Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple6()
{
var input = new List<ValueTuple<int, int, int, int, int, int>>
{
ValueTuple.Create(1, 2, 3, 4, 5, 6),
ValueTuple.Create(100, 200, 300, 400, 500, 600)
};
foreach (var valueTuple in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
[Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple7()
{
var input = new List<ValueTuple<int, int, int, int, int, int, int>>
{
ValueTuple.Create(1, 2, 3, 4, 5, 6, 7),
ValueTuple.Create(100, 200, 300, 400, 500, 600, 700)
};
foreach (var valueTuple in input)
{
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
[Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Serialization")]
public void SerializationTests_ValueTuple8()
{
var valueTuple = ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, 8);
var output = this.fixture.SerializationManager.RoundTripSerializationForTesting(valueTuple);
Assert.Equal(valueTuple, output);
}
}
}
| |
#region License
// Copyright (c) 2014 The Sentry Team and individual contributors.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. 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.
//
// 3. Neither the name of the Sentry nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SharpRaven.Data.Context;
using SharpRaven.Serialization;
using SharpRaven.Utilities;
namespace SharpRaven.Data
{
/// <summary>
/// Represents the JSON packet that is transmitted to Sentry.
/// </summary>
public class JsonPacket
{
/// <summary>
/// Initializes a new instance of the <see cref="JsonPacket"/> class.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="exception">The <see cref="Exception"/>.</param>
public JsonPacket(string project, Exception exception)
: this(project)
{
if (exception == null)
throw new ArgumentNullException("exception");
Initialize(exception);
Contexts = Contexts.Create();
}
/// <summary>Initializes a new instance of the <see cref="JsonPacket"/> class.</summary>
/// <param name="project">The project.</param>
/// <param name="event">The event.</param>
public JsonPacket(string project, SentryEvent @event)
: this(project)
{
if (@event == null)
throw new ArgumentNullException("event");
if (@event.Exception != null)
Initialize(@event.Exception, @event.ForceCaptureStackTrace);
Message = @event.Message != null ? @event.Message.ToString() : null;
Level = @event.Level;
Extra = Merge(@event);
Tags = @event.Tags;
Fingerprint = @event.Fingerprint.ToArray();
MessageObject = @event.Message;
Contexts = @event.Contexts;
}
private static object Merge(SentryEvent @event)
{
var exception = @event.Exception;
var extra = @event.Extra;
if (exception == null && extra == null)
return null;
if (extra != null && exception == null)
return extra;
var exceptionData = new ExceptionData(exception);
if (extra == null)
return exceptionData;
JObject result;
if (extra.GetType().IsArray)
{
result = new JObject();
var array = JArray.FromObject(extra);
foreach (var o in array)
{
var jo = o as JObject;
JProperty[] properties;
if (jo == null || (properties = jo.Properties().ToArray()).Length != 2 || properties[0].Name != "Key"
|| properties[1].Name != "Value")
{
result.Merge(o);
continue;
}
var key = properties[0].Value.ToString();
var value = properties[1].Value;
result.Add(key, value);
}
}
else
{
try
{
result = JObject.FromObject(extra);
}
catch (ArgumentException)
{
result = JObject.FromObject(new Dictionary<string, object> { { extra.GetType().ToString(), extra } });
}
}
var jExceptionData = JObject.FromObject(exceptionData);
result.Merge(jExceptionData);
return result;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonPacket"/> class.
/// </summary>
/// <param name="project">The project.</param>
public JsonPacket(string project)
: this()
{
if (project == null)
throw new ArgumentNullException("project");
Project = project;
}
/// <summary>
/// Prevents a default instance of the <see cref="JsonPacket"/> class from being created.
/// </summary>
private JsonPacket()
{
// Get assemblies.
Modules = SystemUtil.GetModules();
// The current hostname
ServerName = System.Environment.MachineName;
// Create timestamp
TimeStamp = DateTime.UtcNow;
// Default logger.
Logger = "root";
// Default error level.
Level = ErrorLevel.Error;
// Create a guid.
EventID = Guid.NewGuid().ToString("n");
// Project
Project = "default";
// Platform
Platform = "csharp";
// Release
Release = "";
// Environment
Environment = "";
}
/// <summary>
/// Represents Sentry's structured Context
/// </summary>
/// <seealso href="https://docs.sentry.io/clientdev/interfaces/contexts/"/>
[JsonProperty(PropertyName = "contexts", NullValueHandling = NullValueHandling.Ignore)]
public Contexts Contexts { get; set; }
/// <summary>
/// Function call which was the primary perpetrator of this event.
/// A map or list of tags for this event.
/// </summary>
[JsonProperty(PropertyName = "culprit", NullValueHandling = NullValueHandling.Ignore)]
public string Culprit { get; set; }
/// <summary>
/// Identifies the operating environment (e.g. production).
/// </summary>
[JsonProperty(PropertyName = "environment", NullValueHandling = NullValueHandling.Ignore)]
public string Environment { get; set; }
/// <summary>
/// Hexadecimal string representing a uuid4 value.
/// </summary>
[JsonProperty(PropertyName = "event_id", NullValueHandling = NullValueHandling.Ignore)]
public string EventID { get; set; }
/// <summary>
/// Gets or sets the exceptions.
/// </summary>
/// <value>
/// The exceptions.
/// </value>
[JsonProperty(PropertyName = "exception", NullValueHandling = NullValueHandling.Ignore)]
public List<SentryException> Exceptions { get; set; }
/// <summary>
/// An arbitrary mapping of additional metadata to store with the event.
/// </summary>
[JsonProperty(PropertyName = "extra", NullValueHandling = NullValueHandling.Ignore)]
public object Extra { get; set; }
/// <summary>
/// Gets or sets the fingerprint used for custom grouping
/// </summary>
[JsonProperty(PropertyName = "fingerprint", NullValueHandling = NullValueHandling.Ignore)]
public string[] Fingerprint { get; set; }
/// <summary>
/// The record severity.
/// Defaults to error.
/// </summary>
[JsonProperty(PropertyName = "level", NullValueHandling = NullValueHandling.Ignore, Required = Required.Always)]
[JsonConverter(typeof(LowerInvariantStringEnumConverter))]
public ErrorLevel Level { get; set; }
/// <summary>
/// The name of the logger which created the record.
/// If missing, defaults to the string root.
///
/// Ex: "my.logger.name"
/// </summary>
[JsonProperty(PropertyName = "logger", NullValueHandling = NullValueHandling.Ignore)]
public string Logger { get; set; }
/// <summary>
/// User-readable representation of this event
/// </summary>
[JsonProperty(PropertyName = "message", NullValueHandling = NullValueHandling.Ignore)]
public string Message { get; set; }
/// <summary>
/// Optional Message with arguments.
/// </summary>
[JsonProperty(PropertyName = "sentry.interfaces.Message", NullValueHandling = NullValueHandling.Ignore)]
public SentryMessage MessageObject { get; set; }
/// <summary>
/// A list of relevant modules (libraries) and their versions.
/// Automated to report all modules currently loaded in project.
/// </summary>
/// <value>
/// The modules.
/// </value>
[JsonProperty(PropertyName = "modules", NullValueHandling = NullValueHandling.Ignore)]
public IDictionary<string, string> Modules { get; set; }
/// <summary>
/// A string representing the platform the client is submitting from.
/// This will be used by the Sentry interface to customize various components in the interface.
/// </summary>
[JsonProperty(PropertyName = "platform", NullValueHandling = NullValueHandling.Ignore)]
public string Platform { get; set; }
/// <summary>
/// String value representing the project
/// </summary>
[JsonProperty(PropertyName = "project", NullValueHandling = NullValueHandling.Ignore)]
public string Project { get; set; }
/// <summary>
/// Identifies the version of the application.
/// </summary>
[JsonProperty(PropertyName = "release", NullValueHandling = NullValueHandling.Ignore)]
public string Release { get; set; }
/// <summary>
/// Gets or sets the <see cref="SentryRequest"/> object, containing information about the HTTP request.
/// </summary>
/// <value>
/// The <see cref="SentryRequest"/> object, containing information about the HTTP request.
/// </value>
[JsonProperty(PropertyName = "request", NullValueHandling = NullValueHandling.Ignore)]
public ISentryRequest Request { get; set; }
/// <summary>
/// Identifies the host client from which the event was recorded.
/// </summary>
[JsonProperty(PropertyName = "server_name", NullValueHandling = NullValueHandling.Ignore)]
public string ServerName { get; set; }
/// <summary>
/// A map or list of tags for this event.
/// </summary>
[JsonProperty(PropertyName = "tags", NullValueHandling = NullValueHandling.Ignore)]
public IDictionary<string, string> Tags { get; set; }
/// <summary>
/// Indicates when the logging record was created (in the Sentry client).
/// Defaults to DateTime.UtcNow()
/// </summary>
[JsonProperty(PropertyName = "timestamp", NullValueHandling = NullValueHandling.Ignore)]
public DateTime TimeStamp { get; set; }
/// <summary>
/// Gets or sets the breadcrumbs <see cref="Breadcrumb"/> class.
/// </summary>
/// <value>
/// The breadcrumbs.
/// </value>
[JsonProperty(PropertyName = "breadcrumbs", NullValueHandling = NullValueHandling.Ignore)]
public List<Breadcrumb> Breadcrumbs { get; set; }
/// <summary>
/// Gets or sets the <see cref="SentryUser"/> object, which describes the authenticated User for a request.
/// </summary>
/// <value>
/// The <see cref="SentryUser"/> object, which describes the authenticated User for a request.
/// </value>
[JsonProperty(PropertyName = "user", NullValueHandling = NullValueHandling.Ignore)]
public SentryUser User { get; set; }
/// <summary>
/// Converts the <see cref="JsonPacket" /> into a JSON string.
/// </summary>
/// <param name="formatting">The formatting.</param>
/// <returns>
/// The <see cref="JsonPacket" /> as a JSON string.
/// </returns>
public virtual string ToString(Formatting formatting)
{
return JsonConvert.SerializeObject(this, formatting);
}
/// <summary>
/// Converts the <see cref="JsonPacket"/> into a JSON string.
/// </summary>
/// <returns>
/// The <see cref="JsonPacket"/> as a JSON string.
/// </returns>
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
private void Initialize(Exception exception, bool forceCaptureStackTrace = false)
{
Message = exception.Message;
if (exception.TargetSite != null)
{
// ReSharper disable ConditionIsAlwaysTrueOrFalse => not for dynamic types.
Culprit = String.Format("{0} in {1}",
((exception.TargetSite.ReflectedType == null)
? "<dynamic type>"
: exception.TargetSite.ReflectedType.FullName),
exception.TargetSite.Name);
// ReSharper restore ConditionIsAlwaysTrueOrFalse
}
Exceptions = new List<SentryException>();
for (Exception currentException = exception;
currentException != null;
currentException = currentException.InnerException)
{
SentryException sentryException = new SentryException(currentException, forceCaptureStackTrace)
{
Module = currentException.Source,
Type = currentException.GetType().Name,
Value = currentException.Message
};
Exceptions.Add(sentryException);
}
// ReflectionTypeLoadException doesn't contain much useful info in itself, and needs special handling
ReflectionTypeLoadException reflectionTypeLoadException = exception as ReflectionTypeLoadException;
if (reflectionTypeLoadException != null)
{
foreach (Exception loaderException in reflectionTypeLoadException.LoaderExceptions)
{
SentryException sentryException = new SentryException(loaderException);
Exceptions.Add(sentryException);
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// SpoolingTask.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Linq.Parallel
{
/// <summary>
/// A factory class to execute spooling logic.
/// </summary>
internal static class SpoolingTask
{
//-----------------------------------------------------------------------------------
// Creates and begins execution of a new spooling task. Executes synchronously,
// and by the time this API has returned all of the results have been produced.
//
// Arguments:
// groupState - values for inter-task communication
// partitions - the producer enumerators
// channels - the producer-consumer channels
// taskScheduler - the task manager on which to execute
//
internal static void SpoolStopAndGo<TInputOutput, TIgnoreKey>(
QueryTaskGroupState groupState, PartitionedStream<TInputOutput, TIgnoreKey> partitions,
SynchronousChannel<TInputOutput>[] channels, TaskScheduler taskScheduler)
{
Contract.Requires(partitions.PartitionCount == channels.Length);
Contract.Requires(groupState != null);
// Ensure all tasks in this query are parented under a common root.
Task rootTask = new Task(
() =>
{
int maxToRunInParallel = partitions.PartitionCount - 1;
// A stop-and-go merge uses the current thread for one task and then blocks before
// returning to the caller, until all results have been accumulated. We do this by
// running the last partition on the calling thread.
for (int i = 0; i < maxToRunInParallel; i++)
{
TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] asynchronously", i);
QueryTask asyncTask = new StopAndGoSpoolingTask<TInputOutput, TIgnoreKey>(i, groupState, partitions[i], channels[i]);
asyncTask.RunAsynchronously(taskScheduler);
}
TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] synchronously", maxToRunInParallel);
// Run one task synchronously on the current thread.
QueryTask syncTask = new StopAndGoSpoolingTask<TInputOutput, TIgnoreKey>(
maxToRunInParallel, groupState, partitions[maxToRunInParallel], channels[maxToRunInParallel]);
syncTask.RunSynchronously(taskScheduler);
});
// Begin the query on the calling thread.
groupState.QueryBegin(rootTask);
// We don't want to return until the task is finished. Run it on the calling thread.
rootTask.RunSynchronously(taskScheduler);
// Wait for the query to complete, propagate exceptions, and so on.
// For pipelined queries, this step happens in the async enumerator.
groupState.QueryEnd(false);
}
//-----------------------------------------------------------------------------------
// Creates and begins execution of a new spooling task. Runs asynchronously.
//
// Arguments:
// groupState - values for inter-task communication
// partitions - the producer enumerators
// channels - the producer-consumer channels
// taskScheduler - the task manager on which to execute
//
internal static void SpoolPipeline<TInputOutput, TIgnoreKey>(
QueryTaskGroupState groupState, PartitionedStream<TInputOutput, TIgnoreKey> partitions,
AsynchronousChannel<TInputOutput>[] channels, TaskScheduler taskScheduler)
{
Contract.Requires(partitions.PartitionCount == channels.Length);
Contract.Requires(groupState != null);
// Ensure all tasks in this query are parented under a common root. Because this
// is a pipelined query, we detach it from the parent (to avoid blocking the calling
// thread), and run the query on a separate thread.
Task rootTask = new Task(
() =>
{
// Create tasks that will enumerate the partitions in parallel. Because we're pipelining,
// we will begin running these tasks in parallel and then return.
for (int i = 0; i < partitions.PartitionCount; i++)
{
TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] asynchronously", i);
QueryTask asyncTask = new PipelineSpoolingTask<TInputOutput, TIgnoreKey>(i, groupState, partitions[i], channels[i]);
asyncTask.RunAsynchronously(taskScheduler);
}
});
// Begin the query on the calling thread.
groupState.QueryBegin(rootTask);
// And schedule it for execution. This is done after beginning to ensure no thread tries to
// end the query before its root task has been recorded properly.
rootTask.Start(taskScheduler);
// We don't call QueryEnd here; when we return, the query is still executing, and the
// last enumerator to be disposed of will call QueryEnd for us.
}
//-----------------------------------------------------------------------------------
// Creates and begins execution of a new spooling task. This is a for-all style
// execution, meaning that the query will be run fully (for effect) before returning
// and that there are no channels into which data will be queued.
//
// Arguments:
// groupState - values for inter-task communication
// partitions - the producer enumerators
// taskScheduler - the task manager on which to execute
//
internal static void SpoolForAll<TInputOutput, TIgnoreKey>(
QueryTaskGroupState groupState, PartitionedStream<TInputOutput, TIgnoreKey> partitions, TaskScheduler taskScheduler)
{
Contract.Requires(groupState != null);
// Ensure all tasks in this query are parented under a common root.
Task rootTask = new Task(
() =>
{
int maxToRunInParallel = partitions.PartitionCount - 1;
// Create tasks that will enumerate the partitions in parallel "for effect"; in other words,
// no data will be placed into any kind of producer-consumer channel.
for (int i = 0; i < maxToRunInParallel; i++)
{
TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] asynchronously", i);
QueryTask asyncTask = new ForAllSpoolingTask<TInputOutput, TIgnoreKey>(i, groupState, partitions[i]);
asyncTask.RunAsynchronously(taskScheduler);
}
TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] synchronously", maxToRunInParallel);
// Run one task synchronously on the current thread.
QueryTask syncTask = new ForAllSpoolingTask<TInputOutput, TIgnoreKey>(maxToRunInParallel, groupState, partitions[maxToRunInParallel]);
syncTask.RunSynchronously(taskScheduler);
});
// Begin the query on the calling thread.
groupState.QueryBegin(rootTask);
// We don't want to return until the task is finished. Run it on the calling thread.
rootTask.RunSynchronously(taskScheduler);
// Wait for the query to complete, propagate exceptions, and so on.
// For pipelined queries, this step happens in the async enumerator.
groupState.QueryEnd(false);
}
}
/// <summary>
/// A spooling task handles marshaling data from a producer to a consumer. It's given
/// a single enumerator object that contains all of the production algorithms, a single
/// destination channel from which consumers draw results, and (optionally) a
/// synchronization primitive using which to notify asynchronous consumers.
/// </summary>
/// <typeparam name="TInputOutput"></typeparam>
/// <typeparam name="TIgnoreKey"></typeparam>
internal class StopAndGoSpoolingTask<TInputOutput, TIgnoreKey> : SpoolingTaskBase
{
// The data source from which to pull data.
private QueryOperatorEnumerator<TInputOutput, TIgnoreKey> _source;
// The destination channel into which data is placed. This can be null if we are
// enumerating "for effect", e.g. forall loop.
private SynchronousChannel<TInputOutput> _destination;
//-----------------------------------------------------------------------------------
// Creates, but does not execute, a new spooling task.
//
// Arguments:
// taskIndex - the unique index of this task
// source - the producer enumerator
// destination - the destination channel into which to spool elements
//
// Assumptions:
// Source cannot be null, although the other arguments may be.
//
internal StopAndGoSpoolingTask(
int taskIndex, QueryTaskGroupState groupState,
QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source, SynchronousChannel<TInputOutput> destination)
: base(taskIndex, groupState)
{
Contract.Requires(source != null);
_source = source;
_destination = destination;
}
//-----------------------------------------------------------------------------------
// This method is responsible for enumerating results and enqueueing them to
// the output channel(s) as appropriate. Each base class implements its own.
//
protected override void SpoolingWork()
{
// We just enumerate over the entire source data stream, placing each element
// into the destination channel.
TInputOutput current = default(TInputOutput);
TIgnoreKey keyUnused = default(TIgnoreKey);
QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source = _source;
SynchronousChannel<TInputOutput> destination = _destination;
CancellationToken cancelToken = _groupState.CancellationState.MergedCancellationToken;
destination.Init();
while (source.MoveNext(ref current, ref keyUnused))
{
// If an abort has been requested, stop this worker immediately.
if (cancelToken.IsCancellationRequested)
{
break;
}
destination.Enqueue(current);
}
}
//-----------------------------------------------------------------------------------
// Ensure we signal that the channel is complete.
//
protected override void SpoolingFinally()
{
// Call the base implementation.
base.SpoolingFinally();
// Signal that we are done, in the case of asynchronous consumption.
if (_destination != null)
{
_destination.SetDone();
}
// Dispose of the source enumerator *after* signaling that the task is done.
// We call Dispose() last to ensure that if it throws an exception, we will not cause a deadlock.
_source.Dispose();
}
}
/// <summary>
/// A spooling task handles marshaling data from a producer to a consumer. It's given
/// a single enumerator object that contains all of the production algorithms, a single
/// destination channel from which consumers draw results, and (optionally) a
/// synchronization primitive using which to notify asynchronous consumers.
/// </summary>
/// <typeparam name="TInputOutput"></typeparam>
/// <typeparam name="TIgnoreKey"></typeparam>
internal class PipelineSpoolingTask<TInputOutput, TIgnoreKey> : SpoolingTaskBase
{
// The data source from which to pull data.
private QueryOperatorEnumerator<TInputOutput, TIgnoreKey> _source;
// The destination channel into which data is placed. This can be null if we are
// enumerating "for effect", e.g. forall loop.
private AsynchronousChannel<TInputOutput> _destination;
//-----------------------------------------------------------------------------------
// Creates, but does not execute, a new spooling task.
//
// Arguments:
// taskIndex - the unique index of this task
// source - the producer enumerator
// destination - the destination channel into which to spool elements
//
// Assumptions:
// Source cannot be null, although the other arguments may be.
//
internal PipelineSpoolingTask(
int taskIndex, QueryTaskGroupState groupState,
QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source, AsynchronousChannel<TInputOutput> destination)
: base(taskIndex, groupState)
{
Debug.Assert(source != null);
_source = source;
_destination = destination;
}
//-----------------------------------------------------------------------------------
// This method is responsible for enumerating results and enqueueing them to
// the output channel(s) as appropriate. Each base class implements its own.
//
protected override void SpoolingWork()
{
// We just enumerate over the entire source data stream, placing each element
// into the destination channel.
TInputOutput current = default(TInputOutput);
TIgnoreKey keyUnused = default(TIgnoreKey);
QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source = _source;
AsynchronousChannel<TInputOutput> destination = _destination;
CancellationToken cancelToken = _groupState.CancellationState.MergedCancellationToken;
while (source.MoveNext(ref current, ref keyUnused))
{
// If an abort has been requested, stop this worker immediately.
if (cancelToken.IsCancellationRequested)
{
break;
}
destination.Enqueue(current);
}
// Flush remaining data to the query consumer in preparation for channel shutdown.
destination.FlushBuffers();
}
//-----------------------------------------------------------------------------------
// Ensure we signal that the channel is complete.
//
protected override void SpoolingFinally()
{
// Call the base implementation.
base.SpoolingFinally();
// Signal that we are done, in the case of asynchronous consumption.
if (_destination != null)
{
_destination.SetDone();
}
// Dispose of the source enumerator *after* signaling that the task is done.
// We call Dispose() last to ensure that if it throws an exception, we will not cause a deadlock.
_source.Dispose();
}
}
/// <summary>
/// A spooling task handles marshaling data from a producer to a consumer. It's given
/// a single enumerator object that contains all of the production algorithms, a single
/// destination channel from which consumers draw results, and (optionally) a
/// synchronization primitive using which to notify asynchronous consumers.
/// </summary>
/// <typeparam name="TInputOutput"></typeparam>
/// <typeparam name="TIgnoreKey"></typeparam>
internal class ForAllSpoolingTask<TInputOutput, TIgnoreKey> : SpoolingTaskBase
{
// The data source from which to pull data.
private QueryOperatorEnumerator<TInputOutput, TIgnoreKey> _source;
//-----------------------------------------------------------------------------------
// Creates, but does not execute, a new spooling task.
//
// Arguments:
// taskIndex - the unique index of this task
// source - the producer enumerator
// destination - the destination channel into which to spool elements
//
// Assumptions:
// Source cannot be null, although the other arguments may be.
//
internal ForAllSpoolingTask(
int taskIndex, QueryTaskGroupState groupState,
QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source)
: base(taskIndex, groupState)
{
Debug.Assert(source != null);
_source = source;
}
//-----------------------------------------------------------------------------------
// This method is responsible for enumerating results and enqueueing them to
// the output channel(s) as appropriate. Each base class implements its own.
//
protected override void SpoolingWork()
{
// We just enumerate over the entire source data stream for effect.
TInputOutput currentUnused = default(TInputOutput);
TIgnoreKey keyUnused = default(TIgnoreKey);
//Note: this only ever runs with a ForAll operator, and ForAllEnumerator performs cancellation checks
while (_source.MoveNext(ref currentUnused, ref keyUnused))
;
}
//-----------------------------------------------------------------------------------
// Ensure we signal that the channel is complete.
//
protected override void SpoolingFinally()
{
// Call the base implementation.
base.SpoolingFinally();
// Dispose of the source enumerator
_source.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.Data.Common;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace System.Data.SqlTypes
{
/// <summary>
/// Represents an integer value that is either 1 or 0.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[XmlSchemaProvider("GetXsdType")]
public struct SqlBoolean : INullable, IComparable, IXmlSerializable
{
// m_value: 2 (true), 1 (false), 0 (unknown/Null)
private byte _value;
private const byte x_Null = 0;
private const byte x_False = 1;
private const byte x_True = 2;
// constructor
/// <summary>
/// Initializes a new instance of the <see cref='SqlBoolean'/> class.
/// </summary>
public SqlBoolean(bool value)
{
_value = value ? x_True : x_False;
}
public SqlBoolean(int value) : this(value, false)
{
}
private SqlBoolean(int value, bool fNull)
{
if (fNull)
_value = x_Null;
else
_value = (value != 0) ? x_True : x_False;
}
// INullable
/// <summary>
/// Gets whether the current <see cref='Value'/> is <see cref='SqlBoolean.Null'/>.
/// </summary>
public bool IsNull
{
get { return _value == x_Null; }
}
// property: Value
/// <summary>
/// Gets or sets the <see cref='SqlBoolean'/> to be <see langword='true'/> or <see langword='false'/>.
/// </summary>
public bool Value
{
get
{
switch (_value)
{
case x_True:
return true;
case x_False:
return false;
default:
throw new SqlNullValueException();
}
}
}
/// <summary>
/// Gets whether the current <see cref='Value'/> is <see cref='SqlBoolean.True'/>.
/// </summary>
public bool IsTrue
{
get { return _value == x_True; }
}
/// <summary>
/// Gets whether the current <see cref='Value'/> is <see cref='SqlBoolean.False'/>.
/// </summary>
public bool IsFalse
{
get { return _value == x_False; }
}
// Implicit conversion from bool to SqlBoolean
/// <summary>
/// Converts a boolean to a <see cref='SqlBoolean'/>.
/// </summary>
public static implicit operator SqlBoolean(bool x)
{
return new SqlBoolean(x);
}
// Explicit conversion from SqlBoolean to bool. Throw exception if x is Null.
/// <summary>
/// Converts a <see cref='SqlBoolean'/> to a boolean.
/// </summary>
public static explicit operator bool (SqlBoolean x)
{
return x.Value;
}
// Unary operators
/// <summary>
/// Performs a NOT operation on a <see cref='SqlBoolean'/>.
/// </summary>
public static SqlBoolean operator !(SqlBoolean x)
{
switch (x._value)
{
case x_True:
return SqlBoolean.False;
case x_False:
return SqlBoolean.True;
default:
Debug.Assert(x._value == x_Null);
return SqlBoolean.Null;
}
}
public static bool operator true(SqlBoolean x)
{
return x.IsTrue;
}
public static bool operator false(SqlBoolean x)
{
return x.IsFalse;
}
// Binary operators
/// <summary>
/// Performs a bitwise AND operation on two instances of <see cref='SqlBoolean'/>.
/// </summary>
public static SqlBoolean operator &(SqlBoolean x, SqlBoolean y)
{
if (x._value == x_False || y._value == x_False)
return SqlBoolean.False;
else if (x._value == x_True && y._value == x_True)
return SqlBoolean.True;
else
return SqlBoolean.Null;
}
/// <summary>
/// Performs a bitwise OR operation on two instances of a <see cref='SqlBoolean'/>.
/// </summary>
public static SqlBoolean operator |(SqlBoolean x, SqlBoolean y)
{
if (x._value == x_True || y._value == x_True)
return SqlBoolean.True;
else if (x._value == x_False && y._value == x_False)
return SqlBoolean.False;
else
return SqlBoolean.Null;
}
// property: ByteValue
public byte ByteValue
{
get
{
if (!IsNull)
return (_value == x_True) ? (byte)1 : (byte)0;
else
throw new SqlNullValueException();
}
}
public override string ToString()
{
return IsNull ? SQLResource.NullString : Value.ToString();
}
public static SqlBoolean Parse(string s)
{
if (null == s)
// Let Boolean.Parse throw exception
return new SqlBoolean(bool.Parse(s));
if (s == SQLResource.NullString)
return SqlBoolean.Null;
s = s.TrimStart();
char wchFirst = s[0];
if (char.IsNumber(wchFirst) || ('-' == wchFirst) || ('+' == wchFirst))
{
return new SqlBoolean(int.Parse(s, null));
}
else
{
return new SqlBoolean(bool.Parse(s));
}
}
// Unary operators
public static SqlBoolean operator ~(SqlBoolean x)
{
return (!x);
}
// Binary operators
public static SqlBoolean operator ^(SqlBoolean x, SqlBoolean y)
{
return (x.IsNull || y.IsNull) ? Null : new SqlBoolean(x._value != y._value);
}
// Implicit conversions
// Explicit conversions
// Explicit conversion from SqlByte to SqlBoolean
public static explicit operator SqlBoolean(SqlByte x)
{
return x.IsNull ? Null : new SqlBoolean(x.Value != 0);
}
// Explicit conversion from SqlInt16 to SqlBoolean
public static explicit operator SqlBoolean(SqlInt16 x)
{
return x.IsNull ? Null : new SqlBoolean(x.Value != 0);
}
// Explicit conversion from SqlInt32 to SqlBoolean
public static explicit operator SqlBoolean(SqlInt32 x)
{
return x.IsNull ? Null : new SqlBoolean(x.Value != 0);
}
// Explicit conversion from SqlInt64 to SqlBoolean
public static explicit operator SqlBoolean(SqlInt64 x)
{
return x.IsNull ? Null : new SqlBoolean(x.Value != 0);
}
// Explicit conversion from SqlDouble to SqlBoolean
public static explicit operator SqlBoolean(SqlDouble x)
{
return x.IsNull ? Null : new SqlBoolean(x.Value != 0.0);
}
// Explicit conversion from SqlSingle to SqlBoolean
public static explicit operator SqlBoolean(SqlSingle x)
{
return x.IsNull ? Null : new SqlBoolean(x.Value != 0.0);
}
// Explicit conversion from SqlMoney to SqlBoolean
public static explicit operator SqlBoolean(SqlMoney x)
{
return x.IsNull ? Null : (x != SqlMoney.Zero);
}
// Explicit conversion from SqlDecimal to SqlBoolean
public static explicit operator SqlBoolean(SqlDecimal x)
{
return x.IsNull ? SqlBoolean.Null : new SqlBoolean(x._data1 != 0 || x._data2 != 0 ||
x._data3 != 0 || x._data4 != 0);
}
// Explicit conversion from SqlString to SqlBoolean
// Throws FormatException or OverflowException if necessary.
public static explicit operator SqlBoolean(SqlString x)
{
return x.IsNull ? Null : SqlBoolean.Parse(x.Value);
}
// Overloading comparison operators
public static SqlBoolean operator ==(SqlBoolean x, SqlBoolean y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value == y._value);
}
public static SqlBoolean operator !=(SqlBoolean x, SqlBoolean y)
{
return !(x == y);
}
public static SqlBoolean operator <(SqlBoolean x, SqlBoolean y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value < y._value);
}
public static SqlBoolean operator >(SqlBoolean x, SqlBoolean y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value > y._value);
}
public static SqlBoolean operator <=(SqlBoolean x, SqlBoolean y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value <= y._value);
}
public static SqlBoolean operator >=(SqlBoolean x, SqlBoolean y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value >= y._value);
}
//--------------------------------------------------
// Alternative methods for overloaded operators
//--------------------------------------------------
// Alternative method for operator ~
public static SqlBoolean OnesComplement(SqlBoolean x)
{
return ~x;
}
// Alternative method for operator &
public static SqlBoolean And(SqlBoolean x, SqlBoolean y)
{
return x & y;
}
// Alternative method for operator |
public static SqlBoolean Or(SqlBoolean x, SqlBoolean y)
{
return x | y;
}
// Alternative method for operator ^
public static SqlBoolean Xor(SqlBoolean x, SqlBoolean y)
{
return x ^ y;
}
// Alternative method for operator ==
public static SqlBoolean Equals(SqlBoolean x, SqlBoolean y)
{
return (x == y);
}
// Alternative method for operator !=
public static SqlBoolean NotEquals(SqlBoolean x, SqlBoolean y)
{
return (x != y);
}
// Alternative method for operator >
public static SqlBoolean GreaterThan(SqlBoolean x, SqlBoolean y)
{
return (x > y);
}
// Alternative method for operator <
public static SqlBoolean LessThan(SqlBoolean x, SqlBoolean y)
{
return (x < y);
}
// Alternative method for operator <=
public static SqlBoolean GreaterThanOrEquals(SqlBoolean x, SqlBoolean y)
{
return (x >= y);
}
// Alternative method for operator !=
public static SqlBoolean LessThanOrEquals(SqlBoolean x, SqlBoolean y)
{
return (x <= y);
}
// Alternative method for conversions.
public SqlByte ToSqlByte()
{
return (SqlByte)this;
}
public SqlDouble ToSqlDouble()
{
return (SqlDouble)this;
}
public SqlInt16 ToSqlInt16()
{
return (SqlInt16)this;
}
public SqlInt32 ToSqlInt32()
{
return (SqlInt32)this;
}
public SqlInt64 ToSqlInt64()
{
return (SqlInt64)this;
}
public SqlMoney ToSqlMoney()
{
return (SqlMoney)this;
}
public SqlDecimal ToSqlDecimal()
{
return (SqlDecimal)this;
}
public SqlSingle ToSqlSingle()
{
return (SqlSingle)this;
}
public SqlString ToSqlString()
{
return (SqlString)this;
}
// IComparable
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this < object, zero if this = object,
// or a value greater than zero if this > object.
// null is considered to be less than any instance.
// If object is not of same type, this method throws an ArgumentException.
public int CompareTo(object value)
{
if (value is SqlBoolean)
{
SqlBoolean i = (SqlBoolean)value;
return CompareTo(i);
}
throw ADP.WrongType(value.GetType(), typeof(SqlBoolean));
}
public int CompareTo(SqlBoolean value)
{
// If both Null, consider them equal.
// Otherwise, Null is less than anything.
if (IsNull)
return value.IsNull ? 0 : -1;
else if (value.IsNull)
return 1;
if (ByteValue < value.ByteValue) return -1;
if (ByteValue > value.ByteValue) return 1;
return 0;
}
// Compares this instance with a specified object
public override bool Equals(object value)
{
if (!(value is SqlBoolean))
{
return false;
}
SqlBoolean i = (SqlBoolean)value;
if (i.IsNull || IsNull)
return (i.IsNull && IsNull);
else
return (this == i).Value;
}
// For hashing purpose
public override int GetHashCode()
{
return IsNull ? 0 : Value.GetHashCode();
}
XmlSchema IXmlSerializable.GetSchema() { return null; }
void IXmlSerializable.ReadXml(XmlReader reader)
{
string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace);
if (isNull != null && XmlConvert.ToBoolean(isNull))
{
// Read the next value.
reader.ReadElementString();
_value = x_Null;
}
else
{
_value = XmlConvert.ToBoolean(reader.ReadElementString()) ? x_True : x_False;
}
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
if (IsNull)
{
writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true");
}
else
{
writer.WriteString(_value == x_True ? "true" : "false");
}
}
public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet)
{
return new XmlQualifiedName("boolean", XmlSchema.Namespace);
}
/// <summary>
/// Represents a true value that can be assigned to the
/// <see cref='Value'/> property of an instance of the <see cref='SqlBoolean'/> class.
/// </summary>
public static readonly SqlBoolean True = new SqlBoolean(true);
/// <summary>
/// Represents a false value that can be assigned to the <see cref='Value'/> property of an instance of
/// the <see cref='SqlBoolean'/> class.
/// </summary>
public static readonly SqlBoolean False = new SqlBoolean(false);
/// <summary>
/// Represents a null value that can be assigned to the <see cref='Value'/> property of an instance of
/// the <see cref='SqlBoolean'/> class.
/// </summary>
public static readonly SqlBoolean Null = new SqlBoolean(0, true);
public static readonly SqlBoolean Zero = new SqlBoolean(0);
public static readonly SqlBoolean One = new SqlBoolean(1);
} // SqlBoolean
} // namespace System.Data.SqlTypes
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
namespace Irony.Parsing
{
[Flags]
public enum ParseOptions
{
Reserved = 0x01,
AnalyzeCode = 0x10, //run code analysis; effective only in Module mode
}
public enum ParseMode
{
File, //default, continuous input file
VsLineScan, // line-by-line scanning in VS integration for syntax highlighting
CommandLine, //line-by-line from console
}
public enum ParserStatus
{
Init, //initial state
Parsing,
Previewing, //previewing tokens
Recovering, //recovering from error
Accepted,
AcceptedPartial,
Error,
}
// The purpose of this class is to provide a container for information shared
// between parser, scanner and token filters.
public partial class ParsingContext
{
public readonly Parser Parser;
public readonly LanguageData Language;
//Parser settings
public ParseOptions Options;
public bool TracingEnabled;
public ParseMode Mode = ParseMode.File;
public int MaxErrors = 20; //maximum error count to report
public CultureInfo Culture; //defaults to Grammar.DefaultCulture, might be changed by app code
#region properties and fields
//Parser fields
public ParseTree CurrentParseTree { get; internal set; }
public readonly TokenStack OpenBraces = new TokenStack();
public ParserTrace ParserTrace = new ParserTrace();
internal readonly ParserStack ParserStack = new ParserStack();
public ParserState CurrentParserState { get; internal set; }
public ParseTreeNode CurrentParserInput { get; internal set; }
public Token CurrentToken; //The token just scanned by Scanner
//public TokenList CurrentCommentTokens = new TokenList(); //accumulated comment tokens
public Queue<Trivia> Trivias = new Queue<Trivia>();
public Token PreviousToken;
public SourceLocation PreviousLineStart; //Location of last line start
//list for terminals - for current parser state and current input char
public TerminalList CurrentTerminals = new TerminalList();
public ISourceStream Source;
//Internal fields
internal TokenFilterList TokenFilters = new TokenFilterList();
internal TokenStack BufferedTokens = new TokenStack();
internal IEnumerator<Token> FilteredTokens; //stream of tokens after filter
internal TokenStack PreviewTokens = new TokenStack();
internal ParsingEventArgs SharedParsingEventArgs;
internal ValidateTokenEventArgs SharedValidateTokenEventArgs;
public VsScannerStateMap VsLineScanState; //State variable used in line scanning mode for VS integration
public ParserStatus Status { get; internal set; }
public bool HasErrors; //error flag, once set remains set
//values dictionary to use by custom language implementations to save some temporary values during parsing
public readonly Dictionary<string, object> Values = new Dictionary<string, object>();
public int TabWidth = 8;
public bool HasFatalErrors;
#endregion
#region constructors
public ParsingContext(Parser parser)
{
this.Parser = parser;
Language = Parser.Language;
Culture = Language.Grammar.DefaultCulture;
//This might be a problem for multi-threading - if we have several contexts on parallel threads with different culture.
//Resources.Culture is static property (this is not Irony's fault, this is auto-generated file).
Resources.Culture = Culture;
SharedParsingEventArgs = new ParsingEventArgs(this);
SharedValidateTokenEventArgs = new ValidateTokenEventArgs(this);
}
#endregion
#region Events: TokenCreated
public event EventHandler<ParsingEventArgs> TokenCreated;
internal void OnTokenCreated()
{
if (TokenCreated != null)
TokenCreated(this, SharedParsingEventArgs);
}
#endregion
#region Error handling and tracing
public Token CreateErrorToken(string message, params object[] args)
{
if (args != null && args.Length > 0)
message = string.Format(message, args);
return Source.CreateToken(Language.Grammar.SyntaxError, message);
}
public void AddParserError(string message, params object[] args)
{
var location = CurrentParserInput == null ? new SourceSpan(Source.Location, 1) : CurrentParserInput.Span;
HasErrors = true;
AddParserMessage(ErrorLevel.Error, location, message, args);
}
public void AddParserMessage(ErrorLevel level, SourceSpan location, string message, params object[] args)
{
if (CurrentParseTree == null) return;
if (CurrentParseTree.ParserMessages.Count >= MaxErrors) return;
if (args != null && args.Length > 0)
message = string.Format(message, args);
CurrentParseTree.ParserMessages.Add(new LogMessage(level, location, message, CurrentParserState));
if (TracingEnabled)
AddTrace(true, message);
}
public void AddTrace(string message, params object[] args)
{
AddTrace(false, message, args);
}
public void AddTrace(bool asError, string message, params object[] args)
{
if (!TracingEnabled)
return;
if (args != null && args.Length > 0)
message = string.Format(message, args);
ParserTrace.Add(new ParserTraceEntry(CurrentParserState, ParserStack.Top, CurrentParserInput, message, asError));
}
#region comments
// Computes set of expected terms in a parser state. While there may be extended list of symbols expected at some point,
// we want to reorganize and reduce it. For example, if the current state expects all arithmetic operators as an input,
// it would be better to not list all operators (+, -, *, /, etc) but simply put "operator" covering them all.
// To achieve this grammar writer can group operators (or any other terminals) into named groups using Grammar's methods
// AddTermReportGroup, AddNoReportGroup etc. Then instead of reporting each operator separately, Irony would include
// a single "group name" to represent them all.
// The "expected report set" is not computed during parser construction (it would take considerable time),
// but does it on demand during parsing, when error is detected and the expected set is actually needed for error message.
// Multi-threading concerns. When used in multi-threaded environment (web server), the LanguageData would be shared in
// application-wide cache to avoid rebuilding the parser data on every request. The LanguageData is immutable, except
// this one case - the expected sets are constructed late by CoreParser on the when-needed basis.
// We don't do any locking here, just compute the set and on return from this function the state field is assigned.
// We assume that this field assignment is an atomic, concurrency-safe operation. The worst thing that might happen
// is "double-effort" when two threads start computing the same set around the same time, and the last one to finish would
// leave its result in the state field.
#endregion
internal static StringSet ComputeGroupedExpectedSetForState(Grammar grammar, ParserState state)
{
var terms = new TerminalSet();
terms.UnionWith(state.ExpectedTerminals);
var result = new StringSet();
//Eliminate no-report terminals
foreach (var group in grammar.TermReportGroups)
if (group.GroupType == TermReportGroupType.DoNotReport)
terms.ExceptWith(group.Terminals);
//Add normal and operator groups
foreach (var group in grammar.TermReportGroups)
if ((group.GroupType == TermReportGroupType.Normal || group.GroupType == TermReportGroupType.Operator) &&
terms.Overlaps(group.Terminals))
{
result.Add(group.Alias);
terms.ExceptWith(group.Terminals);
}
//Add remaining terminals "as is"
foreach (var terminal in terms)
result.Add(terminal.ErrorAlias);
return result;
}
#endregion
internal void Reset()
{
CurrentParserState = Parser.InitialState;
CurrentParserInput = null;
Trivias.Clear();
ParserStack.Clear();
HasErrors = HasFatalErrors = false;
ParserStack.Push(new ParseTreeNode(CurrentParserState));
CurrentParseTree = null;
OpenBraces.Clear();
ParserTrace.Clear();
CurrentTerminals.Clear();
CurrentToken = null;
PreviousToken = null;
PreviousLineStart = new SourceLocation(0, -1, 0);
BufferedTokens.Clear();
PreviewTokens.Clear();
Values.Clear();
foreach (var filter in TokenFilters)
filter.Reset();
}
public void SetSourceLocation(SourceLocation location)
{
foreach (var filter in TokenFilters)
filter.OnSetSourceLocation(location);
Source.Location = location;
}
public SourceSpan ComputeStackRangeSpan(int nodeCount)
{
if (nodeCount == 0)
return new SourceSpan(CurrentParserInput.Span.Location, 0);
var first = ParserStack[ParserStack.Count - nodeCount];
var last = ParserStack.Top;
return new SourceSpan(first.Span.Location, last.Span.EndPosition - first.Span.Location.Position);
}
#region Expected term set computations
public StringSet GetExpectedTermSet()
{
if (CurrentParserState == null)
return new StringSet();
//See note about multi-threading issues in ComputeReportedExpectedSet comments.
if (CurrentParserState.ReportedExpectedSet == null)
CurrentParserState.ReportedExpectedSet = Construction.ParserDataBuilder.ComputeGroupedExpectedSetForState(Language.Grammar, CurrentParserState);
//Filter out closing braces which are not expected based on previous input.
// While the closing parenthesis ")" might be expected term in a state in general,
// if there was no opening parenthesis in preceding input then we would not
// expect a closing one.
var expectedSet = FilterBracesInExpectedSet(CurrentParserState.ReportedExpectedSet);
return expectedSet;
}
private StringSet FilterBracesInExpectedSet(StringSet stateExpectedSet)
{
var result = new StringSet();
result.UnionWith(stateExpectedSet);
//Find what brace we expect
var nextClosingBrace = string.Empty;
if (OpenBraces.Count > 0)
{
var lastOpenBraceTerm = OpenBraces.Peek().KeyTerm;
var nextClosingBraceTerm = lastOpenBraceTerm.IsPairFor as KeyTerm;
if (nextClosingBraceTerm != null)
nextClosingBrace = nextClosingBraceTerm.Text;
}
//Now check all closing braces in result set, and leave only nextClosingBrace
foreach (var term in Language.Grammar.KeyTerms.Values)
{
if (term.Flags.IsSet(TermFlags.IsCloseBrace))
{
var brace = term.Text;
if (result.Contains(brace) && brace != nextClosingBrace)
result.Remove(brace);
}
}//foreach term
return result;
}
#endregion
}//class
// A struct used for packing/unpacking ScannerState int value; used for VS integration.
// When Terminal produces incomplete token, it sets
// this state to non-zero value; this value identifies this terminal as the one who will continue scanning when
// it resumes, and the terminal's internal state when there may be several types of multi-line tokens for one terminal.
// For ex., there maybe several types of string literal like in Python.
[StructLayout(LayoutKind.Explicit)]
public struct VsScannerStateMap
{
[FieldOffset(0)]
public int Value;
[FieldOffset(0)]
public byte TerminalIndex; //1-based index of active multiline term in MultilineTerminals
[FieldOffset(1)]
public byte TokenSubType; //terminal subtype (used in StringLiteral to identify string kind)
[FieldOffset(2)]
public short TerminalFlags; //Terminal flags
}//struct
}
| |
using System;
using NationalInstruments.DAQmx;
using RRLab.PhysiologyWorkbench.Data;
namespace RRLab.PhysiologyWorkbench.Devices
{
/// <summary>
/// The Amplifier class provides an abstraction to controlling an Axon Instruments Axopatch 220B.
/// It provides methods for decoding information output by the Axopatch about its settings as well
/// as commands for setting the holding potential.
/// </summary>
[Serializable]
public class Amplifier : RRLab.PhysiologyWorkbench.Devices.Device
{
[field:NonSerialized] public event EventHandler AbsoluteVHoldChanged;
private delegate void RestartDelegate();
private String _VHoldAO, _CapacAI, _CurrentAI, _GainAI; // The addresses for vhold, capac, and current
private double theVHoldMin, theVHoldMax; // The min and max VHold
[NonSerialized] private ForwardAbsoluteVHoldSettingChange _ForwardAbsoluteVHoldSettingChange;
public ForwardAbsoluteVHoldSettingChange ForwardAbsoluteVHoldSettingChange
{
get { return _ForwardAbsoluteVHoldSettingChange; }
set { _ForwardAbsoluteVHoldSettingChange = value; }
}
public Amplifier()
{
Name = DeviceSettings.Default.AmplifierName;
// Set range properties
this.VHoldMin = -10;
this.VHoldMax = 10;
this.CurrentMin = -10;
this.CurrentMax = 10;
this.CapacMin = -10;
this.CapacMax = 10;
this.GainMin = -10;
this.GainMax = 10;
}
// Methods
/// <summary>
/// <c>CalculateVtoIFactorFromGain(double gain)</c> returns the voltage to current conversion factor
/// of the Axopatch 200B in mV/pA. <c>gain</c> should be between 0-6.5.
/// </summary>
/// <param genotype="gain">The GainAI voltage, which should be between 0 and 6.5.</param>
/// <returns>The conversion factor for the CurrentAI line, in mV/pA.</returns>
public static double CalculateVtoIFactorFromTTL(double gain)
{
gain = Math.Round(gain, 2);
// From the Axopatch 200B manual
double VtoI = 1; // mV/pA
if(gain<=0.75) VtoI = 0.05;
else if(gain<=1.25) VtoI = 0.1;
else if(gain<=1.75) VtoI = 0.2;
else if(gain<=2.25) VtoI = 0.5;
else if(gain<=2.75) VtoI = 1;
else if(gain<=3.25) VtoI = 2;
else if(gain<=3.75) VtoI = 5;
else if(gain<=4.25) VtoI = 10;
else if(gain<=4.75) VtoI = 20;
else if(gain<=5.25) VtoI = 50;
else if(gain<=5.75) VtoI = 100;
else if(gain<=6.25) VtoI = 200;
else if(gain<=6.75) VtoI = 500;
return VtoI;
}
/// <summary>
/// <c>CalculateCellCapacitanceFromTTL(double capac, double beta)</c> returns the cell capacitance
/// correction factor obtained from the capacitance TTL line output voltage <c>capac</c> of an Axopatch 200B with
/// given <c>beta</c> setting in pF.
/// </summary>
/// <param genotype="capac">The input from the CapacAI line.</param>
/// <param genotype="beta">The beta setting on the Axopatch220B (only available by manual inspection). Either 0.1 or 1.</param>
/// <returns>The capacitance correction setting, in pF.</returns>
public double CalculateCellCapacitanceFromTTL(double capac)
{
double cellCapac = 1;
double maxCapac = 0;
if(Beta == 1) maxCapac = 100; // pF
else if(Beta == 0.1) maxCapac = 1000; // pF
cellCapac = maxCapac/10*capac; // (maxCapac-0 pF)/(10V)*V
return cellCapac;
}
/// <summary>
/// <c>CalculateFilterFrequencyFromTTL(double freq)</c> returns the amplifier filter frequency
/// in kHz from the TTL output voltage.
/// </summary>
/// <param genotype="freq">The input from the the FrequencyAI line. Should be between 0-10.</param>
/// <returns>The filter frequency setting in kHz.</returns>
public static int CalculateFilterFrequencyFromTTL(double freq)
{
// Conversion from the manual for the Axopatch 200B
int filter = 0;
if(freq<=2) filter = 1;
if(freq<=4) filter = 2;
if(freq<=6) filter = 5;
if(freq<=8) filter = 10;
if(freq<=10) filter = 100;
return filter;
}
/// <summary>
/// <c>SetHoldingPotential(double vhold)</c> sets the cell holding potential to <c>vhold</c> mV.
/// </summary>
/// <param genotype="vhold">The new holding potential, in mV.</param>
public virtual void SetHoldingPotential(short vhold)
{
if (ForwardAbsoluteVHoldSettingChange != null)
if (ForwardAbsoluteVHoldSettingChange(vhold))
{
AbsoluteVHold = vhold;
return;
}
Task task = new Task("Set Holding Potential");
task.AOChannels.CreateVoltageChannel(VHoldAO,"VHold",VHoldMin, VHoldMax, AOVoltageUnits.Volts);
// No timing set up, just sending one sample with software timing
task.Control(TaskAction.Verify);
AnalogSingleChannelWriter writer = new AnalogSingleChannelWriter(task.Stream);
double output = vhold*this.VoltageOutScalingFactor;
writer.WriteSingleSample(true,output);
task.Dispose();
AbsoluteVHold = vhold;
}
public virtual void AnnotateEquipmentData(Recording recording)
{
recording.SetEquipmentSetting(Name + "-VHold", AbsoluteVHold.ToString());
recording.HoldingPotential = AbsoluteVHold;
}
// Properties
/// <summary>
/// The DAQmx address for VHold AO
/// </summary>
[System.ComponentModel.Category("Connection")]
public String VHoldAO
{
get
{
return _VHoldAO;
}
set
{
_VHoldAO = value;
FireDeviceSettingsChanged(this, EventArgs.Empty);
}
}
/// <summary>
/// The DAQmx address for CapacAI
/// </summary>
[System.ComponentModel.Category("Connection")]
public String CapacAI
{
get
{
return _CapacAI;
}
set
{
_CapacAI = value;
FireDeviceSettingsChanged(this, EventArgs.Empty);
}
}
/// <summary>
/// The DAQmx address for CurrentAI
/// </summary>
[System.ComponentModel.Category("Connection")]
public String CurrentAI
{
get
{
return _CurrentAI;
}
set
{
_CurrentAI = value;
FireDeviceSettingsChanged(this, EventArgs.Empty);
}
}
/// <summary>
/// The DAQmx address for GainAI
/// </summary>
[System.ComponentModel.Category("Connection")]
public String GainAI
{
get
{
return _GainAI;
}
set
{
this._GainAI = value;
FireDeviceSettingsChanged(this, EventArgs.Empty);
}
}
/// <summary>
/// The minimum output voltage for VHoldAO
/// </summary>
[System.ComponentModel.Category("Behavior")]
public double VHoldMin
{
get
{
return theVHoldMin;
}
set
{
theVHoldMin = value;
FireDeviceSettingsChanged(this, EventArgs.Empty);
}
}
/// <summary>
/// The maximum output voltage for VHoldAO
/// </summary>
[System.ComponentModel.Category("Behavior")]
public double VHoldMax
{
get
{
return theVHoldMax;
}
set
{
theVHoldMax = value;
FireDeviceSettingsChanged(this, EventArgs.Empty);
}
}
private double _VoltageOutScalingFactor = 0.01;
/// <summary>
/// The scaling factor to use when sending a holding potential to the amplifer.
/// </summary>
[System.ComponentModel.Category("Settings")]
public double VoltageOutScalingFactor
{
get
{
return _VoltageOutScalingFactor;
}
set
{
_VoltageOutScalingFactor = value;
FireDeviceSettingsChanged(this, EventArgs.Empty);
}
}
private double _CurrentMin, _CurrentMax;
/// <summary>
/// The minimum input voltage for CurrentAI.
/// </summary>
[System.ComponentModel.Category("Behavior")]
public double CurrentMin
{
get
{
return _CurrentMin;
}
set
{
_CurrentMin = value;
FireDeviceSettingsChanged(this, EventArgs.Empty);
}
}
/// <summary>
/// The maximum input voltage for CurrentAI.
/// </summary>
[System.ComponentModel.Category("Behavior")]
public double CurrentMax
{
get
{
return _CurrentMax;
}
set
{
_CurrentMax = value;
FireDeviceSettingsChanged(this, EventArgs.Empty);
}
}
private int _CapacMin;
/// <summary>
/// The minimum input voltage for CapacAI.
/// </summary>
[System.ComponentModel.Category("Behavior")]
public int CapacMin
{
get { return _CapacMin; }
set {
_CapacMin = value;
FireDeviceSettingsChanged(this, EventArgs.Empty);
}
}
private int _CapacMax;
/// <summary>
/// The maximum input voltage for CapacAI.
/// </summary>
[System.ComponentModel.Category("Behavior")]
public int CapacMax
{
get { return _CapacMax; }
set {
_CapacMax = value;
FireDeviceSettingsChanged(this, EventArgs.Empty);
}
}
private int _GainMin;
/// <summary>
/// The minimum input voltage for GainAI.
/// </summary>
[System.ComponentModel.Category("Behavior")]
public int GainMin
{
get { return _GainMin; }
set {
_GainMin = value;
FireDeviceSettingsChanged(this, EventArgs.Empty);
}
}
private int _GainMax;
/// <summary>
/// The maximum input voltage for GainAI.
/// </summary>
[System.ComponentModel.Category("Behavior")]
public int GainMax
{
get { return _GainMax; }
set {
_GainMax = value;
FireDeviceSettingsChanged(this, EventArgs.Empty);
}
}
private short _AbsoluteVHold = 0;
public short AbsoluteVHold
{
get { return _AbsoluteVHold; }
protected set
{
_AbsoluteVHold = value;
if (AbsoluteVHoldChanged != null) AbsoluteVHoldChanged(this, EventArgs.Empty);
}
}
private double _Beta = 1;
public double Beta
{
get { return _Beta; }
set {
_Beta = value;
FireDeviceSettingsChanged(this, EventArgs.Empty);
}
}
}
public delegate bool ForwardAbsoluteVHoldSettingChange(double vhold);
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
namespace System.Numerics
{
/// <summary>
/// A structure encapsulating a four-dimensional vector (x,y,z,w),
/// which is used to efficiently rotate an object about the (x,y,z) vector by the angle theta, where w = cos(theta/2).
/// </summary>
public struct Quaternion : IEquatable<Quaternion>
{
/// <summary>
/// Specifies the X-value of the vector component of the Quaternion.
/// </summary>
public float X;
/// <summary>
/// Specifies the Y-value of the vector component of the Quaternion.
/// </summary>
public float Y;
/// <summary>
/// Specifies the Z-value of the vector component of the Quaternion.
/// </summary>
public float Z;
/// <summary>
/// Specifies the rotation component of the Quaternion.
/// </summary>
public float W;
/// <summary>
/// Returns a Quaternion representing no rotation.
/// </summary>
public static Quaternion Identity
{
get { return new Quaternion(0, 0, 0, 1); }
}
/// <summary>
/// Returns whether the Quaternion is the identity Quaternion.
/// </summary>
public bool IsIdentity
{
get { return X == 0f && Y == 0f && Z == 0f && W == 1f; }
}
/// <summary>
/// Constructs a Quaternion from the given components.
/// </summary>
/// <param name="x">The X component of the Quaternion.</param>
/// <param name="y">The Y component of the Quaternion.</param>
/// <param name="z">The Z component of the Quaternion.</param>
/// <param name="w">The W component of the Quaternion.</param>
public Quaternion(float x, float y, float z, float w)
{
this.X = x;
this.Y = y;
this.Z = z;
this.W = w;
}
/// <summary>
/// Constructs a Quaternion from the given vector and rotation parts.
/// </summary>
/// <param name="vectorPart">The vector part of the Quaternion.</param>
/// <param name="scalarPart">The rotation part of the Quaternion.</param>
public Quaternion(Vector3 vectorPart, float scalarPart)
{
X = vectorPart.X;
Y = vectorPart.Y;
Z = vectorPart.Z;
W = scalarPart;
}
/// <summary>
/// Calculates the length of the Quaternion.
/// </summary>
/// <returns>The computed length of the Quaternion.</returns>
public float Length()
{
float ls = X * X + Y * Y + Z * Z + W * W;
return (float)Math.Sqrt((double)ls);
}
/// <summary>
/// Calculates the length squared of the Quaternion. This operation is cheaper than Length().
/// </summary>
/// <returns>The length squared of the Quaternion.</returns>
public float LengthSquared()
{
return X * X + Y * Y + Z * Z + W * W;
}
/// <summary>
/// Divides each component of the Quaternion by the length of the Quaternion.
/// </summary>
/// <param name="value">The source Quaternion.</param>
/// <returns>The normalized Quaternion.</returns>
public static Quaternion Normalize(Quaternion value)
{
Quaternion ans;
float ls = value.X * value.X + value.Y * value.Y + value.Z * value.Z + value.W * value.W;
float invNorm = 1.0f / (float)Math.Sqrt((double)ls);
ans.X = value.X * invNorm;
ans.Y = value.Y * invNorm;
ans.Z = value.Z * invNorm;
ans.W = value.W * invNorm;
return ans;
}
/// <summary>
/// Creates the conjugate of a specified Quaternion.
/// </summary>
/// <param name="value">The Quaternion of which to return the conjugate.</param>
/// <returns>A new Quaternion that is the conjugate of the specified one.</returns>
public static Quaternion Conjugate(Quaternion value)
{
Quaternion ans;
ans.X = -value.X;
ans.Y = -value.Y;
ans.Z = -value.Z;
ans.W = value.W;
return ans;
}
/// <summary>
/// Returns the inverse of a Quaternion.
/// </summary>
/// <param name="value">The source Quaternion.</param>
/// <returns>The inverted Quaternion.</returns>
public static Quaternion Inverse(Quaternion value)
{
// -1 ( a -v )
// q = ( ------------- ------------- )
// ( a^2 + |v|^2 , a^2 + |v|^2 )
Quaternion ans;
float ls = value.X * value.X + value.Y * value.Y + value.Z * value.Z + value.W * value.W;
float invNorm = 1.0f / ls;
ans.X = -value.X * invNorm;
ans.Y = -value.Y * invNorm;
ans.Z = -value.Z * invNorm;
ans.W = value.W * invNorm;
return ans;
}
/// <summary>
/// Creates a Quaternion from a normalized vector axis and an angle to rotate about the vector.
/// </summary>
/// <param name="axis">The unit vector to rotate around.
/// This vector must be normalized before calling this function or the resulting Quaternion will be incorrect.</param>
/// <param name="angle">The angle, in radians, to rotate around the vector.</param>
/// <returns>The created Quaternion.</returns>
public static Quaternion CreateFromAxisAngle(Vector3 axis, float angle)
{
Quaternion ans;
float halfAngle = angle * 0.5f;
float s = (float)Math.Sin(halfAngle);
float c = (float)Math.Cos(halfAngle);
ans.X = axis.X * s;
ans.Y = axis.Y * s;
ans.Z = axis.Z * s;
ans.W = c;
return ans;
}
/// <summary>
/// Creates a new Quaternion from the given yaw, pitch, and roll, in radians.
/// </summary>
/// <param name="yaw">The yaw angle, in radians, around the Y-axis.</param>
/// <param name="pitch">The pitch angle, in radians, around the X-axis.</param>
/// <param name="roll">The roll angle, in radians, around the Z-axis.</param>
/// <returns></returns>
public static Quaternion CreateFromYawPitchRoll(float yaw, float pitch, float roll)
{
// Roll first, about axis the object is facing, then
// pitch upward, then yaw to face into the new heading
float sr, cr, sp, cp, sy, cy;
float halfRoll = roll * 0.5f;
sr = (float)Math.Sin(halfRoll);
cr = (float)Math.Cos(halfRoll);
float halfPitch = pitch * 0.5f;
sp = (float)Math.Sin(halfPitch);
cp = (float)Math.Cos(halfPitch);
float halfYaw = yaw * 0.5f;
sy = (float)Math.Sin(halfYaw);
cy = (float)Math.Cos(halfYaw);
Quaternion result;
result.X = cy * sp * cr + sy * cp * sr;
result.Y = sy * cp * cr - cy * sp * sr;
result.Z = cy * cp * sr - sy * sp * cr;
result.W = cy * cp * cr + sy * sp * sr;
return result;
}
/// <summary>
/// Creates a Quaternion from the given rotation matrix.
/// </summary>
/// <param name="matrix">The rotation matrix.</param>
/// <returns>The created Quaternion.</returns>
public static Quaternion CreateFromRotationMatrix(Matrix4x4 matrix)
{
float trace = matrix.M11 + matrix.M22 + matrix.M33;
Quaternion q = new Quaternion();
if (trace > 0.0f)
{
float s = (float)Math.Sqrt(trace + 1.0f);
q.W = s * 0.5f;
s = 0.5f / s;
q.X = (matrix.M23 - matrix.M32) * s;
q.Y = (matrix.M31 - matrix.M13) * s;
q.Z = (matrix.M12 - matrix.M21) * s;
}
else
{
if (matrix.M11 >= matrix.M22 && matrix.M11 >= matrix.M33)
{
float s = (float)Math.Sqrt(1.0f + matrix.M11 - matrix.M22 - matrix.M33);
float invS = 0.5f / s;
q.X = 0.5f * s;
q.Y = (matrix.M12 + matrix.M21) * invS;
q.Z = (matrix.M13 + matrix.M31) * invS;
q.W = (matrix.M23 - matrix.M32) * invS;
}
else if (matrix.M22 > matrix.M33)
{
float s = (float)Math.Sqrt(1.0f + matrix.M22 - matrix.M11 - matrix.M33);
float invS = 0.5f / s;
q.X = (matrix.M21 + matrix.M12) * invS;
q.Y = 0.5f * s;
q.Z = (matrix.M32 + matrix.M23) * invS;
q.W = (matrix.M31 - matrix.M13) * invS;
}
else
{
float s = (float)Math.Sqrt(1.0f + matrix.M33 - matrix.M11 - matrix.M22);
float invS = 0.5f / s;
q.X = (matrix.M31 + matrix.M13) * invS;
q.Y = (matrix.M32 + matrix.M23) * invS;
q.Z = 0.5f * s;
q.W = (matrix.M12 - matrix.M21) * invS;
}
}
return q;
}
/// <summary>
/// Calculates the dot product of two Quaternions.
/// </summary>
/// <param name="quaternion1">The first source Quaternion.</param>
/// <param name="quaternion2">The second source Quaternion.</param>
/// <returns>The dot product of the Quaternions.</returns>
public static float Dot(Quaternion quaternion1, Quaternion quaternion2)
{
return quaternion1.X * quaternion2.X +
quaternion1.Y * quaternion2.Y +
quaternion1.Z * quaternion2.Z +
quaternion1.W * quaternion2.W;
}
/// <summary>
/// Interpolates between two quaternions, using spherical linear interpolation.
/// </summary>
/// <param name="quaternion1">The first source Quaternion.</param>
/// <param name="quaternion2">The second source Quaternion.</param>
/// <param name="amount">The relative weight of the second source Quaternion in the interpolation.</param>
/// <returns>The interpolated Quaternion.</returns>
public static Quaternion Slerp(Quaternion quaternion1, Quaternion quaternion2, float amount)
{
const float epsilon = 1e-6f;
float t = amount;
float cosOmega = quaternion1.X * quaternion2.X + quaternion1.Y * quaternion2.Y +
quaternion1.Z * quaternion2.Z + quaternion1.W * quaternion2.W;
bool flip = false;
if (cosOmega < 0.0f)
{
flip = true;
cosOmega = -cosOmega;
}
float s1, s2;
if (cosOmega > (1.0f - epsilon))
{
// Too close, do straight linear interpolation.
s1 = 1.0f - t;
s2 = (flip) ? -t : t;
}
else
{
float omega = (float)Math.Acos(cosOmega);
float invSinOmega = (float)(1 / Math.Sin(omega));
s1 = (float)Math.Sin((1.0f - t) * omega) * invSinOmega;
s2 = (flip)
? (float)-Math.Sin(t * omega) * invSinOmega
: (float)Math.Sin(t * omega) * invSinOmega;
}
Quaternion ans;
ans.X = s1 * quaternion1.X + s2 * quaternion2.X;
ans.Y = s1 * quaternion1.Y + s2 * quaternion2.Y;
ans.Z = s1 * quaternion1.Z + s2 * quaternion2.Z;
ans.W = s1 * quaternion1.W + s2 * quaternion2.W;
return ans;
}
/// <summary>
/// Linearly interpolates between two quaternions.
/// </summary>
/// <param name="quaternion1">The first source Quaternion.</param>
/// <param name="quaternion2">The second source Quaternion.</param>
/// <param name="amount">The relative weight of the second source Quaternion in the interpolation.</param>
/// <returns>The interpolated Quaternion.</returns>
public static Quaternion Lerp(Quaternion quaternion1, Quaternion quaternion2, float amount)
{
float t = amount;
float t1 = 1.0f - t;
Quaternion r = new Quaternion();
float dot = quaternion1.X * quaternion2.X + quaternion1.Y * quaternion2.Y +
quaternion1.Z * quaternion2.Z + quaternion1.W * quaternion2.W;
if (dot >= 0.0f)
{
r.X = t1 * quaternion1.X + t * quaternion2.X;
r.Y = t1 * quaternion1.Y + t * quaternion2.Y;
r.Z = t1 * quaternion1.Z + t * quaternion2.Z;
r.W = t1 * quaternion1.W + t * quaternion2.W;
}
else
{
r.X = t1 * quaternion1.X - t * quaternion2.X;
r.Y = t1 * quaternion1.Y - t * quaternion2.Y;
r.Z = t1 * quaternion1.Z - t * quaternion2.Z;
r.W = t1 * quaternion1.W - t * quaternion2.W;
}
// Normalize it.
float ls = r.X * r.X + r.Y * r.Y + r.Z * r.Z + r.W * r.W;
float invNorm = 1.0f / (float)Math.Sqrt((double)ls);
r.X *= invNorm;
r.Y *= invNorm;
r.Z *= invNorm;
r.W *= invNorm;
return r;
}
/// <summary>
/// Concatenates two Quaternions; the result represents the value1 rotation followed by the value2 rotation.
/// </summary>
/// <param name="value1">The first Quaternion rotation in the series.</param>
/// <param name="value2">The second Quaternion rotation in the series.</param>
/// <returns>A new Quaternion representing the concatenation of the value1 rotation followed by the value2 rotation.</returns>
public static Quaternion Concatenate(Quaternion value1, Quaternion value2)
{
Quaternion ans;
// Concatenate rotation is actually q2 * q1 instead of q1 * q2.
// So that's why value2 goes q1 and value1 goes q2.
float q1x = value2.X;
float q1y = value2.Y;
float q1z = value2.Z;
float q1w = value2.W;
float q2x = value1.X;
float q2y = value1.Y;
float q2z = value1.Z;
float q2w = value1.W;
// cross(av, bv)
float cx = q1y * q2z - q1z * q2y;
float cy = q1z * q2x - q1x * q2z;
float cz = q1x * q2y - q1y * q2x;
float dot = q1x * q2x + q1y * q2y + q1z * q2z;
ans.X = q1x * q2w + q2x * q1w + cx;
ans.Y = q1y * q2w + q2y * q1w + cy;
ans.Z = q1z * q2w + q2z * q1w + cz;
ans.W = q1w * q2w - dot;
return ans;
}
/// <summary>
/// Flips the sign of each component of the quaternion.
/// </summary>
/// <param name="value">The source Quaternion.</param>
/// <returns>The negated Quaternion.</returns>
public static Quaternion Negate(Quaternion value)
{
Quaternion ans;
ans.X = -value.X;
ans.Y = -value.Y;
ans.Z = -value.Z;
ans.W = -value.W;
return ans;
}
/// <summary>
/// Adds two Quaternions element-by-element.
/// </summary>
/// <param name="value1">The first source Quaternion.</param>
/// <param name="value2">The second source Quaternion.</param>
/// <returns>The result of adding the Quaternions.</returns>
public static Quaternion Add(Quaternion value1, Quaternion value2)
{
Quaternion ans;
ans.X = value1.X + value2.X;
ans.Y = value1.Y + value2.Y;
ans.Z = value1.Z + value2.Z;
ans.W = value1.W + value2.W;
return ans;
}
/// <summary>
/// Subtracts one Quaternion from another.
/// </summary>
/// <param name="value1">The first source Quaternion.</param>
/// <param name="value2">The second Quaternion, to be subtracted from the first.</param>
/// <returns>The result of the subtraction.</returns>
public static Quaternion Subtract(Quaternion value1, Quaternion value2)
{
Quaternion ans;
ans.X = value1.X - value2.X;
ans.Y = value1.Y - value2.Y;
ans.Z = value1.Z - value2.Z;
ans.W = value1.W - value2.W;
return ans;
}
/// <summary>
/// Multiplies two Quaternions together.
/// </summary>
/// <param name="value1">The Quaternion on the left side of the multiplication.</param>
/// <param name="value2">The Quaternion on the right side of the multiplication.</param>
/// <returns>The result of the multiplication.</returns>
public static Quaternion Multiply(Quaternion value1, Quaternion value2)
{
Quaternion ans;
float q1x = value1.X;
float q1y = value1.Y;
float q1z = value1.Z;
float q1w = value1.W;
float q2x = value2.X;
float q2y = value2.Y;
float q2z = value2.Z;
float q2w = value2.W;
// cross(av, bv)
float cx = q1y * q2z - q1z * q2y;
float cy = q1z * q2x - q1x * q2z;
float cz = q1x * q2y - q1y * q2x;
float dot = q1x * q2x + q1y * q2y + q1z * q2z;
ans.X = q1x * q2w + q2x * q1w + cx;
ans.Y = q1y * q2w + q2y * q1w + cy;
ans.Z = q1z * q2w + q2z * q1w + cz;
ans.W = q1w * q2w - dot;
return ans;
}
/// <summary>
/// Multiplies a Quaternion by a scalar value.
/// </summary>
/// <param name="value1">The source Quaternion.</param>
/// <param name="value2">The scalar value.</param>
/// <returns>The result of the multiplication.</returns>
public static Quaternion Multiply(Quaternion value1, float value2)
{
Quaternion ans;
ans.X = value1.X * value2;
ans.Y = value1.Y * value2;
ans.Z = value1.Z * value2;
ans.W = value1.W * value2;
return ans;
}
/// <summary>
/// Divides a Quaternion by another Quaternion.
/// </summary>
/// <param name="value1">The source Quaternion.</param>
/// <param name="value2">The divisor.</param>
/// <returns>The result of the division.</returns>
public static Quaternion Divide(Quaternion value1, Quaternion value2)
{
Quaternion ans;
float q1x = value1.X;
float q1y = value1.Y;
float q1z = value1.Z;
float q1w = value1.W;
//-------------------------------------
// Inverse part.
float ls = value2.X * value2.X + value2.Y * value2.Y +
value2.Z * value2.Z + value2.W * value2.W;
float invNorm = 1.0f / ls;
float q2x = -value2.X * invNorm;
float q2y = -value2.Y * invNorm;
float q2z = -value2.Z * invNorm;
float q2w = value2.W * invNorm;
//-------------------------------------
// Multiply part.
// cross(av, bv)
float cx = q1y * q2z - q1z * q2y;
float cy = q1z * q2x - q1x * q2z;
float cz = q1x * q2y - q1y * q2x;
float dot = q1x * q2x + q1y * q2y + q1z * q2z;
ans.X = q1x * q2w + q2x * q1w + cx;
ans.Y = q1y * q2w + q2y * q1w + cy;
ans.Z = q1z * q2w + q2z * q1w + cz;
ans.W = q1w * q2w - dot;
return ans;
}
/// <summary>
/// Flips the sign of each component of the quaternion.
/// </summary>
/// <param name="value">The source Quaternion.</param>
/// <returns>The negated Quaternion.</returns>
public static Quaternion operator -(Quaternion value)
{
Quaternion ans;
ans.X = -value.X;
ans.Y = -value.Y;
ans.Z = -value.Z;
ans.W = -value.W;
return ans;
}
/// <summary>
/// Adds two Quaternions element-by-element.
/// </summary>
/// <param name="value1">The first source Quaternion.</param>
/// <param name="value2">The second source Quaternion.</param>
/// <returns>The result of adding the Quaternions.</returns>
public static Quaternion operator +(Quaternion value1, Quaternion value2)
{
Quaternion ans;
ans.X = value1.X + value2.X;
ans.Y = value1.Y + value2.Y;
ans.Z = value1.Z + value2.Z;
ans.W = value1.W + value2.W;
return ans;
}
/// <summary>
/// Subtracts one Quaternion from another.
/// </summary>
/// <param name="value1">The first source Quaternion.</param>
/// <param name="value2">The second Quaternion, to be subtracted from the first.</param>
/// <returns>The result of the subtraction.</returns>
public static Quaternion operator -(Quaternion value1, Quaternion value2)
{
Quaternion ans;
ans.X = value1.X - value2.X;
ans.Y = value1.Y - value2.Y;
ans.Z = value1.Z - value2.Z;
ans.W = value1.W - value2.W;
return ans;
}
/// <summary>
/// Multiplies two Quaternions together.
/// </summary>
/// <param name="value1">The Quaternion on the left side of the multiplication.</param>
/// <param name="value2">The Quaternion on the right side of the multiplication.</param>
/// <returns>The result of the multiplication.</returns>
public static Quaternion operator *(Quaternion value1, Quaternion value2)
{
Quaternion ans;
float q1x = value1.X;
float q1y = value1.Y;
float q1z = value1.Z;
float q1w = value1.W;
float q2x = value2.X;
float q2y = value2.Y;
float q2z = value2.Z;
float q2w = value2.W;
// cross(av, bv)
float cx = q1y * q2z - q1z * q2y;
float cy = q1z * q2x - q1x * q2z;
float cz = q1x * q2y - q1y * q2x;
float dot = q1x * q2x + q1y * q2y + q1z * q2z;
ans.X = q1x * q2w + q2x * q1w + cx;
ans.Y = q1y * q2w + q2y * q1w + cy;
ans.Z = q1z * q2w + q2z * q1w + cz;
ans.W = q1w * q2w - dot;
return ans;
}
/// <summary>
/// Multiplies a Quaternion by a scalar value.
/// </summary>
/// <param name="value1">The source Quaternion.</param>
/// <param name="value2">The scalar value.</param>
/// <returns>The result of the multiplication.</returns>
public static Quaternion operator *(Quaternion value1, float value2)
{
Quaternion ans;
ans.X = value1.X * value2;
ans.Y = value1.Y * value2;
ans.Z = value1.Z * value2;
ans.W = value1.W * value2;
return ans;
}
/// <summary>
/// Divides a Quaternion by another Quaternion.
/// </summary>
/// <param name="value1">The source Quaternion.</param>
/// <param name="value2">The divisor.</param>
/// <returns>The result of the division.</returns>
public static Quaternion operator /(Quaternion value1, Quaternion value2)
{
Quaternion ans;
float q1x = value1.X;
float q1y = value1.Y;
float q1z = value1.Z;
float q1w = value1.W;
//-------------------------------------
// Inverse part.
float ls = value2.X * value2.X + value2.Y * value2.Y +
value2.Z * value2.Z + value2.W * value2.W;
float invNorm = 1.0f / ls;
float q2x = -value2.X * invNorm;
float q2y = -value2.Y * invNorm;
float q2z = -value2.Z * invNorm;
float q2w = value2.W * invNorm;
//-------------------------------------
// Multiply part.
// cross(av, bv)
float cx = q1y * q2z - q1z * q2y;
float cy = q1z * q2x - q1x * q2z;
float cz = q1x * q2y - q1y * q2x;
float dot = q1x * q2x + q1y * q2y + q1z * q2z;
ans.X = q1x * q2w + q2x * q1w + cx;
ans.Y = q1y * q2w + q2y * q1w + cy;
ans.Z = q1z * q2w + q2z * q1w + cz;
ans.W = q1w * q2w - dot;
return ans;
}
/// <summary>
/// Returns a boolean indicating whether the two given Quaternions are equal.
/// </summary>
/// <param name="value1">The first Quaternion to compare.</param>
/// <param name="value2">The second Quaternion to compare.</param>
/// <returns>True if the Quaternions are equal; False otherwise.</returns>
public static bool operator ==(Quaternion value1, Quaternion value2)
{
return (value1.X == value2.X &&
value1.Y == value2.Y &&
value1.Z == value2.Z &&
value1.W == value2.W);
}
/// <summary>
/// Returns a boolean indicating whether the two given Quaternions are not equal.
/// </summary>
/// <param name="value1">The first Quaternion to compare.</param>
/// <param name="value2">The second Quaternion to compare.</param>
/// <returns>True if the Quaternions are not equal; False if they are equal.</returns>
public static bool operator !=(Quaternion value1, Quaternion value2)
{
return (value1.X != value2.X ||
value1.Y != value2.Y ||
value1.Z != value2.Z ||
value1.W != value2.W);
}
/// <summary>
/// Returns a boolean indicating whether the given Quaternion is equal to this Quaternion instance.
/// </summary>
/// <param name="other">The Quaternion to compare this instance to.</param>
/// <returns>True if the other Quaternion is equal to this instance; False otherwise.</returns>
public bool Equals(Quaternion other)
{
return (X == other.X &&
Y == other.Y &&
Z == other.Z &&
W == other.W);
}
/// <summary>
/// Returns a boolean indicating whether the given Object is equal to this Quaternion instance.
/// </summary>
/// <param name="obj">The Object to compare against.</param>
/// <returns>True if the Object is equal to this Quaternion; False otherwise.</returns>
public override bool Equals(object obj)
{
if (obj is Quaternion)
{
return Equals((Quaternion)obj);
}
return false;
}
/// <summary>
/// Returns a String representing this Quaternion instance.
/// </summary>
/// <returns>The string representation.</returns>
public override string ToString()
{
CultureInfo ci = CultureInfo.CurrentCulture;
return String.Format(ci, "{{X:{0} Y:{1} Z:{2} W:{3}}}", X.ToString(ci), Y.ToString(ci), Z.ToString(ci), W.ToString(ci));
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
return unchecked(X.GetHashCode() + Y.GetHashCode() + Z.GetHashCode() + W.GetHashCode());
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the cloudhsm-2014-05-30.normal.json service model.
*/
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.CloudHSM.Model;
using Amazon.CloudHSM.Model.Internal.MarshallTransformations;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.CloudHSM
{
/// <summary>
/// Implementation for accessing CloudHSM
///
/// AWS CloudHSM Service
/// </summary>
public partial class AmazonCloudHSMClient : AmazonServiceClient, IAmazonCloudHSM
{
#region Constructors
/// <summary>
/// Constructs AmazonCloudHSMClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonCloudHSMClient(AWSCredentials credentials)
: this(credentials, new AmazonCloudHSMConfig())
{
}
/// <summary>
/// Constructs AmazonCloudHSMClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonCloudHSMClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonCloudHSMConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonCloudHSMClient with AWS Credentials and an
/// AmazonCloudHSMClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonCloudHSMClient Configuration Object</param>
public AmazonCloudHSMClient(AWSCredentials credentials, AmazonCloudHSMConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonCloudHSMClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonCloudHSMClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonCloudHSMConfig())
{
}
/// <summary>
/// Constructs AmazonCloudHSMClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonCloudHSMClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonCloudHSMConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonCloudHSMClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonCloudHSMClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonCloudHSMClient Configuration Object</param>
public AmazonCloudHSMClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonCloudHSMConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonCloudHSMClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonCloudHSMClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCloudHSMConfig())
{
}
/// <summary>
/// Constructs AmazonCloudHSMClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonCloudHSMClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCloudHSMConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonCloudHSMClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonCloudHSMClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonCloudHSMClient Configuration Object</param>
public AmazonCloudHSMClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonCloudHSMConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region CreateHapg
internal CreateHapgResponse CreateHapg(CreateHapgRequest request)
{
var marshaller = new CreateHapgRequestMarshaller();
var unmarshaller = CreateHapgResponseUnmarshaller.Instance;
return Invoke<CreateHapgRequest,CreateHapgResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Creates a high-availability partition group. A high-availability partition group is
/// a group of partitions that spans multiple physical HSMs.
/// </summary>
/// <param name="label">The label of the new high-availability partition group.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateHapg service method, as returned by CloudHSM.</returns>
/// <exception cref="Amazon.CloudHSM.Model.CloudHsmInternalException">
/// Indicates that an internal error occurred.
/// </exception>
/// <exception cref="Amazon.CloudHSM.Model.CloudHsmServiceException">
/// Indicates that an exception occurred in the AWS CloudHSM service.
/// </exception>
/// <exception cref="Amazon.CloudHSM.Model.InvalidRequestException">
/// Indicates that one or more of the request parameters are not valid.
/// </exception>
public Task<CreateHapgResponse> CreateHapgAsync(string label, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var request = new CreateHapgRequest();
request.Label = label;
return CreateHapgAsync(request, cancellationToken);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateHapg operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateHapg operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<CreateHapgResponse> CreateHapgAsync(CreateHapgRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new CreateHapgRequestMarshaller();
var unmarshaller = CreateHapgResponseUnmarshaller.Instance;
return InvokeAsync<CreateHapgRequest,CreateHapgResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region CreateHsm
internal CreateHsmResponse CreateHsm(CreateHsmRequest request)
{
var marshaller = new CreateHsmRequestMarshaller();
var unmarshaller = CreateHsmResponseUnmarshaller.Instance;
return Invoke<CreateHsmRequest,CreateHsmResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateHsm operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateHsm operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<CreateHsmResponse> CreateHsmAsync(CreateHsmRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new CreateHsmRequestMarshaller();
var unmarshaller = CreateHsmResponseUnmarshaller.Instance;
return InvokeAsync<CreateHsmRequest,CreateHsmResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region CreateLunaClient
internal CreateLunaClientResponse CreateLunaClient(CreateLunaClientRequest request)
{
var marshaller = new CreateLunaClientRequestMarshaller();
var unmarshaller = CreateLunaClientResponseUnmarshaller.Instance;
return Invoke<CreateLunaClientRequest,CreateLunaClientResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateLunaClient operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateLunaClient operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<CreateLunaClientResponse> CreateLunaClientAsync(CreateLunaClientRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new CreateLunaClientRequestMarshaller();
var unmarshaller = CreateLunaClientResponseUnmarshaller.Instance;
return InvokeAsync<CreateLunaClientRequest,CreateLunaClientResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DeleteHapg
internal DeleteHapgResponse DeleteHapg(DeleteHapgRequest request)
{
var marshaller = new DeleteHapgRequestMarshaller();
var unmarshaller = DeleteHapgResponseUnmarshaller.Instance;
return Invoke<DeleteHapgRequest,DeleteHapgResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Deletes a high-availability partition group.
/// </summary>
/// <param name="hapgArn">The ARN of the high-availability partition group to delete.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteHapg service method, as returned by CloudHSM.</returns>
/// <exception cref="Amazon.CloudHSM.Model.CloudHsmInternalException">
/// Indicates that an internal error occurred.
/// </exception>
/// <exception cref="Amazon.CloudHSM.Model.CloudHsmServiceException">
/// Indicates that an exception occurred in the AWS CloudHSM service.
/// </exception>
/// <exception cref="Amazon.CloudHSM.Model.InvalidRequestException">
/// Indicates that one or more of the request parameters are not valid.
/// </exception>
public Task<DeleteHapgResponse> DeleteHapgAsync(string hapgArn, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var request = new DeleteHapgRequest();
request.HapgArn = hapgArn;
return DeleteHapgAsync(request, cancellationToken);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteHapg operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteHapg operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DeleteHapgResponse> DeleteHapgAsync(DeleteHapgRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DeleteHapgRequestMarshaller();
var unmarshaller = DeleteHapgResponseUnmarshaller.Instance;
return InvokeAsync<DeleteHapgRequest,DeleteHapgResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DeleteHsm
internal DeleteHsmResponse DeleteHsm(DeleteHsmRequest request)
{
var marshaller = new DeleteHsmRequestMarshaller();
var unmarshaller = DeleteHsmResponseUnmarshaller.Instance;
return Invoke<DeleteHsmRequest,DeleteHsmResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Deletes an HSM. Once complete, this operation cannot be undone and your key material
/// cannot be recovered.
/// </summary>
/// <param name="hsmArn">The ARN of the HSM to delete.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteHsm service method, as returned by CloudHSM.</returns>
/// <exception cref="Amazon.CloudHSM.Model.CloudHsmInternalException">
/// Indicates that an internal error occurred.
/// </exception>
/// <exception cref="Amazon.CloudHSM.Model.CloudHsmServiceException">
/// Indicates that an exception occurred in the AWS CloudHSM service.
/// </exception>
/// <exception cref="Amazon.CloudHSM.Model.InvalidRequestException">
/// Indicates that one or more of the request parameters are not valid.
/// </exception>
public Task<DeleteHsmResponse> DeleteHsmAsync(string hsmArn, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var request = new DeleteHsmRequest();
request.HsmArn = hsmArn;
return DeleteHsmAsync(request, cancellationToken);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteHsm operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteHsm operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DeleteHsmResponse> DeleteHsmAsync(DeleteHsmRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DeleteHsmRequestMarshaller();
var unmarshaller = DeleteHsmResponseUnmarshaller.Instance;
return InvokeAsync<DeleteHsmRequest,DeleteHsmResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DeleteLunaClient
internal DeleteLunaClientResponse DeleteLunaClient(DeleteLunaClientRequest request)
{
var marshaller = new DeleteLunaClientRequestMarshaller();
var unmarshaller = DeleteLunaClientResponseUnmarshaller.Instance;
return Invoke<DeleteLunaClientRequest,DeleteLunaClientResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Deletes a client.
/// </summary>
/// <param name="clientArn">The ARN of the client to delete.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DeleteLunaClient service method, as returned by CloudHSM.</returns>
/// <exception cref="Amazon.CloudHSM.Model.CloudHsmInternalException">
/// Indicates that an internal error occurred.
/// </exception>
/// <exception cref="Amazon.CloudHSM.Model.CloudHsmServiceException">
/// Indicates that an exception occurred in the AWS CloudHSM service.
/// </exception>
/// <exception cref="Amazon.CloudHSM.Model.InvalidRequestException">
/// Indicates that one or more of the request parameters are not valid.
/// </exception>
public Task<DeleteLunaClientResponse> DeleteLunaClientAsync(string clientArn, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var request = new DeleteLunaClientRequest();
request.ClientArn = clientArn;
return DeleteLunaClientAsync(request, cancellationToken);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteLunaClient operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteLunaClient operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DeleteLunaClientResponse> DeleteLunaClientAsync(DeleteLunaClientRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DeleteLunaClientRequestMarshaller();
var unmarshaller = DeleteLunaClientResponseUnmarshaller.Instance;
return InvokeAsync<DeleteLunaClientRequest,DeleteLunaClientResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DescribeHapg
internal DescribeHapgResponse DescribeHapg(DescribeHapgRequest request)
{
var marshaller = new DescribeHapgRequestMarshaller();
var unmarshaller = DescribeHapgResponseUnmarshaller.Instance;
return Invoke<DescribeHapgRequest,DescribeHapgResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Retrieves information about a high-availability partition group.
/// </summary>
/// <param name="hapgArn">The ARN of the high-availability partition group to describe.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeHapg service method, as returned by CloudHSM.</returns>
/// <exception cref="Amazon.CloudHSM.Model.CloudHsmInternalException">
/// Indicates that an internal error occurred.
/// </exception>
/// <exception cref="Amazon.CloudHSM.Model.CloudHsmServiceException">
/// Indicates that an exception occurred in the AWS CloudHSM service.
/// </exception>
/// <exception cref="Amazon.CloudHSM.Model.InvalidRequestException">
/// Indicates that one or more of the request parameters are not valid.
/// </exception>
public Task<DescribeHapgResponse> DescribeHapgAsync(string hapgArn, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var request = new DescribeHapgRequest();
request.HapgArn = hapgArn;
return DescribeHapgAsync(request, cancellationToken);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeHapg operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeHapg operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DescribeHapgResponse> DescribeHapgAsync(DescribeHapgRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DescribeHapgRequestMarshaller();
var unmarshaller = DescribeHapgResponseUnmarshaller.Instance;
return InvokeAsync<DescribeHapgRequest,DescribeHapgResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DescribeHsm
internal DescribeHsmResponse DescribeHsm(DescribeHsmRequest request)
{
var marshaller = new DescribeHsmRequestMarshaller();
var unmarshaller = DescribeHsmResponseUnmarshaller.Instance;
return Invoke<DescribeHsmRequest,DescribeHsmResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Retrieves information about an HSM. You can identify the HSM by its ARN or its serial
/// number.
/// </summary>
/// <param name="hsmArn">The ARN of the HSM. Either the <i>HsmArn</i> or the <i>SerialNumber</i> parameter must be specified.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeHsm service method, as returned by CloudHSM.</returns>
/// <exception cref="Amazon.CloudHSM.Model.CloudHsmInternalException">
/// Indicates that an internal error occurred.
/// </exception>
/// <exception cref="Amazon.CloudHSM.Model.CloudHsmServiceException">
/// Indicates that an exception occurred in the AWS CloudHSM service.
/// </exception>
/// <exception cref="Amazon.CloudHSM.Model.InvalidRequestException">
/// Indicates that one or more of the request parameters are not valid.
/// </exception>
public Task<DescribeHsmResponse> DescribeHsmAsync(string hsmArn, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var request = new DescribeHsmRequest();
request.HsmArn = hsmArn;
return DescribeHsmAsync(request, cancellationToken);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeHsm operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeHsm operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DescribeHsmResponse> DescribeHsmAsync(DescribeHsmRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DescribeHsmRequestMarshaller();
var unmarshaller = DescribeHsmResponseUnmarshaller.Instance;
return InvokeAsync<DescribeHsmRequest,DescribeHsmResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DescribeLunaClient
internal DescribeLunaClientResponse DescribeLunaClient(DescribeLunaClientRequest request)
{
var marshaller = new DescribeLunaClientRequestMarshaller();
var unmarshaller = DescribeLunaClientResponseUnmarshaller.Instance;
return Invoke<DescribeLunaClientRequest,DescribeLunaClientResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeLunaClient operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeLunaClient operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DescribeLunaClientResponse> DescribeLunaClientAsync(DescribeLunaClientRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DescribeLunaClientRequestMarshaller();
var unmarshaller = DescribeLunaClientResponseUnmarshaller.Instance;
return InvokeAsync<DescribeLunaClientRequest,DescribeLunaClientResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region GetConfig
internal GetConfigResponse GetConfig(GetConfigRequest request)
{
var marshaller = new GetConfigRequestMarshaller();
var unmarshaller = GetConfigResponseUnmarshaller.Instance;
return Invoke<GetConfigRequest,GetConfigResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the GetConfig operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetConfig operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<GetConfigResponse> GetConfigAsync(GetConfigRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new GetConfigRequestMarshaller();
var unmarshaller = GetConfigResponseUnmarshaller.Instance;
return InvokeAsync<GetConfigRequest,GetConfigResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region ListAvailableZones
internal ListAvailableZonesResponse ListAvailableZones(ListAvailableZonesRequest request)
{
var marshaller = new ListAvailableZonesRequestMarshaller();
var unmarshaller = ListAvailableZonesResponseUnmarshaller.Instance;
return Invoke<ListAvailableZonesRequest,ListAvailableZonesResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Lists the Availability Zones that have available AWS CloudHSM capacity.
/// </summary>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListAvailableZones service method, as returned by CloudHSM.</returns>
/// <exception cref="Amazon.CloudHSM.Model.CloudHsmInternalException">
/// Indicates that an internal error occurred.
/// </exception>
/// <exception cref="Amazon.CloudHSM.Model.CloudHsmServiceException">
/// Indicates that an exception occurred in the AWS CloudHSM service.
/// </exception>
/// <exception cref="Amazon.CloudHSM.Model.InvalidRequestException">
/// Indicates that one or more of the request parameters are not valid.
/// </exception>
public Task<ListAvailableZonesResponse> ListAvailableZonesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var request = new ListAvailableZonesRequest();
return ListAvailableZonesAsync(request, cancellationToken);
}
/// <summary>
/// Initiates the asynchronous execution of the ListAvailableZones operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListAvailableZones operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<ListAvailableZonesResponse> ListAvailableZonesAsync(ListAvailableZonesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new ListAvailableZonesRequestMarshaller();
var unmarshaller = ListAvailableZonesResponseUnmarshaller.Instance;
return InvokeAsync<ListAvailableZonesRequest,ListAvailableZonesResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region ListHapgs
internal ListHapgsResponse ListHapgs(ListHapgsRequest request)
{
var marshaller = new ListHapgsRequestMarshaller();
var unmarshaller = ListHapgsResponseUnmarshaller.Instance;
return Invoke<ListHapgsRequest,ListHapgsResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Lists the high-availability partition groups for the account.
///
///
/// <para>
/// This operation supports pagination with the use of the <i>NextToken</i> member. If
/// more results are available, the <i>NextToken</i> member of the response contains a
/// token that you pass in the next call to <a>ListHapgs</a> to retrieve the next set
/// of items.
/// </para>
/// </summary>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListHapgs service method, as returned by CloudHSM.</returns>
/// <exception cref="Amazon.CloudHSM.Model.CloudHsmInternalException">
/// Indicates that an internal error occurred.
/// </exception>
/// <exception cref="Amazon.CloudHSM.Model.CloudHsmServiceException">
/// Indicates that an exception occurred in the AWS CloudHSM service.
/// </exception>
/// <exception cref="Amazon.CloudHSM.Model.InvalidRequestException">
/// Indicates that one or more of the request parameters are not valid.
/// </exception>
public Task<ListHapgsResponse> ListHapgsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var request = new ListHapgsRequest();
return ListHapgsAsync(request, cancellationToken);
}
/// <summary>
/// Initiates the asynchronous execution of the ListHapgs operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListHapgs operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<ListHapgsResponse> ListHapgsAsync(ListHapgsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new ListHapgsRequestMarshaller();
var unmarshaller = ListHapgsResponseUnmarshaller.Instance;
return InvokeAsync<ListHapgsRequest,ListHapgsResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region ListHsms
internal ListHsmsResponse ListHsms(ListHsmsRequest request)
{
var marshaller = new ListHsmsRequestMarshaller();
var unmarshaller = ListHsmsResponseUnmarshaller.Instance;
return Invoke<ListHsmsRequest,ListHsmsResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Retrieves the identifiers of all of the HSMs provisioned for the current customer.
///
///
/// <para>
/// This operation supports pagination with the use of the <i>NextToken</i> member. If
/// more results are available, the <i>NextToken</i> member of the response contains a
/// token that you pass in the next call to <a>ListHsms</a> to retrieve the next set of
/// items.
/// </para>
/// </summary>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListHsms service method, as returned by CloudHSM.</returns>
/// <exception cref="Amazon.CloudHSM.Model.CloudHsmInternalException">
/// Indicates that an internal error occurred.
/// </exception>
/// <exception cref="Amazon.CloudHSM.Model.CloudHsmServiceException">
/// Indicates that an exception occurred in the AWS CloudHSM service.
/// </exception>
/// <exception cref="Amazon.CloudHSM.Model.InvalidRequestException">
/// Indicates that one or more of the request parameters are not valid.
/// </exception>
public Task<ListHsmsResponse> ListHsmsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var request = new ListHsmsRequest();
return ListHsmsAsync(request, cancellationToken);
}
/// <summary>
/// Initiates the asynchronous execution of the ListHsms operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListHsms operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<ListHsmsResponse> ListHsmsAsync(ListHsmsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new ListHsmsRequestMarshaller();
var unmarshaller = ListHsmsResponseUnmarshaller.Instance;
return InvokeAsync<ListHsmsRequest,ListHsmsResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region ListLunaClients
internal ListLunaClientsResponse ListLunaClients(ListLunaClientsRequest request)
{
var marshaller = new ListLunaClientsRequestMarshaller();
var unmarshaller = ListLunaClientsResponseUnmarshaller.Instance;
return Invoke<ListLunaClientsRequest,ListLunaClientsResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Lists all of the clients.
///
///
/// <para>
/// This operation supports pagination with the use of the <i>NextToken</i> member. If
/// more results are available, the <i>NextToken</i> member of the response contains a
/// token that you pass in the next call to <a>ListLunaClients</a> to retrieve the next
/// set of items.
/// </para>
/// </summary>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListLunaClients service method, as returned by CloudHSM.</returns>
/// <exception cref="Amazon.CloudHSM.Model.CloudHsmInternalException">
/// Indicates that an internal error occurred.
/// </exception>
/// <exception cref="Amazon.CloudHSM.Model.CloudHsmServiceException">
/// Indicates that an exception occurred in the AWS CloudHSM service.
/// </exception>
/// <exception cref="Amazon.CloudHSM.Model.InvalidRequestException">
/// Indicates that one or more of the request parameters are not valid.
/// </exception>
public Task<ListLunaClientsResponse> ListLunaClientsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var request = new ListLunaClientsRequest();
return ListLunaClientsAsync(request, cancellationToken);
}
/// <summary>
/// Initiates the asynchronous execution of the ListLunaClients operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListLunaClients operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<ListLunaClientsResponse> ListLunaClientsAsync(ListLunaClientsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new ListLunaClientsRequestMarshaller();
var unmarshaller = ListLunaClientsResponseUnmarshaller.Instance;
return InvokeAsync<ListLunaClientsRequest,ListLunaClientsResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region ModifyHapg
internal ModifyHapgResponse ModifyHapg(ModifyHapgRequest request)
{
var marshaller = new ModifyHapgRequestMarshaller();
var unmarshaller = ModifyHapgResponseUnmarshaller.Instance;
return Invoke<ModifyHapgRequest,ModifyHapgResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the ModifyHapg operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ModifyHapg operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<ModifyHapgResponse> ModifyHapgAsync(ModifyHapgRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new ModifyHapgRequestMarshaller();
var unmarshaller = ModifyHapgResponseUnmarshaller.Instance;
return InvokeAsync<ModifyHapgRequest,ModifyHapgResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region ModifyHsm
internal ModifyHsmResponse ModifyHsm(ModifyHsmRequest request)
{
var marshaller = new ModifyHsmRequestMarshaller();
var unmarshaller = ModifyHsmResponseUnmarshaller.Instance;
return Invoke<ModifyHsmRequest,ModifyHsmResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the ModifyHsm operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ModifyHsm operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<ModifyHsmResponse> ModifyHsmAsync(ModifyHsmRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new ModifyHsmRequestMarshaller();
var unmarshaller = ModifyHsmResponseUnmarshaller.Instance;
return InvokeAsync<ModifyHsmRequest,ModifyHsmResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region ModifyLunaClient
internal ModifyLunaClientResponse ModifyLunaClient(ModifyLunaClientRequest request)
{
var marshaller = new ModifyLunaClientRequestMarshaller();
var unmarshaller = ModifyLunaClientResponseUnmarshaller.Instance;
return Invoke<ModifyLunaClientRequest,ModifyLunaClientResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the ModifyLunaClient operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ModifyLunaClient operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<ModifyLunaClientResponse> ModifyLunaClientAsync(ModifyLunaClientRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new ModifyLunaClientRequestMarshaller();
var unmarshaller = ModifyLunaClientResponseUnmarshaller.Instance;
return InvokeAsync<ModifyLunaClientRequest,ModifyLunaClientResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
}
}
| |
// Copyright (c) 2015 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Threading;
using Alachisoft.NCache.Caching.AutoExpiration;
using Alachisoft.NCache.Caching.Statistics;
using Alachisoft.NCache.Storage;
using Alachisoft.NCache.Runtime.Exceptions;
using Alachisoft.NCache.Caching.EvictionPolicies;
using Alachisoft.NCache.Util;
using Alachisoft.NCache.Common.Monitoring;
using Alachisoft.NCache.Common.Net;
using Alachisoft.NCache.Common.Util;
using System.Net;
using Alachisoft.NCache.Caching.Queries;
namespace Alachisoft.NCache.Caching.Topologies.Local
{
/// <summary>
/// This class provides the local storage options i.e. the actual storage of objects. It is used
/// by the Cache Manager, replicated cache and partitioned cache.
/// </summary>
internal class LocalCache : LocalCacheBase
{
/// <summary> The underlying physical data store. </summary>
protected ICacheStorage _cacheStore;
/// <summary> The eviction policy for the cache. </summary>
protected IEvictionPolicy _evictionPolicy;
/// <summary> Thread which evicts item when cache is full.</summary>
private Thread _evictionThread;
private object _eviction_sync_mutex = new object();
/// <summary>Flag which indicates whether to explicitly call GC.Collect or not</summary>
private bool _allowExplicitGCCollection = true;
private bool _notifyCacheFull = false;
/// <summary>
/// Overloaded constructor. Takes the properties as a map.
/// </summary>
/// <param name="cacheSchemes">collection of cache schemes (config properties).</param>
/// <param name="properties">properties collection for this cache.</param>
/// <param name="listener">cache events listener</param>
/// <param name="timeSched">scheduler to use for periodic tasks</param>
public LocalCache(IDictionary cacheClasses, CacheBase parentCache, IDictionary properties, ICacheEventsListener listener, CacheRuntimeContext context)
: base(properties, parentCache, listener, context)
{
_stats.ClassName = "local-cache";
Initialize(cacheClasses, properties);
}
#region / --- IDisposable --- /
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or
/// resetting unmanaged resources.
/// </summary>
public override void Dispose()
{
if (_cacheStore != null)
{
_cacheStore.Dispose();
_cacheStore = null;
}
base.Dispose();
}
#endregion
/// <summary>
/// returns the number of objects contained in the cache.
/// </summary>
public override long Count
{
get
{
if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("LocalCache.Count", "");
if (_cacheStore == null)
throw new InvalidOperationException();
return _cacheStore.Count;
}
}
public override int ServersCount
{
get { return 1; }
}
public override bool IsServerNodeIp(Address clientAddress)
{
return false;
}
/// <summary>
/// Get the size of data in store, in bytes.
/// </summary>
internal override long Size
{
get
{
if (_cacheStore != null) return _cacheStore.Size;
return 0;
}
}
internal override float EvictRatio
{
get
{
if (_evictionPolicy != null) return _evictionPolicy.EvictRatio;
return 0;
}
set
{
if (_evictionPolicy != null)
{
_evictionPolicy.EvictRatio = value;
}
}
}
/// <summary>
/// Returns true if cache is started as backup mirror cache, false otherwise.
/// In Case of replica space will not be checked at storage level
/// </summary>
public override bool VirtualUnlimitedSpace
{
get
{
return this._cacheStore.VirtualUnlimitedSpace;
}
set
{
this._cacheStore.VirtualUnlimitedSpace = value;
}
}
internal override long MaxSize
{
get
{
if (_cacheStore != null) return _cacheStore.MaxSize;
return 0;
}
set
{
if (_cacheStore != null)
{
//if the cache has less data than the new maximum size.
//we can not apply the new size to the cache if the cache has already more data.
if (_cacheStore.Size <= value)
{
_cacheStore.MaxSize = value;
_stats.MaxSize = value;
}
else
{
throw new Exception("You need to remove some data from cache before applying the new size");
}
}
}
}
internal override bool CanChangeCacheSize(long size)
{
return (_cacheStore.Size <= size);
}
/// <summary>
/// Method that allows the object to initialize itself. Passes the property map down
/// the object hierarchy so that other objects may configure themselves as well..
/// </summary>
/// <param name="properties">configuration properties</param>
protected override void Initialize(IDictionary cacheClasses, IDictionary properties)
{
if (properties == null)
throw new ArgumentNullException("properties");
try
{
base.Initialize(cacheClasses, properties);
if (System.Configuration.ConfigurationSettings.AppSettings.Get("NCache.EnableGCCollection") != null)
{
_allowExplicitGCCollection = Convert.ToBoolean(System.Configuration.ConfigurationSettings.AppSettings.Get("NCache.EnableGCCollection"));
}
if (!properties.Contains("storage"))
throw new ConfigurationException("Missing configuration option 'storage'");
if (properties.Contains("scavenging-policy"))
{
IDictionary evictionProps = properties["scavenging-policy"] as IDictionary;
if (evictionProps != null && evictionProps.Contains("eviction-enabled"))
if (Convert.ToBoolean(evictionProps["eviction-enabled"]) && Convert.ToDouble(evictionProps["evict-ratio"]) > 0)
_evictionPolicy = EvictionPolicyFactory.CreateEvictionPolicy(evictionProps);
}
else
{
_evictionPolicy = EvictionPolicyFactory.CreateDefaultEvictionPolicy();
}
IDictionary storageProps = properties["storage"] as IDictionary;
_cacheStore = CacheStorageFactory.CreateStorageProvider(storageProps, this._context.SerializationContext, _evictionPolicy != null, _context.NCacheLog);
_stats.MaxCount = _cacheStore.MaxCount;
_stats.MaxSize = _cacheStore.MaxSize;
}
catch (ConfigurationException e)
{
if (_context != null)
{
_context.NCacheLog.Error("LocalCache.Initialize()", e.ToString());
}
Dispose();
throw;
}
catch (Exception e)
{
if (_context != null)
{
_context.NCacheLog.Error("LocalCache.Initialize()", e.ToString());
}
Dispose();
throw new ConfigurationException("Configuration Error: " + e.ToString(), e);
}
}
#region / --- LocalCacheBase --- /
/// <summary>
/// Removes all entries from the store.
/// </summary>
internal override void ClearInternal()
{
if (_cacheStore == null)
throw new InvalidOperationException();
_cacheStore.Clear();
_context.PerfStatsColl.SetCacheSize(0); // on clear cache cachesize set to zero
if (_evictionThread != null)
{
NCacheLog.Flush();
_evictionThread.Abort();
}
if (_evictionPolicy != null)
{
_evictionPolicy.Clear();
if (_context.PerfStatsColl != null)
{
_context.PerfStatsColl.SetEvictionIndexSize(_evictionPolicy.IndexInMemorySize);
}
}
}
/// <summary>
/// Determines whether the cache contains a specific key.
/// </summary>
/// <param name="key">The key to locate in the cache.</param>
/// <returns>true if the cache contains an element
/// with the specified key; otherwise, false.</returns>
internal override bool ContainsInternal(object key)
{
if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("LocalCache.Cont", "");
if (_cacheStore == null)
throw new InvalidOperationException();
return _cacheStore.Contains(key);
}
/// <summary>
/// Retrieve the object from the cache. A string key is passed as parameter.
/// </summary>
/// <param name="key">key of the entry.</param>
/// <returns>cache entry.</returns>
internal override CacheEntry GetInternal(object key, bool isUserOperation, OperationContext operationContext)
{
if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("LocalCache.Get", "");
if (_cacheStore == null)
throw new InvalidOperationException();
CacheEntry e = (CacheEntry)_cacheStore.Get(key);
if (e != null)
{
EvictionHint evh = e.EvictionHint;
if (isUserOperation && _evictionPolicy != null && evh != null && evh.IsVariant)
_evictionPolicy.Notify(key, evh, null);
}
return e;
}
/// <summary>
/// Special purpose internal method. Derived classes don't override this method.
/// </summary>
/// <param name="key"></param>
/// <param name="isUserOperation"></param>
/// <returns></returns>
internal override CacheEntry GetEntryInternal(object key, bool isUserOperation)
{
if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("LocalCache.GetInternal", "");
if (_cacheStore == null)
throw new InvalidOperationException();
CacheEntry e = (CacheEntry)_cacheStore.Get(key);
if (e == null) return e;
EvictionHint evh = e.EvictionHint;
if (isUserOperation && _evictionPolicy != null && evh != null && evh.IsVariant)
_evictionPolicy.Notify(key, evh, null);
return e;
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="eh"></param>
/// <returns></returns>
internal override bool AddInternal(object key, ExpirationHint eh, OperationContext operationContext)
{
if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("LocalCache.Add_2", "");
if (_cacheStore == null)
throw new InvalidOperationException();
CacheEntry e = (CacheEntry)_cacheStore.Get(key);
if (e == null) return false;
//We only allow either idle expiration or Fixed expiration both cannot be set at the same time
if ((e.ExpirationHint is IdleExpiration && eh is FixedExpiration)
|| (e.ExpirationHint is FixedExpiration && eh is IdleExpiration))
{
return false;
}
e.ExpirationHint = eh;
_cacheStore.Insert(key, e, true);
e.LastModifiedTime = System.DateTime.Now;
if (_context.PerfStatsColl != null)
{
if (_evictionPolicy != null)
_context.PerfStatsColl.SetEvictionIndexSize((long)_evictionPolicy.IndexInMemorySize);
if (_context.ExpiryMgr != null)
_context.PerfStatsColl.SetExpirationIndexSize((long)_context.ExpiryMgr.IndexInMemorySize);
}
return true;
}
/// <summary>
/// Get the item size stored in cache
/// </summary>
/// <param name="key">key</param>
/// <returns>item size</returns>
public override int GetItemSize(object key)
{
if (_cacheStore == null) return 0;
return _cacheStore.GetItemSize(key);
}
/// <summary>
/// Adds a pair of key and value to the cache. Throws an exception or reports error
/// if the specified key already exists in the cache.
/// </summary>
/// <param name="key">key of the entry.</param>
/// <param name="cacheEntry">the cache entry.</param>
/// <returns>returns the result of operation.</returns>
internal override CacheAddResult AddInternal(object key, CacheEntry cacheEntry, bool isUserOperation)
{
if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("LocalCache.Add_1", "");
if (_cacheStore == null)
throw new InvalidOperationException();
if (_evictionPolicy != null)
{
if (cacheEntry.EvictionHint is PriorityEvictionHint)
cacheEntry.Priority = ((PriorityEvictionHint)cacheEntry.EvictionHint).Priority;
cacheEntry.EvictionHint = _evictionPolicy.CompatibleHint(cacheEntry.EvictionHint);
}
//+ Numan@14102014: No Need to insert Eviction if Eviction is turned off it will reduce cache-entry overhead
if (_evictionPolicy == null)
cacheEntry.EvictionHint = null;
//+ Numan@14102014
StoreAddResult result = _cacheStore.Add(key, cacheEntry, !isUserOperation);
// Operation completed!
if (result == StoreAddResult.Success || result == StoreAddResult.SuccessNearEviction)
{
if (_evictionPolicy != null)
_evictionPolicy.Notify(key, null, cacheEntry.EvictionHint);
}
if (result == StoreAddResult.NotEnoughSpace && !_notifyCacheFull)
{
_notifyCacheFull = true;
_context.NCacheLog.Error("LocalCache.AddInternal", "The cache is full and not enough items could be evicted.");
}
if (_context.PerfStatsColl != null)
{
if (_evictionPolicy != null)
_context.PerfStatsColl.SetEvictionIndexSize((long)_evictionPolicy.IndexInMemorySize);
if (_context.ExpiryMgr != null)
_context.PerfStatsColl.SetExpirationIndexSize((long)_context.ExpiryMgr.IndexInMemorySize);
}
switch (result)
{
case StoreAddResult.Success: return CacheAddResult.Success;
case StoreAddResult.KeyExists: return CacheAddResult.KeyExists;
case StoreAddResult.NotEnoughSpace: return CacheAddResult.NeedsEviction;
case StoreAddResult.SuccessNearEviction: return CacheAddResult.SuccessNearEviction;
}
return CacheAddResult.Failure;
}
/// <summary>
/// Adds a pair of key and value to the cache. If the specified key already exists
/// in the cache; it is updated, otherwise a new item is added to the cache.
/// </summary>
/// <param name="key">key of the entry.</param>
/// <param name="cacheEntry">the cache entry.</param>
/// <returns>returns the result of operation.</returns>
internal override CacheInsResult InsertInternal(object key, CacheEntry cacheEntry, bool isUserOperation, CacheEntry oldEntry, OperationContext operationContext)
{
if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("LocalCache.Insert", "");
if (_cacheStore == null)
throw new InvalidOperationException();
if (cacheEntry.EvictionHint is PriorityEvictionHint)
cacheEntry.Priority = ((PriorityEvictionHint)cacheEntry.EvictionHint).Priority;
if (_evictionPolicy != null)
{
cacheEntry.EvictionHint = _evictionPolicy.CompatibleHint(cacheEntry.EvictionHint);
}
EvictionHint peEvh = oldEntry == null ? null : oldEntry.EvictionHint;
//+ Numan@14102014: No Need to insert Eviction if Eviction is turned off it will reduce cache-entry overhead
if (_evictionPolicy == null)
cacheEntry.EvictionHint = null;
//+ Numan@14102014
StoreInsResult result = _cacheStore.Insert(key, cacheEntry, !isUserOperation);
// Operation completed!
if (result == StoreInsResult.Success || result == StoreInsResult.SuccessNearEviction)
{
if (_evictionPolicy != null)
_evictionPolicy.Notify(key, null, cacheEntry.EvictionHint);
}
else if (result == StoreInsResult.SuccessOverwrite || result == StoreInsResult.SuccessOverwriteNearEviction)
{
//alam:
//update the cache item last modifeid time...
cacheEntry.UpdateLastModifiedTime(oldEntry);
if (_evictionPolicy != null)
_evictionPolicy.Notify(key, peEvh, cacheEntry.EvictionHint);
}
if (result == StoreInsResult.NotEnoughSpace && !_notifyCacheFull)
{
_notifyCacheFull = true;
_context.NCacheLog.Error("LocalCache.InsertInternal", "The cache is full and not enough items could be evicted.");
}
if (_context.PerfStatsColl != null)
{
if (_evictionPolicy != null)
_context.PerfStatsColl.SetEvictionIndexSize((long)_evictionPolicy.IndexInMemorySize);
if (_context.ExpiryMgr != null)
_context.PerfStatsColl.SetExpirationIndexSize((long)_context.ExpiryMgr.IndexInMemorySize);
}
switch (result)
{
case StoreInsResult.Success: return CacheInsResult.Success;
case StoreInsResult.SuccessOverwrite: return CacheInsResult.SuccessOverwrite;
case StoreInsResult.NotEnoughSpace: return CacheInsResult.NeedsEviction;
case StoreInsResult.SuccessNearEviction: return CacheInsResult.SuccessNearEvicition;
case StoreInsResult.SuccessOverwriteNearEviction: return CacheInsResult.SuccessOverwriteNearEviction;
}
return CacheInsResult.Failure;
}
/// <summary>
/// Removes the object and key pair from the cache. The key is specified as parameter.
/// Moreover it take a removal reason and a boolean specifying if a notification should
/// be raised.
/// </summary>
/// <param name="key">key of the entry.</param>
/// <param name="removalReason">reason for the removal.</param>
/// <param name="notify">boolean specifying to raise the event.</param>
/// <returns>item value</returns>
internal override CacheEntry RemoveInternal(object key, ItemRemoveReason removalReason, bool isUserOperation, OperationContext operationContext)
{
if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("LocalCache.Remove", "");
if (_cacheStore == null)
throw new InvalidOperationException();
CacheEntry e = (CacheEntry)_cacheStore.Remove(key);
if (e != null)
{
if (_evictionPolicy != null && e.EvictionHint!=null)
_evictionPolicy.Remove(key, e.EvictionHint);
if (_notifyCacheFull)
{
_notifyCacheFull = false;
}
}
if (_context.PerfStatsColl != null)
{
if (_evictionPolicy != null)
_context.PerfStatsColl.SetEvictionIndexSize((long)_evictionPolicy.IndexInMemorySize);
if (_context.ExpiryMgr != null)
_context.PerfStatsColl.SetExpirationIndexSize((long)_context.ExpiryMgr.IndexInMemorySize);
}
return e;
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="eh"></param>
/// <returns></returns>
internal override bool RemoveInternal(object key, ExpirationHint eh)
{
if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("LocalCache.Remove", "");
if (_cacheStore == null)
throw new InvalidOperationException();
CacheEntry e = (CacheEntry)_cacheStore.Get(key);
if (e == null || e.ExpirationHint == null)
{
return false;
}
else if (e.ExpirationHint.Equals(eh))
{
e.ExpirationHint = null;
}
//SAL: Our store may not be an in memory store
if (_notifyCacheFull)
{
_notifyCacheFull = false;
}
_cacheStore.Insert(key, e, true);
e.LastModifiedTime = System.DateTime.Now;
if (_context.PerfStatsColl != null)
{
if (_evictionPolicy != null)
_context.PerfStatsColl.SetEvictionIndexSize((long)_evictionPolicy.IndexInMemorySize);
if (_context.ExpiryMgr != null)
_context.PerfStatsColl.SetExpirationIndexSize((long)_context.ExpiryMgr.IndexInMemorySize);
}
return true;
}
#endregion
#region / --- ICache --- /
/// <summary>
/// Returns a .NET IEnumerator interface so that a client should be able
/// to iterate over the elements of the cache store.
/// </summary>
/// <returns>IDictionaryEnumerator enumerator.</returns>
public override IDictionaryEnumerator GetEnumerator()
{
if (_cacheStore == null)
throw new InvalidOperationException();
return _cacheStore.GetEnumerator();
}
public override Array Keys
{
get
{
if (_cacheStore == null)
throw new InvalidOperationException();
return _cacheStore.Keys;
}
}
#endregion
/// <summary>
/// Evicts items from the store.
/// </summary>
/// <returns></returns>
public override void Evict()
{
if (_evictionPolicy == null)
{
return;
}
lock (_eviction_sync_mutex)
{
if (_parentCache.IsEvictionAllowed)
{
if (_allowAsyncEviction)
{
if (_evictionThread == null)
{
_evictionThread = new Thread(new ThreadStart(EvictAysnc));
_evictionThread.IsBackground = true;
_evictionThread.Start();
}
}
else
{
DoEvict(this);
}
}
}
}
/// <summary>
/// Evicts the items from the cache.
/// </summary>
private void DoEvict(CacheBase cache)
{
try
{
if (_evictionPolicy != null)
{
_evictionPolicy.Execute(cache, _context, Size);
}
}
finally
{
}
}
/// <summary>
/// Called by async thread to evict the item from the store.
/// </summary>
private void EvictAysnc()
{
try
{
if (!IsSelfInternal)
DoEvict(_context.CacheImpl);
else
DoEvict(_context.CacheInternal);
}
catch (ThreadAbortException) { }
catch (ThreadInterruptedException) { }
catch (Exception e)
{
if (_context != null)
{
_context.NCacheLog.Error("LocalCache._evictionRun", e.ToString());
}
}
finally
{
lock (_eviction_sync_mutex)
{
_evictionThread = null;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using SimpleCompiler.Shared;
namespace SimpleCompiler.Compiler
{
public class SyntTree
{
public enum SyntTypeEnum
{
SYNT_INSTRUCTION_NULL,
SYNT_INSTRUCTION,
SYNT_RETURN,
SYNT_FUNCTIONS_LIST,
SYNT_INSTRUCTIONS_LIST,
SYNT_FUNCTION_DECLARATION,
SYNT_VARIABLE_DECLARATION,
SYNT_FUNCTION_CALL,
SYNT_SYMBOLS_TABLE,
SYNT_VARIABLE,
SYNT_IDENTIFIER,
SYNT_CONSTANT,
SYNT_CONVERSION,
SYNT_OP_COMPARISON_EQUAL,
SYNT_OP_COMPARISON_NOT_EQUAL,
SYNT_OP_ASSIGNATION,
SYNT_OP_ADDITION,
SYNT_OP_SUBTRACT,
SYNT_OP_MULTIPLICATION,
SYNT_OP_DIVISION,
SYNT_IF,
SYNT_FOR,
SYNT_WHILE,
SYNT_NONE
};
public SyntTypeEnum Type;
public Symbol ReturnType;
public Symbol FunctionDefinitionSymbol;
private List<SyntTree> childs;
public long Integer;
public float Float;
public string String;
public SymbolTable SymbolsTable;
public SyntTree()
{
String = "";
}
private void Clear()
{
SymbolsTable = null;
ReturnType = null;
FunctionDefinitionSymbol = null;
childs = null;
Integer = 0;
Float = 0.0f;
String = "";
}
public void AddChild(SyntTree node)
{
if (childs == null)
childs = new List<SyntTree>();
childs.Add(node);
}
public int GetChilds()
{
if (childs == null)
return 0;
return(childs.Count);
}
public SyntTree GetChild(int n)
{
return childs[n];
}
public void Print(int n)
{
int i;
for (i = 0; i < n; i++)
Console.Write(" ");
int childNumber = 0;
switch(Type)
{
case SyntTypeEnum.SYNT_INSTRUCTION:
Console.Write("Instruction: \n");
break;
case SyntTypeEnum.SYNT_RETURN:
Console.Write("Return: \n");
break;
case SyntTypeEnum.SYNT_FOR:
Console.Write("Instruction For:\n");
for (i = 0; i < n + 1; i++)
Console.Write(" ");
Console.Write("Initialization:\n");
GetChild(childNumber++).Print(n + 2);
for (i = 0; i < n + 1; i++)
Console.Write(" ");
Console.Write("Condition:\n");
GetChild(childNumber++).Print(n + 2);
for (i = 0; i < n + 1; i++)
Console.Write(" ");
Console.Write("Increment:\n");
GetChild(childNumber++).Print(n + 2);
for (i = 0; i < n + 1; i++)
Console.Write(" ");
Console.Write("Cycle:\n");
GetChild(childNumber++).Print(n + 2);
break;
case SyntTypeEnum.SYNT_WHILE:
Console.Write("Instruction While:\n");
for (i = 0; i < n + 1; i++)
Console.Write(" ");
Console.Write("Condition:\n");
GetChild(childNumber++).Print(n + 2);
for (i = 0; i < n + 1; i++)
Console.Write(" ");
Console.Write("Cycle:\n");
GetChild(childNumber++).Print(n + 2);
break;
case SyntTypeEnum.SYNT_IF:
Console.Write("Instruction If:\n");
for (i = 0; i < n + 1; i++)
Console.Write(" ");
Console.Write("Condition:\n");
GetChild(childNumber++).Print(n + 2);
for (i = 0; i < n + 1; i++)
Console.Write(" ");
Console.Write("If true:\n");
GetChild(childNumber++).Print(n + 2);
if (GetChilds() == 3)
{
for (i = 0; i < n + 1; i++)
Console.Write(" ");
Console.Write("If false:\n");
GetChild(childNumber++).Print(n + 2);
}
break;
case SyntTypeEnum.SYNT_INSTRUCTION_NULL:
Console.Write("Instruction null\n");
break;
case SyntTypeEnum.SYNT_FUNCTIONS_LIST:
Console.Write("Functions list:\n");
break;
case SyntTypeEnum.SYNT_INSTRUCTIONS_LIST:
Console.Write("Instructions list:\n");
break;
case SyntTypeEnum.SYNT_IDENTIFIER:
Console.Write("Identifier: {0}\n", String);
break;
case SyntTypeEnum.SYNT_VARIABLE:
Console.Write("Variable: {0}\n", String);
break;
case SyntTypeEnum.SYNT_CONSTANT:
Console.Write("Constant value ");
if (ReturnType.Name == DataType.NAME_INT)
Console.Write("(int) {0}\n", Integer);
else
if (ReturnType.Name == DataType.NAME_FLOAT)
Console.Write("(float) {0}\n", Float);
else
if (ReturnType.Name == DataType.NAME_STRING)
Console.Write("(string) {0}\n", String);
break;
case SyntTypeEnum.SYNT_OP_ASSIGNATION:
Console.Write ("Operator =\n");
break;
case SyntTypeEnum.SYNT_OP_ADDITION:
Console.Write ("Operator +\n");
break;
case SyntTypeEnum.SYNT_OP_SUBTRACT:
Console.Write ("Operator -\n");
break;
case SyntTypeEnum.SYNT_OP_MULTIPLICATION:
Console.Write ("Operator *\n");
break;
case SyntTypeEnum.SYNT_OP_DIVISION:
Console.Write ("Operador /\n");
break;
case SyntTypeEnum.SYNT_FUNCTION_CALL:
Console.Write("Function call: {0}\n", String);
break;
case SyntTypeEnum.SYNT_VARIABLE_DECLARATION:
Console.Write("Variable declaration of type {0}\n", String);
break;
case SyntTypeEnum.SYNT_FUNCTION_DECLARATION:
Console.Write("Function declaration: {0}\n", String);
break;
case SyntTypeEnum.SYNT_CONVERSION:
Console.Write("Conversion from {0} to {1}\n", GetChild(0).ReturnType.Name, ReturnType.Name);
break;
case SyntTypeEnum.SYNT_OP_COMPARISON_EQUAL:
Console.Write("Are equal:\n");
break;
case SyntTypeEnum.SYNT_OP_COMPARISON_NOT_EQUAL:
Console.Write("Are not equal:\n");
break;
case SyntTypeEnum.SYNT_SYMBOLS_TABLE:
Console.Write("Symbols table\n");
SymbolsTable.Print(n + 1);
break;
}
n++;
for (; childNumber < GetChilds(); childNumber++)
GetChild(childNumber).Print(n);
}
}
}
| |
// 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.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
#if INSIDE_CLR
using Debug = BCLDebug;
#endif
/*=================================JapaneseCalendar==========================
**
** JapaneseCalendar is based on Gregorian calendar. The month and day values are the same as
** Gregorian calendar. However, the year value is an offset to the Gregorian
** year based on the era.
**
** This system is adopted by Emperor Meiji in 1868. The year value is counted based on the reign of an emperor,
** and the era begins on the day an emperor ascends the throne and continues until his death.
** The era changes at 12:00AM.
**
** For example, the current era is Heisei. It started on 1989/1/8 A.D. Therefore, Gregorian year 1989 is also Heisei 1st.
** 1989/1/8 A.D. is also Heisei 1st 1/8.
**
** Any date in the year during which era is changed can be reckoned in either era. For example,
** 1989/1/1 can be 1/1 Heisei 1st year or 1/1 Showa 64th year.
**
** Note:
** The DateTime can be represented by the JapaneseCalendar are limited to two factors:
** 1. The min value and max value of DateTime class.
** 2. The available era information.
**
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 1868/09/08 9999/12/31
** Japanese Meiji 01/01 Heisei 8011/12/31
============================================================================*/
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public partial class JapaneseCalendar : Calendar
{
internal static readonly DateTime calendarMinValue = new DateTime(1868, 9, 8);
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
{
return (calendarMinValue);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
//
// Using a field initializer rather than a static constructor so that the whole class can be lazy
// init.
static internal volatile EraInfo[] japaneseEraInfo;
//
// Read our era info
//
// m_EraInfo must be listed in reverse chronological order. The most recent era
// should be the first element.
// That is, m_EraInfo[0] contains the most recent era.
//
// We know about 4 built-in eras, however users may add additional era(s) from the
// registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras
// we don't read the registry and instead we call WinRT to get the needed informatio
//
// Registry values look like:
// yyyy.mm.dd=era_abbrev_english_englishabbrev
//
// Where yyyy.mm.dd is the registry value name, and also the date of the era start.
// yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
// era is the Japanese Era name
// abbrev is the Abbreviated Japanese Era Name
// english is the English name for the Era (unused)
// englishabbrev is the Abbreviated English name for the era.
// . is a delimiter, but the value of . doesn't matter.
// '_' marks the space between the japanese era name, japanese abbreviated era name
// english name, and abbreviated english names.
//
internal static EraInfo[] GetEraInfo()
{
// See if we need to build it
if (japaneseEraInfo == null)
{
japaneseEraInfo = GetJapaneseEras();
// See if we have to use the built-in eras
if (japaneseEraInfo == null)
{
// We know about some built-in ranges
EraInfo[] defaultEraRanges = new EraInfo[4];
defaultEraRanges[0] = new EraInfo(4, 1989, 1, 8, 1988, 1, GregorianCalendar.MaxYear - 1988,
"\x5e73\x6210", "\x5e73", "H"); // era #4 start year/month/day, yearOffset, minEraYear
defaultEraRanges[1] = new EraInfo(3, 1926, 12, 25, 1925, 1, 1989 - 1925,
"\x662d\x548c", "\x662d", "S"); // era #3,start year/month/day, yearOffset, minEraYear
defaultEraRanges[2] = new EraInfo(2, 1912, 7, 30, 1911, 1, 1926 - 1911,
"\x5927\x6b63", "\x5927", "T"); // era #2,start year/month/day, yearOffset, minEraYear
defaultEraRanges[3] = new EraInfo(1, 1868, 1, 1, 1867, 1, 1912 - 1867,
"\x660e\x6cbb", "\x660e", "M"); // era #1,start year/month/day, yearOffset, minEraYear
// Remember the ranges we built
japaneseEraInfo = defaultEraRanges;
}
}
// return the era we found/made
return japaneseEraInfo;
}
internal static volatile Calendar s_defaultInstance;
internal GregorianCalendarHelper helper;
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of JapaneseCalendar. Used by NLS+ implementation
** and other calendars.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
internal static Calendar GetDefaultInstance()
{
if (s_defaultInstance == null)
{
s_defaultInstance = new JapaneseCalendar();
}
return (s_defaultInstance);
}
public JapaneseCalendar()
{
try
{
new CultureInfo("ja-JP");
}
catch (ArgumentException e)
{
throw new TypeInitializationException(this.GetType().ToString(), e);
}
helper = new GregorianCalendarHelper(this, GetEraInfo());
}
internal override CalendarId ID
{
get
{
return CalendarId.JAPAN;
}
}
public override DateTime AddMonths(DateTime time, int months)
{
return (helper.AddMonths(time, months));
}
public override DateTime AddYears(DateTime time, int years)
{
return (helper.AddYears(time, years));
}
/*=================================GetDaysInMonth==========================
**Action: Returns the number of days in the month given by the year and month arguments.
**Returns: The number of days in the given month.
**Arguments:
** year The year in Japanese calendar.
** month The month
** era The Japanese era value.
**Exceptions
** ArgumentException If month is less than 1 or greater * than 12.
============================================================================*/
public override int GetDaysInMonth(int year, int month, int era)
{
return (helper.GetDaysInMonth(year, month, era));
}
public override int GetDaysInYear(int year, int era)
{
return (helper.GetDaysInYear(year, era));
}
public override int GetDayOfMonth(DateTime time)
{
return (helper.GetDayOfMonth(time));
}
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return (helper.GetDayOfWeek(time));
}
public override int GetDayOfYear(DateTime time)
{
return (helper.GetDayOfYear(time));
}
public override int GetMonthsInYear(int year, int era)
{
return (helper.GetMonthsInYear(year, era));
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
return (helper.GetWeekOfYear(time, rule, firstDayOfWeek));
}
/*=================================GetEra==========================
**Action: Get the era value of the specified time.
**Returns: The era value for the specified time.
**Arguments:
** time the specified date time.
**Exceptions: ArgumentOutOfRangeException if time is out of the valid era ranges.
============================================================================*/
public override int GetEra(DateTime time)
{
return (helper.GetEra(time));
}
public override int GetMonth(DateTime time)
{
return (helper.GetMonth(time));
}
public override int GetYear(DateTime time)
{
return (helper.GetYear(time));
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
return (helper.IsLeapDay(year, month, day, era));
}
public override bool IsLeapYear(int year, int era)
{
return (helper.IsLeapYear(year, era));
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetLeapMonth(int year, int era)
{
return (helper.GetLeapMonth(year, era));
}
public override bool IsLeapMonth(int year, int month, int era)
{
return (helper.IsLeapMonth(year, month, era));
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era));
}
// For Japanese calendar, four digit year is not used. Few emperors will live for more than one hundred years.
// Therefore, for any two digit number, we just return the original number.
public override int ToFourDigitYear(int year)
{
if (year <= 0)
{
throw new ArgumentOutOfRangeException("year",
SR.ArgumentOutOfRange_NeedPosNum);
}
Contract.EndContractBlock();
if (year > helper.MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
helper.MaxYear));
}
return (year);
}
public override int[] Eras
{
get
{
return (helper.Eras);
}
}
//
// Return the various era strings
// Note: The arrays are backwards of the eras
//
internal static String[] EraNames()
{
EraInfo[] eras = GetEraInfo();
String[] eraNames = new String[eras.Length];
for (int i = 0; i < eras.Length; i++)
{
// Strings are in chronological order, eras are backwards order.
eraNames[i] = eras[eras.Length - i - 1].eraName;
}
return eraNames;
}
internal static String[] AbbrevEraNames()
{
EraInfo[] eras = GetEraInfo();
String[] erasAbbrev = new String[eras.Length];
for (int i = 0; i < eras.Length; i++)
{
// Strings are in chronological order, eras are backwards order.
erasAbbrev[i] = eras[eras.Length - i - 1].abbrevEraName;
}
return erasAbbrev;
}
internal static String[] EnglishEraNames()
{
EraInfo[] eras = GetEraInfo();
String[] erasEnglish = new String[eras.Length];
for (int i = 0; i < eras.Length; i++)
{
// Strings are in chronological order, eras are backwards order.
erasEnglish[i] = eras[eras.Length - i - 1].englishEraName;
}
return erasEnglish;
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 99;
internal override bool IsValidYear(int year, int era)
{
return helper.IsValidYear(year, era);
}
public override int TwoDigitYearMax
{
get
{
if (twoDigitYearMax == -1)
{
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > helper.MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
99,
helper.MaxYear));
}
twoDigitYearMax = value;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
namespace System.Security
{
// DynamicSecurityMethodAttribute:
// Indicates that calling the target method requires space for a security
// object to be allocated on the callers stack. This attribute is only ever
// set on certain security methods defined within mscorlib.
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false )]
sealed internal class DynamicSecurityMethodAttribute : System.Attribute
{
}
// SuppressUnmanagedCodeSecurityAttribute:
// Indicates that the target P/Invoke method(s) should skip the per-call
// security checked for unmanaged code permission.
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = true, Inherited = false )]
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class SuppressUnmanagedCodeSecurityAttribute : System.Attribute
{
}
// UnverifiableCodeAttribute:
// Indicates that the target module contains unverifiable code.
[AttributeUsage(AttributeTargets.Module, AllowMultiple = true, Inherited = false )]
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class UnverifiableCodeAttribute : System.Attribute
{
}
// AllowPartiallyTrustedCallersAttribute:
// Indicates that the Assembly is secure and can be used by untrusted
// and semitrusted clients
// For v.1, this is valid only on Assemblies, but could be expanded to
// include Module, Method, class
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false )]
[System.Runtime.InteropServices.ComVisible(true)]
sealed public class AllowPartiallyTrustedCallersAttribute : System.Attribute
{
private PartialTrustVisibilityLevel _visibilityLevel;
public AllowPartiallyTrustedCallersAttribute () { }
public PartialTrustVisibilityLevel PartialTrustVisibilityLevel
{
get { return _visibilityLevel; }
set { _visibilityLevel = value; }
}
}
public enum PartialTrustVisibilityLevel
{
VisibleToAllHosts = 0,
NotVisibleByDefault = 1
}
[Obsolete("SecurityCriticalScope is only used for .NET 2.0 transparency compatibility.")]
public enum SecurityCriticalScope
{
Explicit = 0,
Everything = 0x1
}
// SecurityCriticalAttribute
// Indicates that the decorated code or assembly performs security critical operations (e.g. Assert, "unsafe", LinkDemand, etc.)
// The attribute can be placed on most targets, except on arguments/return values.
[AttributeUsage(AttributeTargets.Assembly |
AttributeTargets.Class |
AttributeTargets.Struct |
AttributeTargets.Enum |
AttributeTargets.Constructor |
AttributeTargets.Method |
AttributeTargets.Field |
AttributeTargets.Interface |
AttributeTargets.Delegate,
AllowMultiple = false,
Inherited = false )]
sealed public class SecurityCriticalAttribute : System.Attribute
{
#pragma warning disable 618 // We still use SecurityCriticalScope for v2 compat
private SecurityCriticalScope _val;
public SecurityCriticalAttribute () {}
public SecurityCriticalAttribute(SecurityCriticalScope scope)
{
_val = scope;
}
[Obsolete("SecurityCriticalScope is only used for .NET 2.0 transparency compatibility.")]
public SecurityCriticalScope Scope {
get {
return _val;
}
}
#pragma warning restore 618
}
// SecurityTreatAsSafeAttribute:
// Indicates that the code may contain violations to the security critical rules (e.g. transitions from
// critical to non-public transparent, transparent to non-public critical, etc.), has been audited for
// security concerns and is considered security clean.
// At assembly-scope, all rule checks will be suppressed within the assembly and for calls made against the assembly.
// At type-scope, all rule checks will be suppressed for members within the type and for calls made against the type.
// At member level (e.g. field and method) the code will be treated as public - i.e. no rule checks for the members.
[AttributeUsage(AttributeTargets.Assembly |
AttributeTargets.Class |
AttributeTargets.Struct |
AttributeTargets.Enum |
AttributeTargets.Constructor |
AttributeTargets.Method |
AttributeTargets.Field |
AttributeTargets.Interface |
AttributeTargets.Delegate,
AllowMultiple = false,
Inherited = false )]
[Obsolete("SecurityTreatAsSafe is only used for .NET 2.0 transparency compatibility. Please use the SecuritySafeCriticalAttribute instead.")]
sealed public class SecurityTreatAsSafeAttribute : System.Attribute
{
public SecurityTreatAsSafeAttribute () { }
}
// SecuritySafeCriticalAttribute:
// Indicates that the code may contain violations to the security critical rules (e.g. transitions from
// critical to non-public transparent, transparent to non-public critical, etc.), has been audited for
// security concerns and is considered security clean. Also indicates that the code is considered SecurityCritical.
// The effect of this attribute is as if the code was marked [SecurityCritical][SecurityTreatAsSafe].
// At assembly-scope, all rule checks will be suppressed within the assembly and for calls made against the assembly.
// At type-scope, all rule checks will be suppressed for members within the type and for calls made against the type.
// At member level (e.g. field and method) the code will be treated as public - i.e. no rule checks for the members.
[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Struct |
AttributeTargets.Enum |
AttributeTargets.Constructor |
AttributeTargets.Method |
AttributeTargets.Field |
AttributeTargets.Interface |
AttributeTargets.Delegate,
AllowMultiple = false,
Inherited = false )]
sealed public class SecuritySafeCriticalAttribute : System.Attribute
{
public SecuritySafeCriticalAttribute () { }
}
// SecurityTransparentAttribute:
// Indicates the assembly contains only transparent code.
// Security critical actions will be restricted or converted into less critical actions. For example,
// Assert will be restricted, SuppressUnmanagedCode, LinkDemand, unsafe, and unverifiable code will be converted
// into Full-Demands.
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false )]
sealed public class SecurityTransparentAttribute : System.Attribute
{
public SecurityTransparentAttribute () {}
}
public enum SecurityRuleSet : byte
{
None = 0,
Level1 = 1, // v2.0 transparency model
Level2 = 2, // v4.0 transparency model
}
// SecurityRulesAttribute
//
// Indicates which set of security rules an assembly was authored against, and therefore which set of
// rules the runtime should enforce on the assembly. For instance, an assembly marked with
// [SecurityRules(SecurityRuleSet.Level1)] will follow the v2.0 transparency rules, where transparent code
// can call a LinkDemand by converting it to a full demand, public critical methods are implicitly
// treat as safe, and the remainder of the v2.0 rules apply.
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class SecurityRulesAttribute : Attribute
{
private SecurityRuleSet m_ruleSet;
private bool m_skipVerificationInFullTrust = false;
public SecurityRulesAttribute(SecurityRuleSet ruleSet)
{
m_ruleSet = ruleSet;
}
// Should fully trusted transparent code skip IL verification
public bool SkipVerificationInFullTrust
{
get { return m_skipVerificationInFullTrust; }
set { m_skipVerificationInFullTrust = value; }
}
public SecurityRuleSet RuleSet
{
get { return m_ruleSet; }
}
}
}
| |
// 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.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace System.IO
{
// This class implements a TextWriter for writing characters to a Stream.
// This is designed for character output in a particular Encoding,
// whereas the Stream class is designed for byte input and output.
//
public class StreamWriter : TextWriter
{
// For UTF-8, the values of 1K for the default buffer size and 4K for the
// file stream buffer size are reasonable & give very reasonable
// performance for in terms of construction time for the StreamWriter and
// write perf. Note that for UTF-8, we end up allocating a 4K byte buffer,
// which means we take advantage of adaptive buffering code.
// The performance using UnicodeEncoding is acceptable.
internal const int DefaultBufferSize = 1024; // char[]
private const int DefaultFileStreamBufferSize = 4096;
private const int MinBufferSize = 128;
private const int DontCopyOnWriteLineThreshold = 512;
// Bit bucket - Null has no backing store. Non closable.
public new static readonly StreamWriter Null = new StreamWriter(Stream.Null, new UTF8Encoding(false, true), MinBufferSize, true);
private Stream _stream;
private Encoding _encoding;
private Encoder _encoder;
private byte[] _byteBuffer;
private char[] _charBuffer;
private int _charPos;
private int _charLen;
private bool _autoFlush;
private bool _haveWrittenPreamble;
private bool _closable;
// We don't guarantee thread safety on StreamWriter, but we should at
// least prevent users from trying to write anything while an Async
// write from the same thread is in progress.
private volatile Task _asyncWriteTask;
private void CheckAsyncTaskInProgress()
{
// We are not locking the access to _asyncWriteTask because this is not meant to guarantee thread safety.
// We are simply trying to deter calling any Write APIs while an async Write from the same thread is in progress.
Task t = _asyncWriteTask;
if (t != null && !t.IsCompleted)
throw new InvalidOperationException(SR.InvalidOperation_AsyncIOInProgress);
}
// The high level goal is to be tolerant of encoding errors when we read and very strict
// when we write. Hence, default StreamWriter encoding will throw on encoding error.
// Note: when StreamWriter throws on invalid encoding chars (for ex, high surrogate character
// D800-DBFF without a following low surrogate character DC00-DFFF), it will cause the
// internal StreamWriter's state to be irrecoverable as it would have buffered the
// illegal chars and any subsequent call to Flush() would hit the encoding error again.
// Even Close() will hit the exception as it would try to flush the unwritten data.
// Maybe we can add a DiscardBufferedData() method to get out of such situation (like
// StreamReader though for different reason). Either way, the buffered data will be lost!
private static volatile Encoding s_utf8NoBOM;
internal static Encoding UTF8NoBOM
{
//[FriendAccessAllowed]
get
{
if (s_utf8NoBOM == null)
{
// No need for double lock - we just want to avoid extra
// allocations in the common case.
s_utf8NoBOM = new UTF8Encoding(false, true);
}
return s_utf8NoBOM;
}
}
internal StreamWriter() : base(null)
{ // Ask for CurrentCulture all the time
}
public StreamWriter(Stream stream)
: this(stream, UTF8NoBOM, DefaultBufferSize, false)
{
}
public StreamWriter(Stream stream, Encoding encoding)
: this(stream, encoding, DefaultBufferSize, false)
{
}
// Creates a new StreamWriter for the given stream. The
// character encoding is set by encoding and the buffer size,
// in number of 16-bit characters, is set by bufferSize.
//
public StreamWriter(Stream stream, Encoding encoding, int bufferSize)
: this(stream, encoding, bufferSize, false)
{
}
public StreamWriter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen)
: base(null) // Ask for CurrentCulture all the time
{
if (stream == null || encoding == null)
{
throw new ArgumentNullException((stream == null ? "stream" : "encoding"));
}
if (!stream.CanWrite)
{
throw new ArgumentException(SR.Argument_StreamNotWritable);
}
if (bufferSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum);
}
Init(stream, encoding, bufferSize, leaveOpen);
}
private void Init(Stream streamArg, Encoding encodingArg, int bufferSize, bool shouldLeaveOpen)
{
_stream = streamArg;
_encoding = encodingArg;
_encoder = _encoding.GetEncoder();
if (bufferSize < MinBufferSize)
{
bufferSize = MinBufferSize;
}
_charBuffer = new char[bufferSize];
_byteBuffer = new byte[_encoding.GetMaxByteCount(bufferSize)];
_charLen = bufferSize;
// If we're appending to a Stream that already has data, don't write
// the preamble.
if (_stream.CanSeek && _stream.Position > 0)
{
_haveWrittenPreamble = true;
}
_closable = !shouldLeaveOpen;
}
protected override void Dispose(bool disposing)
{
try
{
// We need to flush any buffered data if we are being closed/disposed.
// Also, we never close the handles for stdout & friends. So we can safely
// write any buffered data to those streams even during finalization, which
// is generally the right thing to do.
if (_stream != null)
{
// Note: flush on the underlying stream can throw (ex., low disk space)
if (disposing /* || (LeaveOpen && stream is __ConsoleStream) */)
{
CheckAsyncTaskInProgress();
Flush(true, true);
}
}
}
finally
{
// Dispose of our resources if this StreamWriter is closable.
// Note: Console.Out and other such non closable streamwriters should be left alone
if (!LeaveOpen && _stream != null)
{
try
{
// Attempt to close the stream even if there was an IO error from Flushing.
// Note that Stream.Close() can potentially throw here (may or may not be
// due to the same Flush error). In this case, we still need to ensure
// cleaning up internal resources, hence the finally block.
if (disposing)
{
_stream.Dispose();
}
}
finally
{
_stream = null;
_byteBuffer = null;
_charBuffer = null;
_encoding = null;
_encoder = null;
_charLen = 0;
base.Dispose(disposing);
}
}
}
}
public override void Flush()
{
CheckAsyncTaskInProgress();
Flush(true, true);
}
private void Flush(bool flushStream, bool flushEncoder)
{
// flushEncoder should be true at the end of the file and if
// the user explicitly calls Flush (though not if AutoFlush is true).
// This is required to flush any dangling characters from our UTF-7
// and UTF-8 encoders.
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
// Perf boost for Flush on non-dirty writers.
if (_charPos == 0 && !flushStream && !flushEncoder)
{
return;
}
if (!_haveWrittenPreamble)
{
_haveWrittenPreamble = true;
byte[] preamble = _encoding.GetPreamble();
if (preamble.Length > 0)
{
_stream.Write(preamble, 0, preamble.Length);
}
}
int count = _encoder.GetBytes(_charBuffer, 0, _charPos, _byteBuffer, 0, flushEncoder);
_charPos = 0;
if (count > 0)
{
_stream.Write(_byteBuffer, 0, count);
}
// By definition, calling Flush should flush the stream, but this is
// only necessary if we passed in true for flushStream. The Web
// Services guys have some perf tests where flushing needlessly hurts.
if (flushStream)
{
_stream.Flush();
}
}
public virtual bool AutoFlush
{
get { return _autoFlush; }
set
{
CheckAsyncTaskInProgress();
_autoFlush = value;
if (value)
{
Flush(true, false);
}
}
}
public virtual Stream BaseStream
{
get { return _stream; }
}
internal bool LeaveOpen
{
get { return !_closable; }
}
internal bool HaveWrittenPreamble
{
set { _haveWrittenPreamble = value; }
}
public override Encoding Encoding
{
get { return _encoding; }
}
public override void Write(char value)
{
CheckAsyncTaskInProgress();
if (_charPos == _charLen)
{
Flush(false, false);
}
_charBuffer[_charPos] = value;
_charPos++;
if (_autoFlush)
{
Flush(true, false);
}
}
public override void Write(char[] buffer)
{
// This may be faster than the one with the index & count since it
// has to do less argument checking.
if (buffer == null)
{
return;
}
CheckAsyncTaskInProgress();
int index = 0;
int count = buffer.Length;
while (count > 0)
{
if (_charPos == _charLen)
{
Flush(false, false);
}
int n = _charLen - _charPos;
if (n > count)
{
n = count;
}
Debug.Assert(n > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a race in user code.");
Buffer.BlockCopy(buffer, index * sizeof(char), _charBuffer, _charPos * sizeof(char), n * sizeof(char));
_charPos += n;
index += n;
count -= n;
}
if (_autoFlush)
{
Flush(true, false);
}
}
public override void Write(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
CheckAsyncTaskInProgress();
while (count > 0)
{
if (_charPos == _charLen)
{
Flush(false, false);
}
int n = _charLen - _charPos;
if (n > count)
{
n = count;
}
Debug.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
Buffer.BlockCopy(buffer, index * sizeof(char), _charBuffer, _charPos * sizeof(char), n * sizeof(char));
_charPos += n;
index += n;
count -= n;
}
if (_autoFlush)
{
Flush(true, false);
}
}
public override void Write(string value)
{
if (value != null)
{
CheckAsyncTaskInProgress();
int count = value.Length;
int index = 0;
while (count > 0)
{
if (_charPos == _charLen)
{
Flush(false, false);
}
int n = _charLen - _charPos;
if (n > count)
{
n = count;
}
Debug.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code.");
value.CopyTo(index, _charBuffer, _charPos, n);
_charPos += n;
index += n;
count -= n;
}
if (_autoFlush)
{
Flush(true, false);
}
}
}
#region Task based Async APIs
public override Task WriteAsync(char value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (GetType() != typeof(StreamWriter))
{
return base.WriteAsync(value);
}
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false);
_asyncWriteTask = task;
return task;
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
// Fields that are written to must be assigned at the end of the method *and* before instance invocations.
private static async Task WriteAsyncInternal(StreamWriter _this, char value,
char[] charBuffer, int charPos, int charLen, char[] coreNewLine,
bool autoFlush, bool appendNewLine)
{
if (charPos == charLen)
{
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Debug.Assert(_this._charPos == 0);
charPos = 0;
}
charBuffer[charPos] = value;
charPos++;
if (appendNewLine)
{
for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
{
if (charPos == charLen)
{
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Debug.Assert(_this._charPos == 0);
charPos = 0;
}
charBuffer[charPos] = coreNewLine[i];
charPos++;
}
}
if (autoFlush)
{
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
Debug.Assert(_this._charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
public override Task WriteAsync(string value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (GetType() != typeof(StreamWriter))
{
return base.WriteAsync(value);
}
if (value != null)
{
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false);
_asyncWriteTask = task;
return task;
}
else
{
return MakeCompletedTask();
}
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
// Fields that are written to must be assigned at the end of the method *and* before instance invocations.
private static async Task WriteAsyncInternal(StreamWriter _this, string value,
char[] charBuffer, int charPos, int charLen, char[] coreNewLine,
bool autoFlush, bool appendNewLine)
{
Debug.Assert(value != null);
int count = value.Length;
int index = 0;
while (count > 0)
{
if (charPos == charLen)
{
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Debug.Assert(_this._charPos == 0);
charPos = 0;
}
int n = charLen - charPos;
if (n > count)
{
n = count;
}
Debug.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code.");
value.CopyTo(index, charBuffer, charPos, n);
charPos += n;
index += n;
count -= n;
}
if (appendNewLine)
{
for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
{
if (charPos == charLen)
{
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Debug.Assert(_this._charPos == 0);
charPos = 0;
}
charBuffer[charPos] = coreNewLine[i];
charPos++;
}
}
if (autoFlush)
{
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
Debug.Assert(_this._charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
public override Task WriteAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (GetType() != typeof(StreamWriter))
{
return base.WriteAsync(buffer, index, count);
}
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, buffer, index, count, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false);
_asyncWriteTask = task;
return task;
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
// Fields that are written to must be assigned at the end of the method *and* before instance invocations.
private static async Task WriteAsyncInternal(StreamWriter _this, char[] buffer, int index, int count,
char[] charBuffer, int charPos, int charLen, char[] coreNewLine,
bool autoFlush, bool appendNewLine)
{
Debug.Assert(count == 0 || (count > 0 && buffer != null));
Debug.Assert(index >= 0);
Debug.Assert(count >= 0);
Debug.Assert(buffer == null || (buffer != null && buffer.Length - index >= count));
while (count > 0)
{
if (charPos == charLen)
{
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Debug.Assert(_this._charPos == 0);
charPos = 0;
}
int n = charLen - charPos;
if (n > count)
{
n = count;
}
Debug.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
Buffer.BlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
charPos += n;
index += n;
count -= n;
}
if (appendNewLine)
{
for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
{
if (charPos == charLen)
{
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Debug.Assert(_this._charPos == 0);
charPos = 0;
}
charBuffer[charPos] = coreNewLine[i];
charPos++;
}
}
if (autoFlush)
{
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
Debug.Assert(_this._charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
public override Task WriteLineAsync()
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (GetType() != typeof(StreamWriter))
{
return base.WriteLineAsync();
}
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, null, 0, 0, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
public override Task WriteLineAsync(char value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (GetType() != typeof(StreamWriter))
{
return base.WriteLineAsync(value);
}
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
public override Task WriteLineAsync(string value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (GetType() != typeof(StreamWriter))
{
return base.WriteLineAsync(value);
}
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
public override Task WriteLineAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (GetType() != typeof(StreamWriter))
{
return base.WriteLineAsync(buffer, index, count);
}
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, buffer, index, count, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
public override Task FlushAsync()
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Flush() which a subclass might have overridden. To be safe
// we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Flush) when we are not sure.
if (GetType() != typeof(StreamWriter))
{
return base.FlushAsync();
}
// flushEncoder should be true at the end of the file and if
// the user explicitly calls Flush (though not if AutoFlush is true).
// This is required to flush any dangling characters from our UTF-7
// and UTF-8 encoders.
if (_stream == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed);
}
CheckAsyncTaskInProgress();
Task task = FlushAsyncInternal(true, true, _charBuffer, _charPos);
_asyncWriteTask = task;
return task;
}
private int CharPos_Prop
{
set { _charPos = value; }
}
private bool HaveWrittenPreamble_Prop
{
set { _haveWrittenPreamble = value; }
}
#pragma warning disable 1998 // async method with no await
private async Task MakeCompletedTask()
{
// do nothing. We're taking advantage of the async infrastructure's optimizations, one of which is to
// return a cached already-completed Task when possible.
}
#pragma warning restore 1998
private Task FlushAsyncInternal(bool flushStream, bool flushEncoder,
char[] sCharBuffer, int sCharPos)
{
// Perf boost for Flush on non-dirty writers.
if (sCharPos == 0 && !flushStream && !flushEncoder)
{
return MakeCompletedTask();
}
Task flushTask = FlushAsyncInternal(this, flushStream, flushEncoder, sCharBuffer, sCharPos, _haveWrittenPreamble,
_encoding, _encoder, _byteBuffer, _stream);
_charPos = 0;
return flushTask;
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
private static async Task FlushAsyncInternal(StreamWriter _this, bool flushStream, bool flushEncoder,
char[] charBuffer, int charPos, bool haveWrittenPreamble,
Encoding encoding, Encoder encoder, Byte[] byteBuffer, Stream stream)
{
if (!haveWrittenPreamble)
{
_this.HaveWrittenPreamble_Prop = true;
byte[] preamble = encoding.GetPreamble();
if (preamble.Length > 0)
{
await stream.WriteAsync(preamble, 0, preamble.Length).ConfigureAwait(false);
}
}
int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder);
if (count > 0)
{
await stream.WriteAsync(byteBuffer, 0, count).ConfigureAwait(false);
}
// By definition, calling Flush should flush the stream, but this is
// only necessary if we passed in true for flushStream. The Web
// Services guys have some perf tests where flushing needlessly hurts.
if (flushStream)
{
await stream.FlushAsync().ConfigureAwait(false);
}
}
#endregion
} // class StreamWriter
} // namespace
| |
namespace Cik.PP.Web.Areas.HelpPage.SampleGeneration
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
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 this.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 this.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](++this._index);
}
}
}
}
| |
// 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.Linq;
using Xunit;
namespace Test
{
public class SkipSkipWhileTests
{
//
// Skip
//
public static IEnumerable<object[]> SkipUnorderedData(int[] counts)
{
Func<int, IEnumerable<int>> skip = x => new[] { -x, -1, 0, 1, x / 2, x, x * 2 }.Distinct();
foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), skip)) yield return results;
}
public static IEnumerable<object[]> SkipData(int[] counts)
{
Func<int, IEnumerable<int>> skip = x => new[] { -x, -1, 0, 1, x / 2, x, x * 2 }.Distinct();
foreach (object[] results in Sources.Ranges(counts.Cast<int>(), skip)) yield return results;
}
[Theory]
[MemberData("SkipUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Skip_Unordered(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
// For unordered collections, which elements are skipped isn't actually guaranteed, but an effect of the implementation.
// If this test starts failing it should be updated, and possibly mentioned in release notes.
IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip)));
foreach (int i in query.Skip(skip))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("SkipUnorderedData", (object)(new int[] { 1024 * 32 }))]
public static void Skip_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
Skip_Unordered(labeled, count, skip);
}
[Theory]
[MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Skip(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
int seen = Math.Max(0, skip);
foreach (int i in query.Skip(skip))
{
Assert.Equal(seen++, i);
}
Assert.Equal(Math.Max(skip, count), seen);
}
[Theory]
[OuterLoop]
[MemberData("SkipData", (object)(new int[] { 1024 * 32 }))]
public static void Skip_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
Skip(labeled, count, skip);
}
[Theory]
[MemberData("SkipUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Skip_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
// For unordered collections, which elements are skipped isn't actually guaranteed, but an effect of the implementation.
// If this test starts failing it should be updated, and possibly mentioned in release notes.
IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip)));
Assert.All(query.Skip(skip).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("SkipUnorderedData", (object)(new int[] { 1024 * 32 }))]
public static void Skip_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
Skip_Unordered_NotPipelined(labeled, count, skip);
}
[Theory]
[MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Skip_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
int seen = Math.Max(0, skip);
Assert.All(query.Skip(skip).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(Math.Max(skip, count), seen);
}
[Theory]
[OuterLoop]
[MemberData("SkipData", (object)(new int[] { 1024 * 32 }))]
public static void Skip_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
Skip_NotPipelined(labeled, count, skip);
}
[Fact]
public static void Skip_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).Skip(0));
}
//
// SkipWhile
//
public static IEnumerable<object[]> SkipWhileData(int[] counts)
{
foreach (object[] results in Sources.Ranges(counts.Cast<int>()))
{
yield return new[] { results[0], results[1], new[] { 0 } };
yield return new[] { results[0], results[1], Enumerable.Range((int)results[1] / 2, ((int)results[1] - 1) / 2 + 1) };
yield return new[] { results[0], results[1], new[] { (int)results[1] - 1 } };
}
}
[Theory]
[MemberData("SkipUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void SkipWhile_Unordered(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
// For unordered collections, which elements (if any) are skipped isn't actually guaranteed, but an effect of the implementation.
// If this test starts failing it should be updated, and possibly mentioned in release notes.
IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip)));
foreach (int i in query.SkipWhile(x => x < skip))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("SkipUnorderedData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
SkipWhile_Unordered(labeled, count, skip);
}
[Theory]
[MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void SkipWhile(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
int seen = Math.Max(0, skip);
foreach (int i in query.SkipWhile(x => x < skip))
{
Assert.Equal(seen++, i);
}
Assert.Equal(Math.Max(skip, count), seen);
}
[Theory]
[OuterLoop]
[MemberData("SkipData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
SkipWhile(labeled, count, skip);
}
[Theory]
[MemberData("SkipUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void SkipWhile_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
// For unordered collections, which elements (if any) are skipped isn't actually guaranteed, but an effect of the implementation.
// If this test starts failing it should be updated, and possibly mentioned in release notes.
IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip)));
Assert.All(query.SkipWhile(x => x < skip).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("SkipUnorderedData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
SkipWhile_Unordered_NotPipelined(labeled, count, skip);
}
[Theory]
[MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void SkipWhile_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
int seen = Math.Max(0, skip);
Assert.All(query.SkipWhile(x => x < skip).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(Math.Max(skip, count), seen);
}
[Theory]
[OuterLoop]
[MemberData("SkipData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
SkipWhile_NotPipelined(labeled, count, skip);
}
[Theory]
[MemberData("SkipUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void SkipWhile_Indexed_Unordered(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
// For unordered collections, which elements (if any) are skipped isn't actually guaranteed, but an effect of the implementation.
// If this test starts failing it should be updated, and possibly mentioned in release notes.
IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip)));
foreach (int i in query.SkipWhile((x, index) => index < skip))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("SkipUnorderedData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_Indexed_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
SkipWhile_Indexed_Unordered(labeled, count, skip);
}
[Theory]
[MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void SkipWhile_Indexed(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
int seen = Math.Max(0, skip);
foreach (int i in query.SkipWhile((x, index) => index < skip))
{
Assert.Equal(seen++, i);
}
Assert.Equal(Math.Max(skip, count), seen);
}
[Theory]
[OuterLoop]
[MemberData("SkipData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_Indexed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
SkipWhile_Indexed(labeled, count, skip);
}
[Theory]
[MemberData("SkipUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void SkipWhile_Indexed_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
// For unordered collections, which elements (if any) are skipped isn't actually guaranteed, but an effect of the implementation.
// If this test starts failing it should be updated, and possibly mentioned in release notes.
IntegerRangeSet seen = new IntegerRangeSet(Math.Max(skip, 0), Math.Min(count, Math.Max(0, count - skip)));
Assert.All(query.SkipWhile((x, index) => index < skip), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("SkipUnorderedData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_Indexed_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
SkipWhile_Indexed_Unordered_NotPipelined(labeled, count, skip);
}
[Theory]
[MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void SkipWhile_Indexed_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
int seen = Math.Max(0, skip);
Assert.All(query.SkipWhile((x, index) => index < skip), x => Assert.Equal(seen++, x));
Assert.Equal(Math.Max(skip, count), seen);
}
[Theory]
[OuterLoop]
[MemberData("SkipData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_Indexed_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
SkipWhile_Indexed_NotPipelined(labeled, count, skip);
}
[Theory]
[MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void SkipWhile_AllFalse(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
Assert.All(query.SkipWhile(x => false), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData("SkipData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_AllFalse_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
SkipWhile_AllFalse(labeled, count, skip);
}
[Theory]
[MemberData("SkipData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void SkipWhile_AllTrue(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.Empty(query.SkipWhile(x => seen.Add(x)));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("SkipData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_AllTrue_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int skip)
{
SkipWhile_AllTrue(labeled, count, skip);
}
[Theory]
[MemberData("SkipWhileData", (object)(new int[] { 2, 16 }))]
public static void SkipWhile_SomeTrue(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> skip)
{
ParallelQuery<int> query = labeled.Item;
int seen = skip.Min() == 0 ? 1 : 0;
Assert.All(query.SkipWhile(x => skip.Contains(x)), x => Assert.Equal(seen++, x));
Assert.Equal(skip.Min() >= count ? 0 : count, seen);
}
[Theory]
[OuterLoop]
[MemberData("SkipWhileData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_SomeTrue_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> skip)
{
SkipWhile_SomeTrue(labeled, count, skip);
}
[Theory]
[MemberData("SkipWhileData", (object)(new int[] { 2, 16 }))]
public static void SkipWhile_SomeFalse(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> skip)
{
ParallelQuery<int> query = labeled.Item;
int seen = skip.Min();
Assert.All(query.SkipWhile(x => !skip.Contains(x)), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData("SkipWhileData", (object)(new int[] { 1024 * 32 }))]
public static void SkipWhile_SomeFalse_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> skip)
{
SkipWhile_SomeFalse(labeled, count, skip);
}
[Fact]
public static void SkipWhile_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).SkipWhile(x => true));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().SkipWhile((Func<bool, bool>)null));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().SkipWhile((Func<bool, int, bool>)null));
}
}
}
| |
using System;
using System.Collections.Generic;
namespace DoFactory.GangOfFour.Builder.RealWorld
{
/// <summary>
/// MainApp startup class for Real-World
/// Builder Design Pattern.
/// </summary>
public class MainApp
{
/// <summary>
/// Entry point into console application.
/// </summary>
public static void Main()
{
VehicleBuilder builder;
// Create shop with vehicle builders
Shop shop = new Shop();
// Construct and display vehicles
builder = new ScooterBuilder();
shop.Construct(builder);
builder.Vehicle.Show();
builder = new CarBuilder();
shop.Construct(builder);
builder.Vehicle.Show();
builder = new MotorCycleBuilder();
shop.Construct(builder);
builder.Vehicle.Show();
// Wait for user
Console.ReadKey();
}
}
/// <summary>
/// The 'Director' class
/// </summary>
class Shop
{
// Builder uses a complex series of steps
public void Construct(VehicleBuilder vehicleBuilder)
{
vehicleBuilder.BuildFrame();
vehicleBuilder.BuildEngine();
vehicleBuilder.BuildWheels();
vehicleBuilder.BuildDoors();
}
}
/// <summary>
/// The 'Builder' abstract class
/// </summary>
abstract class VehicleBuilder
{
protected Vehicle vehicle;
// Gets vehicle instance
public Vehicle Vehicle
{
get { return vehicle; }
}
// Abstract build methods
public abstract void BuildFrame();
public abstract void BuildEngine();
public abstract void BuildWheels();
public abstract void BuildDoors();
}
/// <summary>
/// The 'ConcreteBuilder1' class
/// </summary>
class MotorCycleBuilder : VehicleBuilder
{
public MotorCycleBuilder()
{
vehicle = new Vehicle("MotorCycle");
}
public override void BuildFrame()
{
vehicle["frame"] = "MotorCycle Frame";
}
public override void BuildEngine()
{
vehicle["engine"] = "500 cc";
}
public override void BuildWheels()
{
vehicle["wheels"] = "2";
}
public override void BuildDoors()
{
vehicle["doors"] = "0";
}
}
/// <summary>
/// The 'ConcreteBuilder2' class
/// </summary>
class CarBuilder : VehicleBuilder
{
public CarBuilder()
{
vehicle = new Vehicle("Car");
}
public override void BuildFrame()
{
vehicle["frame"] = "Car Frame";
}
public override void BuildEngine()
{
vehicle["engine"] = "2500 cc";
}
public override void BuildWheels()
{
vehicle["wheels"] = "4";
}
public override void BuildDoors()
{
vehicle["doors"] = "4";
}
}
/// <summary>
/// The 'ConcreteBuilder3' class
/// </summary>
class ScooterBuilder : VehicleBuilder
{
public ScooterBuilder()
{
vehicle = new Vehicle("Scooter");
}
public override void BuildFrame()
{
vehicle["frame"] = "Scooter Frame";
}
public override void BuildEngine()
{
vehicle["engine"] = "50 cc";
}
public override void BuildWheels()
{
vehicle["wheels"] = "2";
}
public override void BuildDoors()
{
vehicle["doors"] = "0";
}
}
/// <summary>
/// The 'Product' class
/// </summary>
class Vehicle
{
string vehicleType;
Dictionary<string,string> parts = new Dictionary<string,string>();
// Constructor
public Vehicle(string vehicleType)
{
this.vehicleType = vehicleType;
}
// Indexer
public string this[string key]
{
get { return parts[key]; }
set { parts[key] = value; }
}
public void Show()
{
Console.WriteLine("\n---------------------------");
Console.WriteLine("Vehicle Type: {0}", vehicleType);
Console.WriteLine(" Frame : {0}", parts["frame"]);
Console.WriteLine(" Engine : {0}", parts["engine"]);
Console.WriteLine(" #Wheels: {0}", parts["wheels"]);
Console.WriteLine(" #Doors : {0}", parts["doors"]);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Signum.Engine.Maps;
using Signum.Entities.Authorization;
using Signum.Entities.Basics;
using Signum.Engine.Basics;
using Signum.Utilities;
using Signum.Entities;
using System.Reflection;
using Signum.Entities.DynamicQuery;
namespace Signum.Engine.Authorization
{
public static class QueryAuthLogic
{
static AuthCache<RuleQueryEntity, QueryAllowedRule, QueryEntity, object, QueryAllowed> cache = null!;
public static HashSet<object> AvoidCoerce = new HashSet<object>();
public static IManualAuth<object, QueryAllowed> Manual { get { return cache; } }
public static bool IsStarted { get { return cache != null; } }
public readonly static Dictionary<object, QueryAllowed> MaxAutomaticUpgrade = new Dictionary<object, QueryAllowed>();
public static void Start(SchemaBuilder sb)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
AuthLogic.AssertStarted(sb);
QueryLogic.Start(sb);
QueryLogic.Queries.AllowQuery += new Func<object, bool, bool>(dqm_AllowQuery);
sb.Include<RuleQueryEntity>()
.WithUniqueIndex(rt => new { rt.Resource, rt.Role });
cache = new AuthCache<RuleQueryEntity, QueryAllowedRule, QueryEntity, object, QueryAllowed>(sb,
toKey: qn => QueryLogic.ToQueryName(qn.Key),
toEntity: QueryLogic.GetQueryEntity,
isEquals: (q1, q2) => q1 == q2,
merger: new QueryMerger(),
invalidateWithTypes: true,
coercer: QueryCoercer.Instance);
sb.Schema.EntityEvents<RoleEntity>().PreUnsafeDelete += query =>
{
Database.Query<RuleQueryEntity>().Where(r => query.Contains(r.Role.Entity)).UnsafeDelete();
return null;
};
AuthLogic.ExportToXml += exportAll => cache.ExportXml("Queries", "Query", QueryUtils.GetKey, b => b.ToString(),
exportAll ? QueryLogic.QueryNames.Values.ToList(): null);
AuthLogic.ImportFromXml += (x, roles, replacements) =>
{
string replacementKey = "AuthRules:" + typeof(QueryEntity).Name;
replacements.AskForReplacements(
x.Element("Queries")!.Elements("Role").SelectMany(r => r.Elements("Query")).Select(p => p.Attribute("Resource")!.Value).ToHashSet(),
QueryLogic.QueryNames.Keys.ToHashSet(),
replacementKey);
return cache.ImportXml(x, "Queries", "Query", roles, s =>
{
var qn = QueryLogic.TryToQueryName(replacements.Apply(replacementKey, s));
if (qn == null)
return null;
return QueryLogic.GetQueryEntity(qn);
}, str =>
{
if (Enum.TryParse<QueryAllowed>(str, out var result))
return result;
var bResult = bool.Parse(str); //For backwards compatibilityS
return bResult ? QueryAllowed.Allow : QueryAllowed.None;
});
};
sb.Schema.Table<QueryEntity>().PreDeleteSqlSync += new Func<Entity, SqlPreCommand>(AuthCache_PreDeleteSqlSync);
}
}
static SqlPreCommand AuthCache_PreDeleteSqlSync(Entity arg)
{
return Administrator.DeleteWhereScript((RuleQueryEntity rt) => rt.Resource, (QueryEntity)arg);
}
public static void SetMaxAutomaticUpgrade(object queryName, QueryAllowed allowed)
{
MaxAutomaticUpgrade.Add(queryName, allowed);
}
static bool dqm_AllowQuery(object queryName, bool fullScreen)
{
var allowed = GetQueryAllowed(queryName);
return allowed == QueryAllowed.Allow || allowed == QueryAllowed.EmbeddedOnly && !fullScreen;
}
public static DefaultDictionary<object, QueryAllowed> QueryRules()
{
return cache.GetDefaultDictionary();
}
public static QueryRulePack GetQueryRules(Lite<RoleEntity> role, TypeEntity typeEntity)
{
var result = new QueryRulePack { Role = role, Type = typeEntity };
cache.GetRules(result, QueryLogic.GetTypeQueries(typeEntity));
var coercer = QueryCoercer.Instance.GetCoerceValue(role);
result.Rules.ForEach(r => r.CoercedValues = EnumExtensions.GetValues<QueryAllowed>()
.Where(a => !coercer(QueryLogic.ToQueryName(r.Resource.Key), a).Equals(a))
.ToArray());
return result;
}
public static void SetQueryRules(QueryRulePack rules)
{
string[] queryKeys = QueryLogic.Queries.GetTypeQueries(TypeLogic.EntityToType[rules.Type]).Keys.Select(qn => QueryUtils.GetKey(qn)).ToArray();
cache.SetRules(rules, r => queryKeys.Contains(r.Key));
}
public static QueryAllowed GetQueryAllowed(object queryName)
{
if (!AuthLogic.IsEnabled || ExecutionMode.InGlobal)
return QueryAllowed.Allow;
return cache.GetAllowed(RoleEntity.Current, queryName);
}
public static QueryAllowed GetQueryAllowed(Lite<RoleEntity> role, object queryName)
{
return cache.GetAllowed(role, queryName);
}
public static AuthThumbnail? GetAllowedThumbnail(Lite<RoleEntity> role, Type entityType)
{
return QueryLogic.Queries.GetTypeQueries(entityType).Keys.Select(qn => cache.GetAllowed(role, qn)).Collapse();
}
internal static bool AllCanRead(this Implementations implementations, Func<Type, TypeAllowedAndConditions> getAllowed)
{
if (implementations.IsByAll)
return true;
return implementations.Types.All(t => getAllowed(t).MaxUI() != TypeAllowedBasic.None);
}
public static void SetAvoidCoerce(object queryName)
{
AvoidCoerce.Add(queryName);
}
}
class QueryMerger : IMerger<object, QueryAllowed>
{
public QueryAllowed Merge(object key, Lite<RoleEntity> role, IEnumerable<KeyValuePair<Lite<RoleEntity>, QueryAllowed>> baseValues)
{
QueryAllowed best = AuthLogic.GetMergeStrategy(role) == MergeStrategy.Union ?
Max(baseValues.Select(a => a.Value)) :
Min(baseValues.Select(a => a.Value));
var maxUp = QueryAuthLogic.MaxAutomaticUpgrade.TryGetS(key);
if (maxUp.HasValue && maxUp <= best)
return best;
if (!BasicPermission.AutomaticUpgradeOfQueries.IsAuthorized(role))
return best;
if (baseValues.Where(a => a.Value.Equals(best)).All(a => GetDefault(key, a.Key).Equals(a.Value)))
{
var def = GetDefault(key, role);
return maxUp.HasValue && maxUp <= def ? maxUp.Value : def;
}
return best;
}
static QueryAllowed Max(IEnumerable<QueryAllowed> baseValues)
{
QueryAllowed result = QueryAllowed.None;
foreach (var item in baseValues)
{
if (item > result)
result = item;
if (result == QueryAllowed.Allow)
return result;
}
return result;
}
static QueryAllowed Min(IEnumerable<QueryAllowed> baseValues)
{
QueryAllowed result = QueryAllowed.Allow;
foreach (var item in baseValues)
{
if (item < result)
result = item;
if (result == QueryAllowed.None)
return result;
}
return result;
}
public Func<object, QueryAllowed> MergeDefault(Lite<RoleEntity> role)
{
return key =>
{
if (AuthLogic.GetDefaultAllowed(role))
return QueryAllowed.Allow;
if (!BasicPermission.AutomaticUpgradeOfQueries.IsAuthorized(role))
return QueryAllowed.None;
var maxUp = QueryAuthLogic.MaxAutomaticUpgrade.TryGetS(key);
var def = GetDefault(key, role);
return maxUp.HasValue && maxUp <= def ? maxUp.Value : def;
};
}
QueryAllowed GetDefault(object key, Lite<RoleEntity> role)
{
return QueryLogic.Queries.GetEntityImplementations(key).AllCanRead(t => TypeAuthLogic.GetAllowed(role, t)) ? QueryAllowed.Allow : QueryAllowed.None;
}
}
class QueryCoercer : Coercer<QueryAllowed, object>
{
public static readonly QueryCoercer Instance = new QueryCoercer();
private QueryCoercer()
{
}
public override Func<object, QueryAllowed, QueryAllowed> GetCoerceValue(Lite<RoleEntity> role)
{
return (queryName, allowed) =>
{
if (QueryAuthLogic.AvoidCoerce.Contains(queryName))
return allowed;
if (allowed == QueryAllowed.None)
return allowed;
var implementations = QueryLogic.Queries.GetEntityImplementations(queryName);
return implementations.AllCanRead(t => TypeAuthLogic.GetAllowed(role, t)) ? allowed : QueryAllowed.None;
};
}
public override Func<Lite<RoleEntity>, QueryAllowed, QueryAllowed> GetCoerceValueManual(object queryName)
{
return (role, allowed) =>
{
if (QueryAuthLogic.AvoidCoerce.Contains(queryName))
return allowed;
if (allowed == QueryAllowed.None)
return allowed;
var implementations = QueryLogic.Queries.GetEntityImplementations(queryName);
return implementations.AllCanRead(t => TypeAuthLogic.Manual.GetAllowed(role, t)) ? allowed : QueryAllowed.None;
};
}
}
}
| |
// 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.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Internal.Resources
{
using Azure;
using Management;
using Internal;
using Rest;
using Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ProvidersOperations.
/// </summary>
public static partial class ProvidersOperationsExtensions
{
/// <summary>
/// Unregisters a subscription from a resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The namespace of the resource provider to unregister.
/// </param>
public static Provider Unregister(this IProvidersOperations operations, string resourceProviderNamespace)
{
return operations.UnregisterAsync(resourceProviderNamespace).GetAwaiter().GetResult();
}
/// <summary>
/// Unregisters a subscription from a resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The namespace of the resource provider to unregister.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Provider> UnregisterAsync(this IProvidersOperations operations, string resourceProviderNamespace, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UnregisterWithHttpMessagesAsync(resourceProviderNamespace, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Registers a subscription with a resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The namespace of the resource provider to register.
/// </param>
public static Provider Register(this IProvidersOperations operations, string resourceProviderNamespace)
{
return operations.RegisterAsync(resourceProviderNamespace).GetAwaiter().GetResult();
}
/// <summary>
/// Registers a subscription with a resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The namespace of the resource provider to register.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Provider> RegisterAsync(this IProvidersOperations operations, string resourceProviderNamespace, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RegisterWithHttpMessagesAsync(resourceProviderNamespace, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all resource providers for a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='top'>
/// The number of results to return. If null is passed returns all deployments.
/// </param>
/// <param name='expand'>
/// The properties to include in the results. For example, use
/// &$expand=metadata in the query string to retrieve resource provider
/// metadata. To include property aliases in response, use
/// $expand=resourceTypes/aliases.
/// </param>
public static IPage<Provider> List(this IProvidersOperations operations, int? top = default(int?), string expand = default(string))
{
return operations.ListAsync(top, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all resource providers for a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='top'>
/// The number of results to return. If null is passed returns all deployments.
/// </param>
/// <param name='expand'>
/// The properties to include in the results. For example, use
/// &$expand=metadata in the query string to retrieve resource provider
/// metadata. To include property aliases in response, use
/// $expand=resourceTypes/aliases.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Provider>> ListAsync(this IProvidersOperations operations, int? top = default(int?), string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(top, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the specified resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The namespace of the resource provider.
/// </param>
/// <param name='expand'>
/// The $expand query parameter. For example, to include property aliases in
/// response, use $expand=resourceTypes/aliases.
/// </param>
public static Provider Get(this IProvidersOperations operations, string resourceProviderNamespace, string expand = default(string))
{
return operations.GetAsync(resourceProviderNamespace, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The namespace of the resource provider.
/// </param>
/// <param name='expand'>
/// The $expand query parameter. For example, to include property aliases in
/// response, use $expand=resourceTypes/aliases.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Provider> GetAsync(this IProvidersOperations operations, string resourceProviderNamespace, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceProviderNamespace, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all resource providers for a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Provider> ListNext(this IProvidersOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all resource providers for a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Provider>> ListNextAsync(this IProvidersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* 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.Text;
using AjaxPro;
using ASC.Core;
using ASC.Forum;
using ASC.Web.Community.Modules.Forum.Resources;
using ASC.Web.Studio.Utility;
namespace ASC.Web.Community.Forum
{
[AjaxNamespace("Subscriber")]
public class Subscriber : ISubscriberView
{
public Subscriber()
{
ForumManager.Instance.PresenterFactory.GetPresenter<ISubscriberView>().SetView(this);
}
#region Topic
[AjaxMethod(HttpSessionStateRequirement.ReadWrite)]
public AjaxResponse SubscribeOnTopic(int idTopic, int statusNotify)
{
var resp = new AjaxResponse();
if (statusNotify == 1 && Subscribe != null)
{
Subscribe(this, new SubscribeEventArgs(SubscriptionConstants.NewPostInTopic,
idTopic.ToString(),
SecurityContext.CurrentAccount.ID));
resp.rs1 = "1";
resp.rs2 = RenderTopicSubscription(false, idTopic);
resp.rs3 = "subscribed";
}
else if (UnSubscribe != null)
{
UnSubscribe(this, new SubscribeEventArgs(SubscriptionConstants.NewPostInTopic,
idTopic.ToString(),
SecurityContext.CurrentAccount.ID));
resp.rs1 = "1";
resp.rs2 = RenderTopicSubscription(true, idTopic);
resp.rs3 = "unsubscribed";
}
else
{
resp.rs1 = "0";
resp.rs2 = ForumResource.ErrorSubscription;
}
return resp;
}
public string RenderTopicSubscription(bool isSubscribe, int topicID)
{
var sb = new StringBuilder();
sb.Append("<a id=\"statusSubscribe\" class=\"" +
"follow-status " + (IsTopicSubscribe(topicID) ? "subscribed" : "unsubscribed") +
"\" title=\"" + (!isSubscribe ? ForumResource.UnSubscribeOnTopic : ForumResource.SubscribeOnTopic) +
"\" href=\"#\"onclick=\"ForumSubscriber.SubscribeOnTopic('" + topicID + "', " + (isSubscribe ? 1 : 0) + "); return false;\"></a>");
return sb.ToString();
}
public bool IsTopicSubscribe(int topicID)
{
if (GetSubscriptionState != null)
GetSubscriptionState(this, new SubscribeEventArgs(SubscriptionConstants.NewPostInTopic,
topicID.ToString(),
SecurityContext.CurrentAccount.ID));
return IsSubscribe;
}
#endregion
#region Thread
public string RenderThreadSubscription(bool isSubscribe, int threadID)
{
var sb = new StringBuilder();
sb.Append("<a id=\"statusSubscribe\" class=\"" +
"follow-status " + (IsThreadSubscribe(threadID) ? "subscribed" : "unsubscribed") +
"\" title=\"" + (!isSubscribe ? ForumResource.UnSubscribeOnThread : ForumResource.SubscribeOnThread) +
"\" href=\"#\" onclick=\"ForumSubscriber.SubscribeOnThread('" + threadID + "', " + (isSubscribe ? 1 : 0) + "); return false;\"></a>");
return sb.ToString();
}
public bool IsThreadSubscribe(int threadID)
{
if (GetSubscriptionState != null)
GetSubscriptionState(this, new SubscribeEventArgs(SubscriptionConstants.NewPostInThread,
threadID.ToString(),
SecurityContext.CurrentAccount.ID));
return IsSubscribe;
}
[AjaxMethod(HttpSessionStateRequirement.ReadWrite)]
public AjaxResponse SubscribeOnThread(int idThread, int statusNotify)
{
var resp = new AjaxResponse();
if (statusNotify == 1 && Subscribe != null)
{
Subscribe(this, new SubscribeEventArgs(SubscriptionConstants.NewPostInThread,
idThread.ToString(),
SecurityContext.CurrentAccount.ID));
resp.rs1 = "1";
resp.rs2 = RenderThreadSubscription(false, idThread);
resp.rs3 = "subscribed";
}
else if (UnSubscribe != null)
{
UnSubscribe(this, new SubscribeEventArgs(SubscriptionConstants.NewPostInThread,
idThread.ToString(),
SecurityContext.CurrentAccount.ID));
resp.rs1 = "1";
resp.rs2 = RenderThreadSubscription(true, idThread);
resp.rs3 = "unsubscribed";
}
else
{
resp.rs1 = "0";
resp.rs2 = ForumResource.ErrorSubscription;
}
return resp;
}
#endregion
#region Topic on forum
public string RenderNewTopicSubscription(bool isSubscribe)
{
var sb = new StringBuilder();
sb.Append("<div id=\"forum_subcribeOnNewTopicBox\">");
sb.Append("<a class='linkAction' href=\"#\" onclick=\"ForumSubscriber.SubscribeOnNewTopics(" + (isSubscribe ? 1 : 0) + "); return false;\">" + (!isSubscribe ? ForumResource.UnsubscribeOnNewTopicInForum : ForumResource.SubscribeOnNewTopicInForum) + "</a>");
sb.Append("</div>");
return sb.ToString();
}
public bool IsNewTopicSubscribe()
{
if (GetSubscriptionState != null)
GetSubscriptionState(this, new SubscribeEventArgs(SubscriptionConstants.NewTopicInForum,
null,
SecurityContext.CurrentAccount.ID));
return IsSubscribe;
}
[AjaxMethod(HttpSessionStateRequirement.ReadWrite)]
public AjaxResponse SubscribeOnNewTopic(int statusNotify)
{
var resp = new AjaxResponse();
if (statusNotify == 1 && Subscribe != null)
{
Subscribe(this, new SubscribeEventArgs(SubscriptionConstants.NewTopicInForum,
null,
SecurityContext.CurrentAccount.ID));
resp.rs1 = "1";
resp.rs2 = RenderNewTopicSubscription(false);
}
else if (UnSubscribe != null)
{
UnSubscribe(this, new SubscribeEventArgs(SubscriptionConstants.NewTopicInForum,
null,
SecurityContext.CurrentAccount.ID));
resp.rs1 = "1";
resp.rs2 = RenderNewTopicSubscription(true);
}
else
{
resp.rs1 = "0";
resp.rs2 = ForumResource.ErrorSubscription;
}
return resp;
}
#endregion
#region ISubscriberView Members
public event EventHandler<SubscribeEventArgs> GetSubscriptionState;
public bool IsSubscribe { get; set; }
public event EventHandler<SubscribeEventArgs> Subscribe;
public event EventHandler<SubscribeEventArgs> UnSubscribe;
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Collections.Immutable
{
public partial struct ImmutableArray<T>
{
/// <summary>
/// A writable array accessor that can be converted into an <see cref="ImmutableArray{T}"/>
/// instance without allocating memory.
/// </summary>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableArrayBuilderDebuggerProxy<>))]
public sealed class Builder : IList<T>, IReadOnlyList<T>
{
/// <summary>
/// The backing array for the builder.
/// </summary>
private T[] _elements;
/// <summary>
/// The number of initialized elements in the array.
/// </summary>
private int _count;
/// <summary>
/// Initializes a new instance of the <see cref="Builder"/> class.
/// </summary>
/// <param name="capacity">The initial capacity of the internal array.</param>
internal Builder(int capacity)
{
Requires.Range(capacity >= 0, nameof(capacity));
_elements = new T[capacity];
_count = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="Builder"/> class.
/// </summary>
internal Builder()
: this(8)
{
}
/// <summary>
/// Get and sets the length of the internal array. When set the internal array is
/// reallocated to the given capacity if it is not already the specified length.
/// </summary>
public int Capacity
{
get { return _elements.Length; }
set
{
if (value < _count)
{
throw new ArgumentException(SR.CapacityMustBeGreaterThanOrEqualToCount, paramName: nameof(value));
}
if (value != _elements.Length)
{
if (value > 0)
{
var temp = new T[value];
if (_count > 0)
{
Array.Copy(_elements, 0, temp, 0, _count);
}
_elements = temp;
}
else
{
_elements = ImmutableArray<T>.Empty.array;
}
}
}
}
/// <summary>
/// Gets or sets the length of the builder.
/// </summary>
/// <remarks>
/// If the value is decreased, the array contents are truncated.
/// If the value is increased, the added elements are initialized to the default value of type <typeparamref name="T"/>.
/// </remarks>
public int Count
{
get
{
return _count;
}
set
{
Requires.Range(value >= 0, nameof(value));
if (value < _count)
{
// truncation mode
// Clear the elements of the elements that are effectively removed.
// PERF: Array.Clear works well for big arrays,
// but may have too much overhead with small ones (which is the common case here)
if (_count - value > 64)
{
Array.Clear(_elements, value, _count - value);
}
else
{
for (int i = value; i < this.Count; i++)
{
_elements[i] = default(T);
}
}
}
else if (value > _count)
{
// expansion
this.EnsureCapacity(value);
}
_count = value;
}
}
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <returns></returns>
/// <exception cref="IndexOutOfRangeException">
/// </exception>
public T this[int index]
{
get
{
if (index >= this.Count)
{
throw new IndexOutOfRangeException();
}
return _elements[index];
}
set
{
if (index >= this.Count)
{
throw new IndexOutOfRangeException();
}
_elements[index] = value;
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only.
/// </summary>
/// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.
/// </returns>
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
/// <summary>
/// Returns an immutable copy of the current contents of this collection.
/// </summary>
/// <returns>An immutable array.</returns>
public ImmutableArray<T> ToImmutable()
{
if (Count == 0)
{
return Empty;
}
return new ImmutableArray<T>(this.ToArray());
}
/// <summary>
/// Extracts the internal array as an <see cref="ImmutableArray{T}"/> and replaces it
/// with a zero length array.
/// </summary>
/// <exception cref="InvalidOperationException">When <see cref="ImmutableArray{T}.Builder.Count"/> doesn't
/// equal <see cref="ImmutableArray{T}.Builder.Capacity"/>.</exception>
public ImmutableArray<T> MoveToImmutable()
{
if (Capacity != Count)
{
throw new InvalidOperationException(SR.CapacityMustEqualCountOnMove);
}
T[] temp = _elements;
_elements = ImmutableArray<T>.Empty.array;
_count = 0;
return new ImmutableArray<T>(temp);
}
/// <summary>
/// Removes all items from the <see cref="ICollection{T}"/>.
/// </summary>
public void Clear()
{
this.Count = 0;
}
/// <summary>
/// Inserts an item to the <see cref="IList{T}"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
/// <param name="item">The object to insert into the <see cref="IList{T}"/>.</param>
public void Insert(int index, T item)
{
Requires.Range(index >= 0 && index <= this.Count, nameof(index));
this.EnsureCapacity(this.Count + 1);
if (index < this.Count)
{
Array.Copy(_elements, index, _elements, index + 1, this.Count - index);
}
_count++;
_elements[index] = item;
}
/// <summary>
/// Adds an item to the <see cref="ICollection{T}"/>.
/// </summary>
/// <param name="item">The object to add to the <see cref="ICollection{T}"/>.</param>
public void Add(T item)
{
this.EnsureCapacity(this.Count + 1);
_elements[_count++] = item;
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(IEnumerable<T> items)
{
Requires.NotNull(items, nameof(items));
int count;
if (items.TryGetCount(out count))
{
this.EnsureCapacity(this.Count + count);
}
foreach (var item in items)
{
this.Add(item);
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(params T[] items)
{
Requires.NotNull(items, nameof(items));
var offset = this.Count;
this.Count += items.Length;
Array.Copy(items, 0, _elements, offset, items.Length);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange<TDerived>(TDerived[] items) where TDerived : T
{
Requires.NotNull(items, nameof(items));
var offset = this.Count;
this.Count += items.Length;
Array.Copy(items, 0, _elements, offset, items.Length);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
/// <param name="length">The number of elements from the source array to add.</param>
public void AddRange(T[] items, int length)
{
Requires.NotNull(items, nameof(items));
Requires.Range(length >= 0 && length <= items.Length, nameof(length));
var offset = this.Count;
this.Count += length;
Array.Copy(items, 0, _elements, offset, length);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(ImmutableArray<T> items)
{
this.AddRange(items, items.Length);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
/// <param name="length">The number of elements from the source array to add.</param>
public void AddRange(ImmutableArray<T> items, int length)
{
Requires.Range(length >= 0, nameof(length));
if (items.array != null)
{
this.AddRange(items.array, length);
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange<TDerived>(ImmutableArray<TDerived> items) where TDerived : T
{
if (items.array != null)
{
this.AddRange(items.array);
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(Builder items)
{
Requires.NotNull(items, nameof(items));
this.AddRange(items._elements, items.Count);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange<TDerived>(ImmutableArray<TDerived>.Builder items) where TDerived : T
{
Requires.NotNull(items, nameof(items));
this.AddRange(items._elements, items.Count);
}
/// <summary>
/// Removes the specified element.
/// </summary>
/// <param name="element">The element.</param>
/// <returns>A value indicating whether the specified element was found and removed from the collection.</returns>
public bool Remove(T element)
{
int index = this.IndexOf(element);
if (index >= 0)
{
this.RemoveAt(index);
return true;
}
return false;
}
/// <summary>
/// Removes the <see cref="IList{T}"/> item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
public void RemoveAt(int index)
{
Requires.Range(index >= 0 && index < this.Count, nameof(index));
if (index < this.Count - 1)
{
Array.Copy(_elements, index + 1, _elements, index, this.Count - index - 1);
}
this.Count--;
}
/// <summary>
/// Determines whether the <see cref="ICollection{T}"/> contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the <see cref="ICollection{T}"/>.</param>
/// <returns>
/// true if <paramref name="item"/> is found in the <see cref="ICollection{T}"/>; otherwise, false.
/// </returns>
public bool Contains(T item)
{
return this.IndexOf(item) >= 0;
}
/// <summary>
/// Creates a new array with the current contents of this Builder.
/// </summary>
public T[] ToArray()
{
T[] result = new T[this.Count];
Array.Copy(_elements, 0, result, 0, this.Count);
return result;
}
/// <summary>
/// Copies the current contents to the specified array.
/// </summary>
/// <param name="array">The array to copy to.</param>
/// <param name="index">The starting index of the target array.</param>
public void CopyTo(T[] array, int index)
{
Requires.NotNull(array, nameof(array));
Requires.Range(index >= 0 && index + this.Count <= array.Length, nameof(index));
Array.Copy(_elements, 0, array, index, this.Count);
}
/// <summary>
/// Resizes the array to accommodate the specified capacity requirement.
/// </summary>
/// <param name="capacity">The required capacity.</param>
private void EnsureCapacity(int capacity)
{
if (_elements.Length < capacity)
{
int newCapacity = Math.Max(_elements.Length * 2, capacity);
Array.Resize(ref _elements, newCapacity);
}
}
/// <summary>
/// Determines the index of a specific item in the <see cref="IList{T}"/>.
/// </summary>
/// <param name="item">The object to locate in the <see cref="IList{T}"/>.</param>
/// <returns>
/// The index of <paramref name="item"/> if found in the list; otherwise, -1.
/// </returns>
[Pure]
public int IndexOf(T item)
{
return this.IndexOf(item, 0, _count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex)
{
return this.IndexOf(item, startIndex, this.Count - startIndex, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex, int count)
{
return this.IndexOf(item, startIndex, count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <param name="equalityComparer">
/// The equality comparer to use in the search.
/// If <c>null</c>, <see cref="EqualityComparer{T}.Default"/> is used.
/// </param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex, int count, IEqualityComparer<T> equalityComparer)
{
if (count == 0 && startIndex == 0)
{
return -1;
}
Requires.Range(startIndex >= 0 && startIndex < this.Count, nameof(startIndex));
Requires.Range(count >= 0 && startIndex + count <= this.Count, nameof(count));
equalityComparer = equalityComparer ?? EqualityComparer<T>.Default;
if (equalityComparer == EqualityComparer<T>.Default)
{
return Array.IndexOf(_elements, item, startIndex, count);
}
else
{
for (int i = startIndex; i < startIndex + count; i++)
{
if (equalityComparer.Equals(_elements[i], item))
{
return i;
}
}
return -1;
}
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item)
{
if (this.Count == 0)
{
return -1;
}
return this.LastIndexOf(item, this.Count - 1, this.Count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item, int startIndex)
{
if (this.Count == 0 && startIndex == 0)
{
return -1;
}
Requires.Range(startIndex >= 0 && startIndex < this.Count, nameof(startIndex));
return this.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item, int startIndex, int count)
{
return this.LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <param name="equalityComparer">The equality comparer to use in the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T> equalityComparer)
{
if (count == 0 && startIndex == 0)
{
return -1;
}
Requires.Range(startIndex >= 0 && startIndex < this.Count, nameof(startIndex));
Requires.Range(count >= 0 && startIndex - count + 1 >= 0, nameof(count));
equalityComparer = equalityComparer ?? EqualityComparer<T>.Default;
if (equalityComparer == EqualityComparer<T>.Default)
{
return Array.LastIndexOf(_elements, item, startIndex, count);
}
else
{
for (int i = startIndex; i >= startIndex - count + 1; i--)
{
if (equalityComparer.Equals(item, _elements[i]))
{
return i;
}
}
return -1;
}
}
/// <summary>
/// Reverses the order of elements in the collection.
/// </summary>
public void Reverse()
{
// The non-generic Array.Reverse is not used because it does not perform
// well for non-primitive value types.
// If/when a generic Array.Reverse<T> becomes available, the below code
// can be deleted and replaced with a call to Array.Reverse<T>.
int i = 0;
int j = _count - 1;
T[] array = _elements;
while (i < j)
{
T temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
}
/// <summary>
/// Sorts the array.
/// </summary>
public void Sort()
{
if (Count > 1)
{
Array.Sort(_elements, 0, this.Count, Comparer<T>.Default);
}
}
/// <summary>
/// Sorts the elements in the entire array using
/// the specified <see cref="Comparison{T}"/>.
/// </summary>
/// <param name="comparison">
/// The <see cref="Comparison{T}"/> to use when comparing elements.
/// </param>
/// <exception cref="ArgumentNullException"><paramref name="comparison"/> is null.</exception>
[Pure]
public void Sort(Comparison<T> comparison)
{
Requires.NotNull(comparison, nameof(comparison));
if (Count > 1)
{
// Array.Sort does not have an overload that takes both bounds and a Comparison.
// We could special case _count == _elements.Length in order to try to avoid
// the IComparer allocation, but the Array.Sort overload that takes a Comparison
// allocates such an IComparer internally, anyway.
Array.Sort(_elements, 0, _count, Comparer<T>.Create(comparison));
}
}
/// <summary>
/// Sorts the array.
/// </summary>
/// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param>
public void Sort(IComparer<T> comparer)
{
if (Count > 1)
{
Array.Sort(_elements, 0, _count, comparer);
}
}
/// <summary>
/// Sorts the array.
/// </summary>
/// <param name="index">The index of the first element to consider in the sort.</param>
/// <param name="count">The number of elements to include in the sort.</param>
/// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param>
public void Sort(int index, int count, IComparer<T> comparer)
{
// Don't rely on Array.Sort's argument validation since our internal array may exceed
// the bounds of the publicly addressable region.
Requires.Range(index >= 0, nameof(index));
Requires.Range(count >= 0 && index + count <= this.Count, nameof(count));
if (count > 1)
{
Array.Sort(_elements, index, count, comparer);
}
}
/// <summary>
/// Returns an enumerator for the contents of the array.
/// </summary>
/// <returns>An enumerator.</returns>
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < this.Count; i++)
{
yield return this[i];
}
}
/// <summary>
/// Returns an enumerator for the contents of the array.
/// </summary>
/// <returns>An enumerator.</returns>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Returns an enumerator for the contents of the array.
/// </summary>
/// <returns>An enumerator.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Adds items to this collection.
/// </summary>
/// <typeparam name="TDerived">The type of source elements.</typeparam>
/// <param name="items">The source array.</param>
/// <param name="length">The number of elements to add to this array.</param>
private void AddRange<TDerived>(TDerived[] items, int length) where TDerived : T
{
this.EnsureCapacity(this.Count + length);
var offset = this.Count;
this.Count += length;
var nodes = _elements;
for (int i = 0; i < length; i++)
{
nodes[offset + i] = items[i];
}
}
}
}
/// <summary>
/// A simple view of the immutable collection that the debugger can show to the developer.
/// </summary>
internal sealed class ImmutableArrayBuilderDebuggerProxy<T>
{
/// <summary>
/// The collection to be enumerated.
/// </summary>
private readonly ImmutableArray<T>.Builder _builder;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArrayBuilderDebuggerProxy{T}"/> class.
/// </summary>
/// <param name="builder">The collection to display in the debugger</param>
public ImmutableArrayBuilderDebuggerProxy(ImmutableArray<T>.Builder builder)
{
_builder = builder;
}
/// <summary>
/// Gets a simple debugger-viewable collection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] A
{
get
{
return _builder.ToArray();
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
namespace Collections
{
/// <summary>
/// Tests the public methods in ReadOnlyDictionary<TKey, Value>.
/// properly.
/// </summary>
public class ReadOnlyDictionaryTests
{
/// <summary>
/// Current key that the m_generateItemFunc is at.
/// </summary>
private static int s_currentKey = int.MaxValue;
/// <summary>
/// Function to generate a KeyValuePair.
/// </summary>
private static Func<KeyValuePair<int, string>> s_generateItemFunc = () =>
{
var kvp = new KeyValuePair<int, string>(s_currentKey, s_currentKey.ToString());
s_currentKey--;
return kvp;
};
/// <summary>
/// Tests that the ReadOnlyDictionary is constructed with the given
/// Dictionary.
/// </summary>
[Fact]
public static void CtorTests()
{
KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] {
new KeyValuePair<int, string>(1, "one"),
new KeyValuePair<int, string>(2, "two"),
new KeyValuePair<int, string>(3, "three"),
new KeyValuePair<int, string>(4, "four"),
new KeyValuePair<int, string>(5, "five")
};
DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr);
ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict);
IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(dictionary, expectedArr, s_generateItemFunc);
helper.InitialItems_Tests();
IDictionary<int, string> dictAsIDictionary = dictionary;
Assert.True(dictAsIDictionary.IsReadOnly, "ReadonlyDictionary Should be readonly");
}
/// <summary>
/// Tests that an argument null exception is returned when given
/// a null dictionary to initialise ReadOnlyDictionary.
/// </summary>
[Fact]
public static void CtorTests_Negative()
{
Assert.Throws<ArgumentNullException>(() => { ReadOnlyDictionary<int, string> dict = new ReadOnlyDictionary<int, string>(null); });
}
/// <summary>
/// Tests that true is returned when the key exists in the dictionary
/// and false otherwise.
/// </summary>
[Fact]
public static void ContainsKeyTests()
{
KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] {
new KeyValuePair<int, string>(1, "one"),
new KeyValuePair<int, string>(2, "two"),
new KeyValuePair<int, string>(3, "three"),
new KeyValuePair<int, string>(4, "four"),
new KeyValuePair<int, string>(5, "five")
};
DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr);
ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict);
IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(dictionary, expectedArr, s_generateItemFunc);
helper.ContainsKey_Tests();
}
/// <summary>
/// Tests that the value is retrieved from a dictionary when its
/// key exists in the dictionary and false when it does not.
/// </summary>
[Fact]
public static void TryGetValueTests()
{
KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] {
new KeyValuePair<int, string>(1, "one"),
new KeyValuePair<int, string>(2, "two"),
new KeyValuePair<int, string>(3, "three"),
new KeyValuePair<int, string>(4, "four"),
new KeyValuePair<int, string>(5, "five")
};
DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr);
ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict);
IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(dictionary, expectedArr, s_generateItemFunc);
helper.TryGetValue_Tests();
}
/// <summary>
/// Tests that the dictionary's keys can be retrieved.
/// </summary>
[Fact]
public static void GetKeysTests()
{
KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] {
new KeyValuePair<int, string>(1, "one"),
new KeyValuePair<int, string>(2, "two"),
new KeyValuePair<int, string>(3, "three"),
new KeyValuePair<int, string>(4, "four"),
new KeyValuePair<int, string>(5, "five")
};
DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr);
ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict);
IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(dictionary, expectedArr, s_generateItemFunc);
helper.Keys_get_Tests();
}
/// <summary>
/// Tests that the dictionary's values can be retrieved.
/// </summary>
[Fact]
public static void GetValuesTests()
{
KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] {
new KeyValuePair<int, string>(1, "one"),
new KeyValuePair<int, string>(2, "two"),
new KeyValuePair<int, string>(3, "three"),
new KeyValuePair<int, string>(4, "four"),
new KeyValuePair<int, string>(5, "five")
};
DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr);
ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict);
IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(dictionary, expectedArr, s_generateItemFunc);
helper.Values_get_Tests();
}
/// <summary>
/// Tests that items can be retrieved by key from the Dictionary.
/// </summary>
[Fact]
public static void GetItemTests()
{
KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] {
new KeyValuePair<int, string>(1, "one"),
new KeyValuePair<int, string>(2, "two"),
new KeyValuePair<int, string>(3, "three"),
new KeyValuePair<int, string>(4, "four"),
new KeyValuePair<int, string>(5, "five")
};
DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr);
ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict);
IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(dictionary, expectedArr, s_generateItemFunc);
helper.Item_get_Tests();
}
/// <summary>
/// Tests that an KeyNotFoundException is thrown when retrieving the
/// value of an item whose key is not in the dictionary.
/// </summary>
[Fact]
public static void GetItemTests_Negative()
{
KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] {
new KeyValuePair<int, string>(1, "one"),
new KeyValuePair<int, string>(2, "two"),
new KeyValuePair<int, string>(3, "three"),
new KeyValuePair<int, string>(4, "four"),
new KeyValuePair<int, string>(5, "five")
};
DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr);
ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict);
IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(dictionary, expectedArr, s_generateItemFunc);
helper.Item_get_Tests_Negative();
}
/// <summary>
/// Tests that a ReadOnlyDictionary cannot be modified. That is, that
/// Add, Remove, Clear does not work.
/// </summary>
[Fact]
public static void CannotModifyDictionaryTests_Negative()
{
KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] {
new KeyValuePair<int, string>(1, "one"),
new KeyValuePair<int, string>(2, "two"),
new KeyValuePair<int, string>(3, "three"),
new KeyValuePair<int, string>(4, "four"),
new KeyValuePair<int, string>(5, "five")
};
DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr);
ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict);
IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>();
IDictionary<int, string> dictAsIDictionary = dictionary;
Assert.Throws<NotSupportedException>(() => dictAsIDictionary.Add(new KeyValuePair<int, string>(7, "seven")));
Assert.Throws<NotSupportedException>(() => dictAsIDictionary.Add(7, "seven"));
Assert.Throws<NotSupportedException>(() => dictAsIDictionary.Remove(new KeyValuePair<int, string>(1, "one")));
Assert.Throws<NotSupportedException>(() => dictAsIDictionary.Remove(1));
Assert.Throws<NotSupportedException>(() => dictAsIDictionary.Clear());
helper.VerifyCollection(dictionary, expectedArr); //verifying that the collection has not changed.
}
[Fact]
public static void DebuggerAttributeTests()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(new ReadOnlyDictionary<int, int>(new Dictionary<int, int>()));
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(new ReadOnlyDictionary<int, int>(new Dictionary<int, int>()));
DebuggerAttributes.ValidateDebuggerDisplayReferences(new ReadOnlyDictionary<int, int>(new Dictionary<int, int>()).Keys);
DebuggerAttributes.ValidateDebuggerDisplayReferences(new ReadOnlyDictionary<int, int>(new Dictionary<int, int>()).Values);
}
}
/// <summary>
/// Helper class that performs all of the IReadOnlyDictionary
/// verifications.
/// </summary>
public class IReadOnlyDictionary_T_Test<TKey, TValue>
{
private readonly IReadOnlyDictionary<TKey, TValue> _collection;
private readonly KeyValuePair<TKey, TValue>[] _expectedItems;
private readonly Func<KeyValuePair<TKey, TValue>> _generateItem;
/// <summary>
/// Initializes a new instance of the IReadOnlyDictionary_T_Test.
/// </summary>
public IReadOnlyDictionary_T_Test(
IReadOnlyDictionary<TKey, TValue> collection, KeyValuePair<TKey, TValue>[] expectedItems,
Func<KeyValuePair<TKey, TValue>> generateItem)
{
_collection = collection;
_expectedItems = expectedItems;
_generateItem = generateItem;
}
public IReadOnlyDictionary_T_Test()
{
}
/// <summary>
/// Tests that the initial items in the readonly collection
/// are equivalent to the collection it was initialised with.
/// </summary>
public void InitialItems_Tests()
{
//[] Verify the initial items in the collection
VerifyCollection(_collection, _expectedItems);
//verifies the non-generic enumerator.
VerifyEnumerator(_collection, _expectedItems);
}
/// <summary>
/// Checks that the dictionary contains all keys of the expected items.
/// And returns false when the dictionary does not contain a key.
/// </summary>
public void ContainsKey_Tests()
{
Assert.Equal(_expectedItems.Length, _collection.Count);
for (int i = 0; i < _collection.Count; i++)
{
Assert.True(_collection.ContainsKey(_expectedItems[i].Key),
"Err_5983muqjl Verifying ContainsKey the item in the collection and the expected existing items(" + _expectedItems[i].Key + ")");
}
//Verify that the collection was not mutated
VerifyCollection(_collection, _expectedItems);
KeyValuePair<TKey, TValue> nonExistingItem = _generateItem();
while (!IsUniqueKey(_expectedItems, nonExistingItem))
{
nonExistingItem = _generateItem();
}
TKey nonExistingKey = nonExistingItem.Key;
Assert.False(_collection.ContainsKey(nonExistingKey), "Err_4713ebda Verifying ContainsKey the non-existing item in the collection and the expected non-existing items key:" + nonExistingKey);
//Verify that the collection was not mutated
VerifyCollection(_collection, _expectedItems);
}
/// <summary>
/// Tests that you can get values that exist in the collection
/// and not when the value is not in the collection.
/// </summary>
public void TryGetValue_Tests()
{
Assert.Equal(_expectedItems.Length, _collection.Count);
for (int i = 0; i < _collection.Count; i++)
{
TValue itemValue;
Assert.True(_collection.TryGetValue(_expectedItems[i].Key, out itemValue),
"Err_2621pnyan Verifying TryGetValue the item in the collection and the expected existing items(" + _expectedItems[i].Value + ")");
Assert.Equal(_expectedItems[i].Value, itemValue);
}
//Verify that the collection was not mutated
VerifyCollection(_collection, _expectedItems);
KeyValuePair<TKey, TValue> nonExistingItem = _generateItem();
while (!IsUniqueKey(_expectedItems, nonExistingItem))
{
nonExistingItem = _generateItem();
}
TValue nonExistingItemValue;
Assert.False(_collection.TryGetValue(nonExistingItem.Key, out nonExistingItemValue),
"Err_4561rtio Verifying TryGetValue returns false when looking for a non-existing item in the collection (" + nonExistingItem.Key + ")");
//Verify that the collection was not mutated
VerifyCollection(_collection, _expectedItems);
}
/// <summary>
/// Tests that you can get all the keys in the collection.
/// </summary>
public void Keys_get_Tests()
{
// Verify Key get_Values
int numItemsSeen = 0;
foreach (TKey key in _collection.Keys)
{
numItemsSeen++;
TValue value;
Assert.True(_collection.TryGetValue(key, out value), "Items in the Keys collection should exist in the dictionary!");
}
Assert.Equal(_collection.Count, numItemsSeen);
}
/// <summary>
/// Tests that you can get all the values in the collection.
/// </summary>
public void Values_get_Tests()
{
// Verify Values get_Values
// Copy collection values to another collection, then compare them.
List<TValue> knownValuesList = new List<TValue>();
foreach (KeyValuePair<TKey, TValue> pair in _collection)
knownValuesList.Add(pair.Value);
int numItemsSeen = 0;
foreach (TValue value in _collection.Values)
{
numItemsSeen++;
Assert.True(knownValuesList.Contains(value), "Items in the Values collection should exist in the dictionary!");
}
Assert.Equal(_collection.Count, numItemsSeen);
}
/// <summary>
/// Runs all of the tests on get Item.
/// </summary>
public void Item_get_Tests()
{
// Verify get_Item with existing item on Collection
Assert.Equal(_expectedItems.Length, _collection.Count);
for (int i = 0; i < _expectedItems.Length; ++i)
{
TKey expectedKey = _expectedItems[i].Key;
TValue expectedValue = _expectedItems[i].Value;
TValue actualValue = _collection[expectedKey];
Assert.Equal(expectedValue, actualValue);
}
//Verify that the collection was not mutated
VerifyCollection(_collection, _expectedItems);
}
/// <summary>
/// Tests that KeyNotFoundException is thrown when trying to get from
/// a Dictionary whose key is not in the collection.
/// </summary>
public void Item_get_Tests_Negative()
{
// Verify get_Item with non-existing on Collection
TKey nonExistingKey = _generateItem().Key;
Assert.Throws<KeyNotFoundException>(() => { TValue itemValue = _collection[nonExistingKey]; });
//Verify that the collection was not mutated
VerifyCollection(_collection, _expectedItems);
}
/// <summary>
/// Verifies that the items in the given collection match the expected items.
/// </summary>
public void VerifyCollection(IReadOnlyDictionary<TKey, TValue> collection, KeyValuePair<TKey, TValue>[] expectedItems)
{
// verify that you can get all items in collection.
Assert.Equal(expectedItems.Length, collection.Count);
for (int i = 0; i < expectedItems.Length; ++i)
{
TKey expectedKey = expectedItems[i].Key;
TValue expectedValue = expectedItems[i].Value;
Assert.Equal(expectedValue, collection[expectedKey]);
}
VerifyGenericEnumerator(collection, expectedItems);
}
#region Helper Methods
/// <summary>
/// Verifies that the generic enumerator retrieves the correct items.
/// </summary>
private void VerifyGenericEnumerator(IReadOnlyDictionary<TKey, TValue> collection, KeyValuePair<TKey, TValue>[] expectedItems)
{
IEnumerator<KeyValuePair<TKey, TValue>> enumerator = collection.GetEnumerator();
int iterations = 0;
int expectedCount = expectedItems.Length;
// There is no sequential order to the collection, so we're testing that all the items
// in the readonlydictionary exist in the array.
bool[] itemsVisited = new bool[expectedCount];
bool itemFound;
while ((iterations < expectedCount) && enumerator.MoveNext())
{
KeyValuePair<TKey, TValue> currentItem = enumerator.Current;
KeyValuePair<TKey, TValue> tempItem;
// Verify we have not gotten more items then we expected
Assert.True(iterations < expectedCount,
"Err_9844awpa More items have been returned fromt the enumerator(" + iterations + " items) then are in the expectedElements(" + expectedCount + " items)");
// Verify Current returned the correct value
itemFound = false;
for (int i = 0; i < itemsVisited.Length; ++i)
{
if (!itemsVisited[i] && currentItem.Equals(expectedItems[i]))
{
itemsVisited[i] = true;
itemFound = true;
break;
}
}
Assert.True(itemFound, "Err_1432pauy Current returned unexpected value=" + currentItem);
// Verify Current always returns the same value every time it is called
for (int i = 0; i < 3; i++)
{
tempItem = enumerator.Current;
Assert.Equal(currentItem, tempItem);
}
iterations++;
}
for (int i = 0; i < expectedCount; ++i)
{
Assert.True(itemsVisited[i], "Err_052848ahiedoi Expected Current to return true for item: " + expectedItems[i] + "index: " + i);
}
Assert.Equal(expectedCount, iterations);
for (int i = 0; i < 3; i++)
{
Assert.False(enumerator.MoveNext(), "Err_2929ahiea Expected MoveNext to return false after" + iterations + " iterations");
}
enumerator.Dispose();
}
/// <summary>
/// Verifies that the non-generic enumerator retrieves the correct items.
/// </summary>
private void VerifyEnumerator(IReadOnlyDictionary<TKey, TValue> collection, KeyValuePair<TKey, TValue>[] expectedItems)
{
IEnumerator enumerator = collection.GetEnumerator();
int iterations = 0;
int expectedCount = expectedItems.Length;
// There is no sequential order to the collection, so we're testing that all the items
// in the readonlydictionary exist in the array.
bool[] itemsVisited = new bool[expectedCount];
bool itemFound;
while ((iterations < expectedCount) && enumerator.MoveNext())
{
object currentItem = enumerator.Current;
object tempItem;
// Verify we have not gotten more items then we expected
Assert.True(iterations < expectedCount,
"Err_9844awpa More items have been returned fromt the enumerator(" + iterations + " items) then are in the expectedElements(" + expectedCount + " items)");
// Verify Current returned the correct value
itemFound = false;
for (int i = 0; i < itemsVisited.Length; ++i)
{
if (!itemsVisited[i] && expectedItems[i].Equals(currentItem))
{
itemsVisited[i] = true;
itemFound = true;
break;
}
}
Assert.True(itemFound, "Err_1432pauy Current returned unexpected value=" + currentItem);
// Verify Current always returns the same value every time it is called
for (int i = 0; i < 3; i++)
{
tempItem = enumerator.Current;
Assert.Equal(currentItem, tempItem);
}
iterations++;
}
for (int i = 0; i < expectedCount; ++i)
{
Assert.True(itemsVisited[i], "Err_052848ahiedoi Expected Current to return true for item: " + expectedItems[i] + "index: " + i);
}
Assert.Equal(expectedCount, iterations);
for (int i = 0; i < 3; i++)
{
Assert.False(enumerator.MoveNext(), "Err_2929ahiea Expected MoveNext to return false after" + iterations + " iterations");
}
}
/// <summary>
/// tests whether the given item's key is unique in a collection.
/// returns true if it is and false otherwise.
/// </summary>
private bool IsUniqueKey(KeyValuePair<TKey, TValue>[] items, KeyValuePair<TKey, TValue> item)
{
for (int i = 0; i < items.Length; ++i)
{
if (items[i].Key != null && items[i].Key.Equals(item.Key))
{
return false;
}
}
return true;
}
#endregion
}
/// <summary>
/// Helper Dictionary class that implements basic IDictionary
/// functionality but none of the modifier methods.
/// </summary>
public class DummyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private readonly List<KeyValuePair<TKey, TValue>> _items;
private readonly TKey[] _keys;
private readonly TValue[] _values;
public DummyDictionary(KeyValuePair<TKey, TValue>[] items)
{
_keys = new TKey[items.Length];
_values = new TValue[items.Length];
_items = new List<KeyValuePair<TKey, TValue>>(items);
for (int i = 0; i < items.Length; i++)
{
_keys[i] = items[i].Key;
_values[i] = items[i].Value;
}
}
#region IDictionary<TKey, TValue> methods
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return _items.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _items.GetEnumerator();
}
public int Count
{
get { return _items.Count; }
}
public bool ContainsKey(TKey key)
{
foreach (var item in _items)
{
if (item.Key.Equals(key))
return true;
}
return false;
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
foreach (var i in _items)
{
if (i.Equals(item))
return true;
}
return false;
}
public ICollection<TKey> Keys
{
get { return _keys; }
}
public ICollection<TValue> Values
{
get { return _values; }
}
public TValue this[TKey key]
{
get
{
foreach (var item in _items)
{
if (item.Key.Equals(key))
return item.Value;
}
throw new KeyNotFoundException("key does not exist");
}
set
{
throw new NotImplementedException();
}
}
public bool TryGetValue(TKey key, out TValue value)
{
value = default(TValue);
if (!ContainsKey(key))
return false;
value = this[key];
return true;
}
public bool IsReadOnly
{
get { return false; }
}
#endregion
#region Not Implemented Methods
public void Add(TKey key, TValue value)
{
throw new NotImplementedException("Should not have been able to add to the collection.");
}
public void Add(KeyValuePair<TKey, TValue> item)
{
throw new NotImplementedException("Should not have been able to add to the collection.");
}
public bool Remove(TKey key)
{
throw new NotImplementedException("Should not have been able remove items from the collection.");
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
throw new NotImplementedException("Should not have been able remove items from the collection.");
}
public void Clear()
{
throw new NotImplementedException("Should not have been able clear the collection.");
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
throw new NotImplementedException();
}
#endregion
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="CorePropertiesFilter.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description:
// Implements indexing filters for core properties.
// Invoked by PackageFilter and EncryptedPackageFilter
// for filtering core properties in Package and
// EncryptedPackageEnvelope respectively.
//
// History:
// 07/18/2005: ArindamB: Initial implementation
//---------------------------------------------------------------------------
using System;
using System.Windows;
using System.IO.Packaging;
using MS.Internal.Interop;
using System.Runtime.InteropServices;
using System.Globalization;
namespace MS.Internal.IO.Packaging
{
#region CorePropertiesFilter
/// <summary>
/// Class for indexing filters for core properties.
/// Implements IManagedFilter to extract property chunks and values
/// from CoreProperties.
/// </summary>
internal class CorePropertiesFilter : IManagedFilter
{
#region Nested types
/// <summary>
/// Represents a property chunk.
/// </summary>
private class PropertyChunk : ManagedChunk
{
internal PropertyChunk(uint chunkId, Guid guid, uint propId)
: base(
chunkId,
CHUNK_BREAKTYPE.CHUNK_EOS,
new ManagedFullPropSpec(guid, propId),
(uint)CultureInfo.InvariantCulture.LCID,
CHUNKSTATE.CHUNK_VALUE
)
{
}
}
#endregion Nested types
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
/// <param name="coreProperties">core properties to filter</param>
internal CorePropertiesFilter(PackageProperties coreProperties)
{
if (coreProperties == null)
{
throw new ArgumentNullException("coreProperties");
}
_coreProperties = coreProperties;
}
#endregion Constructor
#region IManagedFilter methods
/// <summary>
/// Initialzes the session for this filter.
/// </summary>
/// <param name="grfFlags">usage flags</param>
/// <param name="aAttributes">array of Managed FULLPROPSPEC structs to restrict responses</param>
/// <returns>IFILTER_FLAGS_NONE. Return value is effectively ignored by the caller.</returns>
public IFILTER_FLAGS Init(IFILTER_INIT grfFlags, ManagedFullPropSpec[] aAttributes)
{
// NOTE: Methods parameters have already been validated by XpsFilter.
_grfFlags = grfFlags;
_aAttributes = aAttributes;
// Each call to Init() creates a new enumerator
// with parameters corresponding to current Init() call.
_corePropertyEnumerator = new CorePropertyEnumerator(
_coreProperties, _grfFlags, _aAttributes);
return IFILTER_FLAGS.IFILTER_FLAGS_NONE;
}
/// <summary>
/// Returns description of the next chunk.
/// </summary>
/// <returns>Chunk descriptor if there is a next chunk, else null.</returns>
public ManagedChunk GetChunk()
{
// No GetValue() call pending from this point on.
_pendingGetValue = false;
//
// Move to the next core property that exists and has a value
// and create a chunk descriptor out of it.
//
if (!CorePropertyEnumerator.MoveNext())
{
// End of chunks.
return null;
}
ManagedChunk chunk = new PropertyChunk(
AllocateChunkID(),
CorePropertyEnumerator.CurrentGuid,
CorePropertyEnumerator.CurrentPropId
);
// GetValue() call pending from this point on
// for the current GetChunk call.
_pendingGetValue = true;
return chunk;
}
/// <summary>
/// Gets text content corresponding to current chunk.
/// </summary>
/// <param name="bufferCharacterCount"></param>
/// <returns></returns>
/// <remarks>Not supported in indexing of core properties.</remarks>
public string GetText(int bufferCharacterCount)
{
throw new COMException(SR.Get(SRID.FilterGetTextNotSupported),
(int)FilterErrorCode.FILTER_E_NO_TEXT);
}
/// <summary>
/// Gets the property value corresponding to current chunk.
/// </summary>
/// <returns>Property value</returns>
public object GetValue()
{
// If GetValue() is already called for current chunk,
// return error with FILTER_E_NO_MORE_VALUES.
if (!_pendingGetValue)
{
throw new COMException(SR.Get(SRID.FilterGetValueAlreadyCalledOnCurrentChunk),
(int)FilterErrorCode.FILTER_E_NO_MORE_VALUES);
}
// No GetValue() call pending from this point on
// until another call to GetChunk() is made successfully.
_pendingGetValue = false;
return CorePropertyEnumerator.CurrentValue;
}
#endregion IManagedFilter methods
#region Private methods
/// <summary>
/// Generates unique and legal chunk ID.
/// To be called prior to returning a chunk.
/// </summary>
/// <remarks>
/// 0 is an illegal value, so this function never returns 0.
/// After the counter reaches UInt32.MaxValue, it wraps around to 1.
/// </remarks>
private uint AllocateChunkID()
{
if (_chunkID == UInt32.MaxValue)
{
_chunkID = 1;
}
else
{
_chunkID++;
}
return _chunkID;
}
#endregion
#region Properties
/// <summary>
/// Enumerates core properties based on the
/// core properties and parameters passed in to Init() call.
/// </summary>
private CorePropertyEnumerator CorePropertyEnumerator
{
get
{
if (_corePropertyEnumerator == null)
{
_corePropertyEnumerator = new CorePropertyEnumerator(
_coreProperties, _grfFlags, _aAttributes);
}
return _corePropertyEnumerator;
}
}
#endregion Properties
#region Fields
/// <summary>
/// IFilter.Init parameters.
/// Used to initialize CorePropertyEnumerator.
/// </summary>
IFILTER_INIT _grfFlags = 0;
ManagedFullPropSpec[] _aAttributes = null;
/// <summary>
/// Chunk ID for the current chunk. Incremented for
/// every next chunk.
/// </summary>
private uint _chunkID = 0;
/// <summary>
/// Indicates if GetValue() call is pending
/// for the current chunk queried using GetChunk().
/// If not, GetValue() returns FILTER_E_NO_MORE_VALUES.
/// </summary>
private bool _pendingGetValue = false;
/// <summary>
/// Enumerator used to iterate over the
/// core properties and create chunk out of them.
/// </summary>
private CorePropertyEnumerator _corePropertyEnumerator = null;
/// <summary>
/// Core properties being filtered.
/// Could be PackageCoreProperties or EncryptedPackageCoreProperties.
/// </summary>
private PackageProperties _coreProperties = null;
#endregion Fields
}
#endregion CorePropertiesFilter
#region CorePropertyEnumerator
/// <summary>
/// Enumerator for CoreProperties. Used to iterate through the
/// properties and obtain their property set GUID, property ID and value.
/// </summary>
internal class CorePropertyEnumerator
{
#region Constructors
/// <summary>
/// Constructor.
/// </summary>
/// <param name="coreProperties">CoreProperties to enumerate</param>
/// <param name="grfFlags">
/// if IFILTER_INIT_APPLY_INDEX_ATTRIBUTES is specified,
/// this indicates all core properties to be returned unless
/// the parameter aAttributes is non-empty.
/// </param>
/// <param name="attributes">
/// attributes specified corresponding to the properties to filter.
/// </param>
internal CorePropertyEnumerator(PackageProperties coreProperties,
IFILTER_INIT grfFlags,
ManagedFullPropSpec[] attributes)
{
if (attributes != null && attributes.Length > 0)
{
//
// If attruibutes list specified,
// return core properties for only those attributes.
//
_attributes = attributes;
}
else if ((grfFlags & IFILTER_INIT.IFILTER_INIT_APPLY_INDEX_ATTRIBUTES)
== IFILTER_INIT.IFILTER_INIT_APPLY_INDEX_ATTRIBUTES)
{
//
// If no attributes list specified,
// but IFILTER_INIT_APPLY_INDEX_ATTRIBUTES is present in grfFlags,
// return all core properties.
//
_attributes = new ManagedFullPropSpec[]
{
//
// SummaryInformation
//
new ManagedFullPropSpec(FormatId.SummaryInformation, PropertyId.Title),
new ManagedFullPropSpec(FormatId.SummaryInformation, PropertyId.Subject),
new ManagedFullPropSpec(FormatId.SummaryInformation, PropertyId.Creator),
new ManagedFullPropSpec(FormatId.SummaryInformation, PropertyId.Keywords),
new ManagedFullPropSpec(FormatId.SummaryInformation, PropertyId.Description),
new ManagedFullPropSpec(FormatId.SummaryInformation, PropertyId.LastModifiedBy),
new ManagedFullPropSpec(FormatId.SummaryInformation, PropertyId.Revision),
new ManagedFullPropSpec(FormatId.SummaryInformation, PropertyId.LastPrinted),
new ManagedFullPropSpec(FormatId.SummaryInformation, PropertyId.DateCreated),
new ManagedFullPropSpec(FormatId.SummaryInformation, PropertyId.DateModified),
//
// DocumentSummaryInformation
//
new ManagedFullPropSpec(FormatId.DocumentSummaryInformation, PropertyId.Category),
new ManagedFullPropSpec(FormatId.DocumentSummaryInformation, PropertyId.Identifier),
new ManagedFullPropSpec(FormatId.DocumentSummaryInformation, PropertyId.ContentType),
new ManagedFullPropSpec(FormatId.DocumentSummaryInformation, PropertyId.Language),
new ManagedFullPropSpec(FormatId.DocumentSummaryInformation, PropertyId.Version),
new ManagedFullPropSpec(FormatId.DocumentSummaryInformation, PropertyId.ContentStatus)
};
}
else
{
// No core properties to be returned.
}
_coreProperties = coreProperties;
_currentIndex = -1;
}
#endregion Constructors
#region Internal methods
/// <summary>
/// Move to next property in the enumeration
/// which exists and has a value.
/// </summary>
/// <returns></returns>
internal bool MoveNext()
{
if (_attributes == null)
{
return false;
}
_currentIndex++;
// Move to next existing property with value present.
while (_currentIndex < _attributes.Length)
{
if ( _attributes[_currentIndex].Property.PropType == PropSpecType.Id
&& CurrentValue != null)
{
return true;
}
_currentIndex++;
}
// End of properties.
return false;
}
#endregion Internal methods
#region Internal properties
/// <summary>
/// Property set GUID for current propery.
/// </summary>
internal Guid CurrentGuid
{
get
{
ValidateCurrent();
return _attributes[_currentIndex].Guid;
}
}
/// <summary>
/// Property ID for current property.
/// </summary>
internal uint CurrentPropId
{
get
{
ValidateCurrent();
return _attributes[_currentIndex].Property.PropId;
}
}
/// <summary>
/// Value for current property.
/// </summary>
internal object CurrentValue
{
get
{
ValidateCurrent();
return GetValue(CurrentGuid, CurrentPropId);
}
}
#endregion Internal properties
#region Private methods
/// <summary>
/// Check if the current entry in enumeration is valid.
/// </summary>
private void ValidateCurrent()
{
if (_currentIndex < 0 || _currentIndex >= _attributes.Length)
{
throw new InvalidOperationException(
SR.Get(SRID.CorePropertyEnumeratorPositionedOutOfBounds));
}
}
#endregion
#region Private properties
/// <summary>
/// Get value for the property corresponding to the
/// property set GUID and property ID.
/// </summary>
/// <param name="guid">property set GUID</param>
/// <param name="propId">property ID</param>
/// <returns>
/// property value which could be string or DateTime,
/// or null if it doesn't exist.
/// </returns>
private object GetValue(Guid guid, uint propId)
{
if (guid == FormatId.SummaryInformation)
{
switch (propId)
{
case PropertyId.Title:
return _coreProperties.Title;
case PropertyId.Subject:
return _coreProperties.Subject;
case PropertyId.Creator:
return _coreProperties.Creator;
case PropertyId.Keywords:
return _coreProperties.Keywords;
case PropertyId.Description:
return _coreProperties.Description;
case PropertyId.LastModifiedBy:
return _coreProperties.LastModifiedBy;
case PropertyId.Revision:
return _coreProperties.Revision;
case PropertyId.LastPrinted:
if (_coreProperties.LastPrinted != null)
{
return _coreProperties.LastPrinted.Value;
}
return null;
case PropertyId.DateCreated:
if (_coreProperties.Created != null)
{
return _coreProperties.Created.Value;
}
return null;
case PropertyId.DateModified:
if (_coreProperties.Modified != null)
{
return _coreProperties.Modified.Value;
}
return null;
}
}
else if (guid == FormatId.DocumentSummaryInformation)
{
switch (propId)
{
case PropertyId.Category:
return _coreProperties.Category;
case PropertyId.Identifier:
return _coreProperties.Identifier;
case PropertyId.ContentType:
return _coreProperties.ContentType;
case PropertyId.Language:
return _coreProperties.Language;
case PropertyId.Version:
return _coreProperties.Version;
case PropertyId.ContentStatus:
return _coreProperties.ContentStatus;
}
}
// Property/value not found.
return null;
}
#endregion Private properties
#region Fields
/// <summary>
/// Reference to the CorePropeties to enumerate.
/// </summary>
private PackageProperties _coreProperties;
/// <summary>
/// Indicates the list of properties to be enumerated.
/// </summary>
private ManagedFullPropSpec[] _attributes = null;
/// <summary>
/// Index of the current property in enumeration.
/// </summary>
private int _currentIndex;
#endregion Fields
}
#endregion CorePropertyEnumerator
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DeOps.Interface;
using DeOps.Interface.TLVex;
using DeOps.Interface.Views;
using DeOps.Interface.Views.Res;
using DeOps.Implementation;
using DeOps.Implementation.Transport;
using DeOps.Services.Buddy;
using DeOps.Services.IM;
using DeOps.Services.Location;
using DeOps.Services.Mail;
using DeOps.Services.Trust;
using DeOps.Services.Share;
using DeOps.Services.Voice;
namespace DeOps.Services.Chat
{
public partial class RoomView : UserControl
{
public ChatView ParentView;
public ChatService Chat;
public ChatRoom Room;
public OpCore Core;
LocationService Locations;
ToolStripMenuItem TimestampMenu;
Font BoldFont = new Font("Tahoma", 10, FontStyle.Bold);
Font RegularFont = new Font("Tahoma", 10, FontStyle.Regular);
Font TimeFont = new Font("Tahoma", 8, FontStyle.Regular);
Font SystemFont = new Font("Tahoma", 8, FontStyle.Bold);
Dictionary<ulong, MemberNode> NodeMap = new Dictionary<ulong, MemberNode>();
VoiceToolstripButton VoiceButton;
public RoomView(ChatView parent, ChatService chat, ChatRoom room)
{
InitializeComponent();
ParentView = parent;
Chat = chat;
Room = room;
Core = chat.Core;
Locations = Core.Locations;
GuiUtils.SetupToolstrip(BottomStrip, new OpusColorTable());
if (room.Kind == RoomKind.Command_High || room.Kind == RoomKind.Live_High)
MessageTextBox.BackColor = Color.FromArgb(255, 250, 250);
else if(room.Kind == RoomKind.Command_Low || room.Kind == RoomKind.Live_Low )
MessageTextBox.BackColor = Color.FromArgb(250, 250, 255);
MemberTree.PreventCollapse = true;
MessageTextBox.Core = Core;
MessageTextBox.ContextMenuStrip.Items.Insert(0, new ToolStripSeparator());
TimestampMenu = new ToolStripMenuItem("Timestamps", ViewRes.timestamp, new EventHandler(Menu_Timestamps));
MessageTextBox.ContextMenuStrip.Items.Insert(0, TimestampMenu);
VoiceService voices = Core.GetService(ServiceIDs.Voice) as VoiceService;
if (voices != null)
{
VoiceButton = new VoiceToolstripButton(voices);
BottomStrip.Items.Add(VoiceButton);
}
}
public void Init()
{
InputControl.SendMessage += new TextInput.SendMessageHandler(Input_SendMessage);
Room.MembersUpdate += new MembersUpdateHandler(Chat_MembersUpdate);
Room.ChatUpdate += new ChatUpdateHandler(Chat_Update);
Chat_MembersUpdate();
DisplayLog();
ActiveControl = InputControl.InputBox;
}
public bool Fin()
{
InputControl.SendMessage -= new TextInput.SendMessageHandler(Input_SendMessage);
Room.MembersUpdate -= new MembersUpdateHandler(Chat_MembersUpdate);
Room.ChatUpdate -= new ChatUpdateHandler(Chat_Update);
return true;
}
private void DisplayLog()
{
MessageTextBox.Clear();
Room.Log.LockReading(delegate()
{
foreach (ChatMessage message in Room.Log)
Chat_Update(message);
});
}
public void Input_SendMessage(string message, TextFormat format)
{
Chat.SendMessage(Room, message, format);
}
void Chat_MembersUpdate()
{
MemberTree.BeginUpdate();
MemberTree.Nodes.Clear();
NodeMap.Clear();
List<ulong> users = new List<ulong>();
Room.Members.LockReading(delegate()
{
if (Room.Members.SafeCount == 0)
{
MemberTree.EndUpdate();
return;
}
users = Room.Members.ToList();
TreeListNode root = MemberTree.virtualParent;
if (Room.Host != 0)
{
root = new MemberNode(this, Room.Host);
if (Room.IsLoop)
((MemberNode)root).IsLoopRoot = true;
else
NodeMap[Room.Host] = root as MemberNode;
UpdateNode(root as MemberNode);
MemberTree.Nodes.Add(root);
root.Expand();
}
foreach (ulong id in Room.Members)
if (id != Room.Host)
{
// if they left the room dont show them
if (!ChatService.IsCommandRoom(Room.Kind))
if (Room.Members.SafeCount == 0)
continue;
MemberNode node = new MemberNode(this, id);
NodeMap[id] = node;
UpdateNode(node);
GuiUtils.InsertSubNode(root, node);
}
});
MemberTree.EndUpdate();
if (VoiceButton != null)
{
AudioDirection direction = AudioDirection.Both;
if (ParentView.ViewHigh != null && ParentView.ViewLow != null)
{
if (Room.Kind == RoomKind.Command_High || Room.Kind == RoomKind.Live_High)
direction = AudioDirection.Left;
else if (Room.Kind == RoomKind.Command_Low || Room.Kind == RoomKind.Live_Low)
direction = AudioDirection.Right;
}
VoiceButton.SetUsers(users, direction);
}
}
void UpdateNode(MemberNode node)
{
if (!Room.Members.SafeContains(node.UserID))
{
if (node.IsLoopRoot)
node.Text = "Trust Loop";
return;
}
// get if node is connected
bool connected = (Room.Active &&
(node.UserID == Core.UserID || Chat.Network.RudpControl.GetActiveSessions(node.UserID).Count > 0));
// get away status
bool away = false;
foreach (ClientInfo info in Core.Locations.GetClients(node.UserID))
if (info != null && info.Data.Away)
away = true;
node.Text = Core.GetName(node.UserID);
if (away)
node.Text += " [away]";
// bold if local
if (node.UserID == Core.UserID)
node.Font = new Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
// color based on connect status
Color foreColor = connected ? Color.Black : Color.Gray;
if (node.ForeColor == foreColor)
{
MemberTree.Invalidate();
return; // no change
}
/*if (!node.Unset) // on first run don't show everyone as joined
{
string message = "";
if (connected)
message = Core.GetName(node.UserID) + " has joined the room";
else
message = Core.GetName(node.UserID) + " has left the room";
// dont log
Chat_Update(new ChatMessage(Core, message, true));
}*/
node.Unset = false;
node.ForeColor = foreColor;
MemberTree.Invalidate();
}
void Chat_Update(ChatMessage message)
{
int oldStart = MessageTextBox.SelectionStart;
int oldLength = MessageTextBox.SelectionLength;
MessageTextBox.SelectionStart = MessageTextBox.Text.Length;
MessageTextBox.SelectionLength = 0;
// name, in bold, blue for incoming, red for outgoing
if (message.System)
MessageTextBox.SelectionColor = Color.Black;
else if (Core.Network.Local.Equals(message))
MessageTextBox.SelectionColor = message.Sent ? Color.Red : Color.LightCoral;
else
MessageTextBox.SelectionColor = Color.Blue;
MessageTextBox.SelectionFont = BoldFont;
string prefix = " ";
if (!message.System)
prefix += Chat.GetNameAndLocation(message);
if (MessageTextBox.Text.Length != 0)
prefix = "\n" + prefix;
// add timestamp
if (TimestampMenu.Checked)
{
MessageTextBox.AppendText(prefix);
MessageTextBox.SelectionFont = TimeFont;
MessageTextBox.AppendText(" (" + message.TimeStamp.ToString("T") + ")");
MessageTextBox.SelectionFont = BoldFont;
prefix = "";
}
if (!message.System)
prefix += ": ";
MessageTextBox.AppendText(prefix);
// message, grey for not acked
MessageTextBox.SelectionColor = Color.Black;
if (Core.Network.Local.Equals(message) && !message.Sent)
MessageTextBox.SelectionColor = Color.LightGray;
if (message.System)
{
MessageTextBox.SelectionFont = SystemFont;
MessageTextBox.AppendText(" *" + message.Text);
}
else
{
MessageTextBox.SelectionFont = RegularFont;
if(message.Format == TextFormat.RTF)
MessageTextBox.SelectedRtf = GuiUtils.RtftoColor(message.Text, MessageTextBox.SelectionColor);
else
MessageTextBox.AppendText(message.Text);
}
MessageTextBox.SelectionStart = oldStart;
MessageTextBox.SelectionLength = oldLength;
MessageTextBox.DetectLinksDefault();
if (!MessageTextBox.Focused)
{
MessageTextBox.SelectionStart = MessageTextBox.Text.Length;
MessageTextBox.ScrollToCaret();
}
ParentView.MessageFlash();
}
private void MemberTree_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Right)
return;
MemberNode node = MemberTree.GetNodeAt(e.Location) as MemberNode;
if (node == null)
return;
if(Core.Trust != null)
Core.Trust.Research(node.UserID, 0, false);
Core.Locations.Research(node.UserID);
ContextMenuStripEx treeMenu = new ContextMenuStripEx();
// views
List<MenuItemInfo> quickMenus = new List<MenuItemInfo>();
List<MenuItemInfo> extMenus = new List<MenuItemInfo>();
foreach (var service in ParentView.UI.Services.Values)
{
if (service is TrustService || service is BuddyService)
continue;
service.GetMenuInfo(InterfaceMenuType.Quick, quickMenus, node.UserID, Room.ProjectID);
service.GetMenuInfo(InterfaceMenuType.External, extMenus, node.UserID, Room.ProjectID);
}
if (quickMenus.Count > 0 || extMenus.Count > 0)
if (treeMenu.Items.Count > 0)
treeMenu.Items.Add("-");
foreach (MenuItemInfo info in quickMenus)
treeMenu.Items.Add(new OpMenuItem(node.UserID, Room.ProjectID, info.Path, info));
if (extMenus.Count > 0)
{
ToolStripMenuItem viewItem = new ToolStripMenuItem("Views", InterfaceRes.views);
foreach (MenuItemInfo info in extMenus)
viewItem.DropDownItems.SortedAdd(new OpMenuItem(node.UserID, Room.ProjectID, info.Path, info));
treeMenu.Items.Add(viewItem);
}
// add trust/buddy options at bottom
quickMenus.Clear();
ParentView.UI.Services[ServiceIDs.Buddy].GetMenuInfo(InterfaceMenuType.Quick, quickMenus, node.UserID, Room.ProjectID);
if (ParentView.UI.Services.ContainsKey(ServiceIDs.Trust))
ParentView.UI.Services[ServiceIDs.Trust].GetMenuInfo(InterfaceMenuType.Quick, quickMenus, node.UserID, Room.ProjectID);
if (quickMenus.Count > 0)
{
treeMenu.Items.Add("-");
foreach (MenuItemInfo info in quickMenus)
treeMenu.Items.Add(new OpMenuItem(node.UserID, Room.ProjectID, info.Path, info));
}
// show
if (treeMenu.Items.Count > 0)
treeMenu.Show(MemberTree, e.Location);
}
private void MemberTree_MouseDoubleClick(object sender, MouseEventArgs e)
{
MemberNode node = MemberTree.GetNodeAt(e.Location) as MemberNode;
if (node == null)
return;
OpMenuItem info = new OpMenuItem(node.UserID, 0);
if (Locations.ActiveClientCount(node.UserID) > 0)
{
var im = ParentView.UI.GetService(ServiceIDs.IM) as IMUI;
if (im != null)
im.OpenIMWindow(info.UserID);
}
else
{
var mail = ParentView.UI.GetService(ServiceIDs.Mail) as MailUI;
if (mail != null)
mail.OpenComposeWindow(info.UserID);
}
}
void Menu_Timestamps(object sender, EventArgs e)
{
TimestampMenu.Checked = !TimestampMenu.Checked;
DisplayLog();
}
private void SendFileButton_Click(object sender, EventArgs e)
{
SendFileForm form = new SendFileForm(ParentView.UI, 0);
form.FileProcessed = new Tuple<FileProcessedHandler, object>(new FileProcessedHandler(Chat.Share_FileProcessed), Room);
form.ShowDialog();
}
}
public class MemberNode : TreeListNode
{
OpCore Core;
public ulong UserID;
public bool Unset = true;
public bool IsLoopRoot;
public MemberNode(RoomView view, ulong id)
{
Core = view.Core;
UserID = id;
//Update();
}
/*public void Update()
{
if (IsLoopRoot)
{
Text = "Trust Loop";
return;
}
else
Text = Core.Core.GetName(DhtID);
if (DhtID == Core.LocalDhtID)
Font = new Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
ForeColor = Color.Gray;
}*/
}
}
| |
// 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;
namespace ILCompiler.DependencyAnalysis.ARM
{
public struct ARMEmitter
{
public ARMEmitter(NodeFactory factory, bool relocsOnly)
{
Builder = new ObjectDataBuilder(factory, relocsOnly);
TargetRegister = new TargetRegisterMap(factory.Target.OperatingSystem);
}
public ObjectDataBuilder Builder;
public TargetRegisterMap TargetRegister;
// check the value length
private static bool IsBitNumOverflow(int value, byte numBits)
{
return (value >> numBits) != 0;
}
private static bool IsLowReg(Register reg)
{
return !IsBitNumOverflow((int)reg, 3);
}
private static bool IsValidReg(Register reg)
{
return !IsBitNumOverflow((int)reg, 4);
}
// mov reg, immediate
// reg range: [0..7]
// immediage range: [0..255]
public void EmitMOV(Register reg, int immediate)
{
Debug.Assert(IsLowReg(reg) && !IsBitNumOverflow(immediate, 8));
Builder.EmitShort((short)(0x2000 + ((byte)reg << 8) + immediate));
}
// cmp reg, immediate
// reg range: [0..7]
// immediage range: [0..255]
public void EmitCMP(Register reg, int immediate)
{
Debug.Assert(IsLowReg(reg) && !IsBitNumOverflow(immediate, 8));
Builder.EmitShort((short)(0x2800 + ((byte)reg << 8) + immediate));
}
// add reg, immediate
// reg range: [0..7]
// immediage range: [0..255]
public void EmitADD(Register reg, int immediate)
{
Debug.Assert(IsLowReg(reg) && !IsBitNumOverflow(immediate, 8));
Builder.EmitShort((short)(0x3000 + ((byte)reg << 8) + immediate));
}
// sub reg, immediate
// reg range: [0..7]
// immediage range: [0..255]
public void EmitSUB(Register reg, int immediate)
{
Debug.Assert(IsLowReg(reg) && !IsBitNumOverflow(immediate, 8));
Builder.EmitShort((short)(0x3800 + ((byte)reg << 8) + immediate));
}
// nop
public void EmitNOP()
{
Builder.EmitByte(0x00);
Builder.EmitByte(0xbf);
}
// __debugbreak
public void EmitDebugBreak()
{
Builder.EmitByte(0xde);
Builder.EmitByte(0xfe);
}
// push reg
// reg range: [0..12, LR]
public void EmitPUSH(Register reg)
{
Debug.Assert(reg >= Register.R0 && (reg <= Register.R12 || reg == TargetRegister.LR));
Builder.EmitByte(0x4d);
Builder.EmitByte(0xf8);
Builder.EmitShort((short)(0x0d04 + ((byte)reg << 12)));
}
// pop reg
// reg range: [0..12, LR, PC]
public void EmitPOP(Register reg)
{
Debug.Assert(IsValidReg(reg) && reg != TargetRegister.SP);
Builder.EmitByte(0x5d);
Builder.EmitByte(0xf8);
Builder.EmitShort((short)(0x0b04 + ((byte)reg << 12)));
}
// mov reg, reg
// reg range: [0..PC]
public void EmitMOV(Register destination, Register source)
{
Debug.Assert(IsValidReg(destination) && IsValidReg(source));
Builder.EmitShort((short)(0x4600 + (((byte)destination & 0x8) << 4) + (((byte)source & 0x8) << 3) + (((byte)source & 0x7) << 3) + ((byte)destination & 0x7)));
}
// ldr reg, [reg]
// reg range: [0..7]
public void EmitLDR(Register destination, Register source)
{
Debug.Assert(IsLowReg(destination) && IsLowReg(source));
Builder.EmitShort((short)(0x6800 + (((byte)source & 0x7) << 3) + ((byte)destination & 0x7)));
}
// ldr.w reg, [reg, #offset]
// reg range: [0..PC]
// offset range: [-255..4095]
public void EmitLDR(Register destination, Register source, int offset)
{
Debug.Assert(IsValidReg(destination) && IsValidReg(source));
Debug.Assert(offset >= -255 && offset <= 4095);
if (offset >= 0)
{
Builder.EmitShort((short)(0xf8d0 + ((byte)(source))));
Builder.EmitShort((short)(offset + (((byte)destination) << 12)));
}
else
{
Builder.EmitShort((short)(0xf850 + ((byte)(source))));
Builder.EmitShort((short)(-offset + (((byte)destination) << 12) + (((byte)12) << 8)));
}
}
// movw reg, [reloc] & 0x0000FFFF
// movt reg, [reloc] & 0xFFFF0000
// reg range: [0..12, LR]
public void EmitMOV(Register destination, ISymbolNode symbol)
{
Debug.Assert(destination >= Register.R0 && (destination <= Register.R12 || destination == TargetRegister.LR));
Builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_THUMB_MOV32);
Builder.EmitShort(unchecked((short)0xf240));
Builder.EmitShort((short)((byte)destination << 8));
Builder.EmitShort(unchecked((short)0xf2c0));
Builder.EmitShort((short)((byte)destination << 8));
}
// b.w symbol
public void EmitJMP(ISymbolNode symbol)
{
Debug.Assert(!symbol.RepresentsIndirectionCell);
Builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_THUMB_BRANCH24);
Builder.EmitByte(0);
Builder.EmitByte(0xF0);
Builder.EmitByte(0);
Builder.EmitByte(0xB8);
}
// bx reg
// reg range: [0..PC]
public void EmitJMP(Register destination)
{
Debug.Assert(IsValidReg(destination));
Builder.EmitShort((short)(0x4700 + ((byte)destination << 3)));
}
// bx lr
public void EmitRET()
{
EmitJMP(TargetRegister.LR);
}
// bne #offset
// offset range: [-256..254]
public void EmitBNE(int immediate)
{
Debug.Assert(immediate >= -256 && immediate <= 254);
// considering the pipeline with PC
immediate -= 4;
Builder.EmitByte((byte)(immediate >> 1));
Builder.EmitByte(0xD1);
}
// beq #offset
// offset range: [-256..254]
public void EmitBEQ(int immediate)
{
Debug.Assert(immediate >= -256 && immediate <= 254);
// considering the pipeline with PC
immediate -= 4;
Builder.EmitByte((byte)(immediate >> 1));
Builder.EmitByte(0xD0);
}
// bne label(+4): ret(2) + next(2)
// bx lr
// label: ...
public void EmitRETIfEqual()
{
EmitBNE(4);
EmitRET();
}
}
}
| |
// dnlib: See LICENSE.txt for more info
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using dnlib.DotNet.MD;
using dnlib.DotNet.Pdb;
using dnlib.PE;
using dnlib.Threading;
namespace dnlib.DotNet {
/// <summary>
/// A high-level representation of a row in the Field table
/// </summary>
public abstract class FieldDef : IHasConstant, IHasCustomAttribute, IHasFieldMarshal, IMemberForwarded, IHasCustomDebugInformation, IField, ITokenOperand, IMemberDef {
/// <summary>
/// The row id in its table
/// </summary>
protected uint rid;
#if THREAD_SAFE
readonly Lock theLock = Lock.Create();
#endif
/// <inheritdoc/>
public MDToken MDToken => new MDToken(Table.Field, rid);
/// <inheritdoc/>
public uint Rid {
get => rid;
set => rid = value;
}
/// <inheritdoc/>
public int HasConstantTag => 0;
/// <inheritdoc/>
public int HasCustomAttributeTag => 1;
/// <inheritdoc/>
public int HasFieldMarshalTag => 0;
/// <inheritdoc/>
public int MemberForwardedTag => 0;
/// <summary>
/// Gets all custom attributes
/// </summary>
public CustomAttributeCollection CustomAttributes {
get {
if (customAttributes is null)
InitializeCustomAttributes();
return customAttributes;
}
}
/// <summary/>
protected CustomAttributeCollection customAttributes;
/// <summary>Initializes <see cref="customAttributes"/></summary>
protected virtual void InitializeCustomAttributes() =>
Interlocked.CompareExchange(ref customAttributes, new CustomAttributeCollection(), null);
/// <inheritdoc/>
public int HasCustomDebugInformationTag => 1;
/// <inheritdoc/>
public bool HasCustomDebugInfos => CustomDebugInfos.Count > 0;
/// <summary>
/// Gets all custom debug infos
/// </summary>
public IList<PdbCustomDebugInfo> CustomDebugInfos {
get {
if (customDebugInfos is null)
InitializeCustomDebugInfos();
return customDebugInfos;
}
}
/// <summary/>
protected IList<PdbCustomDebugInfo> customDebugInfos;
/// <summary>Initializes <see cref="customDebugInfos"/></summary>
protected virtual void InitializeCustomDebugInfos() =>
Interlocked.CompareExchange(ref customDebugInfos, new List<PdbCustomDebugInfo>(), null);
/// <summary>
/// From column Field.Flags
/// </summary>
public FieldAttributes Attributes {
get => (FieldAttributes)attributes;
set => attributes = (int)value;
}
/// <summary>Attributes</summary>
protected int attributes;
/// <summary>
/// From column Field.Name
/// </summary>
public UTF8String Name {
get => name;
set => name = value;
}
/// <summary>Name</summary>
protected UTF8String name;
/// <summary>
/// From column Field.Signature
/// </summary>
public CallingConventionSig Signature {
get => signature;
set => signature = value;
}
/// <summary/>
protected CallingConventionSig signature;
/// <summary>
/// Gets/sets the field layout offset
/// </summary>
public uint? FieldOffset {
get {
if (!fieldOffset_isInitialized)
InitializeFieldOffset();
return fieldOffset;
}
set {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
fieldOffset = value;
fieldOffset_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
}
/// <summary/>
protected uint? fieldOffset;
/// <summary/>
protected bool fieldOffset_isInitialized;
void InitializeFieldOffset() {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
if (fieldOffset_isInitialized)
return;
fieldOffset = GetFieldOffset_NoLock();
fieldOffset_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
/// <summary>Called to initialize <see cref="fieldOffset"/></summary>
protected virtual uint? GetFieldOffset_NoLock() => null;
/// <inheritdoc/>
public MarshalType MarshalType {
get {
if (!marshalType_isInitialized)
InitializeMarshalType();
return marshalType;
}
set {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
marshalType = value;
marshalType_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
}
/// <summary/>
protected MarshalType marshalType;
/// <summary/>
protected bool marshalType_isInitialized;
void InitializeMarshalType() {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
if (marshalType_isInitialized)
return;
marshalType = GetMarshalType_NoLock();
marshalType_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
/// <summary>Called to initialize <see cref="marshalType"/></summary>
protected virtual MarshalType GetMarshalType_NoLock() => null;
/// <summary>Reset <see cref="MarshalType"/></summary>
protected void ResetMarshalType() =>
marshalType_isInitialized = false;
/// <summary>
/// Gets/sets the field RVA
/// </summary>
public RVA RVA {
get {
if (!rva_isInitialized)
InitializeRVA();
return rva;
}
set {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
rva = value;
rva_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
}
/// <summary/>
protected RVA rva;
/// <summary/>
protected bool rva_isInitialized;
void InitializeRVA() {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
if (rva_isInitialized)
return;
rva = GetRVA_NoLock();
rva_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
/// <summary>Called to initialize <see cref="rva"/></summary>
protected virtual RVA GetRVA_NoLock() => 0;
/// <summary>Reset <see cref="RVA"/></summary>
protected void ResetRVA() => rva_isInitialized = false;
/// <summary>
/// Gets/sets the initial value. Be sure to set <see cref="HasFieldRVA"/> to <c>true</c> if
/// you write to this field.
/// </summary>
public byte[] InitialValue {
get {
if (!initialValue_isInitialized)
InitializeInitialValue();
return initialValue;
}
set {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
initialValue = value;
initialValue_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
}
/// <summary/>
protected byte[] initialValue;
/// <summary/>
protected bool initialValue_isInitialized;
void InitializeInitialValue() {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
if (initialValue_isInitialized)
return;
initialValue = GetInitialValue_NoLock();
initialValue_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
/// <summary>Called to initialize <see cref="initialValue"/></summary>
protected virtual byte[] GetInitialValue_NoLock() => null;
/// <summary>Reset <see cref="InitialValue"/></summary>
protected void ResetInitialValue() => initialValue_isInitialized = false;
/// <inheritdoc/>
public ImplMap ImplMap {
get {
if (!implMap_isInitialized)
InitializeImplMap();
return implMap;
}
set {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
implMap = value;
implMap_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
}
/// <summary/>
protected ImplMap implMap;
/// <summary/>
protected bool implMap_isInitialized;
void InitializeImplMap() {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
if (implMap_isInitialized)
return;
implMap = GetImplMap_NoLock();
implMap_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
/// <summary>Called to initialize <see cref="implMap"/></summary>
protected virtual ImplMap GetImplMap_NoLock() => null;
/// <inheritdoc/>
public Constant Constant {
get {
if (!constant_isInitialized)
InitializeConstant();
return constant;
}
set {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
constant = value;
constant_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
}
/// <summary/>
protected Constant constant;
/// <summary/>
protected bool constant_isInitialized;
void InitializeConstant() {
#if THREAD_SAFE
theLock.EnterWriteLock(); try {
#endif
if (constant_isInitialized)
return;
constant = GetConstant_NoLock();
constant_isInitialized = true;
#if THREAD_SAFE
} finally { theLock.ExitWriteLock(); }
#endif
}
/// <summary>Called to initialize <see cref="constant"/></summary>
protected virtual Constant GetConstant_NoLock() => null;
/// <summary>Reset <see cref="Constant"/></summary>
protected void ResetConstant() => constant_isInitialized = false;
/// <inheritdoc/>
public bool HasCustomAttributes => CustomAttributes.Count > 0;
/// <inheritdoc/>
public bool HasImplMap => ImplMap is not null;
/// <summary>
/// Gets/sets the declaring type (owner type)
/// </summary>
public TypeDef DeclaringType {
get => declaringType2;
set {
var currentDeclaringType = DeclaringType2;
if (currentDeclaringType == value)
return;
if (currentDeclaringType is not null)
currentDeclaringType.Fields.Remove(this); // Will set DeclaringType2 = null
if (value is not null)
value.Fields.Add(this); // Will set DeclaringType2 = value
}
}
/// <inheritdoc/>
ITypeDefOrRef IMemberRef.DeclaringType => declaringType2;
/// <summary>
/// Called by <see cref="DeclaringType"/> and should normally not be called by any user
/// code. Use <see cref="DeclaringType"/> instead. Only call this if you must set the
/// declaring type without inserting it in the declaring type's method list.
/// </summary>
public TypeDef DeclaringType2 {
get => declaringType2;
set => declaringType2 = value;
}
/// <summary/>
protected TypeDef declaringType2;
/// <summary>
/// Gets/sets the <see cref="FieldSig"/>
/// </summary>
public FieldSig FieldSig {
get => signature as FieldSig;
set => signature = value;
}
/// <inheritdoc/>
public ModuleDef Module => declaringType2?.Module;
bool IIsTypeOrMethod.IsType => false;
bool IIsTypeOrMethod.IsMethod => false;
bool IMemberRef.IsField => true;
bool IMemberRef.IsTypeSpec => false;
bool IMemberRef.IsTypeRef => false;
bool IMemberRef.IsTypeDef => false;
bool IMemberRef.IsMethodSpec => false;
bool IMemberRef.IsMethodDef => false;
bool IMemberRef.IsMemberRef => false;
bool IMemberRef.IsFieldDef => true;
bool IMemberRef.IsPropertyDef => false;
bool IMemberRef.IsEventDef => false;
bool IMemberRef.IsGenericParam => false;
/// <summary>
/// <c>true</c> if <see cref="FieldOffset"/> is not <c>null</c>
/// </summary>
public bool HasLayoutInfo => FieldOffset is not null;
/// <summary>
/// <c>true</c> if <see cref="Constant"/> is not <c>null</c>
/// </summary>
public bool HasConstant => Constant is not null;
/// <summary>
/// Gets the constant element type or <see cref="dnlib.DotNet.ElementType.End"/> if there's no constant
/// </summary>
public ElementType ElementType {
get {
var c = Constant;
return c is null ? ElementType.End : c.Type;
}
}
/// <summary>
/// <c>true</c> if <see cref="MarshalType"/> is not <c>null</c>
/// </summary>
public bool HasMarshalType => MarshalType is not null;
/// <summary>
/// Gets/sets the field type
/// </summary>
public TypeSig FieldType {
get => FieldSig.GetFieldType();
set {
var sig = FieldSig;
if (sig is not null)
sig.Type = value;
}
}
/// <summary>
/// Modify <see cref="attributes"/> field: <see cref="attributes"/> =
/// (<see cref="attributes"/> & <paramref name="andMask"/>) | <paramref name="orMask"/>.
/// </summary>
/// <param name="andMask">Value to <c>AND</c></param>
/// <param name="orMask">Value to OR</param>
void ModifyAttributes(FieldAttributes andMask, FieldAttributes orMask) =>
attributes = (attributes & (int)andMask) | (int)orMask;
/// <summary>
/// Set or clear flags in <see cref="attributes"/>
/// </summary>
/// <param name="set"><c>true</c> if flags should be set, <c>false</c> if flags should
/// be cleared</param>
/// <param name="flags">Flags to set or clear</param>
void ModifyAttributes(bool set, FieldAttributes flags) {
if (set)
attributes |= (int)flags;
else
attributes &= ~(int)flags;
}
/// <summary>
/// Gets/sets the field access
/// </summary>
public FieldAttributes Access {
get => (FieldAttributes)attributes & FieldAttributes.FieldAccessMask;
set => ModifyAttributes(~FieldAttributes.FieldAccessMask, value & FieldAttributes.FieldAccessMask);
}
/// <summary>
/// <c>true</c> if <see cref="FieldAttributes.PrivateScope"/> is set
/// </summary>
public bool IsCompilerControlled => IsPrivateScope;
/// <summary>
/// <c>true</c> if <see cref="FieldAttributes.PrivateScope"/> is set
/// </summary>
public bool IsPrivateScope => ((FieldAttributes)attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.PrivateScope;
/// <summary>
/// <c>true</c> if <see cref="FieldAttributes.Private"/> is set
/// </summary>
public bool IsPrivate => ((FieldAttributes)attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Private;
/// <summary>
/// <c>true</c> if <see cref="FieldAttributes.FamANDAssem"/> is set
/// </summary>
public bool IsFamilyAndAssembly => ((FieldAttributes)attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamANDAssem;
/// <summary>
/// <c>true</c> if <see cref="FieldAttributes.Assembly"/> is set
/// </summary>
public bool IsAssembly => ((FieldAttributes)attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Assembly;
/// <summary>
/// <c>true</c> if <see cref="FieldAttributes.Family"/> is set
/// </summary>
public bool IsFamily => ((FieldAttributes)attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Family;
/// <summary>
/// <c>true</c> if <see cref="FieldAttributes.FamORAssem"/> is set
/// </summary>
public bool IsFamilyOrAssembly => ((FieldAttributes)attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamORAssem;
/// <summary>
/// <c>true</c> if <see cref="FieldAttributes.Public"/> is set
/// </summary>
public bool IsPublic => ((FieldAttributes)attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Public;
/// <summary>
/// Gets/sets the <see cref="FieldAttributes.Static"/> bit
/// </summary>
public bool IsStatic {
get => ((FieldAttributes)attributes & FieldAttributes.Static) != 0;
set => ModifyAttributes(value, FieldAttributes.Static);
}
/// <summary>
/// Gets/sets the <see cref="FieldAttributes.InitOnly"/> bit
/// </summary>
public bool IsInitOnly {
get => ((FieldAttributes)attributes & FieldAttributes.InitOnly) != 0;
set => ModifyAttributes(value, FieldAttributes.InitOnly);
}
/// <summary>
/// Gets/sets the <see cref="FieldAttributes.Literal"/> bit
/// </summary>
public bool IsLiteral {
get => ((FieldAttributes)attributes & FieldAttributes.Literal) != 0;
set => ModifyAttributes(value, FieldAttributes.Literal);
}
/// <summary>
/// Gets/sets the <see cref="FieldAttributes.NotSerialized"/> bit
/// </summary>
public bool IsNotSerialized {
get => ((FieldAttributes)attributes & FieldAttributes.NotSerialized) != 0;
set => ModifyAttributes(value, FieldAttributes.NotSerialized);
}
/// <summary>
/// Gets/sets the <see cref="FieldAttributes.SpecialName"/> bit
/// </summary>
public bool IsSpecialName {
get => ((FieldAttributes)attributes & FieldAttributes.SpecialName) != 0;
set => ModifyAttributes(value, FieldAttributes.SpecialName);
}
/// <summary>
/// Gets/sets the <see cref="FieldAttributes.PinvokeImpl"/> bit
/// </summary>
public bool IsPinvokeImpl {
get => ((FieldAttributes)attributes & FieldAttributes.PinvokeImpl) != 0;
set => ModifyAttributes(value, FieldAttributes.PinvokeImpl);
}
/// <summary>
/// Gets/sets the <see cref="FieldAttributes.RTSpecialName"/> bit
/// </summary>
public bool IsRuntimeSpecialName {
get => ((FieldAttributes)attributes & FieldAttributes.RTSpecialName) != 0;
set => ModifyAttributes(value, FieldAttributes.RTSpecialName);
}
/// <summary>
/// Gets/sets the <see cref="FieldAttributes.HasFieldMarshal"/> bit
/// </summary>
public bool HasFieldMarshal {
get => ((FieldAttributes)attributes & FieldAttributes.HasFieldMarshal) != 0;
set => ModifyAttributes(value, FieldAttributes.HasFieldMarshal);
}
/// <summary>
/// Gets/sets the <see cref="FieldAttributes.HasDefault"/> bit
/// </summary>
public bool HasDefault {
get => ((FieldAttributes)attributes & FieldAttributes.HasDefault) != 0;
set => ModifyAttributes(value, FieldAttributes.HasDefault);
}
/// <summary>
/// Gets/sets the <see cref="FieldAttributes.HasFieldRVA"/> bit
/// </summary>
public bool HasFieldRVA {
get => ((FieldAttributes)attributes & FieldAttributes.HasFieldRVA) != 0;
set => ModifyAttributes(value, FieldAttributes.HasFieldRVA);
}
/// <summary>
/// Returns the full name of this field
/// </summary>
public string FullName => FullNameFactory.FieldFullName(declaringType2?.FullName, name, FieldSig, null, null);
/// <summary>
/// Gets the size of this field in bytes or <c>0</c> if unknown.
/// </summary>
public uint GetFieldSize() {
if (!GetFieldSize(out uint size))
return 0;
return size;
}
/// <summary>
/// Gets the size of this field in bytes or <c>0</c> if unknown.
/// </summary>
/// <param name="size">Updated with size</param>
/// <returns><c>true</c> if <paramref name="size"/> is valid, <c>false</c> otherwise</returns>
public bool GetFieldSize(out uint size) => GetFieldSize(declaringType2, FieldSig, out size);
/// <summary>
/// Gets the size of this field in bytes or <c>0</c> if unknown.
/// </summary>
/// <param name="declaringType">The declaring type of <c>this</c></param>
/// <param name="fieldSig">The field signature of <c>this</c></param>
/// <param name="size">Updated with size</param>
/// <returns><c>true</c> if <paramref name="size"/> is valid, <c>false</c> otherwise</returns>
protected bool GetFieldSize(TypeDef declaringType, FieldSig fieldSig, out uint size) => GetFieldSize(declaringType, fieldSig, GetPointerSize(declaringType), out size);
/// <summary>
/// Gets the size of this field in bytes or <c>0</c> if unknown.
/// </summary>
/// <param name="declaringType">The declaring type of <c>this</c></param>
/// <param name="fieldSig">The field signature of <c>this</c></param>
/// <param name="ptrSize">Size of a pointer</param>
/// <param name="size">Updated with size</param>
/// <returns><c>true</c> if <paramref name="size"/> is valid, <c>false</c> otherwise</returns>
protected bool GetFieldSize(TypeDef declaringType, FieldSig fieldSig, int ptrSize, out uint size) {
size = 0;
if (fieldSig is null)
return false;
return GetClassSize(declaringType, fieldSig.Type, ptrSize, out size);
}
bool GetClassSize(TypeDef declaringType, TypeSig ts, int ptrSize, out uint size) {
size = 0;
ts = ts.RemovePinnedAndModifiers();
if (ts is null)
return false;
int size2 = ts.ElementType.GetPrimitiveSize(ptrSize);
if (size2 >= 0) {
size = (uint)size2;
return true;
}
var tdrs = ts as TypeDefOrRefSig;
if (tdrs is null)
return false;
var td = tdrs.TypeDef;
if (td is not null)
return TypeDef.GetClassSize(td, out size);
var tr = tdrs.TypeRef;
if (tr is not null)
return TypeDef.GetClassSize(tr.Resolve(), out size);
return false;
}
int GetPointerSize(TypeDef declaringType) {
if (declaringType is null)
return 4;
var module = declaringType.Module;
if (module is null)
return 4;
return module.GetPointerSize();
}
/// <inheritdoc/>
public override string ToString() => FullName;
}
/// <summary>
/// A Field row created by the user and not present in the original .NET file
/// </summary>
public class FieldDefUser : FieldDef {
/// <summary>
/// Default constructor
/// </summary>
public FieldDefUser() {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">Name</param>
public FieldDefUser(UTF8String name)
: this(name, null) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">Name</param>
/// <param name="signature">Signature</param>
public FieldDefUser(UTF8String name, FieldSig signature)
: this(name, signature, 0) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">Name</param>
/// <param name="signature">Signature</param>
/// <param name="attributes">Flags</param>
public FieldDefUser(UTF8String name, FieldSig signature, FieldAttributes attributes) {
this.name = name;
this.signature = signature;
this.attributes = (int)attributes;
}
}
/// <summary>
/// Created from a row in the Field table
/// </summary>
sealed class FieldDefMD : FieldDef, IMDTokenProviderMD {
/// <summary>The module where this instance is located</summary>
readonly ModuleDefMD readerModule;
readonly uint origRid;
readonly FieldAttributes origAttributes;
/// <inheritdoc/>
public uint OrigRid => origRid;
/// <inheritdoc/>
protected override void InitializeCustomAttributes() {
var list = readerModule.Metadata.GetCustomAttributeRidList(Table.Field, origRid);
var tmp = new CustomAttributeCollection(list.Count, list, (list2, index) => readerModule.ReadCustomAttribute(list[index]));
Interlocked.CompareExchange(ref customAttributes, tmp, null);
}
/// <inheritdoc/>
protected override void InitializeCustomDebugInfos() {
var list = new List<PdbCustomDebugInfo>();
readerModule.InitializeCustomDebugInfos(new MDToken(MDToken.Table, origRid), new GenericParamContext(declaringType2), list);
Interlocked.CompareExchange(ref customDebugInfos, list, null);
}
/// <inheritdoc/>
protected override uint? GetFieldOffset_NoLock() {
if (readerModule.TablesStream.TryReadFieldLayoutRow(readerModule.Metadata.GetFieldLayoutRid(origRid), out var row))
return row.OffSet;
return null;
}
/// <inheritdoc/>
protected override MarshalType GetMarshalType_NoLock() =>
readerModule.ReadMarshalType(Table.Field, origRid, new GenericParamContext(declaringType2));
/// <inheritdoc/>
protected override RVA GetRVA_NoLock() {
GetFieldRVA_NoLock(out var rva2);
return rva2;
}
/// <inheritdoc/>
protected override byte[] GetInitialValue_NoLock() {
if (!GetFieldRVA_NoLock(out var rva2))
return null;
return ReadInitialValue_NoLock(rva2);
}
/// <inheritdoc/>
protected override ImplMap GetImplMap_NoLock() =>
readerModule.ResolveImplMap(readerModule.Metadata.GetImplMapRid(Table.Field, origRid));
/// <inheritdoc/>
protected override Constant GetConstant_NoLock() =>
readerModule.ResolveConstant(readerModule.Metadata.GetConstantRid(Table.Field, origRid));
/// <summary>
/// Constructor
/// </summary>
/// <param name="readerModule">The module which contains this <c>Field</c> row</param>
/// <param name="rid">Row ID</param>
/// <exception cref="ArgumentNullException">If <paramref name="readerModule"/> is <c>null</c></exception>
/// <exception cref="ArgumentException">If <paramref name="rid"/> is invalid</exception>
public FieldDefMD(ModuleDefMD readerModule, uint rid) {
#if DEBUG
if (readerModule is null)
throw new ArgumentNullException("readerModule");
if (readerModule.TablesStream.FieldTable.IsInvalidRID(rid))
throw new BadImageFormatException($"Field rid {rid} does not exist");
#endif
origRid = rid;
this.rid = rid;
this.readerModule = readerModule;
bool b = readerModule.TablesStream.TryReadFieldRow(origRid, out var row);
Debug.Assert(b);
name = readerModule.StringsStream.ReadNoNull(row.Name);
attributes = row.Flags;
origAttributes = (FieldAttributes)attributes;
declaringType2 = readerModule.GetOwnerType(this);
signature = readerModule.ReadSignature(row.Signature, new GenericParamContext(declaringType2));
}
internal FieldDefMD InitializeAll() {
MemberMDInitializer.Initialize(CustomAttributes);
MemberMDInitializer.Initialize(Attributes);
MemberMDInitializer.Initialize(Name);
MemberMDInitializer.Initialize(Signature);
MemberMDInitializer.Initialize(FieldOffset);
MemberMDInitializer.Initialize(MarshalType);
MemberMDInitializer.Initialize(RVA);
MemberMDInitializer.Initialize(InitialValue);
MemberMDInitializer.Initialize(ImplMap);
MemberMDInitializer.Initialize(Constant);
MemberMDInitializer.Initialize(DeclaringType);
return this;
}
bool GetFieldRVA_NoLock(out RVA rva) {
if ((origAttributes & FieldAttributes.HasFieldRVA) == 0) {
rva = 0;
return false;
}
if (!readerModule.TablesStream.TryReadFieldRVARow(readerModule.Metadata.GetFieldRVARid(origRid), out var row)) {
rva = 0;
return false;
}
rva = (RVA)row.RVA;
return true;
}
byte[] ReadInitialValue_NoLock(RVA rva) {
if (!GetFieldSize(declaringType2, signature as FieldSig, out uint size))
return null;
if (size >= int.MaxValue)
return null;
return readerModule.ReadDataAt(rva, (int)size);
}
}
}
| |
using System;
using Xunit;
using System.Data;
namespace IntegrationTestingLibraryForSqlServer.Tests
{
public class DataTypeTests
{
[Fact]
public void IsStringForStringLikeDataType()
{
var dataType = new DataType(SqlDbType.NVarChar);
Assert.True(dataType.IsString);
}
[Fact]
public void IsStringForIntegerDataType()
{
var dataType = new DataType(SqlDbType.Int);
Assert.False(dataType.IsString);
}
[Fact]
public void IsUnicodeStringForStringLikeDataType()
{
var dataType = new DataType(SqlDbType.NVarChar);
Assert.True(dataType.IsUnicodeString);
}
[Fact]
public void IsUnicodeStringForCharDataType()
{
var dataType = new DataType(SqlDbType.Char);
Assert.False(dataType.IsUnicodeString);
}
[Fact]
public void IsMaximumSizeIndicatorFor1()
{
var dataType = new DataType(SqlDbType.NVarChar);
bool actual = dataType.IsMaximumSizeIndicator(1);
Assert.False(actual);
}
[Fact]
public void IsMaximumSizeIndicatorFor0()
{
var dataType = new DataType(SqlDbType.NVarChar);
bool actual = dataType.IsMaximumSizeIndicator(0);
Assert.True(actual);
}
[Fact]
public void IsMaximumSizeIndicatorForNull()
{
var dataType = new DataType(SqlDbType.NVarChar);
bool actual = dataType.IsMaximumSizeIndicator(null);
Assert.False(actual);
}
[Fact]
public void IsIntegerTrue()
{
var dataType = new DataType(SqlDbType.Int);
bool actual = dataType.IsInteger;
Assert.True(actual);
}
[Fact]
public void IsIntegerFalse()
{
var dataType = new DataType(SqlDbType.VarChar);
bool actual = dataType.IsInteger;
Assert.False(actual);
}
[Fact]
public void IsDecimalTrue()
{
var dataType = new DataType(SqlDbType.Decimal);
bool actual = dataType.IsDecimal;
Assert.True(actual);
}
[Fact]
public void IsDecimalFalse()
{
var dataType = new DataType(SqlDbType.VarChar);
bool actual = dataType.IsDecimal;
Assert.False(actual);
}
[Fact]
public void IsBinaryTrue()
{
var dataType = new DataType(SqlDbType.Binary);
bool actual = dataType.IsBinary;
Assert.True(actual);
}
[Fact]
public void IsBinaryFalse()
{
var dataType = new DataType(SqlDbType.VarChar);
bool actual = dataType.IsBinary;
Assert.False(actual);
}
[Fact]
public void IsValidPrecisionTrue()
{
var dataType = new DataType(SqlDbType.Decimal);
bool actual = dataType.IsValidPrecision(10);
Assert.True(actual);
}
[Fact]
public void IsValidPrecisionFalseMinBound()
{
var dataType = new DataType(SqlDbType.VarChar);
bool actual = dataType.IsValidPrecision(0);
Assert.False(actual);
}
[Fact]
public void IsValidPrecisionFalseMaxBound()
{
var dataType = new DataType(SqlDbType.VarChar);
bool actual = dataType.IsValidPrecision(39);
Assert.False(actual);
}
[Fact]
public void ConstructorStringDataType()
{
var dataType = new DataType("VarChar");
Assert.Equal(SqlDbType.VarChar, dataType.SqlType);
}
[Fact]
public void ConstructorStringDataTypeBadType()
{
Assert.Throws<ArgumentException>(() => new DataType("aaVarChar"));
}
[Fact]
public void ConstructorStringDataTypeNumericAsDecimal()
{
var dataType = new DataType("Numeric");
Assert.Equal(SqlDbType.Decimal, dataType.SqlType);
}
[Fact]
public void DataTypeGetHashCode()
{
var dataType = new DataType(SqlDbType.VarChar);
int expected = SqlDbType.VarChar.GetHashCode();
int actual = dataType.GetHashCode();
Assert.Equal(expected, actual);
}
[Fact]
public void DataTypeEquals()
{
var dataTypeA = new DataType(SqlDbType.VarChar);
var dataTypeB = new DataType(SqlDbType.VarChar);
bool actual = dataTypeA.Equals(dataTypeB);
Assert.True(actual);
}
[Fact]
public void DataTypeEqualsObject()
{
var dataTypeA = new DataType(SqlDbType.VarChar);
var dataTypeB = new DataType(SqlDbType.VarChar);
bool actual = dataTypeA.Equals((object)dataTypeB);
Assert.True(actual);
}
[Fact]
public void DataTypeNotEqualsWrongType()
{
var dataType = new DataType(SqlDbType.VarChar);
bool actual = dataType.Equals(string.Empty);
Assert.False(actual);
}
}
}
| |
// ----------------------------------------------------------------------------
// XmlDocCommentReader.cs
//
// Contains the definition of the XmlDocCommentReader class.
// Copyright 2008 Steve Guidi.
//
// File created: 12/28/2008 22:49:42
// ----------------------------------------------------------------------------
using System;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Xml.Linq;
using Jolt.IO;
using Jolt.Properties;
namespace Jolt
{
// Represents a factory method for creating types that implement
// the IXmlDocCommentReadPolicy interface. The string parameter
// contains the full path of the XML doc comment file that is to
// be read by the policy.
using CreateReadPolicyDelegate=Func<string, IXmlDocCommentReadPolicy>;
/// <summary>
/// Provides methods to retrieve the XML Documentation Comments for an
/// object having a metadata type from the System.Reflection namespace.
/// </summary>
public sealed class XmlDocCommentReader : IXmlDocCommentReader
{
#region constructors ----------------------------------------------------------------------
/// <summary>
/// Creates a new instance of the <see cref="XmlDocCommentReader"/> class
/// by searching for a doc comments file that corresponds to the given assembly.
/// </summary>
///
/// <param name="assembly">
/// The <see cref="System.Reflection.Assembly"/> whose doc comments are retrieved.
/// </param>
///
/// <remarks>
/// Searches in the application's configured search paths, if any.
/// </remarks>
public XmlDocCommentReader(Assembly assembly)
: this(assembly, CreateDefaultReadPolicy) { }
/// <summary>
/// Creates a new instance of the <see cref="XmlDocCommentReader"/> class
/// by searching for a doc comments file that corresponds to the given assembly.
/// Configures the reader to use a user-defined read policy.
/// </summary>
///
/// <param name="assembly">
/// The <see cref="System.Reflection.Assembly"/> whose doc comments are retrieved.
/// </param>
///
/// <param name="createReadPolicy">
/// A factory method that accepts the full path to an XML doc comments file,
/// returning a user-defined read policy.
/// </param>
///
/// <remarks>
/// Searches in the application's configured search paths, if any.
/// </remarks>
public XmlDocCommentReader(Assembly assembly, CreateReadPolicyDelegate createReadPolicy)
: this(assembly, ConfigurationManager.GetSection("XmlDocCommentsReader") as XmlDocCommentReaderSettings, createReadPolicy) { }
/// <summary>
/// Creates a new instance of the <see cref="XmlDocCommentReader"/> class
/// by searching for a doc comments file that corresponds to the given assembly.
/// Searches the given paths, and configures the reader to use a user-defined read policy.
/// </summary>
///
/// <param name="assembly">
/// The <see cref="System.Reflection.Assembly"/> whose doc comments are retrieved.
/// </param>
///
/// <param name="settings">
/// The <see cref="XmlDocCommentReaderSettings"/> object containing the doc comment search paths.
/// </param>
///
/// <param name="createReadPolicy">
/// A factory method that accepts the full path to an XML doc comments file,
/// returning a user-defined read policy.
/// </param>
public XmlDocCommentReader(Assembly assembly, XmlDocCommentReaderSettings settings, CreateReadPolicyDelegate createReadPolicy)
: this(assembly, settings, DefaultFileProxy, createReadPolicy) { }
/// <summary>
/// Creates a new instance of the <see cref="XmlDocCommentReader"/> class
/// with a given path to the XML doc comments.
/// </summary>
///
/// <param name="docCommentsFullPath">
/// The full path of the XML doc comments.
/// </param>
public XmlDocCommentReader(string docCommentsFullPath)
: this(docCommentsFullPath, CreateDefaultReadPolicy) { }
/// <summary>
/// Creates a new instance of the <see cref="XmlDocCommentReader"/> class
/// with a given path to the XML doc comments, and configures the reader
/// to use a user-defined read policy.
/// </summary>
///
/// <param name="docCommentsFullPath">
/// The full path of the XML doc comments.
/// </param>
///
/// <param name="createReadPolicy">
/// A factory method that accepts the full path to an XML doc comments file,
/// returning a user-defined read policy.
/// </param>
public XmlDocCommentReader(string docCommentsFullPath, CreateReadPolicyDelegate createReadPolicy)
: this(docCommentsFullPath, DefaultFileProxy, createReadPolicy(docCommentsFullPath)) { }
/// <summary>
/// Creates a new instance of the <see cref="XmlDocCommentReader"/> class
/// by searching for a doc comments file that corresponds to the given assembly.
/// Searches the given paths, and configures the reader to use a user-defined read policy.
/// </summary>
///
/// <param name="assembly">
/// The <see cref="System.Reflection.Assembly"/> whose doc comments are retrieved.
/// </param>
///
/// <param name="settings">
/// The <see cref="XmlDocCommentReaderSettings"/> object containing the doc comment search paths.
/// </param>
///
/// <param name="fileProxy">
/// The proxy to the file system.
/// </param>
///
/// <param name="createReadPolicy">
/// A factory method that accepts the full path to an XML doc comments file,
/// returning a user-defined read policy.
/// </param>
///
/// <remarks>
/// Used internally by test code to override file IO operations.
/// </remarks>
internal XmlDocCommentReader(Assembly assembly, XmlDocCommentReaderSettings settings, IFile fileProxy, CreateReadPolicyDelegate createReadPolicy)
{
m_settings = settings ?? XmlDocCommentReaderSettings.Default;
m_docCommentsFullPath = ResolveDocCommentsLocation(assembly, m_settings.DirectoryNames, fileProxy);
m_fileProxy = fileProxy;
m_docCommentsReadPolicy = createReadPolicy(m_docCommentsFullPath);
}
/// <summary>
/// Creates a new instance of the <see cref="XmlDocCommentReader"/> class
/// with a given path to the XML doc comments, and configures the reader
/// to use a user-defined read policy.
/// </summary>
///
/// <param name="docCommentsFullPath">
/// The full path of the XML doc comments.
/// </param>
///
/// <param name="fileProxy">
/// The proxy to the file system.
/// </param>
///
/// <param name="readPolicy">
/// The doc comment read policy.
/// </param>
///
/// <remarks>
/// Used internally by test code to override file IO operations.
/// </remarks>
///
/// <exception cref="System.IO.FileNotFoundException">
/// <paramref name="docCommentsFullPath"/> could does not exist or is inaccessible.
/// </exception>
internal XmlDocCommentReader(string docCommentsFullPath, IFile fileProxy, IXmlDocCommentReadPolicy readPolicy)
{
if (!fileProxy.Exists(docCommentsFullPath))
{
throw new FileNotFoundException(
String.Format(Resources.Error_XmlDocComments_FileNotFound, docCommentsFullPath),
docCommentsFullPath);
}
m_fileProxy = fileProxy;
m_docCommentsFullPath = docCommentsFullPath;
m_docCommentsReadPolicy = readPolicy;
m_settings = XmlDocCommentReaderSettings.Default;
}
#endregion
#region public methods --------------------------------------------------------------------
/// <summary>
/// Retrieves the xml doc comments for a given <see cref="System.Type"/>.
/// </summary>
///
/// <param name="type">
/// The <see cref="System.Type"/> for which the doc comments are retrieved.
/// </param>
///
/// <returns>
/// An <see cref="XElement"/> containing the requested XML doc comments,
/// or NULL if none were found.
/// </returns>
public XElement GetComments(Type type)
{
return m_docCommentsReadPolicy.ReadMember(Convert.ToXmlDocCommentMember(type));
}
/// <summary>
/// Retrieves the xml doc comments for a given <see cref="System.Refection.EventInfo"/>.
/// </summary>
///
/// <param name="eventInfo">
/// The <see cref="System.Refection.EventInfo"/> for which the doc comments are retrieved.
/// </param>
///
/// <returns>
/// An <see cref="XElement"/> containing the requested XML doc comments,
/// or NULL if none were found.
/// </returns>
public XElement GetComments(EventInfo eventInfo)
{
return m_docCommentsReadPolicy.ReadMember(Convert.ToXmlDocCommentMember(eventInfo));
}
/// <summary>
/// Retrieves the xml doc comments for a given <see cref="System.Reflection.FieldInfo"/>.
/// </summary>
///
/// <param name="field">
/// The <see cref="System.Reflection.FieldInfo"/> for which the doc comments are retrieved.
/// </param>
///
/// <returns>
/// An <see cref="XElement"/> containing the requested XML doc comments,
/// or NULL if none were found.
/// </returns>
public XElement GetComments(FieldInfo field)
{
return m_docCommentsReadPolicy.ReadMember(Convert.ToXmlDocCommentMember(field));
}
/// <summary>
/// Retrieves the xml doc comments for a given <see cref="System.Reflection.PropertyInfo"/>.
/// </summary>
///
/// <param name="property">
/// The <see cref="System.Reflection.PropertyInfo"/> for which the doc comments are retrieved.
/// </param>
///
/// <returns>
/// An <see cref="XElement"/> containing the requested XML doc comments,
/// or NULL if none were found.
/// </returns>
public XElement GetComments(PropertyInfo property)
{
return m_docCommentsReadPolicy.ReadMember(Convert.ToXmlDocCommentMember(property));
}
/// <summary>
/// Retrieves the xml doc comments for a given <see cref="System.Reflection.ConstructorInfo"/>.
/// </summary>
///
/// <param name="constructor">
/// The <see cref="System.Reflection.ConstructorInfo"/> for which the doc comments are retrieved.
/// </param>
///
/// <returns>
/// An <see cref="XElement"/> containing the requested XML doc comments,
/// or NULL if none were found.
/// </returns>
public XElement GetComments(ConstructorInfo constructor)
{
return m_docCommentsReadPolicy.ReadMember(Convert.ToXmlDocCommentMember(constructor));
}
/// <summary>
/// Retrieves the xml doc comments for a given <see cref="System.Reflection.MethodInfo"/>.
/// </summary>
///
/// <param name="method">
/// The <see cref="System.Reflection.MethodInfo"/> for which the doc comments are retrieved.
/// </param>
///
/// <returns>
/// An <see cref="XElement"/> containing the requested XML doc comments,
/// or NULL if none were found.
/// </returns>
public XElement GetComments(MethodInfo method)
{
return m_docCommentsReadPolicy.ReadMember(Convert.ToXmlDocCommentMember(method));
}
#endregion
#region public properties -----------------------------------------------------------------
/// <summary>
/// Gets the full path to the XML doc comments file that is
/// read by the reader.
/// </summary>
public string FullPath
{
get { return m_docCommentsFullPath; }
}
/// <summary>
/// Gets the configuration settings associated with this object.
/// </summary>
public XmlDocCommentReaderSettings Settings
{
get { return m_settings; }
}
#endregion
#region internal properties ---------------------------------------------------------------
/// <summary>
/// Gets the file proxy used by the class.
/// </summary>
internal IFile FileProxy
{
get { return m_fileProxy; }
}
/// <summary>
/// Gets the read policy used by the class.
/// </summary>
internal IXmlDocCommentReadPolicy ReadPolicy
{
get { return m_docCommentsReadPolicy; }
}
#endregion
#region private methods -------------------------------------------------------------------
/// <summary>
/// Locates the XML doc comment file corresponding to the given
/// <see cref="System.Reflection.Assembly"/>, in the given directories.
/// </summary>
///
/// <param name="assembly">
/// The assembly whose doc comments are retrieved.
/// </param>
///
/// <param name="directories">
/// The directory names to search.
/// </param>
///
/// <param name="fileProxy">
/// The proxy to the file system.
/// </param>
///
/// <returns>
/// The full path to the requested XML doc comment file, if it exists.
/// </returns>
///
/// <exception cref="System.IO.FileNotFoundException">
/// The XML doc comments file was not found, for the given set of parameters.
/// </exception>
private static string ResolveDocCommentsLocation(Assembly assembly, XmlDocCommentDirectoryElementCollection directories, IFile fileProxy)
{
string assemblyFileName = assembly.GetName().Name;
string xmlDocCommentsFilename = String.Concat(assemblyFileName, XmlFileExtension);
foreach (XmlDocCommentDirectoryElement directory in directories)
{
string xmlDocCommentsFullPath = Path.GetFullPath(Path.Combine(directory.Name, xmlDocCommentsFilename));
if (fileProxy.Exists(xmlDocCommentsFullPath))
{
return xmlDocCommentsFullPath;
}
}
throw new FileNotFoundException(
String.Format(Resources.Error_XmlDocComments_AssemblyNotResolved, assemblyFileName),
assemblyFileName);
}
#endregion
#region private fields --------------------------------------------------------------------
private readonly IFile m_fileProxy;
private readonly string m_docCommentsFullPath;
private readonly IXmlDocCommentReadPolicy m_docCommentsReadPolicy;
private readonly XmlDocCommentReaderSettings m_settings;
private static readonly IFile DefaultFileProxy = new FileProxy();
private static readonly CreateReadPolicyDelegate CreateDefaultReadPolicy = path => new DefaultXDCReadPolicy(path, DefaultFileProxy);
private static readonly string XmlFileExtension = ".xml";
#endregion
}
}
| |
using Raging.Data.ReverseEngineering.Infrastructure.Metadata;
using Raging.Data.ReverseEngineering.Infrastructure.Pluralization;
using Raging.Data.Schema;
using Raging.Toolbox.Extensions;
namespace Raging.Data.ReverseEngineering.EntityFramework.Adapters
{
public class PropertyInfoAdapter : IPropertyInfoAdapter
{
private readonly ISchemaTable table;
private readonly IIdentifierGenerationService identifierGenerationService;
private readonly ISchemaColumn column;
#region . Ctors .
public PropertyInfoAdapter(ISchemaColumn column, ISchemaTable table, IIdentifierGenerationService identifierGenerationService)
{
this.column = column;
this.table = table;
this.identifierGenerationService = identifierGenerationService;
}
#endregion
#region . IPropertyInfoAdapter .
public string GetMappingText()
{
// this.Property(t => t.Name).IsRequired().HasMaxLength(250);
// this.Property(t => t.Name).IsRequired().IsFixedLength().HasMaxLength(10);
// this.Property(t => t.ArtworkTypeId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
return @"this.Property(t => t.{0}){1}{2}{3}{4}{5};"
.FormatWith(
this.GetPropertyName(),
this.column.IsNullable ? "\r\n\t.IsOptional()" : "\r\n\t.IsRequired()",
this.column.MaxLength > 0 ? "\r\n\t.HasMaxLength({0})".FormatWith(this.column.MaxLength) : string.Empty,
this.column.Scale > 0 ? "\r\n\t.HasPrecision({0},{1})".FormatWith(this.column.Precision, this.column.Scale) : string.Empty,
//column.IsStoreGenerated && column.SystemType.Like("timestamp") ? ".IsFixedLength().IsRowVersion()" : string.Empty,
this.column.IsRowVersion ? "\r\n\t.IsFixedLength()\r\n\t.IsRowVersion()" : string.Empty,
GetDatabaseGeneratedOption(this.column)
);
}
public string GetColumnMapppingText()
{
// this.Plural(t => t.ModelId).HasColumnName("ModelId");
return @"this.Property(t => t.{0}).HasColumnName(""{1}"");"
.FormatWith(this.GetPropertyName(), this.column.Name);
}
public string GetPropertyName()
{
return this.identifierGenerationService.Generate(this.column.Name, NounForms.Singular, "{0}.{1}".FormatWith(this.table.FullName, this.column.Name));
}
public string GetPropertyText()
{
// public int ModelId { get; set; } // ratingId (Primary key)
// public DateTime? SomeDate { get; set; } // someDate
// public int Computed { get; private set; } // computed
var text = "public {0}{1} {2} {{ {3} }} // {4}{5}"
.FormatWith(
this.column.SystemType,
CheckNullable(this.column),
this.GetPropertyName(),
this.column.IsStoreGenerated ? "get; private set;" : "get; set;",
this.column.Name,
this.column.IsPrimaryKey ? " (Primary key)" : string.Empty
);
return text;
}
const string ConstructorInitializationTextTemplate = @"this.{0} = {1};";
public string GetConstructorInitializationText()
{
//this.Name = @"John Doe";
//this.Age = 25;
//this.BirthDate = DateTime.Parse("2014-05-01 15:40:47.713");
//this.ExternalId = Guid.Parse("37993BAC-E895-4EFA-B726-2FD1405ADC53");
if(HasComputedDefaultValue(this.column)) return null;
string defaultValue = null;
if(this.column.DefaultValue.IsNotBlank())
{
defaultValue = CleanDefaultValue(this.column);
switch (this.column.SystemType)
{
case "Guid":
defaultValue = @"Guid.Parse(""{0}"")".FormatWith(defaultValue);
break;
case "DateTime":
defaultValue = @"DateTime.Parse(""{0}"")".FormatWith(defaultValue);
break;
case "System.Data.Entity.Spatial.DbGeography":
defaultValue = @"DbGeography.Parse(""{0}"")".FormatWith(column.DefaultValue);
break;
case "System.Data.Entity.Spatial.DbGeometry":
defaultValue = @"DbGeometry.Parse(""{0}"")".FormatWith(column.DefaultValue);
break;
case "string":
defaultValue = @"@""{0}""".FormatWith(defaultValue);
break;
//case "long":
//case "short":
//case "int":
// defaultValue = this.column.DefaultValue;
// break;
case "double":
defaultValue = @"{0}d".FormatWith(defaultValue);
break;
case "decimal":
defaultValue = @"{0}m".FormatWith(defaultValue);
break;
case "float":
defaultValue = @"{0}f".FormatWith(defaultValue);
break;
case "bool":
defaultValue = @"{0}".FormatWith(defaultValue == "1" ? "true" : "false");
break;
}
}
else if(!this.column.IsNullable)
{
//only types requiring initialization
switch(this.column.SystemType)
{
case "Guid":
defaultValue = "Guid.NewGuid()";
break;
case "DateTime":
defaultValue = "DateTime.UtcNow";
break;
}
}
return defaultValue.IsBlank()
? null
: ConstructorInitializationTextTemplate
.FormatWith(
this.GetPropertyName(),
defaultValue);
}
#endregion
#region . Helpers .
private static readonly string[] NonNullableTypes =
{
"byte[]",
"string",
"DbGeography",
"DbGeometry"
};
private static string CheckNullable(ISchemaColumn column)
{
return column.IsNullable && column.SystemType.NotLikeAll(NonNullableTypes)
? "?"
: string.Empty;
}
private static bool HasComputedDefaultValue(ISchemaColumn column)
{
return column.DefaultValue.ContainsAny("getdate", "getutcdate", "newid", "newsequentialid");
}
private static string GetDatabaseGeneratedOption(ISchemaColumn column)
{
var hasDatabaseGeneratedOption = (column.SystemType.Like("guid") || column.SystemType.Like("long") ||
column.SystemType.Like("short") || column.SystemType.Like("int") ||
column.SystemType.Like("double") || column.SystemType.Like("float") ||
column.SystemType.Like("decimal"));
if (!hasDatabaseGeneratedOption)
return string.Empty;
if (column.IsIdentity)
return "\r\n\t.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)";
if (column.IsStoreGenerated)
return "\r\n\t.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed)";
if (column.IsPrimaryKey && !column.IsIdentity && !column.IsStoreGenerated)
return "\r\n\t.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)";
return string.Empty;
}
private static string CleanDefaultValue(ISchemaColumn column)
{
return column.SystemType.LikeAny("string","guid","datetime","bool","long","short","int","double","float","decimal")
? column.DefaultValue.Substring(2).Remove(column.DefaultValue.Length - 4, 2)
: column.DefaultValue;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Diagnostics {
using System.Runtime.Remoting;
using System;
using System.Security.Permissions;
using System.IO;
using System.Collections;
using System.Runtime.CompilerServices;
using Encoding = System.Text.Encoding;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
// LogMessageEventHandlers are triggered when a message is generated which is
// "on" per its switch.
//
// By default, the debugger (if attached) is the only event handler.
// There is also a "built-in" console device which can be enabled
// programatically, by registry (specifics....) or environment
// variables.
[Serializable]
[HostProtection(Synchronization=true, ExternalThreading=true)]
internal delegate void LogMessageEventHandler(LoggingLevels level, LogSwitch category,
String message,
StackTrace location);
// LogSwitchLevelHandlers are triggered when the level of a LogSwitch is modified
// NOTE: These are NOT triggered when the log switch setting is changed from the
// attached debugger.
//
[Serializable]
internal delegate void LogSwitchLevelHandler(LogSwitch ls, LoggingLevels newLevel);
internal static class Log
{
// Switches allow relatively fine level control of which messages are
// actually shown. Normally most debugging messages are not shown - the
// user will typically enable those which are relevant to what is being
// investigated.
//
// An attached debugger can enable or disable which messages will
// actually be reported to the user through the COM+ debugger
// services API. This info is communicated to the runtime so only
// desired events are actually reported to the debugger.
internal static Hashtable m_Hashtable;
private static volatile bool m_fConsoleDeviceEnabled;
private static LogMessageEventHandler _LogMessageEventHandler;
private static volatile LogSwitchLevelHandler _LogSwitchLevelHandler;
private static Object locker;
// Constant representing the global switch
public static readonly LogSwitch GlobalSwitch;
static Log()
{
m_Hashtable = new Hashtable();
m_fConsoleDeviceEnabled = false;
//pConsole = null;
//iNumOfMsgHandlers = 0;
//iMsgHandlerArraySize = 0;
locker = new Object();
// allocate the GlobalSwitch object
GlobalSwitch = new LogSwitch ("Global", "Global Switch for this log");
GlobalSwitch.MinimumLevel = LoggingLevels.ErrorLevel;
}
public static void AddOnLogMessage(LogMessageEventHandler handler)
{
lock (locker)
_LogMessageEventHandler =
(LogMessageEventHandler) MulticastDelegate.Combine(_LogMessageEventHandler, handler);
}
public static void RemoveOnLogMessage(LogMessageEventHandler handler)
{
lock (locker)
_LogMessageEventHandler =
(LogMessageEventHandler) MulticastDelegate.Remove(_LogMessageEventHandler, handler);
}
public static void AddOnLogSwitchLevel(LogSwitchLevelHandler handler)
{
lock (locker)
_LogSwitchLevelHandler =
(LogSwitchLevelHandler) MulticastDelegate.Combine(_LogSwitchLevelHandler, handler);
}
public static void RemoveOnLogSwitchLevel(LogSwitchLevelHandler handler)
{
lock (locker)
_LogSwitchLevelHandler =
(LogSwitchLevelHandler) MulticastDelegate.Remove(_LogSwitchLevelHandler, handler);
}
internal static void InvokeLogSwitchLevelHandlers (LogSwitch ls, LoggingLevels newLevel)
{
LogSwitchLevelHandler handler = _LogSwitchLevelHandler;
if (handler != null)
handler(ls, newLevel);
}
// Property to Enable/Disable ConsoleDevice. Enabling the console device
// adds the console device as a log output, causing any
// log messages which make it through filters to be written to the
// application console. The console device is enabled by default if the
// ??? registry entry or ??? environment variable is set.
public static bool IsConsoleEnabled
{
get { return m_fConsoleDeviceEnabled; }
set { m_fConsoleDeviceEnabled = value; }
}
// Generates a log message. If its switch (or a parent switch) allows the
// level for the message, it is "broadcast" to all of the log
// devices.
//
public static void LogMessage(LoggingLevels level, String message)
{
LogMessage (level, GlobalSwitch, message);
}
// Generates a log message. If its switch (or a parent switch) allows the
// level for the message, it is "broadcast" to all of the log
// devices.
//
public static void LogMessage(LoggingLevels level, LogSwitch logswitch, String message)
{
if (logswitch == null)
throw new ArgumentNullException ("LogSwitch");
if (level < 0)
throw new ArgumentOutOfRangeException("level", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Is logging for this level for this switch enabled?
if (logswitch.CheckLevel (level) == true)
{
// Send message for logging
// first send it to the debugger
Debugger.Log ((int) level, logswitch.strName, message);
// Send to the console device
if (m_fConsoleDeviceEnabled)
{
Console.Write(message);
}
}
}
/*
* Following are convenience entry points; all go through Log()
* Note that the (Switch switch, String message) variations
* are preferred.
*/
public static void Trace(LogSwitch logswitch, String message)
{
LogMessage (LoggingLevels.TraceLevel0, logswitch, message);
}
public static void Trace(String switchname, String message)
{
LogSwitch ls;
ls = LogSwitch.GetSwitch (switchname);
LogMessage (LoggingLevels.TraceLevel0, ls, message);
}
public static void Trace(String message)
{
LogMessage (LoggingLevels.TraceLevel0, GlobalSwitch, message);
}
public static void Status(LogSwitch logswitch, String message)
{
LogMessage (LoggingLevels.StatusLevel0, logswitch, message);
}
public static void Status(String switchname, String message)
{
LogSwitch ls;
ls = LogSwitch.GetSwitch (switchname);
LogMessage (LoggingLevels.StatusLevel0, ls, message);
}
public static void Status(String message)
{
LogMessage (LoggingLevels.StatusLevel0, GlobalSwitch, message);
}
public static void Warning(LogSwitch logswitch, String message)
{
LogMessage (LoggingLevels.WarningLevel, logswitch, message);
}
public static void Warning(String switchname, String message)
{
LogSwitch ls;
ls = LogSwitch.GetSwitch (switchname);
LogMessage (LoggingLevels.WarningLevel, ls, message);
}
public static void Warning(String message)
{
LogMessage (LoggingLevels.WarningLevel, GlobalSwitch, message);
}
public static void Error(LogSwitch logswitch, String message)
{
LogMessage (LoggingLevels.ErrorLevel, logswitch, message);
}
public static void Error(String switchname, String message)
{
LogSwitch ls;
ls = LogSwitch.GetSwitch (switchname);
LogMessage (LoggingLevels.ErrorLevel, ls, message);
}
public static void Error(String message)
{
LogMessage (LoggingLevels.ErrorLevel, GlobalSwitch, message);
}
public static void Panic(String message)
{
LogMessage (LoggingLevels.PanicLevel, GlobalSwitch, message);
}
// Native method to inform the EE about the creation of a new LogSwitch
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void AddLogSwitch(LogSwitch logSwitch);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ModifyLogSwitch (int iNewLevel, String strSwitchName, String strParentName);
}
}
| |
#region --- License ---
/* Licensed under the MIT/X11 license.
* Copyright (c) 2006-2008 the OpenTK Team.
* This notice may not be removed from any source distribution.
* See license.txt for licensing details.
*/
#endregion
using System;
using System.IO;
using OpenTK.Audio;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace OpenTK.Audio
{
internal sealed class WaveReader : AudioReader
{
SoundData decoded_data;
//RIFF header
string signature;
int riff_chunck_size;
string format;
//WAVE header
string format_signature;
int format_chunk_size;
short audio_format;
short channels;
int sample_rate;
int byte_rate;
short block_align;
short bits_per_sample;
//DATA header
string data_signature;
int data_chunk_size;
BinaryReader reader;
internal WaveReader() { }
internal WaveReader(Stream s)
{
if (s == null) throw new ArgumentNullException();
if (!s.CanRead) throw new ArgumentException("Cannot read from specified Stream.");
reader = new BinaryReader(s);
this.Stream = s;
}
#if false
/// <summary>
/// Writes the WaveSound's data to the specified OpenAL buffer in the correct format.
/// </summary>
/// <param name="bid">
/// A <see cref="System.UInt32"/>
/// </param>
public void WriteToBuffer(uint bid)
{
unsafe
{
//fix the array as a byte
fixed (byte* p_Data = _Data)
{
if (Channels == 1)
{
if (BitsPerSample == 16)
{
Console.Write("Uploading 16-bit mono data to OpenAL...");
AL.BufferData(bid, ALFormat.Mono16, (IntPtr)p_Data, _Data.Length, SampleRate);
}
else
{
if (BitsPerSample == 8)
{
Console.Write("Uploading 8-bit mono data to OpenAL...");
AL.BufferData(bid, ALFormat.Mono8, (IntPtr)p_Data, _Data.Length, SampleRate);
}
}
}
else
{
if (Channels == 2)
{
if (BitsPerSample == 16)
{
Console.Write("Uploading 16-bit stereo data to OpenAL...");
AL.BufferData(bid, ALFormat.Stereo16, (IntPtr)p_Data, _Data.Length, SampleRate);
}
else
{
if (BitsPerSample == 8)
{
Console.Write("Uploading 8-bit stereo data to OpenAL...");
AL.BufferData(bid, ALFormat.Stereo8, (IntPtr)p_Data, _Data.Length, SampleRate);
}
}
}
}
}
}
}
/// <summary>
/// Writes all relevent information about the WaveSound to the console window.
/// </summary>
public void DumpParamsToConsole()
{
Console.WriteLine("AudioFormat:" + AudioFormat);
Console.WriteLine("Channels:" + Channels);
Console.WriteLine("SampleRate:" + SampleRate);
Console.WriteLine("ByteRate:" + ByteRate);
Console.WriteLine("BlockAlign:" + BlockAlign);
Console.WriteLine("BitsPerSample:" + BitsPerSample);
}
/// <value>
/// Returns the WaveSound's raw sound data as an array of bytes.
/// </value>
public byte[] Data
{
get
{
return _Data;
}
}
#endif
#region --- Public Members ---
#region public override bool Supports(Stream s)
/// <summary>
/// Checks whether the specified stream contains valid WAVE/RIFF buffer.
/// </summary>
/// <param name="s">The System.IO.Stream to check.</param>
/// <returns>True if the stream is a valid WAVE/RIFF file; false otherwise.</returns>
public override bool Supports(Stream s)
{
BinaryReader reader = new BinaryReader(s);
return this.ReadHeaders(reader);
}
#endregion
#region public override SoundData ReadSamples(int samples)
/// <summary>
/// Reads and decodes the specified number of samples from the sound stream.
/// </summary>
/// <param name="samples">The number of samples to read and decode.</param>
/// <returns>An OpenTK.Audio.SoundData object that contains the decoded buffer.</returns>
public override SoundData ReadSamples(long samples)
{
if (samples > reader.BaseStream.Length - reader.BaseStream.Position)
samples = reader.BaseStream.Length - reader.BaseStream.Position;
//while (samples > decoded_data.Data.Length * (bits_per_sample / 8))
// Array.Resize<byte>(ref decoded_data.Data, decoded_data.Data.Length * 2);
decoded_data = new SoundData(new SoundFormat(channels, bits_per_sample, sample_rate),
reader.ReadBytes((int)samples));
return decoded_data;
}
#endregion
#region public override SoundData ReadToEnd()
/// <summary>
/// Reads and decodes the sound stream.
/// </summary>
/// <returns>An OpenTK.Audio.SoundData object that contains the decoded buffer.</returns>
public override SoundData ReadToEnd()
{
try
{
//read the buffer into a byte array, even if the format is 16 bit
//decoded_data = new byte[data_chunk_size];
decoded_data = new SoundData(new SoundFormat(channels, bits_per_sample, sample_rate),
reader.ReadBytes((int)reader.BaseStream.Length));
Debug.WriteLine("decoded!");
//return new SoundData(decoded_data, new SoundFormat(channels, bits_per_sample, sample_rate));
return decoded_data;
}
catch (AudioReaderException)
{
reader.Close();
throw;
}
}
#endregion
#endregion
#region --- Protected Members ---
protected override Stream Stream
{
get { return base.Stream; }
set
{
base.Stream = value;
if (!ReadHeaders(reader))
throw new AudioReaderException("Invalid WAVE/RIFF file: invalid or corrupt signature.");
Debug.Write(String.Format("Opened WAVE/RIFF file: ({0}, {1}, {2}, {3}) ", sample_rate.ToString(), bits_per_sample.ToString(),
channels.ToString(), audio_format.ToString()));
}
}
#endregion
#region --- Private Members ---
// Tries to read the WAVE/RIFF headers, and returns true if they are valid.
bool ReadHeaders(BinaryReader reader)
{
// Don't explicitly call reader.Close()/.Dispose(), as that will close the inner stream.
// There's no such danger if the BinaryReader isn't explicitly destroyed.
// RIFF header
signature = new string(reader.ReadChars(4));
if (signature != "RIFF")
return false;
riff_chunck_size = reader.ReadInt32();
format = new string(reader.ReadChars(4));
if (format != "WAVE")
return false;
// WAVE header
format_signature = new string(reader.ReadChars(4));
if (format_signature != "fmt ")
return false;
format_chunk_size = reader.ReadInt32();
audio_format = reader.ReadInt16();
channels = reader.ReadInt16();
sample_rate = reader.ReadInt32();
byte_rate = reader.ReadInt32();
block_align = reader.ReadInt16();
bits_per_sample = reader.ReadInt16();
data_signature = new string(reader.ReadChars(4));
if (data_signature != "data")
return false;
data_chunk_size = reader.ReadInt32();
return true;
}
#endregion
}
}
| |
using System;
using UnityEngine;
using System.Runtime.InteropServices;
/// <summary>Functions relating to liquidfun fixtures</summary>
public static class LPAPIFixture {
#region AddFixture
/**
* <summary>Creates a fixture, and returns an IntPtr containing its memory address.</summary>
* <param name="bodyPointer">A pointer to the body that the fixture will be attached to.</param>
* <param name="shapeType">The shape of the fixture. 0 for Polygon, 1 for Circle, 2 for Edge, 3 for Chain or Ellipse.</param>
* <param name="shapePointer">Pointer to the shape.</param>
* <param name="density">Density of the fixture.</param>
* <param name="userData">User data for the fixture.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern IntPtr AddFixture(IntPtr bodyPointer, int shapeType, IntPtr shapePointer, float density, float friction, float restitution, bool isSensor, int userData);
#endregion AddFixture
#region GetFixtureInfo
/**
* <summary>Returns an IntPtr to an array of floats containing basic information about a fixture, with its X Position at array[0], Y Position at array[1], and its Angle at array[2] </summary>
* <param name="fixture">A pointer to the fixture who's information will be returned.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern IntPtr GetFixtureInfo(IntPtr fixture);
#endregion GetFixtureInfo
#region GetFixtureUserData
/**
* <summary>Gets the user data of a fixture.</summary>
* <param name="fixture">A pointer to the fixture who's user data will be returned.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern int GetFixtureUserData(IntPtr fixture);
#endregion GetFixtureUserData
#region SetFixtureFilterData
/**
* <summary>Sets the filter data of a fixture.</summary>
* <param name="fixture">A pointer to the fixture who's user data will be returned.</param>
* <param name="groupIndex">Specify an integral group index. You can have all fixtures with the same group index always collide (positive index) or never collide (negative index). Note: Collisions between fixtures of different group indices are filtered according the category and mask bits.</param>
* <param name="categoryBits">Specify which category this fixture belongs to. LiquidFun supports 16 categories (0-15).</param>
* <param name="maskBits">Specify which category this fixture can collide with.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern void SetFixtureFilterData(IntPtr fixture, Int16 groupIndex, UInt16 categoryBits, UInt16 maskBits);
#endregion SetFixtureFilterData
#region GetFixtureGroupIndex
/**
* <summary>Gets the groupIndex filter data of a fixture.</summary>
* <param name="fixture">A pointer to the fixture who's index will be returned.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern UInt16 GetFixtureGroupIndex(IntPtr fixture);
#endregion GetFixtureGroupIndex
#region GetFixtureCategoryBits
/**
* <summary>Gets the categoryBits filter data of a fixture.</summary>
* <param name="fixture">A pointer to the fixture who's filter data will be returned.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern UInt16 GetFixtureCategoryBits(IntPtr fixture);
#endregion GetFixtureCategoryBits
#region GetFixtureMaskBits
/**
* <summary>Gets the maskBits filter data of a fixture.</summary>
* <param name="fixture">A pointer to the fixture who's filter data will be returned.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern UInt16 GetFixtureMaskBits(IntPtr fixture);
#endregion GetFixtureMaskBits
#region TestPoint
/**
* <summary>Tests whether a point is contained in a fixture.</summary>
* <param name="fixture">A pointer to the fixture who's fixture.</param>
* <param name="x">The point to test (x position).</param>
* <param name="y">The point to test (y position).</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern bool TestPoint(IntPtr fixture, float x, float y);
#endregion TestPoint
#region SetFixtureIsSensor
/**
* <summary>Set whether this fixture is a sensor.</summary>
* <param name="fixture">A pointer to the fixture.</param>
* <param name="flag">Is it a sensor?</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern void SetFixtureIsSensor(IntPtr fixture, bool flag);
#endregion SetFixtureIsSensor
#region GetFixtureIsSensor
/**
* <summary>Is this fixture is a sensor?</summary>
* <param name="fixture">A pointer to the fixture.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern bool GetFixtureIsSensor(IntPtr fixture);
#endregion GetFixtureIsSensor
#region SetFixtureDensity
/**
* <summary>Set the density of a fixture.</summary>
* <param name="fixture">A pointer to the fixture.</param>
* <param name="density">The density.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern void SetFixtureDensity(IntPtr fixture, float density);
#endregion SetFixtureDensity
#region GetFixtureDensity
/**
* <summary>Get the density of a fixture.</summary>
* <param name="fixture">A pointer to the fixture.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern float GetFixtureDensity(IntPtr fixture);
#endregion GetFixtureDensity
#region SetFixtureFriction
/**
* <summary>Set the friction of a fixture.</summary>
* <param name="fixture">A pointer to the fixture.</param>
* <param name="friction">The friction.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern void SetFixtureFriction(IntPtr fixture, float friction);
#endregion SetFixtureFriction
#region GetFixtureFriction
/**
* <summary>Get the friction of a fixture.</summary>
* <param name="fixture">A pointer to the fixture.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern float GetFixtureFriction(IntPtr fixture);
#endregion GetFixtureFriction
#region SetFixtureRestitution
/**
* <summary>Set the restitution of a fixture.</summary>
* <param name="fixture">A pointer to the fixture.</param>
* <param name="restitution">The restitution.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern void SetFixtureRestitution(IntPtr fixture, float restitution);
#endregion SetFixtureRestitution
#region GetFixtureRestitution
/**
* <summary>Get the restitution of a fixture.</summary>
* <param name="fixture">A pointer to the fixture.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern float GetFixtureRestitution(IntPtr fixture);
#endregion GetFixtureRestitution
#region DeleteFixture
/**
* <summary>Deletes a fixture. This will automatically adjust the mass of the body if the body is dynamic and the fixture has positive density. This function is locked during callbacks.</summary>
* <param name="bodyPointer">Pointer to the body that the fixture is associated with.</param>
* <param name="fixturePointer">The fixture which will be deleted.</param>
**/
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport ("__Internal")]
#else
[DllImport ("liquidfundll")]
#endif
public static extern void DeleteFixture(IntPtr bodyPointer, IntPtr fixturePointer);
#endregion DeleteFixture
}
| |
namespace PastaPricer
{
using System;
using System.Collections.Generic;
using Michonne.Implementation;
using Michonne.Interfaces;
/// <summary>
/// Computes prices for a given pasta.
/// </summary>
public sealed class PastaPricingAgentNewAPI
{
#region Fields
/// <summary>
/// The sequencer.
/// </summary>
private readonly ISequencer pastaSequencer;
private readonly IDataProcessor<decimal> flourProcessor;
private readonly IDataProcessor<decimal> eggProcessor;
private readonly IDataProcessor<decimal> flavorProcessor;
private readonly IDataProcessor<decimal> packagingProcessor;
private readonly IDataProcessor<decimal> sizeProcessor;
/// <summary>
/// The component prices.
/// </summary>
private decimal? eggPrice;
private decimal? flavorPrice;
private decimal? flourPrice;
private decimal? sizePrice;
private decimal? packagingPrice;
private IEnumerable<IRawMaterialMarketData> marketDatas;
private EventHandler<PastaPriceChangedEventArgs> pastaPriceChangedObservers;
private decimal price;
#endregion
#region Constructors and Destructors
// constructor
public PastaPricingAgentNewAPI(ISequencer pastaSequencer, string pastaName, bool conflationEnabled = false)
{
this.pastaSequencer = pastaSequencer;
this.PastaName = pastaName;
// data processor
this.flourProcessor = this.pastaSequencer.BuildProcessor<decimal>(this.FlourUpdate, conflationEnabled);
this.eggProcessor = this.pastaSequencer.BuildProcessor<decimal>(this.EggUpdate, conflationEnabled);
this.flavorProcessor = this.pastaSequencer.BuildProcessor<decimal>(this.FlavorUpdate, conflationEnabled);
this.packagingProcessor = this.pastaSequencer.BuildProcessor<decimal>(this.PackagingUpdate, conflationEnabled);
this.sizeProcessor = this.pastaSequencer.BuildProcessor<decimal>(this.SizeUpdate, conflationEnabled);
}
#endregion
#region Public Events
// raised when the price is computed
public event EventHandler<PastaPriceChangedEventArgs> PastaPriceChanged
{
add
{
this.pastaSequencer.Dispatch(() => this.pastaPriceChangedObservers += value);
}
remove
{
// ReSharper disable once DelegateSubtraction
this.pastaSequencer.Dispatch(() => this.pastaPriceChangedObservers -= value);
}
}
#endregion
#region Public Properties
private string PastaName { get; set; }
#endregion
#region Methods
#region Constructor
#endregion
// initialization logic
public void SubscribeToMarketData(IEnumerable<IRawMaterialMarketData> sourceMarketDatas)
{
this.marketDatas = sourceMarketDatas;
// ingredient prices are set at 0
this.eggPrice = 0;
this.flourPrice = 0;
this.flavorPrice = 0;
foreach (var rawMaterialMarketData in this.marketDatas)
{
// indentify the argument family, subscribe to it
// and invalidate the current value.
var role = RecipeHelper.ParseRawMaterialRole(rawMaterialMarketData.RawMaterialName);
switch (role)
{
case RawMaterialRole.Flour:
this.flourPrice = null;
rawMaterialMarketData.PriceChanged += this.MarketDataFlourPriceChanged;
break;
case RawMaterialRole.Egg:
this.eggPrice = null;
rawMaterialMarketData.PriceChanged += this.MarketDataEggPriceChanged;
break;
case RawMaterialRole.Flavor:
this.flavorPrice = null;
rawMaterialMarketData.PriceChanged += this.MarketDataFlavorPriceChanged;
break;
case RawMaterialRole.Size:
this.sizePrice = null;
rawMaterialMarketData.PriceChanged += this.MarketDataSizePriceChanged;
break;
case RawMaterialRole.Packaging:
this.packagingPrice = null;
rawMaterialMarketData.PriceChanged += this.MarketDataPackagingPriceChanged;
break;
}
}
}
#region Overrides of Object
public override string ToString()
{
return this.PastaName;
}
#endregion
private void MarketDataPackagingPriceChanged(object sender, RawMaterialPriceChangedEventArgs e)
{
this.packagingProcessor.Post(e.Price);
}
private void MarketDataSizePriceChanged(object sender, RawMaterialPriceChangedEventArgs e)
{
this.sizeProcessor.Post(e.Price);
}
private void MarketDataEggPriceChanged(object sender, RawMaterialPriceChangedEventArgs e)
{
this.eggProcessor.Post(e.Price);
}
private void Compute()
{
if (!this.HasAllRequestedInputsForComputation())
{
return;
}
// ReSharper disable once PossibleInvalidOperationException
this.price = PastaCalculator.Compute(this.flourPrice.Value, this.eggPrice.Value, this.flavorPrice.Value, this.sizePrice, this.packagingPrice);
this.RaisePastaPriceChanged(this.price);
}
private bool HasAllRequestedInputsForComputation()
{
// TODO: cache the "true" value
return this.flourPrice.HasValue && this.eggPrice.HasValue && this.flavorPrice.HasValue;
}
private void RaisePastaPriceChanged(decimal newPrice)
{
this.pastaPriceChangedObservers?.Invoke(this, new PastaPriceChangedEventArgs(this.PastaName, newPrice));
}
#region other price handlers
private void MarketDataFlavorPriceChanged(object sender, RawMaterialPriceChangedEventArgs e)
{
this.flavorProcessor.Post(e.Price);
}
private void MarketDataFlourPriceChanged(object sender, RawMaterialPriceChangedEventArgs e)
{
this.flourProcessor.Post(e.Price);
}
private void SizeUpdate(decimal newPrice)
{
this.sizePrice = newPrice;
this.Compute();
}
private void PackagingUpdate(decimal newPrice)
{
this.packagingPrice = newPrice;
this.Compute();
}
private void FlavorUpdate(decimal newPrice)
{
this.flavorPrice = newPrice;
this.Compute();
}
private void FlourUpdate(decimal newPrice)
{
this.flourPrice = newPrice;
this.Compute();
}
private void EggUpdate(decimal newPrice)
{
this.eggPrice = newPrice;
this.Compute();
}
#endregion
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Util;
using Plugin.CustomCamera.Abstractions;
using Android.Hardware;
using Java.IO;
using Android.Media;
namespace Plugin.CustomCamera
{
[Register("Plugin.CustomCamera.CustomCameraView")]
public class CustomCameraView :
FrameLayout,
ICustomCameraView,
TextureView.ISurfaceTextureListener,
Camera.IPictureCallback,
Camera.IPreviewCallback,
Camera.IShutterCallback
{
Camera _camera;
Activity _activity;
Android.Graphics.SurfaceTexture _surface;
Camera.CameraInfo _cameraInfo;
int _w;
int _h;
string pictureName = "picture.jpg";
bool _isCameraStarted = false;
int _imageRotation;
int _cameraHardwareRotation;
public CustomCameraView(Context context, IAttributeSet attrs): base(context, attrs)
{
this._activity = (Activity)context;
if (CustomCameraInstance.CustomCameraView != null)
{
// set properties, otherwise they will be cleared
_selectedCamera = CustomCameraInstance.CustomCameraView.SelectedCamera;
_cameraOrientation = CustomCameraInstance.CustomCameraView.CameraOrientation;
}
var _textureView = new TextureView(context);
_textureView.SurfaceTextureListener = this;
AddView(_textureView);
// make this view available in the PCL
CustomCameraInstance.CustomCameraView = this;
}
#region ICustomCameraView interface implementation
CameraOrientation _cameraOrientation = CameraOrientation.Automatic;
static CameraSelection _selectedCamera;
Action<string> _callback;
/// <summary>
/// The selected camera, front or back
/// </summary>
public CameraSelection SelectedCamera
{
get
{
return _selectedCamera;
}
set
{
if (_selectedCamera == value)
return;
OpenCamera(value);
SetTexture();
}
}
/// <summary>
/// The camera orientation
/// </summary>
public CameraOrientation CameraOrientation
{
get
{
return _cameraOrientation;
}
set
{
if (_cameraOrientation == value)
return;
_cameraOrientation = value;
SetCameraOrientation();
}
}
/// <summary>
/// Take a picture
/// </summary>
/// <param name="callback"></param>
public void TakePicture(Action<string> callback)
{
if (_camera == null)
return;
_callback = callback;
Android.Hardware.Camera.Parameters p = _camera.GetParameters();
p.PictureFormat = Android.Graphics.ImageFormatType.Jpeg;
//var size = p.PreviewSize;
_camera.SetParameters(p);
_camera.TakePicture(this, this, this);
}
/// <summary>
/// Starts the camera
/// </summary>
/// <param name="selectedCamera">The selected camera, default: Back</param>
public void Start(CameraSelection selectedCamera = CameraSelection.Back)
{
_cameraOrientation = Abstractions.CameraOrientation.Automatic;
if (_selectedCamera == CameraSelection.None)
_selectedCamera = selectedCamera;
_isCameraStarted = true;
if (_surface != null)
OpenCamera(_selectedCamera);
}
/// <summary>
/// Stops the camera
/// </summary>
/// <param name="callback"></param>
public void Stop()
{
CloseCamera();
}
/// <summary>
/// Call this method this to reset the camera after taking a picture
/// </summary>
/// <param name="callback"></param>
public void Reset()
{
SetTexture();
}
#endregion
private void Callback(string path)
{
var cb = _callback;
_callback = null;
cb(path);
}
//https://forums.xamarin.com/discussion/17625/custom-camera-takepicture
void Camera.IPictureCallback.OnPictureTaken(byte[] data, Android.Hardware.Camera camera)
{
File dataDir = Android.OS.Environment.ExternalStorageDirectory;
if (data != null)
{
try
{
var path = dataDir + "/" + pictureName;
SaveFile(path, data);
RotateBitmap(path, data);
Callback(path);
}
catch (FileNotFoundException e)
{
System.Console.Out.WriteLine(e.Message);
}
catch (IOException ie)
{
System.Console.Out.WriteLine(ie.Message);
}
}
}
private void SaveFile(string path, byte[] data)
{
using (var outStream = new FileOutputStream(path))
{
outStream.Write(data);
outStream.Close();
}
}
void SetCameraOrientation()
{
// Google's camera orientation vs device orientation is all over the place, it changes per api version, per device type (phone/tablet) and per device brand
// Credits: http://stackoverflow.com/questions/4645960/how-to-set-android-camera-orientation-properly
if (_cameraInfo == null)
return;
Display display = _activity.WindowManager.DefaultDisplay;
//var displayRotation = display.Rotation;
int displayRotation = 0;
switch (display.Rotation)
{
case SurfaceOrientation.Rotation0:
displayRotation = 0;
break;
case SurfaceOrientation.Rotation90:
displayRotation = 90;
break;
case SurfaceOrientation.Rotation180:
displayRotation = 180;
break;
case SurfaceOrientation.Rotation270:
displayRotation = 270;
break;
default:
break;
}
int correctedDisplayRotation;
var camHardwareRotation = _cameraHardwareRotation;
if (SelectedCamera == CameraSelection.Back)
{
camHardwareRotation = MirrorOrientation(_cameraHardwareRotation);
}
correctedDisplayRotation = (camHardwareRotation + displayRotation) % 360;
correctedDisplayRotation = MirrorOrientation(correctedDisplayRotation); // compensate the mirror
_imageRotation = correctedDisplayRotation;
if (SelectedCamera == CameraSelection.Back)
{
_imageRotation = MirrorOrientation(_imageRotation);
}
Android.Hardware.Camera.Parameters p = _camera.GetParameters();
p.PictureFormat = Android.Graphics.ImageFormatType.Jpeg;
_camera.SetParameters(p);
_camera.SetDisplayOrientation(correctedDisplayRotation);
// set dimensions:
double aspectRatio = (double)p.PreviewSize.Height / (double)p.PreviewSize.Width;
if ((int)(_h * aspectRatio) < _w)
{
_h = (int)(_w * aspectRatio);
}
else
{
_w = (int)(_h * aspectRatio);
}
if (correctedDisplayRotation == 90 || correctedDisplayRotation == 270)
{
var w = _w;
// portrait
_w = (int)(_h * aspectRatio);
CorrectDimensions(w, _w);
}
else
{
var h = _h;
// landscape
_h = (int)(_w * aspectRatio);
CorrectDimensions(h, _h);
}
}
private void CorrectDimensions(int fullSize, int scaledSize)
{
if (scaledSize < fullSize)
{
// make sure the camera fills the requested area
double factor = (double)fullSize / (double)scaledSize;
_w = (int)(_w * factor);
_h = (int)(_h * factor);
}
}
private int MirrorOrientation(int orientation)
{
return (360 - orientation) % 360;
}
/// <summary>
/// Rotate the picture taken
/// https://forums.xamarin.com/discussion/5409/photo-being-saved-in-landscape-not-portrait
/// </summary>
/// <param name="path"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns></returns>
void RotateBitmap(string path, byte[] data)
{
try
{
//using (Android.Graphics.Bitmap picture = Android.Graphics.BitmapFactory.DecodeFile(path))
using (Android.Graphics.Bitmap picture = data.ToBitmap())
using (Android.Graphics.Matrix mtx = new Android.Graphics.Matrix())
{
ExifInterface exif = new ExifInterface(path);
string orientation = exif.GetAttribute(ExifInterface.TagOrientation);
var camOrientation = int.Parse(orientation);
switch (_imageRotation)
{
case 0: // landscape
break;
case 90: // landscape upside down
mtx.PreRotate(270);
break;
case 180: // portrait
mtx.PreRotate(180);
break;
case 270: // portrait upside down
mtx.PreRotate(90);
break;
}
var maxSize = 1024;
double w = picture.Width;
double h = picture.Height;
if(picture.Width > maxSize || picture.Height > maxSize)
{
// set scaled width and height to prevent out of memory exception
double scaleFactor = (double)maxSize / (double)picture.Width;
if(picture.Height > picture.Width)
scaleFactor = (double)maxSize / picture.Height;
w = picture.Width * scaleFactor;
h = picture.Height * scaleFactor;
}
using (var scaledPiture = Android.Graphics.Bitmap.CreateScaledBitmap(picture, (int)w, (int)h, false))
using (var rotatedPiture = Android.Graphics.Bitmap.CreateBitmap(scaledPiture, 0, 0, (int)w, (int)h, mtx, false))
{
SaveFile(path, rotatedPiture.ToBytes());
}
}
}
catch (Java.Lang.OutOfMemoryError e)
{
e.PrintStackTrace();
throw;
}
}
void Camera.IPreviewCallback.OnPreviewFrame(byte[] b, Android.Hardware.Camera c)
{
}
void Camera.IShutterCallback.OnShutter()
{
}
public void OnSurfaceTextureAvailable(Android.Graphics.SurfaceTexture surface, int w, int h)
{
_surface = surface;
_w = w;
_h = h;
if (!_isCameraStarted)
return;
OpenCamera(_selectedCamera);
SetTexture();
}
private void SetTexture()
{
if (_camera == null || _surface == null)
return;
SetCameraOrientation();
this.LayoutParameters.Width = _w;
this.LayoutParameters.Height = _h;
try
{
//_camera.SetPreviewCallback(this);
//_camera.Lock();
_camera.SetPreviewTexture(_surface);
_camera.StartPreview();
}
catch (Java.IO.IOException ex)
{
//Console.WriteLine(ex.Message);
}
}
public void OnSurfaceTextureSizeChanged(Android.Graphics.SurfaceTexture surface, int width, int height)
{
// ??
}
public void OnSurfaceTextureUpdated(Android.Graphics.SurfaceTexture surface)
{
// Fires whenever the surface change (moving the camera etc.)
}
public void OnSurfaceChanged(Android.Graphics.SurfaceTexture holder, int format, int w, int h)
{
// Now that the size is known, set up the camera parameters and begin
// the preview.
//Camera.Parameters parameters = mCamera.getParameters();
//parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
//requestLayout();
//mCamera.setParameters(parameters);
//// Important: Call startPreview() to start updating the preview surface.
//// Preview must be started before you can take a picture.
//mCamera.startPreview();
}
public bool OnSurfaceTextureDestroyed(Android.Graphics.SurfaceTexture surface)
{
CloseCamera();
return true;
}
private void OpenCamera(CameraSelection cameraSelection)
{
CloseCamera();
int cameraCount = 0;
_cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.NumberOfCameras;
for (int camIdx = 0; camIdx < cameraCount; camIdx++)
{
Camera.GetCameraInfo(camIdx, _cameraInfo);
if (_cameraInfo.Facing == cameraSelection.ToCameraFacing())
{
try
{
_camera = Camera.Open(camIdx);
//var size = new Camera.Size(_camera, 300, 300);
_cameraHardwareRotation = _cameraInfo.Orientation;
_selectedCamera = cameraSelection;
_isCameraStarted = true;
}
catch (Exception e)
{
CloseCamera();
Log.Error("CustomCameraView OpenCamera", e.Message);
}
}
}
}
//private void GetSize()
//{
// var p = _camera.GetParameters();
// p.PreviewSize
// List<Size> sizes = camera_parameters.getSupportedPreviewSizes();
//}
private void CloseCamera()
{
if (_camera != null)
{
//_camera.Unlock();
_camera.StopPreview();
//_camera.SetPreviewCallback(null);
_camera.Release();
_camera = null;
_isCameraStarted = false;
}
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Xml;
using Umbraco.Core;
using System.Collections.Generic;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using RazorDataTypeModelStaticMappingItem = umbraco.MacroEngines.RazorDataTypeModelStaticMappingItem;
namespace umbraco
{
/// <summary>
/// The UmbracoSettings Class contains general settings information for the entire Umbraco instance based on information from the /config/umbracoSettings.config file
/// </summary>
[Obsolete("Use UmbracoConfig.For.UmbracoSettings() instead, it offers all settings in strongly typed formats. This class will be removed in future versions.")]
public class UmbracoSettings
{
[Obsolete("This hasn't been used since 4.1!")]
public const string TEMP_FRIENDLY_XML_CHILD_CONTAINER_NODENAME = ""; // "children";
/// <summary>
/// Gets the umbraco settings document.
/// </summary>
/// <value>The _umbraco settings.</value>
public static XmlDocument _umbracoSettings
{
get
{
var us = (XmlDocument)HttpRuntime.Cache["umbracoSettingsFile"] ?? EnsureSettingsDocument();
return us;
}
}
/// <summary>
/// Gets a value indicating whether the media library will create new directories in the /media directory.
/// </summary>
/// <value>
/// <c>true</c> if new directories are allowed otherwise, <c>false</c>.
/// </value>
public static bool UploadAllowDirectories
{
get { return UmbracoConfig.For.UmbracoSettings().Content.UploadAllowDirectories; }
}
/// <summary>
/// Gets a value indicating whether logging is enabled in umbracoSettings.config (/settings/logging/enableLogging).
/// </summary>
/// <value><c>true</c> if logging is enabled; otherwise, <c>false</c>.</value>
public static bool EnableLogging
{
get { return UmbracoConfig.For.UmbracoSettings().Logging.EnableLogging; }
}
/// <summary>
/// Gets a value indicating whether logging happens async.
/// </summary>
/// <value><c>true</c> if async logging is enabled; otherwise, <c>false</c>.</value>
public static bool EnableAsyncLogging
{
get { return UmbracoConfig.For.UmbracoSettings().Logging.EnableAsyncLogging; }
}
/// <summary>
/// Gets the assembly of an external logger that can be used to store log items in 3rd party systems
/// </summary>
public static string ExternalLoggerAssembly
{
get { return UmbracoConfig.For.UmbracoSettings().Logging.ExternalLoggerAssembly; }
}
/// <summary>
/// Gets the type of an external logger that can be used to store log items in 3rd party systems
/// </summary>
public static string ExternalLoggerType
{
get { return UmbracoConfig.For.UmbracoSettings().Logging.ExternalLoggerType; }
}
/// <summary>
/// Long Audit Trail to external log too
/// </summary>
public static bool ExternalLoggerLogAuditTrail
{
get { return UmbracoConfig.For.UmbracoSettings().Logging.ExternalLoggerEnableAuditTrail; }
}
/// <summary>
/// Keep user alive as long as they have their browser open? Default is true
/// </summary>
public static bool KeepUserLoggedIn
{
get { return UmbracoConfig.For.UmbracoSettings().Security.KeepUserLoggedIn; }
}
/// <summary>
/// Show disabled users in the tree in the Users section in the backoffice
/// </summary>
public static bool HideDisabledUsersInBackoffice
{
get { return UmbracoConfig.For.UmbracoSettings().Security.HideDisabledUsersInBackoffice; }
}
/// <summary>
/// Gets a value indicating whether the logs will be auto cleaned
/// </summary>
/// <value><c>true</c> if logs are to be automatically cleaned; otherwise, <c>false</c></value>
public static bool AutoCleanLogs
{
get { return UmbracoConfig.For.UmbracoSettings().Logging.AutoCleanLogs; }
}
/// <summary>
/// Gets the value indicating the log cleaning frequency (in miliseconds)
/// </summary>
public static int CleaningMiliseconds
{
get { return UmbracoConfig.For.UmbracoSettings().Logging.CleaningMiliseconds; }
}
public static int MaxLogAge
{
get { return UmbracoConfig.For.UmbracoSettings().Logging.MaxLogAge; }
}
/// <summary>
/// Gets the disabled log types.
/// </summary>
/// <value>The disabled log types.</value>
public static XmlNode DisabledLogTypes
{
get { return GetKeyAsNode("/settings/logging/disabledLogTypes"); }
}
/// <summary>
/// Gets the package server url.
/// </summary>
/// <value>The package server url.</value>
public static string PackageServer
{
get { return "packages.umbraco.org"; }
}
/// <summary>
/// Gets a value indicating whether umbraco will use domain prefixes.
/// </summary>
/// <value><c>true</c> if umbraco will use domain prefixes; otherwise, <c>false</c>.</value>
public static bool UseDomainPrefixes
{
get { return UmbracoConfig.For.UmbracoSettings().RequestHandler.UseDomainPrefixes; }
}
/// <summary>
/// This will add a trailing slash (/) to urls when in directory url mode
/// NOTICE: This will always return false if Directory Urls in not active
/// </summary>
public static bool AddTrailingSlash
{
get { return UmbracoConfig.For.UmbracoSettings().RequestHandler.AddTrailingSlash; }
}
/// <summary>
/// Gets a value indicating whether umbraco will use ASP.NET MasterPages for rendering instead of its propriatary templating system.
/// </summary>
/// <value><c>true</c> if umbraco will use ASP.NET MasterPages; otherwise, <c>false</c>.</value>
public static bool UseAspNetMasterPages
{
get { return UmbracoConfig.For.UmbracoSettings().Templates.UseAspNetMasterPages; }
}
/// <summary>
/// Gets a value indicating whether umbraco will attempt to load any skins to override default template files
/// </summary>
/// <value><c>true</c> if umbraco will override templates with skins if present and configured <c>false</c>.</value>
public static bool EnableTemplateFolders
{
get { return UmbracoConfig.For.UmbracoSettings().Templates.EnableTemplateFolders; }
}
/// <summary>
/// razor DynamicNode typecasting detects XML and returns DynamicXml - Root elements that won't convert to DynamicXml
/// </summary>
public static List<string> NotDynamicXmlDocumentElements
{
get { return UmbracoConfig.For.UmbracoSettings().Scripting.NotDynamicXmlDocumentElements.Select(x => x.Element).ToList(); }
}
public static List<RazorDataTypeModelStaticMappingItem> RazorDataTypeModelStaticMapping
{
get
{
var mapping = UmbracoConfig.For.UmbracoSettings().Scripting.DataTypeModelStaticMappings;
//now we need to map to the old object until we can clean all this nonsense up
return mapping.Select(x => new RazorDataTypeModelStaticMappingItem()
{
DataTypeGuid = x.DataTypeGuid,
NodeTypeAlias = x.NodeTypeAlias,
PropertyTypeAlias = x.PropertyTypeAlias,
Raw = string.Empty,
TypeName = x.MappingName
}).ToList();
}
}
/// <summary>
/// Gets a value indicating whether umbraco will clone XML cache on publish.
/// </summary>
/// <value>
/// <c>true</c> if umbraco will clone XML cache on publish; otherwise, <c>false</c>.
/// </value>
public static bool CloneXmlCacheOnPublish
{
get { return UmbracoConfig.For.UmbracoSettings().Content.CloneXmlContent; }
}
/// <summary>
/// Gets a value indicating whether rich text editor content should be parsed by tidy.
/// </summary>
/// <value><c>true</c> if content is parsed; otherwise, <c>false</c>.</value>
public static bool TidyEditorContent
{
get { return UmbracoConfig.For.UmbracoSettings().Content.TidyEditorContent; }
}
/// <summary>
/// Gets the encoding type for the tidyied content.
/// </summary>
/// <value>The encoding type as string.</value>
public static string TidyCharEncoding
{
get { return UmbracoConfig.For.UmbracoSettings().Content.TidyCharEncoding; }
}
/// <summary>
/// Gets the property context help option, this can either be 'text', 'icon' or 'none'
/// </summary>
/// <value>The property context help option.</value>
public static string PropertyContextHelpOption
{
get { return UmbracoConfig.For.UmbracoSettings().Content.PropertyContextHelpOption; }
}
public static string DefaultBackofficeProvider
{
get { return UmbracoConfig.For.UmbracoSettings().Providers.DefaultBackOfficeUserProvider; }
}
/// <summary>
/// Whether to force safe aliases (no spaces, no special characters) at businesslogic level on contenttypes and propertytypes
/// </summary>
public static bool ForceSafeAliases
{
get { return UmbracoConfig.For.UmbracoSettings().Content.ForceSafeAliases; }
}
/// <summary>
/// File types that will not be allowed to be uploaded via the content/media upload control
/// </summary>
public static IEnumerable<string> DisallowedUploadFiles
{
get { return UmbracoConfig.For.UmbracoSettings().Content.DisallowedUploadFiles; }
}
/// <summary>
/// Gets the allowed image file types.
/// </summary>
/// <value>The allowed image file types.</value>
public static string ImageFileTypes
{
get { return string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.ImageFileTypes.Select(x => x.ToLowerInvariant())); }
}
/// <summary>
/// Gets the allowed script file types.
/// </summary>
/// <value>The allowed script file types.</value>
public static string ScriptFileTypes
{
get { return string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.ScriptFileTypes); }
}
/// <summary>
/// Gets the duration in seconds to cache queries to umbraco library member and media methods
/// Default is 1800 seconds (30 minutes)
/// </summary>
public static int UmbracoLibraryCacheDuration
{
get { return UmbracoConfig.For.UmbracoSettings().Content.UmbracoLibraryCacheDuration; }
}
/// <summary>
/// Gets the path to the scripts folder used by the script editor.
/// </summary>
/// <value>The script folder path.</value>
public static string ScriptFolderPath
{
get { return UmbracoConfig.For.UmbracoSettings().Content.ScriptFolderPath; }
}
/// <summary>
/// Enabled or disable the script/code editor
/// </summary>
public static bool ScriptDisableEditor
{
get { return UmbracoConfig.For.UmbracoSettings().Content.ScriptEditorDisable; }
}
/// <summary>
/// Gets a value indicating whether umbraco will ensure unique node naming.
/// This will ensure that nodes cannot have the same url, but will add extra characters to a url.
/// ex: existingnodename.aspx would become existingnodename(1).aspx if a node with the same name is found
/// </summary>
/// <value><c>true</c> if umbraco ensures unique node naming; otherwise, <c>false</c>.</value>
public static bool EnsureUniqueNaming
{
get { return UmbracoConfig.For.UmbracoSettings().Content.EnsureUniqueNaming; }
}
/// <summary>
/// Gets the notification email sender.
/// </summary>
/// <value>The notification email sender.</value>
public static string NotificationEmailSender
{
get { return UmbracoConfig.For.UmbracoSettings().Content.NotificationEmailAddress; }
}
/// <summary>
/// Gets a value indicating whether notification-emails are HTML.
/// </summary>
/// <value>
/// <c>true</c> if html notification-emails are disabled; otherwise, <c>false</c>.
/// </value>
public static bool NotificationDisableHtmlEmail
{
get { return UmbracoConfig.For.UmbracoSettings().Content.DisableHtmlEmail; }
}
/// <summary>
/// Gets the allowed attributes on images.
/// </summary>
/// <value>The allowed attributes on images.</value>
public static string ImageAllowedAttributes
{
get { return string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.ImageTagAllowedAttributes); }
}
public static XmlNode ImageAutoFillImageProperties
{
get { return GetKeyAsNode("/settings/content/imaging/autoFillImageProperties"); }
}
/// <summary>
/// Gets the scheduled tasks as XML
/// </summary>
/// <value>The scheduled tasks.</value>
public static XmlNode ScheduledTasks
{
get { return GetKeyAsNode("/settings/scheduledTasks"); }
}
/// <summary>
/// Gets a list of characters that will be replaced when generating urls
/// </summary>
/// <value>The URL replacement characters.</value>
public static XmlNode UrlReplaceCharacters
{
get { return GetKeyAsNode("/settings/requestHandler/urlReplacing"); }
}
/// <summary>
/// Whether to replace double dashes from url (ie my--story----from--dash.aspx caused by multiple url replacement chars
/// </summary>
public static bool RemoveDoubleDashesFromUrlReplacing
{
get { return UmbracoConfig.For.UmbracoSettings().RequestHandler.RemoveDoubleDashes; }
}
/// <summary>
/// Gets a value indicating whether umbraco will use distributed calls.
/// This enables umbraco to share cache and content across multiple servers.
/// Used for load-balancing high-traffic sites.
/// </summary>
/// <value><c>true</c> if umbraco uses distributed calls; otherwise, <c>false</c>.</value>
public static bool UseDistributedCalls
{
get { return UmbracoConfig.For.UmbracoSettings().DistributedCall.Enabled; }
}
/// <summary>
/// Gets the ID of the user with access rights to perform the distributed calls.
/// </summary>
/// <value>The distributed call user.</value>
public static int DistributedCallUser
{
get { return UmbracoConfig.For.UmbracoSettings().DistributedCall.UserId; }
}
/// <summary>
/// Gets the html injected into a (x)html page if Umbraco is running in preview mode
/// </summary>
public static string PreviewBadge
{
get { return UmbracoConfig.For.UmbracoSettings().Content.PreviewBadge; }
}
/// <summary>
/// Gets IP or hostnames of the distribution servers.
/// These servers will receive a call everytime content is created/deleted/removed
/// and update their content cache accordingly, ensuring a consistent cache on all servers
/// </summary>
/// <value>The distribution servers.</value>
public static XmlNode DistributionServers
{
get
{
try
{
return GetKeyAsNode("/settings/distributedCall/servers");
}
catch
{
return null;
}
}
}
/// <summary>
/// Gets HelpPage configurations.
/// A help page configuration specify language, user type, application, application url and
/// the target help page url.
/// </summary>
public static XmlNode HelpPages
{
get
{
try
{
return GetKeyAsNode("/settings/help");
}
catch
{
return null;
}
}
}
/// <summary>
/// Gets all repositories registered, and returns them as XmlNodes, containing name, alias and webservice url.
/// These repositories are used by the build-in package installer and uninstaller to install new packages and check for updates.
/// All repositories should have a unique alias.
/// All packages installed from a repository gets the repository alias included in the install information
/// </summary>
/// <value>The repository servers.</value>
public static XmlNode Repositories
{
get
{
try
{
return GetKeyAsNode("/settings/repositories");
}
catch
{
return null;
}
}
}
/// <summary>
/// Gets a value indicating whether umbraco will use the viewstate mover module.
/// The viewstate mover will move all asp.net viewstate information to the bottom of the aspx page
/// to ensure that search engines will index text instead of javascript viewstate information.
/// </summary>
/// <value>
/// <c>true</c> if umbraco will use the viewstate mover module; otherwise, <c>false</c>.
/// </value>
public static bool UseViewstateMoverModule
{
get { return UmbracoConfig.For.UmbracoSettings().ViewStateMoverModule.Enable; }
}
/// <summary>
/// Tells us whether the Xml Content cache is disabled or not
/// Default is enabled
/// </summary>
public static bool isXmlContentCacheDisabled
{
get { return UmbracoConfig.For.UmbracoSettings().Content.XmlCacheEnabled == false; }
}
/// <summary>
/// Check if there's changes to the umbraco.config xml file cache on disk on each request
/// Makes it possible to updates environments by syncing the umbraco.config file across instances
/// Relates to http://umbraco.codeplex.com/workitem/30722
/// </summary>
public static bool XmlContentCheckForDiskChanges
{
get { return UmbracoConfig.For.UmbracoSettings().Content.XmlContentCheckForDiskChanges; }
}
/// <summary>
/// If this is enabled, all Umbraco objects will generate data in the preview table (cmsPreviewXml).
/// If disabled, only documents will generate data.
/// This feature is useful if anyone would like to see how data looked at a given time
/// </summary>
public static bool EnableGlobalPreviewStorage
{
get { return UmbracoConfig.For.UmbracoSettings().Content.GlobalPreviewStorageEnabled; }
}
/// <summary>
/// Whether to use the new 4.1 schema or the old legacy schema
/// </summary>
/// <value>
/// <c>true</c> if yes, use the old node/data model; otherwise, <c>false</c>.
/// </value>
public static bool UseLegacyXmlSchema
{
get { return UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema; }
}
public static IEnumerable<string> AppCodeFileExtensionsList
{
get { return UmbracoConfig.For.UmbracoSettings().Developer.AppCodeFileExtensions.Select(x => x.Extension); }
}
[Obsolete("Use AppCodeFileExtensionsList instead")]
public static XmlNode AppCodeFileExtensions
{
get
{
XmlNode value = GetKeyAsNode("/settings/developer/appCodeFileExtensions");
if (value != null)
{
return value;
}
// default is .cs and .vb
value = _umbracoSettings.CreateElement("appCodeFileExtensions");
value.AppendChild(XmlHelper.AddTextNode(_umbracoSettings, "ext", "cs"));
value.AppendChild(XmlHelper.AddTextNode(_umbracoSettings, "ext", "vb"));
return value;
}
}
/// <summary>
/// Tells us whether the Xml to always update disk cache, when changes are made to content
/// Default is enabled
/// </summary>
public static bool continouslyUpdateXmlDiskCache
{
get { return UmbracoConfig.For.UmbracoSettings().Content.ContinouslyUpdateXmlDiskCache; }
}
/// <summary>
/// Tells us whether to use a splash page while umbraco is initializing content.
/// If not, requests are queued while umbraco loads content. For very large sites (+10k nodes) it might be usefull to
/// have a splash page
/// Default is disabled
/// </summary>
public static bool EnableSplashWhileLoading
{
get { return UmbracoConfig.For.UmbracoSettings().Content.EnableSplashWhileLoading; }
}
public static bool ResolveUrlsFromTextString
{
get { return UmbracoConfig.For.UmbracoSettings().Content.ResolveUrlsFromTextString; }
}
/// <summary>
/// This configuration setting defines how to handle macro errors:
/// - Inline - Show error within macro as text (default and current Umbraco 'normal' behavior)
/// - Silent - Suppress error and hide macro
/// - Throw - Throw an exception and invoke the global error handler (if one is defined, if not you'll get a YSOD)
/// </summary>
/// <value>MacroErrorBehaviour enum defining how to handle macro errors.</value>
public static MacroErrorBehaviour MacroErrorBehaviour
{
get { return UmbracoConfig.For.UmbracoSettings().Content.MacroErrorBehaviour; }
}
/// <summary>
/// This configuration setting defines how to show icons in the document type editor.
/// - ShowDuplicates - Show duplicates in files and sprites. (default and current Umbraco 'normal' behaviour)
/// - HideSpriteDuplicates - Show files on disk and hide duplicates from the sprite
/// - HideFileDuplicates - Show files in the sprite and hide duplicates on disk
/// </summary>
/// <value>MacroErrorBehaviour enum defining how to show icons in the document type editor.</value>
[Obsolete("This is no longer used and will be removed from the core in future versions")]
public static IconPickerBehaviour IconPickerBehaviour
{
get { return IconPickerBehaviour.ShowDuplicates; }
}
/// <summary>
/// Gets the default document type property used when adding new properties through the back-office
/// </summary>
/// <value>Configured text for the default document type property</value>
/// <remarks>If undefined, 'Textstring' is the default</remarks>
public static string DefaultDocumentTypeProperty
{
get { return UmbracoConfig.For.UmbracoSettings().Content.DefaultDocumentTypeProperty; }
}
private static string _path;
/// <summary>
/// Gets the settings file path
/// </summary>
internal static string SettingsFilePath
{
get { return _path ?? (_path = GlobalSettings.FullpathToRoot + Path.DirectorySeparatorChar + "config" + Path.DirectorySeparatorChar); }
}
internal const string Filename = "umbracoSettings.config";
internal static XmlDocument EnsureSettingsDocument()
{
var settingsFile = HttpRuntime.Cache["umbracoSettingsFile"];
// Check for language file in cache
if (settingsFile == null)
{
var temp = new XmlDocument();
var settingsReader = new XmlTextReader(SettingsFilePath + Filename);
try
{
temp.Load(settingsReader);
HttpRuntime.Cache.Insert("umbracoSettingsFile", temp,
new CacheDependency(SettingsFilePath + Filename));
}
catch (XmlException e)
{
throw new XmlException("Your umbracoSettings.config file fails to pass as valid XML. Refer to the InnerException for more information", e);
}
catch (Exception e)
{
LogHelper.Error<UmbracoSettings>("Error reading umbracoSettings file: " + e.ToString(), e);
}
settingsReader.Close();
return temp;
}
else
return (XmlDocument)settingsFile;
}
internal static void Save()
{
_umbracoSettings.Save(SettingsFilePath + Filename);
}
/// <summary>
/// Selects a xml node in the umbraco settings config file.
/// </summary>
/// <param name="key">The xpath query to the specific node.</param>
/// <returns>If found, it returns the specific configuration xml node.</returns>
internal static XmlNode GetKeyAsNode(string key)
{
if (key == null)
throw new ArgumentException("Key cannot be null");
EnsureSettingsDocument();
if (_umbracoSettings == null || _umbracoSettings.DocumentElement == null)
return null;
return _umbracoSettings.DocumentElement.SelectSingleNode(key);
}
/// <summary>
/// Gets the value of configuration xml node with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
internal static string GetKey(string key)
{
EnsureSettingsDocument();
string attrName = null;
var pos = key.IndexOf('@');
if (pos > 0)
{
attrName = key.Substring(pos + 1);
key = key.Substring(0, pos - 1);
}
var node = _umbracoSettings.DocumentElement.SelectSingleNode(key);
if (node == null)
return string.Empty;
if (pos < 0)
{
if (node.FirstChild == null || node.FirstChild.Value == null)
return string.Empty;
return node.FirstChild.Value;
}
else
{
var attr = node.Attributes[attrName];
if (attr == null)
return string.Empty;
return attr.Value;
}
}
}
}
| |
// INFORM request message type.
// 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.
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/8/3
* Time: 15:37
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using Snmp.Core.Security;
namespace Snmp.Core.Messaging
{
/// <summary>
/// INFORM request message.
/// </summary>
public sealed class InformRequestMessage : ISnmpMessage
{
private readonly byte[] _bytes;
/// <summary>
/// Creates a <see cref="InformRequestMessage"/> with all contents.
/// </summary>
/// <param name="requestId">The request id.</param>
/// <param name="version">Protocol version.</param>
/// <param name="community">Community name.</param>
/// <param name="enterprise">Enterprise.</param>
/// <param name="time">Time ticks.</param>
/// <param name="variables">Variables.</param>
public InformRequestMessage(int requestId, VersionCode version, OctetString community, Oid enterprise, uint time, IList<Variable> variables)
{
if (variables == null)
{
throw new ArgumentNullException("variables");
}
if (enterprise == null)
{
throw new ArgumentNullException("enterprise");
}
if (community == null)
{
throw new ArgumentNullException("community");
}
if (version == VersionCode.V3)
{
throw new ArgumentException("only v1 and v2c are supported", "version");
}
Version = version;
Enterprise = enterprise;
TimeStamp = time;
Header = Header.Empty;
Parameters = SecurityParameters.Create(community);
var pdu = new InformRequestPdu(
requestId,
enterprise,
time,
variables);
Scope = new Scope(pdu);
Privacy = DefaultPrivacyProvider.DefaultPair;
_bytes = this.PackMessage(null).ToBytes();
}
/// <summary>
/// Initializes a new instance of the <see cref="InformRequestMessage"/> class.
/// </summary>
/// <param name="version">The version.</param>
/// <param name="messageId">The message id.</param>
/// <param name="requestId">The request id.</param>
/// <param name="userName">Name of the user.</param>
/// <param name="enterprise">The enterprise.</param>
/// <param name="time">The time.</param>
/// <param name="variables">The variables.</param>
/// <param name="privacy">The privacy provider.</param>
/// <param name="report">The report.</param>
[Obsolete("Please use other overloading ones.")]
public InformRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, Oid enterprise, uint time, IList<Variable> variables, IPrivacyProvider privacy, ISnmpMessage report)
: this(version, messageId, requestId, userName, enterprise, time, variables, privacy, 0xFFE3, report)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InformRequestMessage"/> class.
/// </summary>
/// <param name="version">The version.</param>
/// <param name="messageId">The message id.</param>
/// <param name="requestId">The request id.</param>
/// <param name="userName">Name of the user.</param>
/// <param name="enterprise">The enterprise.</param>
/// <param name="time">The time.</param>
/// <param name="variables">The variables.</param>
/// <param name="privacy">The privacy provider.</param>
/// <param name="maxMessageSize">Size of the max message.</param>
/// <param name="report">The report.</param>
public InformRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, Oid enterprise, uint time, IList<Variable> variables, IPrivacyProvider privacy, int maxMessageSize, ISnmpMessage report)
{
if (userName == null)
{
throw new ArgumentNullException("userName");
}
if (variables == null)
{
throw new ArgumentNullException("variables");
}
if (version != VersionCode.V3)
{
throw new ArgumentException("only v3 is supported", "version");
}
if (enterprise == null)
{
throw new ArgumentNullException("enterprise");
}
if (report == null)
{
throw new ArgumentNullException("report");
}
if (privacy == null)
{
throw new ArgumentNullException("privacy");
}
Version = version;
Privacy = privacy;
Enterprise = enterprise;
TimeStamp = time;
Header = new Header(new Integer32(messageId), new Integer32(maxMessageSize), privacy.ToSecurityLevel() | Levels.Reportable);
var parameters = report.Parameters;
var authenticationProvider = Privacy.AuthenticationProvider;
Parameters = new SecurityParameters(
parameters.EngineId,
parameters.EngineBoots,
parameters.EngineTime,
userName,
authenticationProvider.CleanDigest,
Privacy.Salt);
var pdu = new InformRequestPdu(
requestId,
enterprise,
time,
variables);
var scope = report.Scope;
var contextEngineId = scope.ContextEngineId == OctetString.Empty ? parameters.EngineId : scope.ContextEngineId;
Scope = new Scope(contextEngineId, scope.ContextName, pdu);
Privacy.ComputeHash(Version, Header, Parameters, Scope);
_bytes = this.PackMessage(null).ToBytes();
}
internal InformRequestMessage(VersionCode version, Header header, SecurityParameters parameters, Scope scope, IPrivacyProvider privacy, byte[] length)
{
if (scope == null)
{
throw new ArgumentNullException("scope");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (header == null)
{
throw new ArgumentNullException("header");
}
if (privacy == null)
{
throw new ArgumentNullException("privacy");
}
Version = version;
Header = header;
Parameters = parameters;
Scope = scope;
Privacy = privacy;
var pdu = (InformRequestPdu)scope.Pdu;
Enterprise = pdu.Enterprise;
TimeStamp = pdu.TimeStamp;
_bytes = this.PackMessage(length).ToBytes();
}
/// <summary>
/// Gets the privacy provider.
/// </summary>
/// <value>The privacy provider.</value>
public IPrivacyProvider Privacy { get; private set; }
/// <summary>
/// Gets the version.
/// </summary>
/// <value>The version.</value>
public VersionCode Version { get; private set; }
/// <summary>
/// Gets the time stamp.
/// </summary>
/// <value>The time stamp.</value>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TimeStamp")]
public uint TimeStamp { get; private set; }
/// <summary>
/// Enterprise.
/// </summary>
public Oid Enterprise { get; private set; }
/// <summary>
/// Gets the header.
/// </summary>
public Header Header { get; private set; }
/// <summary>
/// Converts to byte format.
/// </summary>
/// <returns></returns>
public byte[] ToBytes()
{
return _bytes;
}
/// <summary>
/// Gets the parameters.
/// </summary>
/// <value>The parameters.</value>
public SecurityParameters Parameters { get; private set; }
/// <summary>
/// Gets the scope.
/// </summary>
/// <value>The scope.</value>
public Scope Scope { get; private set; }
/// <summary>
/// Returns a <see cref="string"/> that represents this <see cref="InformRequestMessage"/>.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"INFORM request message: time stamp: {0}; community: {1}; enterprise: {2}; varbind count: {3}",
this.TimeStamp.ToString(CultureInfo.InvariantCulture),
this.Community(),
this.Enterprise,
this.Variables().Count.ToString(CultureInfo.InvariantCulture));
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.