context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.Text;
using com.calitha.goldparser;
namespace Epi.Core.AnalysisInterpreter.Rules
{
public partial class Rule_Value : AnalysisRule
{
string Id = null;
object value = null;
object ReturnResult = null;
public Rule_Value(Rule_Context pContext, Token pToken) : base(pContext)
{
/* ::= Identifier | <Literal> | Boolean | '(' <Expr List> ')' */
if (pToken is NonterminalToken)
{
NonterminalToken T = (NonterminalToken)pToken;
if (T.Tokens.Length == 1)
{
DateTime dateTime_temp;
switch (T.Rule.Rhs[0].ToString())
{
case "<Qualified ID>":
this.Id = this.SetQualifiedId(T.Tokens[0]);
break;
case "Identifier":
this.Id = this.GetCommandElement(T.Tokens, 0).Trim(new char[] {'[',']'});
break;
case "(":
case "<FunctionCall>":
this.value = new Rule_FunctionCall(pContext, (NonterminalToken)T.Tokens[1]);
break;
case "<Literal>":
this.value = this.GetCommandElement(T.Tokens, 0).Trim('"');
break;
case "<Literal_String>":
case "String":
this.value = this.GetCommandElement(T.Tokens, 0).Trim('"');
break;
case "<Literal_Char>":
case "CharLiteral":
this.value = this.GetCommandElement(T.Tokens, 0).Trim('\'');
break;
case "Boolean":
string string_temp = this.GetCommandElement(T.Tokens, 0);
if (string_temp == "(+)" || string_temp.ToLowerInvariant() == "true" || string_temp.ToLowerInvariant() == "yes")
{
this.value = true;
}
else if (string_temp == "(-)" || string_temp.ToLowerInvariant() == "false" || string_temp.ToLowerInvariant() == "no")
{
this.value = false;
}
else if (string_temp == "(.)")
{
this.value = null;
}
break;
case "<Decimal_Number>":
case "<Number>":
case "<Real_Number>":
case "<Hex_Number>":
case "DecLiteral":
case "RealLiteral":
case "HexLiteral":
double Decimal_temp;
if (double.TryParse(this.GetCommandElement(T.Tokens, 0), out Decimal_temp))
{
this.value = Decimal_temp;
}
break;
case "<Literal_Date>":
case "Date":
if (DateTime.TryParse(this.GetCommandElement(T.Tokens, 0), out dateTime_temp))
{
DateTime dt = new DateTime(dateTime_temp.Year, dateTime_temp.Month, dateTime_temp.Day);
this.value = dt;
}
else
{
this.value = null;
}
break;
case "<Literal_Time>":
case "<Literal_Date_Time>":
case "Time":
case "Date Time":
if (DateTime.TryParse(this.GetCommandElement(T.Tokens, 0), out dateTime_temp))
{
this.value = dateTime_temp;
}
break;
case "<Value>":
this.value = new Rule_Value(this.Context, T.Tokens[0]);
break;
default:
this.value = this.GetCommandElement(T.Tokens, 0).Trim('"');;
break;
}
}
else
{
//this.value = new Rule_ExprList(pContext, (NonterminalToken)T.Tokens[1]);
//this.value = AnalysisRule.BuildStatments(pContext, T.Tokens[1]);
if (T.Tokens.Length == 0)
{
this.value = AnalysisRule.BuildStatments(pContext, T);
}
else
{
this.value = AnalysisRule.BuildStatments(pContext, T.Tokens[1]);
}
}
}
else
{
TerminalToken TT = (TerminalToken)pToken;
DateTime dateTime_temp;
switch (TT.Symbol.ToString())
{
case "Identifier":
this.Id = TT.Text;
break;
case "<Literal>":
this.value = TT.Text.Trim('"');
break;
case "<Literal_String>":
case "String":
this.value = TT.Text.Trim('"');
break;
case "<Literal_Char>":
case "CharLiteral":
this.value = TT.Text.Trim('\'');
break;
case "Boolean":
string string_temp = TT.Text;
if (string_temp == "(+)" || string_temp.ToLowerInvariant() == "true" || string_temp.ToLowerInvariant() == "yes")
{
this.value = true;
}
else if (string_temp == "(-)" || string_temp.ToLowerInvariant() == "false" || string_temp.ToLowerInvariant() == "no")
{
this.value = false;
}
else if (string_temp == "(.)")
{
this.value = null;
}
break;
case "<Decimal_Number>":
case "<Number>":
case "<Real_Number>":
case "<Hex_Number>":
case "DecLiteral":
case "RealLiteral":
case "HexLiteral":
double Decimal_temp;
if (double.TryParse(TT.Text, out Decimal_temp))
{
this.value = Decimal_temp;
}
break;
case "<Literal_Date>":
case "Date":
if (DateTime.TryParse(TT.Text, out dateTime_temp))
{
DateTime dt = new DateTime(dateTime_temp.Year, dateTime_temp.Month, dateTime_temp.Day);
this.value = dt;
}
else
{
this.value = null;
}
break;
case "<Literal_Time>":
case "<Literal_Date_Time>":
case "Time":
case "Date Time":
if (DateTime.TryParse(TT.Text, out dateTime_temp))
{
this.value = dateTime_temp;
}
break;
default:
this.value = TT.Text.Trim('"');;
break;
}
}
if (this.Id == null && this.value == null)
{
}
}
public Rule_Value(string pValue)
{
this.value = pValue;
}
/// <summary>
/// performs execution of retrieving the value of a variable or expression
/// </summary>
/// <returns>object</returns>
public override object Execute()
{
object result = null;
if (this.Id != null)
{
IVariable var;
DataType dataType = DataType.Unknown;
string dataValue = string.Empty;
if (this.Context.MemoryRegion.TryGetVariable(this.Id, out var))
{
if (var.VarType == VariableType.Standard || var.VarType == VariableType.DataSource)
{
if (this.Context.CurrentDataRow != null)
{
if (var.VarType == VariableType.Standard)
{
if (this.Context.Recodes.ContainsKey(var.Name))
{
Epi.Core.AnalysisInterpreter.Rules.RecodeList RL = this.Context.Recodes[var.Name];
result = RL.GetRecode(this.Context.CurrentDataRow[RL.SourceName]);
}
else
{
//result = ParseDataStrings(this.Context.CurrentDataRow[this.Id].ToString());
result = this.Context.CurrentDataRow[this.Id];
}
}
else
{
//result = ParseDataStrings(this.Context.CurrentDataRow[this.Id].ToString());
result = this.Context.CurrentDataRow[this.Id];
}
if (result is System.DBNull)
{
result = "";
}
}
else // there is NO current row go through datarows
{
this.Context.GetOutput(GetResultFromDataTable);
result = ReturnResult;
}
}
else
{
dataType = var.DataType;
dataValue = var.Expression;
result = ConvertEpiDataTypeToSystemObject(dataType, dataValue);
}
}
else if (this.Context.CurrentDataRow != null)
{
if (this.Context.Recodes.ContainsKey(this.Id))
{
Epi.Core.AnalysisInterpreter.Rules.RecodeList RL = this.Context.Recodes[this.Id];
result = RL.GetRecode(this.Context.CurrentDataRow[RL.SourceName]);
}
else
{
result = this.Context.CurrentDataRow[this.Id];
if (result is System.DBNull)
{
result = null;
}
}
}
}
else
{
if (value is AnalysisRule)
{
result = ((AnalysisRule)value).Execute();
}
else
{
result = value;
}
}
return result;
}
private object ConvertEpiDataTypeToSystemObject(DataType dataType, string dataValue)
{
object result = null;
if (dataValue != null)
{
DateTime dateTime;
switch (dataType)
{
case DataType.Boolean:
case DataType.YesNo:
result = new Boolean();
if (dataValue == "(+)" || dataValue.ToLowerInvariant() == "true" || dataValue == "1")
result = true;
else if (dataValue == "(-)" || dataValue.ToLowerInvariant() == "false" || dataValue == "0")
result = false;
else
result = null;
break;
case DataType.Number:
double num;
if (double.TryParse(dataValue, out num))
result = num;
else
result = null;
break;
case DataType.Date:
if (DateTime.TryParse(dataValue, out dateTime))
{
DateTime dt = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day);
result = dt;
}
else
{
result = null;
}
break;
case DataType.DateTime:
case DataType.Time:
if (DateTime.TryParse(dataValue, out dateTime))
{
result = dateTime;
}
else
{
result = null;
}
break;
case DataType.PhoneNumber:
case DataType.GUID:
case DataType.Text:
if (dataValue != null)
result = dataValue.Trim().Trim('\"');
else
result = null;
break;
case DataType.Unknown:
default:
double double_compare;
DateTime DateTime_compare;
bool bool_compare;
if (double.TryParse(dataValue, out double_compare))
{
result = double_compare;
}
else
if (DateTime.TryParse(dataValue, out DateTime_compare))
{
result = DateTime_compare;
}
else
if (bool.TryParse(dataValue, out bool_compare))
{
result = bool_compare;
}
else { result = dataValue; }
break;
}
}
return result;
}
private object ParseDataStrings(object subject)
{
object result = null;
if (subject is Rule_ExprList)
{
result = ((Rule_ExprList)subject).Execute();
}
else if (subject is Rule_FunctionCall)
{
result = ((Rule_FunctionCall)subject).Execute();
}
else if (subject is String)
{
Double number;
DateTime dateTime;
result = ((String)subject).Trim('\"');
//removing the "1" and "0" conditions here because an expression like 1 + 0 was evaluating as two booleans
//if ((String)subject == "1" || (String)subject == "(+)" || ((String)subject).ToLowerInvariant() == "true")
if ((String)subject == "(+)" || ((String)subject).ToLowerInvariant() == "true")
{
result = new Boolean();
result = true;
}
//else if ((String)subject == "0" || (String)subject == "(-)" || ((String)subject).ToLowerInvariant() == "false")
else if ((String)subject == "(-)" || ((String)subject).ToLowerInvariant() == "false")
{
result = new Boolean();
result = false;
}
else if ((String)subject == "(.)")
{
result = null;
}
else if (Double.TryParse(result.ToString(), out number))
{
result = number;
}
else if (DateTime.TryParse(result.ToString(), out dateTime))
{
result = dateTime;
}
}
return result;
}
private void GetResultFromDataTable()
{
object result = null;
if (this.Context.Recodes.ContainsKey(this.Id))
{
Epi.Core.AnalysisInterpreter.Rules.RecodeList RL = this.Context.Recodes[this.Id];
result = RL.GetRecode(this.Context.CurrentDataRow[RL.SourceName]);
}
else
{
result = ParseDataStrings(this.Context.CurrentDataRow[this.Id].ToString());
}
if (result is System.DBNull)
{
result = null;
}
ReturnResult = result;
}
}
}
| |
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using JetBrains.Annotations;
using JsonApiDotNetCore.Configuration;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace TestBuildingBlocks
{
/// <summary>
/// Base class for a test context that creates a new database and server instance before running tests and cleans up afterwards. You can either use this
/// as a fixture on your tests class (init/cleanup runs once before/after all tests) or have your tests class inherit from it (init/cleanup runs once
/// before/after each test). See <see href="https://xunit.net/docs/shared-context" /> for details on shared context usage.
/// </summary>
/// <typeparam name="TStartup">
/// The server Startup class, which can be defined in the test project or API project.
/// </typeparam>
/// <typeparam name="TDbContext">
/// The EF Core database context, which can be defined in the test project or API project.
/// </typeparam>
[UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)]
public class IntegrationTestContext<TStartup, TDbContext> : IntegrationTest, IDisposable
where TStartup : class
where TDbContext : DbContext
{
private readonly Lazy<WebApplicationFactory<TStartup>> _lazyFactory;
private readonly TestControllerProvider _testControllerProvider = new();
private Action<ILoggingBuilder> _loggingConfiguration;
private Action<IServiceCollection> _beforeServicesConfiguration;
private Action<IServiceCollection> _afterServicesConfiguration;
protected override JsonSerializerOptions SerializerOptions
{
get
{
var options = Factory.Services.GetRequiredService<IJsonApiOptions>();
return options.SerializerOptions;
}
}
public WebApplicationFactory<TStartup> Factory => _lazyFactory.Value;
public IntegrationTestContext()
{
_lazyFactory = new Lazy<WebApplicationFactory<TStartup>>(CreateFactory);
}
public void UseController<TController>()
where TController : ControllerBase
{
_testControllerProvider.AddController(typeof(TController));
}
protected override HttpClient CreateClient()
{
return Factory.CreateClient();
}
private WebApplicationFactory<TStartup> CreateFactory()
{
string postgresPassword = Environment.GetEnvironmentVariable("PGPASSWORD") ?? "postgres";
string dbConnectionString = $"Host=localhost;Port=5432;Database=JsonApiTest-{Guid.NewGuid():N};User ID=postgres;Password={postgresPassword}";
var factory = new IntegrationTestWebApplicationFactory();
factory.ConfigureLogging(_loggingConfiguration);
factory.ConfigureServicesBeforeStartup(services =>
{
_beforeServicesConfiguration?.Invoke(services);
services.ReplaceControllers(_testControllerProvider);
services.AddDbContext<TDbContext>(options =>
{
options.UseNpgsql(dbConnectionString, builder =>
// The next line suppresses EF Core Warning:
// "Compiling a query which loads related collections for more than one collection navigation
// either via 'Include' or through projection but no 'QuerySplittingBehavior' has been configured."
// We'd like to use `QuerySplittingBehavior.SplitQuery` because of improved performance, but unfortunately
// it makes EF Core 5 crash on queries that load related data in a projection without Include.
// This is fixed in EF Core 6, tracked at https://github.com/dotnet/efcore/issues/21234.
builder.UseQuerySplittingBehavior(QuerySplittingBehavior.SingleQuery));
#if DEBUG
options.EnableSensitiveDataLogging();
options.EnableDetailedErrors();
#endif
});
});
factory.ConfigureServicesAfterStartup(_afterServicesConfiguration);
// We have placed an appsettings.json in the TestBuildingBlock project folder and set the content root to there. Note that controllers
// are not discovered in the content root but are registered manually using IntegrationTestContext.UseController.
WebApplicationFactory<TStartup> factoryWithConfiguredContentRoot =
factory.WithWebHostBuilder(builder => builder.UseSolutionRelativeContentRoot("test/" + nameof(TestBuildingBlocks)));
using IServiceScope scope = factoryWithConfiguredContentRoot.Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<TDbContext>();
dbContext.Database.EnsureCreated();
return factoryWithConfiguredContentRoot;
}
public void Dispose()
{
RunOnDatabaseAsync(async context => await context.Database.EnsureDeletedAsync()).Wait();
Factory.Dispose();
}
public void ConfigureLogging(Action<ILoggingBuilder> loggingConfiguration)
{
_loggingConfiguration = loggingConfiguration;
}
public void ConfigureServicesBeforeStartup(Action<IServiceCollection> servicesConfiguration)
{
_beforeServicesConfiguration = servicesConfiguration;
}
public void ConfigureServicesAfterStartup(Action<IServiceCollection> servicesConfiguration)
{
_afterServicesConfiguration = servicesConfiguration;
}
public async Task RunOnDatabaseAsync(Func<TDbContext, Task> asyncAction)
{
using IServiceScope scope = Factory.Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<TDbContext>();
await asyncAction(dbContext);
}
private sealed class IntegrationTestWebApplicationFactory : WebApplicationFactory<TStartup>
{
private Action<ILoggingBuilder> _loggingConfiguration;
private Action<IServiceCollection> _beforeServicesConfiguration;
private Action<IServiceCollection> _afterServicesConfiguration;
public void ConfigureLogging(Action<ILoggingBuilder> loggingConfiguration)
{
_loggingConfiguration = loggingConfiguration;
}
public void ConfigureServicesBeforeStartup(Action<IServiceCollection> servicesConfiguration)
{
_beforeServicesConfiguration = servicesConfiguration;
}
public void ConfigureServicesAfterStartup(Action<IServiceCollection> servicesConfiguration)
{
_afterServicesConfiguration = servicesConfiguration;
}
protected override IHostBuilder CreateHostBuilder()
{
// @formatter:wrap_chained_method_calls chop_always
// @formatter:keep_existing_linebreaks true
return Host.CreateDefaultBuilder(null)
.ConfigureAppConfiguration(builder =>
{
// For tests asserting on log output, we discard the logging settings from appsettings.json.
// But using appsettings.json for all other tests makes it easy to quickly toggle when debugging.
if (_loggingConfiguration != null)
{
builder.Sources.Clear();
}
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureServices(services =>
{
_beforeServicesConfiguration?.Invoke(services);
});
webBuilder.UseStartup<TStartup>();
webBuilder.ConfigureServices(services =>
{
_afterServicesConfiguration?.Invoke(services);
});
})
.ConfigureLogging(options =>
{
_loggingConfiguration?.Invoke(options);
});
// @formatter:keep_existing_linebreaks restore
// @formatter:wrap_chained_method_calls restore
}
}
}
}
| |
namespace VisualStudioWPFTests
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using ArtOfTest.WebAii.Controls.Xaml.Wpf;
using ArtOfTest.WebAii.Core;
using ArtOfTest.WebAii.TestTemplates;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Win32;
/// <summary>
/// Summary description for VisualStudioProject
/// </summary>
[TestClass]
public class VisualStudioProject : BaseWpfTest
{
#region [Setup / TearDown]
private TestContext testContextInstance = null;
/// <summary>
///Gets or sets the VS test context which provides
///information about and functionality for the
///current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
//Use ClassInitialize to run code before running the first test in the class
[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
}
// Use TestInitialize to run code before running each test
[TestInitialize()]
public void MyTestInitialize()
{
#region WebAii Initialization
// Initializes WebAii manager to be used by the test case.
// If a WebAii configuration section exists, settings will be
// loaded from it. Otherwise, will create a default settings
// object with system defaults.
//
// Note: We are passing in a delegate to the VisualStudio
// testContext.WriteLine() method in addition to the Visual Studio
// TestLogs directory as our log location. This way any logging
// done from WebAii (i.e. Manager.Log.WriteLine()) is
// automatically logged to the VisualStudio test log and
// the WebAii log file is placed in the same location as VS logs.
//
// If you do not care about unifying the log, then you can simply
// initialize the test by calling Initialize() with no parameters;
// that will cause the log location to be picked up from the config
// file if it exists or will use the default system settings (C:\WebAiiLog\)
// You can also use Initialize(LogLocation) to set a specific log
// location for this test.
Initialize(this.TestContext.TestLogsDir, new TestContextWriteLine(this.TestContext.WriteLine));
// If you need to override any other settings coming from the
// config section you can comment the 'Initialize' line above and instead
// use the following:
/*
// This will get a new Settings object. If a configuration
// section exists, then settings from that section will be
// loaded
Settings settings = GetSettings();
// Override the settings you want. For example:
settings.WaitCheckInterval = 10000;
// Now call Initialize again with your updated settings object
Initialize(settings, new TestContextWriteLine(this.TestContext.WriteLine));
*/
// Set the current test method. This is needed for WebAii to discover
// its custom TestAttributes set on methods and classes.
// This method should always exist in [TestInitialize()] method.
SetTestMethod(this, (string)TestContext.Properties["TestName"]);
#endregion
//
// Place any additional initialization here
//
}
// Use TestCleanup to run code after each test has run
[TestCleanup()]
public void MyTestCleanup()
{
//
// Place any additional cleanup here
//
#region WebAii CleanUp
// Shuts down WebAii manager and closes all applications currently running
// after each test.
this.CleanUp();
#endregion
}
//Use ClassCleanup to run code after all tests in a class have run
[ClassCleanup()]
public static void MyClassCleanup()
{
// This will shut down all applications
ShutDown();
}
#endregion
[TestMethod]
public void CreateNewProject()
{
string vsExecutable = this.GetVisualStudioExecutable();
var application = Manager.LaunchNewApplication(new System.Diagnostics.ProcessStartInfo(vsExecutable));
application.MainWindow.Find.ByTextContent("New Project...").User.Click();
Thread.Sleep(2000);
Manager.ActiveApplication.GetWindow("New Project").Find.ByTextContent("Installed").User.Click();
Manager.ActiveApplication.MainWindow.Find.ByTextContent("Visual C#").User.Click();
Manager.ActiveApplication.MainWindow.Find.ByTextContent("Test").User.Click();
Manager.ActiveApplication.MainWindow.Find.ByTextContent("Unit Test Project").User.Click();
Manager.ActiveApplication.MainWindow.Find.ByName<TextBox>("txt_Name").SetText(false, "MyUnitTest", 10, 10, true);
Manager.ActiveApplication.MainWindow.Find.ByName<TextBox>("txt_SlnName").SetText(false, "MyUnitTestsProject", 10, 10, true);
Manager.ActiveApplication.MainWindow.Find.ByName<ComboBox>("cmb_Location").User.Click();
Manager.Current.Desktop.KeyBoard.TypeText(@"C:\MyProjects");
Manager.ActiveApplication.MainWindow.Find.ByName<Button>("btn_OK").User.Click();
Manager.ActiveApplication.MainWindow.Find.ByName("MS_VS_TextEditorContent").Wait.ForVisible(30000);
Assert.IsTrue(File.Exists(@"C:\MyProjects\MyUnitTestsProject\MyUnitTestsProject.sln"));
BaseWpfTest.ShutDown();
Thread.Sleep(2000);
try
{
Directory.Delete(@"C:\MyProjects", true);
}
catch (Exception e)
{
Log.WriteLine("The process failed: " + e.Message);
}
}
private string GetVisualStudioExecutable()
{
const string VisualStudioRegistryKeyPath = @"SOFTWARE\Microsoft\VisualStudio";
const string VisualCSharpExpressRegistryKeyPath = @"SOFTWARE\Microsoft\VCSExpress";
var vsVersions = new List<Version>
{
new Version("14.0"),
new Version("12.0"),
new Version("11.0"),
new Version("10.0")
};
foreach (var version in vsVersions)
{
foreach (var isExpress in new bool[] { false, true })
{
RegistryKey registryBase32 = RegistryKey.OpenBaseKey(
RegistryHive.LocalMachine,
RegistryView.Registry32);
RegistryKey vsVersionRegistryKey = registryBase32.OpenSubKey(
string.Format(
@"{0}\{1}.{2}",
isExpress ? VisualCSharpExpressRegistryKeyPath : VisualStudioRegistryKeyPath,
version.Major,
version.Minor));
if (vsVersionRegistryKey != null)
{
return vsVersionRegistryKey.GetValue("InstallDir", string.Empty) + "devenv.exe";
}
}
}
return null;
}
}
}
| |
using System.Text;
namespace Equationator
{
/// <summary>
/// This is a single text token from an equation.
/// The first step to compiling an equation is breaking it up into a list tokens and determining what is in those tokens.
/// </summary>
public class Token
{
#region Members
/// <summary>
/// Gets the token text.
/// </summary>
/// <value>The token text.</value>
public string TokenText { get; private set; }
/// <summary>
/// Gets the type of token.
/// </summary>
/// <value>The type of token.</value>
public TokenType TypeOfToken { get; private set; }
#endregion Members
#region Methods
/// <summary>
/// Initializes a new instance of the <see cref="Equationator.Token"/> class.
/// </summary>
public Token()
{
TypeOfToken = TokenType.Invalid;
}
/// <summary>
/// Pull one token out of a string.
/// </summary>
/// <returns>int: the new current index in the string. Use this as the start point for parsing the next token</returns>
/// <param name="strEquationText">The full text string we are tokenizing</param>
/// <param name="iStartIndex">The character index in the string where to start tokenizing</param>
public int ParseToken(string strEquationText, int iStartIndex)
{
//Walk through the text and try to parse it out into an expression
while (iStartIndex < strEquationText.Length)
{
//First check if we are reading in a number
if (IsNumberCharacter(strEquationText, iStartIndex))
{
//read a number and return the new index
return ParseNumberToken(strEquationText, iStartIndex);
}
else if (IsOperatorCharacter(strEquationText, iStartIndex))
{
//We found an operator value...
TypeOfToken = TokenType.Operator;
TokenText = strEquationText[iStartIndex].ToString();
return ++iStartIndex;
}
switch (strEquationText[iStartIndex])
{
case '$':
{
//read a function/param and return the new index
return ParseFunctionToken(strEquationText, iStartIndex);
}
case '(':
{
//we found an open paren!
TypeOfToken = TokenType.OpenParen;
TokenText = strEquationText[iStartIndex].ToString();
return ++iStartIndex;
}
case ')':
{
//we found a close paren!
TypeOfToken = TokenType.CloseParen;
TokenText = strEquationText[iStartIndex].ToString();
return ++iStartIndex;
}
case 'x':
{
//We are going to cheat and use 'x' as $1
return ParamCheat("1", iStartIndex);
}
case 'y':
{
//We are going to cheat and use 'x' as $2
return ParamCheat("2", iStartIndex);
}
case 'z':
{
//We are going to cheat and use 'x' as $3
return ParamCheat("3", iStartIndex);
}
}
//We found some white space
iStartIndex++;
}
return iStartIndex;
}
/// <summary>
/// Our token is a number, parse the full text out of the expression
/// </summary>
/// <returns>The index in the string after our number</returns>
/// <param name="strEquationText">String equation text.</param>
/// <param name="iIndex">start index of this token.</param>
private int ParseNumberToken(string strEquationText, int iIndex)
{
//Set this token as a number
TypeOfToken = TokenType.Number;
//Parse the string into a number
StringBuilder word = new StringBuilder();
while (IsNumberCharacter(strEquationText, iIndex))
{
//Add the digit/decimal to the end of the number
word.Append(strEquationText[iIndex++]);
//If we have reached the end of the text, quit reading
if (iIndex >= strEquationText.Length)
{
break;
}
}
//grab the resulting value and return the new string index
TokenText = word.ToString();
return iIndex;
}
private int ParseFunctionToken(string strEquationText, int iIndex)
{
//first, skip the dollar sign
iIndex++;
//check if it is a param or a function call
StringBuilder word = new StringBuilder();
if (strEquationText[iIndex] >= '0' && strEquationText[iIndex] <= '9')
{
//We have a param value
TypeOfToken = TokenType.Param;
//Parse the param until we hit the end
while (strEquationText[iIndex] >= '0' && strEquationText[iIndex] <= '9')
{
word.Append(strEquationText[iIndex++]);
//If we have reached the end of the text, quit reading
if (iIndex >= strEquationText.Length)
{
break;
}
}
}
else
{
//TODO: Parse the function call until we hit the next token
//Get the function name
string funcName = strEquationText.Substring(iIndex, 4);
//We have a function call
TypeOfToken = TokenType.Function;
//check if the token is stored in our grammar dictionary
word.Append(funcName);
iIndex += 4;
}
//grab the resulting value and return the new string index
TokenText = word.ToString();
return iIndex;
}
private int ParamCheat(string param, int iIndex)
{
TypeOfToken = TokenType.Param;
TokenText = param;
return ++iIndex;
}
/// <summary>
/// Check whether the character at an index is a number
/// </summary>
/// <returns><c>true</c> if this instance is number character the specified strEquationText iIndex; otherwise, <c>false</c>.</returns>
/// <param name="strEquationText">String equation text.</param>
/// <param name="iIndex">I index.</param>
static private bool IsNumberCharacter(string strEquationText, int iIndex)
{
return (('0' <= strEquationText[iIndex] && strEquationText[iIndex] <= '9') || strEquationText[iIndex] == '.');
}
/// <summary>
/// Check whether the character at an index is an operator character
/// </summary>
/// <returns><c>true</c> if this instance is number character the specified strEquationText iIndex; otherwise, <c>false</c>.</returns>
/// <param name="strEquationText">String equation text.</param>
/// <param name="iIndex">I index.</param>
static private bool IsOperatorCharacter(string strEquationText, int iIndex)
{
switch (strEquationText[iIndex])
{
case '*': return true;
case '/': return true;
case '+': return true;
case '-': return true;
case '^': return true;
case '%': return true;
}
return false;
}
#endregion Methods
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.Versioning;
using NuGet.Resources;
using NuGet.V3Interop;
namespace NuGet
{
public static class PackageRepositoryExtensions
{
public static IDisposable StartOperation(this IPackageRepository self, string operation, string mainPackageId, string mainPackageVersion)
{
IOperationAwareRepository repo = self as IOperationAwareRepository;
if (repo != null)
{
return repo.StartOperation(operation, mainPackageId, mainPackageVersion);
}
return DisposableAction.NoOp;
}
public static bool Exists(this IPackageRepository repository, IPackageName package)
{
return repository.Exists(package.Id, package.Version);
}
public static bool Exists(this IPackageRepository repository, string packageId)
{
return Exists(repository, packageId, version: null);
}
public static bool Exists(this IPackageRepository repository, string packageId, SemanticVersion version)
{
IPackageLookup packageLookup = repository as IPackageLookup;
if ((packageLookup != null) && !String.IsNullOrEmpty(packageId) && (version != null))
{
return packageLookup.Exists(packageId, version);
}
return repository.FindPackage(packageId, version) != null;
}
public static bool TryFindPackage(this IPackageRepository repository, string packageId, SemanticVersion version, out IPackage package)
{
package = repository.FindPackage(packageId, version);
return package != null;
}
public static IPackage FindPackage(this IPackageRepository repository, string packageId)
{
return repository.FindPackage(packageId, version: null);
}
public static IPackage FindPackage(this IPackageRepository repository, string packageId, SemanticVersion version)
{
// Default allow pre release versions to true here because the caller typically wants to find all packages in this scenario for e.g when checking if a
// a package is already installed in the local repository. The same applies to allowUnlisted.
return FindPackage(repository, packageId, version, NullConstraintProvider.Instance, allowPrereleaseVersions: true, allowUnlisted: true);
}
public static IPackage FindPackage(this IPackageRepository repository, string packageId, SemanticVersion version, bool allowPrereleaseVersions, bool allowUnlisted)
{
return FindPackage(repository, packageId, version, NullConstraintProvider.Instance, allowPrereleaseVersions, allowUnlisted);
}
public static IPackage FindPackage(
this IPackageRepository repository,
string packageId,
SemanticVersion version,
IPackageConstraintProvider constraintProvider,
bool allowPrereleaseVersions,
bool allowUnlisted)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (packageId == null)
{
throw new ArgumentNullException("packageId");
}
// if an explicit version is specified, disregard the 'allowUnlisted' argument
// and always allow unlisted packages.
if (version != null)
{
allowUnlisted = true;
}
else if (!allowUnlisted && (constraintProvider == null || constraintProvider == NullConstraintProvider.Instance))
{
var packageLatestLookup = repository as ILatestPackageLookup;
if (packageLatestLookup != null)
{
IPackage package;
if (packageLatestLookup.TryFindLatestPackageById(packageId, allowPrereleaseVersions, out package))
{
return package;
}
}
}
// If the repository implements it's own lookup then use that instead.
// This is an optimization that we use so we don't have to enumerate packages for
// sources that don't need to.
var packageLookup = repository as IPackageLookup;
if (packageLookup != null && version != null)
{
return packageLookup.FindPackage(packageId, version);
}
IEnumerable<IPackage> packages = repository.FindPackagesById(packageId);
packages = packages.ToList()
.OrderByDescending(p => p.Version);
if (!allowUnlisted)
{
packages = packages.Where(PackageExtensions.IsListed);
}
if (version != null)
{
packages = packages.Where(p => p.Version == version);
}
else if (constraintProvider != null)
{
packages = FilterPackagesByConstraints(constraintProvider, packages, packageId, allowPrereleaseVersions);
}
return packages.FirstOrDefault();
}
public static IPackage FindPackage(this IPackageRepository repository, string packageId, IVersionSpec versionSpec,
IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool allowUnlisted)
{
var packages = repository.FindPackages(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted);
if (constraintProvider != null)
{
packages = FilterPackagesByConstraints(constraintProvider, packages, packageId, allowPrereleaseVersions);
}
return packages.FirstOrDefault();
}
public static IEnumerable<IPackage> FindPackages(this IPackageRepository repository, IEnumerable<string> packageIds)
{
if (packageIds == null)
{
throw new ArgumentNullException("packageIds");
}
// If we're in V3-land, find packages using that API
var v3Repo = repository as IV3InteropRepository;
if (v3Repo != null)
{
return packageIds.SelectMany(id => v3Repo.FindPackagesById(id)).ToList();
}
else
{
return FindPackages(repository, packageIds, GetFilterExpression);
}
}
public static IEnumerable<IPackage> FindPackagesById(this IPackageRepository repository, string packageId)
{
var directRepo = repository as IV3InteropRepository;
if (directRepo != null)
{
return directRepo.FindPackagesById(packageId);
}
var serviceBasedRepository = repository as IPackageLookup;
if (serviceBasedRepository != null)
{
return serviceBasedRepository.FindPackagesById(packageId).ToList();
}
else
{
return FindPackagesByIdCore(repository, packageId);
}
}
internal static IEnumerable<IPackage> FindPackagesByIdCore(IPackageRepository repository, string packageId)
{
var cultureRepository = repository as ICultureAwareRepository;
if (cultureRepository != null)
{
packageId = packageId.ToLower(cultureRepository.Culture);
}
else
{
packageId = packageId.ToLower(CultureInfo.CurrentCulture);
}
return (from p in repository.GetPackages()
where p.Id.ToLower() == packageId
orderby p.Id
select p).ToList();
}
/// <summary>
/// Since Odata dies when our query for updates is too big. We query for updates 10 packages at a time
/// and return the full list of packages.
/// </summary>
private static IEnumerable<IPackage> FindPackages<T>(
this IPackageRepository repository,
IEnumerable<T> items,
Func<IEnumerable<T>, Expression<Func<IPackage, bool>>> filterSelector)
{
const int batchSize = 10;
while (items.Any())
{
IEnumerable<T> currentItems = items.Take(batchSize);
Expression<Func<IPackage, bool>> filterExpression = filterSelector(currentItems);
var query = repository.GetPackages()
.Where(filterExpression)
.OrderBy(p => p.Id);
foreach (var package in query)
{
yield return package;
}
items = items.Skip(batchSize);
}
}
public static IEnumerable<IPackage> FindPackages(
this IPackageRepository repository,
string packageId,
IVersionSpec versionSpec,
bool allowPrereleaseVersions,
bool allowUnlisted)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (packageId == null)
{
throw new ArgumentNullException("packageId");
}
IEnumerable<IPackage> packages = repository.FindPackagesById(packageId)
.OrderByDescending(p => p.Version);
if (!allowUnlisted)
{
packages = packages.Where(PackageExtensions.IsListed);
}
if (versionSpec != null)
{
packages = packages.FindByVersion(versionSpec);
}
packages = FilterPackagesByConstraints(NullConstraintProvider.Instance, packages, packageId, allowPrereleaseVersions);
return packages;
}
public static IPackage FindPackage(
this IPackageRepository repository,
string packageId,
IVersionSpec versionSpec,
bool allowPrereleaseVersions,
bool allowUnlisted)
{
return repository.FindPackages(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted).FirstOrDefault();
}
public static IEnumerable<IPackage> FindCompatiblePackages(this IPackageRepository repository,
IPackageConstraintProvider constraintProvider,
IEnumerable<string> packageIds,
IPackage package,
FrameworkName targetFramework,
bool allowPrereleaseVersions)
{
return (from p in repository.FindPackages(packageIds)
where allowPrereleaseVersions || p.IsReleaseVersion()
let dependency = p.FindDependency(package.Id, targetFramework)
let otherConstaint = constraintProvider.GetConstraint(p.Id)
where dependency != null &&
dependency.VersionSpec.Satisfies(package.Version) &&
(otherConstaint == null || otherConstaint.Satisfies(package.Version))
select p);
}
public static PackageDependency FindDependency(this IPackageMetadata package, string packageId, FrameworkName targetFramework)
{
return (from dependency in package.GetCompatiblePackageDependencies(targetFramework)
where dependency.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase)
select dependency).FirstOrDefault();
}
public static IQueryable<IPackage> Search(this IPackageRepository repository, string searchTerm, bool allowPrereleaseVersions)
{
return Search(repository, searchTerm, targetFrameworks: Enumerable.Empty<string>(), allowPrereleaseVersions: allowPrereleaseVersions);
}
public static IQueryable<IPackage> Search(this IPackageRepository repository, string searchTerm, IEnumerable<string> targetFrameworks, bool allowPrereleaseVersions, bool includeDelisted)
{
if (targetFrameworks == null)
{
throw new ArgumentNullException("targetFrameworks");
}
var serviceBasedRepository = repository as IServiceBasedRepository;
if (serviceBasedRepository != null)
{
return serviceBasedRepository.Search(searchTerm, targetFrameworks, allowPrereleaseVersions, includeDelisted);
}
// Ignore the target framework if the repository doesn't support searching
var result = repository
.GetPackages()
.Find(searchTerm)
.FilterByPrerelease(allowPrereleaseVersions)
.AsQueryable();
return result;
}
public static IPackage ResolveDependency(this IPackageRepository repository, PackageDependency dependency, bool allowPrereleaseVersions, bool preferListedPackages)
{
return ResolveDependency(repository, dependency, constraintProvider: null, allowPrereleaseVersions: allowPrereleaseVersions, preferListedPackages: preferListedPackages, dependencyVersion: DependencyVersion.Lowest);
}
public static IPackage ResolveDependency(this IPackageRepository repository, PackageDependency dependency, IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool preferListedPackages)
{
return ResolveDependency(repository, dependency, constraintProvider, allowPrereleaseVersions, preferListedPackages, dependencyVersion: DependencyVersion.Lowest);
}
public static IPackage ResolveDependency(this IPackageRepository repository, PackageDependency dependency, IPackageConstraintProvider constraintProvider, bool allowPrereleaseVersions, bool preferListedPackages, DependencyVersion dependencyVersion)
{
IDependencyResolver dependencyResolver = repository as IDependencyResolver;
if (dependencyResolver != null)
{
return dependencyResolver.ResolveDependency(dependency, constraintProvider, allowPrereleaseVersions, preferListedPackages, dependencyVersion);
}
return ResolveDependencyCore(repository, dependency, constraintProvider, allowPrereleaseVersions, preferListedPackages, dependencyVersion);
}
internal static IPackage ResolveDependencyCore(
this IPackageRepository repository,
PackageDependency dependency,
IPackageConstraintProvider constraintProvider,
bool allowPrereleaseVersions,
bool preferListedPackages,
DependencyVersion dependencyVersion)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (dependency == null)
{
throw new ArgumentNullException("dependency");
}
IEnumerable<IPackage> packages = repository.FindPackagesById(dependency.Id).ToList();
// Always filter by constraints when looking for dependencies
packages = FilterPackagesByConstraints(constraintProvider, packages, dependency.Id, allowPrereleaseVersions);
IList<IPackage> candidates = packages.ToList();
if (preferListedPackages)
{
// pick among Listed packages first
IPackage listedSelectedPackage = ResolveDependencyCore(
candidates.Where(PackageExtensions.IsListed),
dependency,
dependencyVersion);
if (listedSelectedPackage != null)
{
return listedSelectedPackage;
}
}
return ResolveDependencyCore(candidates, dependency, dependencyVersion);
}
/// <summary>
/// From the list of packages <paramref name="packages"/>, selects the package that best
/// matches the <paramref name="dependency"/>.
/// </summary>
/// <param name="packages">The list of packages.</param>
/// <param name="dependency">The dependency used to select package from the list.</param>
/// <param name="dependencyVersion">Indicates the method used to select dependency.
/// Applicable only when dependency.VersionSpec is not null.</param>
/// <returns>The selected package.</returns>
private static IPackage ResolveDependencyCore(
IEnumerable<IPackage> packages,
PackageDependency dependency,
DependencyVersion dependencyVersion)
{
// If version info was specified then use it
if (dependency.VersionSpec != null)
{
packages = packages.FindByVersion(dependency.VersionSpec).OrderBy(p => p.Version);
return packages.SelectDependency(dependencyVersion);
}
else
{
// BUG 840: If no version info was specified then pick the latest
return packages.OrderByDescending(p => p.Version)
.FirstOrDefault();
}
}
/// <summary>
/// Returns updates for packages from the repository
/// </summary>
/// <param name="repository">The repository to search for updates</param>
/// <param name="packages">Packages to look for updates</param>
/// <param name="includePrerelease">Indicates whether to consider prerelease updates.</param>
/// <param name="includeAllVersions">Indicates whether to include all versions of an update as opposed to only including the latest version.</param>
public static IEnumerable<IPackage> GetUpdates(
this IPackageRepository repository,
IEnumerable<IPackageName> packages,
bool includePrerelease,
bool includeAllVersions,
IEnumerable<FrameworkName> targetFrameworks = null,
IEnumerable<IVersionSpec> versionConstraints = null)
{
if (packages.IsEmpty())
{
return Enumerable.Empty<IPackage>();
}
var serviceBasedRepository = repository as IServiceBasedRepository;
return serviceBasedRepository != null ? serviceBasedRepository.GetUpdates(packages, includePrerelease, includeAllVersions, targetFrameworks, versionConstraints) :
repository.GetUpdatesCore(packages, includePrerelease, includeAllVersions, targetFrameworks, versionConstraints);
}
public static IEnumerable<IPackage> GetUpdatesCore(
this IPackageRepository repository,
IEnumerable<IPackageName> packages,
bool includePrerelease,
bool includeAllVersions,
IEnumerable<FrameworkName> targetFramework,
IEnumerable<IVersionSpec> versionConstraints)
{
List<IPackageName> packageList = packages.ToList();
if (!packageList.Any())
{
return Enumerable.Empty<IPackage>();
}
IList<IVersionSpec> versionConstraintList;
if (versionConstraints == null)
{
versionConstraintList = new IVersionSpec[packageList.Count];
}
else
{
versionConstraintList = versionConstraints.ToList();
}
if (packageList.Count != versionConstraintList.Count)
{
throw new ArgumentException(NuGetResources.GetUpdatesParameterMismatch);
}
// These are the packages that we need to look at for potential updates.
ILookup<string, IPackage> sourcePackages = GetUpdateCandidates(repository, packageList, includePrerelease)
.ToList()
.ToLookup(package => package.Id, StringComparer.OrdinalIgnoreCase);
var results = new List<IPackage>();
for (int i = 0; i < packageList.Count; i++)
{
var package = packageList[i];
var constraint = versionConstraintList[i];
var updates = from candidate in sourcePackages[package.Id]
where (candidate.Version > package.Version) &&
SupportsTargetFrameworks(targetFramework, candidate) &&
(constraint == null || constraint.Satisfies(candidate.Version))
select candidate;
results.AddRange(updates);
}
if (!includeAllVersions)
{
return results.CollapseById();
}
return results;
}
private static bool SupportsTargetFrameworks(IEnumerable<FrameworkName> targetFramework, IPackage package)
{
return targetFramework.IsEmpty() || targetFramework.Any(t => VersionUtility.IsCompatible(t, package.GetSupportedFrameworks()));
}
public static IPackageRepository Clone(this IPackageRepository repository)
{
var cloneableRepository = repository as ICloneableRepository;
if (cloneableRepository != null)
{
return cloneableRepository.Clone();
}
return repository;
}
/// <summary>
/// Since odata dies when our query for updates is too big. We query for updates 10 packages at a time
/// and return the full list of candidates for updates.
/// </summary>
private static IEnumerable<IPackage> GetUpdateCandidates(
IPackageRepository repository,
IEnumerable<IPackageName> packages,
bool includePrerelease)
{
var query = FindPackages(repository, packages, GetFilterExpression);
if (!includePrerelease)
{
query = query.Where(p => p.IsReleaseVersion());
}
// for updates, we never consider unlisted packages
query = query.Where(PackageExtensions.IsListed);
return query;
}
/// <summary>
/// For the list of input packages generate an expression like:
/// p => p.Id == 'package1id' or p.Id == 'package2id' or p.Id == 'package3id'... up to package n
/// </summary>
private static Expression<Func<IPackage, bool>> GetFilterExpression(IEnumerable<IPackageName> packages)
{
return GetFilterExpression(packages.Select(p => p.Id));
}
[SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "System.String.ToLower", Justification = "This is for a linq query")]
private static Expression<Func<IPackage, bool>> GetFilterExpression(IEnumerable<string> ids)
{
ParameterExpression parameterExpression = Expression.Parameter(typeof(IPackageName));
Expression expressionBody = ids.Select(id => GetCompareExpression(parameterExpression, id.ToLower()))
.Aggregate(Expression.OrElse);
return Expression.Lambda<Func<IPackage, bool>>(expressionBody, parameterExpression);
}
/// <summary>
/// Builds the expression: package.Id.ToLower() == "somepackageid"
/// </summary>
private static Expression GetCompareExpression(Expression parameterExpression, object value)
{
// package.Id
Expression propertyExpression = Expression.Property(parameterExpression, "Id");
// .ToLower()
Expression toLowerExpression = Expression.Call(propertyExpression, typeof(string).GetMethod("ToLower", Type.EmptyTypes));
// == localPackage.Id
return Expression.Equal(toLowerExpression, Expression.Constant(value));
}
private static IEnumerable<IPackage> FilterPackagesByConstraints(
IPackageConstraintProvider constraintProvider,
IEnumerable<IPackage> packages,
string packageId,
bool allowPrereleaseVersions)
{
constraintProvider = constraintProvider ?? NullConstraintProvider.Instance;
// Filter packages by this constraint
IVersionSpec constraint = constraintProvider.GetConstraint(packageId);
if (constraint != null)
{
packages = packages.FindByVersion(constraint);
}
if (!allowPrereleaseVersions)
{
packages = packages.Where(p => p.IsReleaseVersion());
}
return packages;
}
/// <summary>
/// Selects the dependency package from the list of candidate packages
/// according to <paramref name="dependencyVersion"/>.
/// </summary>
/// <param name="packages">The list of candidate packages.</param>
/// <param name="dependencyVersion">The rule used to select the package from
/// <paramref name="packages"/> </param>
/// <returns>The selected package.</returns>
/// <remarks>Precondition: <paramref name="packages"/> are ordered by ascending version.</remarks>
internal static IPackage SelectDependency(this IEnumerable<IPackage> packages, DependencyVersion dependencyVersion)
{
if (packages == null || !packages.Any())
{
return null;
}
if (dependencyVersion == DependencyVersion.Lowest)
{
return packages.FirstOrDefault();
}
else if (dependencyVersion == DependencyVersion.Highest)
{
return packages.LastOrDefault();
}
else if (dependencyVersion == DependencyVersion.HighestPatch)
{
var groups = from p in packages
group p by new { p.Version.Version.Major, p.Version.Version.Minor } into g
orderby g.Key.Major, g.Key.Minor
select g;
return (from p in groups.First()
orderby p.Version descending
select p).FirstOrDefault();
}
else if (dependencyVersion == DependencyVersion.HighestMinor)
{
var groups = from p in packages
group p by new { p.Version.Version.Major } into g
orderby g.Key.Major
select g;
return (from p in groups.First()
orderby p.Version descending
select p).FirstOrDefault();
}
throw new ArgumentOutOfRangeException("dependencyVersion");
}
}
}
| |
using System;
using NUnit.Framework;
using Raksha.Crypto;
using Raksha.Crypto.Engines;
using Raksha.Crypto.Macs;
using Raksha.Crypto.Parameters;
using Raksha.Crypto.Paddings;
using Raksha.Utilities;
using Raksha.Utilities.Encoders;
using Raksha.Tests.Utilities;
namespace Raksha.Tests.Crypto
{
/// <remarks> MAC tester - vectors from
/// <a href="http://www.itl.nist.gov/fipspubs/fip81.htm">FIP 81</a> and
/// <a href="http://www.itl.nist.gov/fipspubs/fip113.htm">FIP 113</a>.
/// </remarks>
[TestFixture]
public class MacTest
: ITest
{
public string Name
{
get { return "IMac"; }
}
internal static byte[] keyBytes;
internal static byte[] ivBytes;
internal static byte[] input1;
internal static byte[] output1;
internal static byte[] output2;
internal static byte[] output3;
//
// these aren't NIST vectors, just for regression testing.
//
internal static byte[] input2;
internal static byte[] output4;
internal static byte[] output5;
internal static byte[] output6;
public MacTest()
{
}
public virtual ITestResult Perform()
{
KeyParameter key = new KeyParameter(keyBytes);
IBlockCipher cipher = new DesEngine();
IMac mac = new CbcBlockCipherMac(cipher);
//
// standard DAC - zero IV
//
mac.Init(key);
mac.BlockUpdate(input1, 0, input1.Length);
byte[] outBytes = new byte[4];
mac.DoFinal(outBytes, 0);
if (!Arrays.AreEqual(outBytes, output1))
{
return new SimpleTestResult(false, Name + ": Failed - expected "
+ Hex.ToHexString(output1) + " got " + Hex.ToHexString(outBytes));
}
//
// mac with IV.
//
ParametersWithIV param = new ParametersWithIV(key, ivBytes);
mac.Init(param);
mac.BlockUpdate(input1, 0, input1.Length);
outBytes = new byte[4];
mac.DoFinal(outBytes, 0);
if (!Arrays.AreEqual(outBytes, output2))
{
return new SimpleTestResult(false, Name + ": Failed - expected "
+ Hex.ToHexString(output2) + " got " + Hex.ToHexString(outBytes));
}
//
// CFB mac with IV - 8 bit CFB mode
//
param = new ParametersWithIV(key, ivBytes);
mac = new CfbBlockCipherMac(cipher);
mac.Init(param);
mac.BlockUpdate(input1, 0, input1.Length);
outBytes = new byte[4];
mac.DoFinal(outBytes, 0);
if (!Arrays.AreEqual(outBytes, output3))
{
return new SimpleTestResult(false, Name + ": Failed - expected "
+ Hex.ToHexString(output3) + " got " + Hex.ToHexString(outBytes));
}
//
// word aligned data - zero IV
//
mac.Init(key);
mac.BlockUpdate(input2, 0, input2.Length);
outBytes = new byte[4];
mac.DoFinal(outBytes, 0);
if (!Arrays.AreEqual(outBytes, output4))
{
return new SimpleTestResult(false, Name + ": Failed - expected "
+ Hex.ToHexString(output4) + " got " + Hex.ToHexString(outBytes));
}
//
// word aligned data - zero IV - CBC padding
//
mac = new CbcBlockCipherMac(cipher, new Pkcs7Padding());
mac.Init(key);
mac.BlockUpdate(input2, 0, input2.Length);
outBytes = new byte[4];
mac.DoFinal(outBytes, 0);
if (!Arrays.AreEqual(outBytes, output5))
{
return new SimpleTestResult(false, Name + ": Failed - expected "
+ Hex.ToHexString(output5) + " got " + Hex.ToHexString(outBytes));
}
//
// non-word aligned data - zero IV - CBC padding
//
mac.Reset();
mac.BlockUpdate(input1, 0, input1.Length);
outBytes = new byte[4];
mac.DoFinal(outBytes, 0);
if (!Arrays.AreEqual(outBytes, output6))
{
return new SimpleTestResult(false, Name + ": Failed - expected "
+ Hex.ToHexString(output6) + " got " + Hex.ToHexString(outBytes));
}
//
// non-word aligned data - zero IV - CBC padding
//
mac.Init(key);
mac.BlockUpdate(input1, 0, input1.Length);
outBytes = new byte[4];
mac.DoFinal(outBytes, 0);
if (!Arrays.AreEqual(outBytes, output6))
{
return new SimpleTestResult(false, Name + ": Failed - expected "
+ Hex.ToHexString(output6) + " got " + Hex.ToHexString(outBytes));
}
return new SimpleTestResult(true, Name + ": Okay");
}
public static void Main(
string[] args)
{
MacTest test = new MacTest();
ITestResult result = test.Perform();
Console.WriteLine(result);
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
static MacTest()
{
keyBytes = Hex.Decode("0123456789abcdef");
ivBytes = Hex.Decode("1234567890abcdef");
input1 = Hex.Decode("37363534333231204e6f77206973207468652074696d6520666f7220");
output1 = Hex.Decode("f1d30f68");
output2 = Hex.Decode("58d2e77e");
output3 = Hex.Decode("cd647403");
input2 = Hex.Decode("3736353433323120");
output4 = Hex.Decode("3af549c9");
output5 = Hex.Decode("188fbdd5");
output6 = Hex.Decode("7045eecd");
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
namespace PixelCrushers.DialogueSystem {
/// <summary>
/// Player setup wizard.
/// </summary>
public class PlayerSetupWizard : EditorWindow {
[MenuItem("Window/Dialogue System/Wizards/Player Setup", false, 1)]
public static void Init() {
(EditorWindow.GetWindow(typeof(PlayerSetupWizard), false, "Player Setup") as PlayerSetupWizard).minSize = new Vector2(700, 500);
}
// Private fields for the window:
private enum Stage {
SelectPC,
Control,
Camera,
Targeting,
Transition,
Persistence,
Review
};
private Stage stage = Stage.SelectPC;
private string[] stageLabels = new string[] { "Player", "Control", "Camera", "Targeting", "Transition", "Persistence", "Review" };
private const float ToggleWidth = 16;
private GameObject pcObject = null;
private bool setEnabledFlag = false;
/// <summary>
/// Draws the window.
/// </summary>
void OnGUI() {
DrawProgressIndicator();
DrawCurrentStage();
}
private void DrawProgressIndicator() {
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Toolbar((int) stage, stageLabels, GUILayout.Width(700));
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
EditorGUI.EndDisabledGroup();
EditorWindowTools.DrawHorizontalLine();
}
private void DrawNavigationButtons(bool backEnabled, bool nextEnabled, bool nextCloses) {
GUILayout.FlexibleSpace();
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Close", GUILayout.Width(100))) {
this.Close();
} else if (backEnabled && GUILayout.Button("Back", GUILayout.Width(100))) {
stage--;
} else {
EditorGUI.BeginDisabledGroup(!nextEnabled);
if (GUILayout.Button(nextCloses ? "Finish" : "Next", GUILayout.Width(100))) {
if (nextCloses) {
Close();
} else {
stage++;
}
}
EditorGUI.EndDisabledGroup();
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.LabelField(string.Empty, GUILayout.Height(2));
}
private void DrawCurrentStage() {
if (pcObject == null) stage = Stage.SelectPC;
switch (stage) {
case Stage.SelectPC: DrawSelectPCStage(); break;
case Stage.Control: DrawControlStage(); break;
case Stage.Camera: DrawCameraStage(); break;
case Stage.Targeting: DrawTargetingStage(); break;
case Stage.Transition: DrawTransitionStage(); break;
case Stage.Persistence: DrawPersistenceStage(); break;
case Stage.Review: DrawReviewStage(); break;
}
if ((pcObject != null) && GUI.changed) EditorUtility.SetDirty(pcObject);
}
private void DrawSelectPCStage() {
EditorGUILayout.LabelField("Select Player Object", EditorStyles.boldLabel);
EditorWindowTools.StartIndentedSection();
EditorGUILayout.HelpBox("This wizard will help you configure a Player object to work with the Dialogue System. First, assign the Player's GameObject below.", MessageType.Info);
pcObject = EditorGUILayout.ObjectField("Player Object", pcObject, typeof(GameObject), true) as GameObject;
EditorWindowTools.EndIndentedSection();
DrawNavigationButtons(false, (pcObject != null), false);
}
private enum ControlStyle {
ThirdPersonShooter,
FollowMouseClicks,
Custom
};
private void DrawControlStage() {
EditorGUILayout.LabelField("Control", EditorStyles.boldLabel);
EditorWindowTools.StartIndentedSection();
PixelCrushers.DialogueSystem.SimpleController simpleController = pcObject.GetComponent<PixelCrushers.DialogueSystem.SimpleController>();
NavigateOnMouseClick navigateOnMouseClick = pcObject.GetComponent<NavigateOnMouseClick>();
ControlStyle controlStyle = (simpleController != null)
? ControlStyle.ThirdPersonShooter
: (navigateOnMouseClick != null)
? ControlStyle.FollowMouseClicks
: ControlStyle.Custom;
EditorGUILayout.HelpBox("How will the player control movement? (Select Custom to provide your own control components instead of using the Dialogue System's.)", MessageType.Info);
controlStyle = (ControlStyle) EditorGUILayout.EnumPopup("Control", controlStyle);
switch (controlStyle) {
case ControlStyle.ThirdPersonShooter:
DestroyImmediate(navigateOnMouseClick);
DrawSimpleControllerSection(simpleController ?? pcObject.AddComponent<PixelCrushers.DialogueSystem.SimpleController>());
break;
case ControlStyle.FollowMouseClicks:
DestroyImmediate(simpleController);
DrawNavigateOnMouseClickSection(navigateOnMouseClick ?? pcObject.AddComponent<NavigateOnMouseClick>());
break;
default:
DestroyImmediate(simpleController);
DestroyImmediate(navigateOnMouseClick);
break;
}
if (GUILayout.Button("Select Player", GUILayout.Width(100))) Selection.activeGameObject = pcObject;
EditorWindowTools.EndIndentedSection();
DrawNavigationButtons(true, true, false);
}
private void DrawSimpleControllerSection(PixelCrushers.DialogueSystem.SimpleController simpleController) {
EditorWindowTools.StartIndentedSection();
if ((simpleController.idle == null) || (simpleController.runForward == null)) {
EditorGUILayout.HelpBox("The player uses third-person shooter style controls. At a minimum, Idle and Run animations are required. Click Select Player to customize further.", MessageType.Info);
}
simpleController.idle = EditorGUILayout.ObjectField("Idle Animation", simpleController.idle, typeof(AnimationClip), false) as AnimationClip;
simpleController.runForward = EditorGUILayout.ObjectField("Run Animation", simpleController.runForward, typeof(AnimationClip), false) as AnimationClip;
EditorWindowTools.StartIndentedSection();
EditorGUILayout.LabelField("Optional", EditorStyles.boldLabel);
simpleController.runSpeed = EditorGUILayout.FloatField("Run Speed", simpleController.runSpeed);
simpleController.runBack = EditorGUILayout.ObjectField("Run Back", simpleController.runBack, typeof(AnimationClip), false) as AnimationClip;
simpleController.aim = EditorGUILayout.ObjectField("Aim", simpleController.aim, typeof(AnimationClip), false) as AnimationClip;
simpleController.fire = EditorGUILayout.ObjectField("Fire", simpleController.fire, typeof(AnimationClip), false) as AnimationClip;
if (simpleController.fire != null) {
if (simpleController.upperBodyMixingTransform == null) EditorGUILayout.HelpBox("Specify the upper body mixing transform for the fire animation.", MessageType.Info);
simpleController.upperBodyMixingTransform = EditorGUILayout.ObjectField("Upper Body Transform", simpleController.upperBodyMixingTransform, typeof(Transform), true) as Transform;
simpleController.fireLayerMask = EditorGUILayout.LayerField("Fire Layer", simpleController.fireLayerMask);
simpleController.fireSound = EditorGUILayout.ObjectField("Fire Sound", simpleController.fireSound, typeof(AudioClip), false) as AudioClip;
AudioSource audioSource = pcObject.GetComponent<AudioSource>();
if (audioSource == null) {
audioSource = pcObject.AddComponent<AudioSource>();
audioSource.playOnAwake = false;
audioSource.loop = false;
}
}
EditorWindowTools.EndIndentedSection();
EditorWindowTools.EndIndentedSection();
}
private void DrawNavigateOnMouseClickSection(NavigateOnMouseClick navigateOnMouseClick) {
EditorWindowTools.StartIndentedSection();
if ((navigateOnMouseClick.idle == null) || (navigateOnMouseClick.run == null)) {
EditorGUILayout.HelpBox("The player clicks on the map to move. At a minimum, Idle and Run animations are required. Click Select Player to customize further.", MessageType.Info);
}
navigateOnMouseClick.idle = EditorGUILayout.ObjectField("Idle Animation", navigateOnMouseClick.idle, typeof(AnimationClip), false) as AnimationClip;
navigateOnMouseClick.run = EditorGUILayout.ObjectField("Run Animation", navigateOnMouseClick.run, typeof(AnimationClip), false) as AnimationClip;
navigateOnMouseClick.mouseButton = (NavigateOnMouseClick.MouseButtonType) EditorGUILayout.EnumPopup("Mouse Button", navigateOnMouseClick.mouseButton);
EditorWindowTools.EndIndentedSection();
}
private void DrawCameraStage() {
EditorGUILayout.LabelField("Camera", EditorStyles.boldLabel);
EditorWindowTools.StartIndentedSection();
UnityEngine.Camera playerCamera = pcObject.GetComponentInChildren<UnityEngine.Camera>() ?? UnityEngine.Camera.main;
SmoothCameraWithBumper smoothCamera = (playerCamera != null) ? playerCamera.GetComponent<SmoothCameraWithBumper>() : null;
EditorGUILayout.BeginHorizontal();
bool useSmoothCamera = EditorGUILayout.Toggle((smoothCamera != null) , GUILayout.Width(ToggleWidth));
EditorGUILayout.LabelField("Use Smooth Follow Camera", EditorStyles.boldLabel);
EditorGUILayout.EndHorizontal();
if (useSmoothCamera) {
if (playerCamera == null) {
GameObject playerCameraObject = new GameObject("Player Camera");
playerCameraObject.transform.parent = pcObject.transform;
playerCamera = playerCameraObject.AddComponent<UnityEngine.Camera>();
playerCamera.tag = "MainCamera";
}
smoothCamera = playerCamera.GetComponentInChildren<SmoothCameraWithBumper>() ?? playerCamera.gameObject.AddComponent<SmoothCameraWithBumper>();
EditorWindowTools.StartIndentedSection();
if (smoothCamera.target == null) {
EditorGUILayout.HelpBox("Specify the transform (usually the head) that the camera should follow.", MessageType.Info);
}
smoothCamera.target = EditorGUILayout.ObjectField("Target", smoothCamera.target, typeof(Transform), true) as Transform;
EditorWindowTools.EndIndentedSection();
} else {
DestroyImmediate(smoothCamera);
}
if (GUILayout.Button("Select Camera", GUILayout.Width(100))) Selection.activeObject = playerCamera;
EditorWindowTools.EndIndentedSection();
DrawNavigationButtons(true, true, false);
}
private void DrawTargetingStage() {
EditorGUILayout.LabelField("Targeting", EditorStyles.boldLabel);
EditorWindowTools.StartIndentedSection();
SelectorType selectorType = GetSelectorType();
if (selectorType == SelectorType.None) EditorGUILayout.HelpBox("Specify how the player will target NPCs to trigger conversations and barks.", MessageType.Info);
selectorType = (SelectorType) EditorGUILayout.EnumPopup("Target NPCs By", selectorType);
switch (selectorType) {
case SelectorType.Proximity:
DrawProximitySelector();
break;
case SelectorType.CenterOfScreen:
case SelectorType.MousePosition:
case SelectorType.CustomPosition:
DrawSelector(selectorType);
break;
default:
DrawNoSelector();
break;
}
EditorWindowTools.EndIndentedSection();
EditorWindowTools.DrawHorizontalLine();
DrawOverrideNameSubsection();
if (GUILayout.Button("Select Player", GUILayout.Width(100))) Selection.activeGameObject = pcObject;
DrawNavigationButtons(true, true, false);
}
private enum SelectorType {
CenterOfScreen,
MousePosition,
Proximity,
CustomPosition,
None,
};
private enum MouseButtonChoice {
LeftMouseButton,
RightMouseButton
}
private SelectorType GetSelectorType() {
if (pcObject.GetComponent<ProximitySelector>() != null) {
return SelectorType.Proximity;
} else {
Selector selector = pcObject.GetComponent<Selector>();
if (selector != null) {
switch (selector.selectAt) {
case Selector.SelectAt.CenterOfScreen:
return SelectorType.CenterOfScreen;
case Selector.SelectAt.MousePosition:
return SelectorType.MousePosition;
default:
return SelectorType.CustomPosition;
}
} else {
return SelectorType.None;
}
}
}
private void DrawNoSelector() {
DestroyImmediate(pcObject.GetComponent<Selector>());
DestroyImmediate(pcObject.GetComponent<ProximitySelector>());
EditorWindowTools.StartIndentedSection();
EditorGUILayout.HelpBox("The player will not use a Dialogue System-provided targeting component.", MessageType.None);
EditorWindowTools.EndIndentedSection();
}
private void DrawProximitySelector() {
DestroyImmediate(pcObject.GetComponent<Selector>());
ProximitySelector proximitySelector = pcObject.GetComponent<ProximitySelector>() ?? pcObject.AddComponent<ProximitySelector>();
EditorWindowTools.StartIndentedSection();
EditorGUILayout.HelpBox("The player can target usable objects (e.g., conversations on NPCs) when inside their trigger areas. Click Select Player to customize the Proximity Selector.", MessageType.None);
DrawSelectorUIPosition();
proximitySelector.useKey = (KeyCode) EditorGUILayout.EnumPopup("'Use' Key", proximitySelector.useKey);
proximitySelector.useButton = EditorGUILayout.TextField("'Use' Button", proximitySelector.useButton);
EditorWindowTools.EndIndentedSection();
}
private void DrawSelector(SelectorType selectorType) {
DestroyImmediate(pcObject.GetComponent<ProximitySelector>());
Selector selector = pcObject.GetComponent<Selector>() ?? pcObject.AddComponent<Selector>();
EditorWindowTools.StartIndentedSection();
switch (selectorType) {
case SelectorType.CenterOfScreen:
EditorGUILayout.HelpBox("Usable objects in the center of the screen will be targeted.", MessageType.None);
selector.selectAt = Selector.SelectAt.CenterOfScreen;
break;
case SelectorType.MousePosition:
EditorGUILayout.HelpBox("Usable objects under the mouse cursor will be targeted. Specify which mouse button activates the targeted object.", MessageType.None);
selector.selectAt = Selector.SelectAt.MousePosition;
MouseButtonChoice mouseButtonChoice = string.Equals(selector.useButton, "Fire2") ? MouseButtonChoice.RightMouseButton : MouseButtonChoice.LeftMouseButton;
mouseButtonChoice = (MouseButtonChoice) EditorGUILayout.EnumPopup("Select With", mouseButtonChoice);
selector.useButton = (mouseButtonChoice == MouseButtonChoice.RightMouseButton) ? "Fire2" : "Fire1";
break;
default:
case SelectorType.CustomPosition:
EditorGUILayout.HelpBox("Usable objects will be targeted at a custom screen position. You are responsible for setting the Selector component's CustomPosition property.", MessageType.None);
selector.selectAt = Selector.SelectAt.CustomPosition;
break;
}
if (selector.reticle != null) {
selector.reticle.inRange = EditorGUILayout.ObjectField("In-Range Reticle", selector.reticle.inRange, typeof(Texture2D), false) as Texture2D;
selector.reticle.outOfRange = EditorGUILayout.ObjectField("Out-of-Range Reticle", selector.reticle.outOfRange, typeof(Texture2D), false) as Texture2D;
}
DrawSelectorUIPosition();
selector.useKey = (KeyCode) EditorGUILayout.EnumPopup("'Use' Key", selector.useKey);
selector.useButton = EditorGUILayout.TextField("'Use' Button", selector.useButton);
EditorGUILayout.HelpBox("Click Select Player to customize the Selector.", MessageType.None);
EditorWindowTools.EndIndentedSection();
}
private enum SelectorUIPositionType {
TopOfScreen,
OnSelectionTarget
}
private void DrawSelectorUIPosition() {
SelectorFollowTarget selectorFollowTarget = pcObject.GetComponent<SelectorFollowTarget>();
SelectorUIPositionType position = (selectorFollowTarget != null) ? SelectorUIPositionType.OnSelectionTarget : SelectorUIPositionType.TopOfScreen;
EditorGUILayout.HelpBox("Specify where the current selection message will be displayed.", MessageType.None);
position = (SelectorUIPositionType) EditorGUILayout.EnumPopup("Message Position", position);
if (position == SelectorUIPositionType.TopOfScreen) {
DestroyImmediate(selectorFollowTarget);
} else {
if (selectorFollowTarget == null) pcObject.AddComponent<SelectorFollowTarget>();
}
}
private void DrawOverrideNameSubsection() {
NPCSetupWizard.DrawOverrideNameSubsection(pcObject);
}
private void DrawTransitionStage() {
EditorGUILayout.LabelField("Gameplay/Conversation Transition", EditorStyles.boldLabel);
EditorWindowTools.StartIndentedSection();
SetEnabledOnDialogueEvent setEnabled = pcObject.GetComponent<SetEnabledOnDialogueEvent>();
setEnabledFlag = setEnabledFlag || (setEnabled != null);
if (!setEnabledFlag) EditorGUILayout.HelpBox("Gameplay components, such as movement and camera control, will interfere with conversations. If you want to disable gameplay components during conversations, tick the checkbox below.", MessageType.None);
EditorGUILayout.BeginHorizontal();
setEnabledFlag = EditorGUILayout.Toggle(setEnabledFlag, GUILayout.Width(ToggleWidth));
EditorGUILayout.LabelField("Disable gameplay components during conversations", EditorStyles.boldLabel);
EditorGUILayout.EndHorizontal();
DrawDisableControlsSection();
DrawShowCursorSection();
if (GUILayout.Button("Select Player", GUILayout.Width(100))) Selection.activeGameObject = pcObject;
EditorWindowTools.EndIndentedSection();
DrawNavigationButtons(true, true, false);
}
private void DrawDisableControlsSection() {
EditorWindowTools.StartIndentedSection();
SetEnabledOnDialogueEvent enabler = FindConversationEnabler();
if (setEnabledFlag) {
if (enabler == null) enabler = pcObject.AddComponent<SetEnabledOnDialogueEvent>();
enabler.trigger = DialogueEvent.OnConversation;
enabler.onStart = GetPlayerControls(enabler.onStart, Toggle.False);
enabler.onEnd = GetPlayerControls(enabler.onEnd, Toggle.True);
ShowDisabledComponents(enabler.onStart);
} else {
DestroyImmediate(enabler);
}
EditorWindowTools.EndIndentedSection();
}
private SetEnabledOnDialogueEvent FindConversationEnabler() {
foreach (var component in pcObject.GetComponents<SetEnabledOnDialogueEvent>()) {
if (component.trigger == DialogueEvent.OnConversation) return component;
}
return null;
}
private void ShowDisabledComponents(SetEnabledOnDialogueEvent.SetEnabledAction[] actionList) {
EditorGUILayout.LabelField("The following components will be disabled during conversations:");
EditorWindowTools.StartIndentedSection();
foreach (SetEnabledOnDialogueEvent.SetEnabledAction action in actionList) {
if (action.target != null) {
EditorGUILayout.LabelField(action.target.GetType().Name);
}
}
EditorWindowTools.EndIndentedSection();
}
private SetEnabledOnDialogueEvent.SetEnabledAction[] GetPlayerControls(SetEnabledOnDialogueEvent.SetEnabledAction[] oldList, Toggle state) {
List<SetEnabledOnDialogueEvent.SetEnabledAction> actions = new List<SetEnabledOnDialogueEvent.SetEnabledAction>();
if (oldList != null) {
actions.AddRange(oldList);
}
foreach (var component in pcObject.GetComponents<MonoBehaviour>()) {
if (IsPlayerControlComponent(component) && !IsInActionList(actions, component)) {
AddToActionList(actions, component, state);
}
}
SmoothCameraWithBumper smoothCamera = pcObject.GetComponentInChildren<SmoothCameraWithBumper>();
if (smoothCamera == null) smoothCamera = UnityEngine.Camera.main.GetComponent<SmoothCameraWithBumper>();
if ((smoothCamera != null) && !IsInActionList(actions, smoothCamera)) {
AddToActionList(actions, smoothCamera, state);
}
actions.RemoveAll(a => ((a == null) || (a.target == null)));
return actions.ToArray();
}
private bool IsPlayerControlComponent(MonoBehaviour component) {
return (component is Selector) ||
(component is ProximitySelector) ||
(component is SimpleController) ||
(component is NavigateOnMouseClick);
}
private bool IsInActionList(List<SetEnabledOnDialogueEvent.SetEnabledAction> actions, MonoBehaviour component) {
return (actions.Find(a => (a.target == component)) != null);
}
private void AddToActionList(List<SetEnabledOnDialogueEvent.SetEnabledAction> actions, MonoBehaviour component, Toggle state) {
SetEnabledOnDialogueEvent.SetEnabledAction newAction = new SetEnabledOnDialogueEvent.SetEnabledAction();
newAction.state = state;
newAction.target = component;
actions.Add(newAction);
}
private void DrawShowCursorSection() {
EditorWindowTools.DrawHorizontalLine();
ShowCursorOnConversation showCursor = pcObject.GetComponent<ShowCursorOnConversation>();
bool showCursorFlag = (showCursor != null);
if (!showCursorFlag) EditorGUILayout.HelpBox("If regular gameplay hides the mouse cursor, tick Show Mouse Cursor to enable it during conversations.", MessageType.Info);
EditorGUILayout.BeginHorizontal();
showCursorFlag = EditorGUILayout.Toggle(showCursorFlag, GUILayout.Width(ToggleWidth));
EditorGUILayout.LabelField("Show mouse cursor during conversations", EditorStyles.boldLabel);
EditorGUILayout.EndHorizontal();
if (showCursorFlag) {
if (showCursor == null) showCursor = pcObject.AddComponent<ShowCursorOnConversation>();
} else {
DestroyImmediate(showCursor);
}
}
private void DrawPersistenceStage() {
EditorGUILayout.LabelField("Persistence", EditorStyles.boldLabel);
PersistentPositionData persistentPositionData = pcObject.GetComponent<PersistentPositionData>();
EditorWindowTools.StartIndentedSection();
if (persistentPositionData == null) EditorGUILayout.HelpBox("The player can be configured to record its position in the Dialogue System's Lua environment so it will be preserved when saving and loading games.", MessageType.Info);
EditorGUILayout.BeginHorizontal();
bool hasPersistentPosition = EditorGUILayout.Toggle((persistentPositionData != null), GUILayout.Width(ToggleWidth));
EditorGUILayout.LabelField("Player records position for saved games", EditorStyles.boldLabel);
EditorGUILayout.EndHorizontal();
if (hasPersistentPosition) {
if (persistentPositionData == null) {
persistentPositionData = pcObject.AddComponent<PersistentPositionData>();
persistentPositionData.overrideActorName = "Player";
}
if (string.IsNullOrEmpty(persistentPositionData.overrideActorName)) {
EditorGUILayout.HelpBox(string.Format("Position data will be saved to the Actor['{0}'] (the name of the GameObject) or the Override Actor Name if defined. You can override the name below.", pcObject.name), MessageType.None);
} else {
EditorGUILayout.HelpBox(string.Format("Position data will be saved to the Actor['{0}']. To use the name of the GameObject instead, clear the field below.", persistentPositionData.overrideActorName), MessageType.None);
}
persistentPositionData.overrideActorName = EditorGUILayout.TextField("Actor Name", persistentPositionData.overrideActorName);
} else {
DestroyImmediate(persistentPositionData);
}
EditorWindowTools.EndIndentedSection();
DrawNavigationButtons(true, true, false);
}
private void DrawReviewStage() {
EditorGUILayout.LabelField("Review", EditorStyles.boldLabel);
EditorWindowTools.StartIndentedSection();
EditorGUILayout.HelpBox("Your Player is ready! Below is a summary of the configuration.", MessageType.Info);
SimpleController simpleController = pcObject.GetComponent<SimpleController>();
NavigateOnMouseClick navigateOnMouseClick = pcObject.GetComponent<NavigateOnMouseClick>();
if (simpleController != null) {
EditorGUILayout.LabelField("Control: Third-Person Shooter Style");
} else if (navigateOnMouseClick != null) {
EditorGUILayout.LabelField("Control: Follow Mouse Clicks");
} else {
EditorGUILayout.LabelField("Control: Custom");
}
switch (GetSelectorType()) {
case SelectorType.CenterOfScreen: EditorGUILayout.LabelField("Targeting: Center of Screen"); break;
case SelectorType.CustomPosition: EditorGUILayout.LabelField("Targeting: Custom Position (you must set Selector.CustomPosition)"); break;
case SelectorType.MousePosition: EditorGUILayout.LabelField("Targeting: Mouse Position"); break;
case SelectorType.Proximity: EditorGUILayout.LabelField("Targeting: Proximity"); break;
default: EditorGUILayout.LabelField("Targeting: None"); break;
}
SetEnabledOnDialogueEvent enabler = FindConversationEnabler();
if (enabler != null) ShowDisabledComponents(enabler.onStart);
ShowCursorOnConversation showCursor = pcObject.GetComponentInChildren<ShowCursorOnConversation>();
if (showCursor != null) EditorGUILayout.LabelField("Show Cursor During Conversations: Yes");
PersistentPositionData persistentPositionData = pcObject.GetComponentInChildren<PersistentPositionData>();
EditorGUILayout.LabelField(string.Format("Save Position: {0}", (persistentPositionData != null) ? "Yes" : "No"));
EditorWindowTools.EndIndentedSection();
DrawNavigationButtons(true, true, true);
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Xml;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Threading;
using Ctrip.Appender;
using Ctrip.Util;
using Ctrip.Repository;
namespace Ctrip.Config
{
/// <summary>
/// Use this class to initialize the Ctrip environment using an Xml tree.
/// </summary>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// <para>
/// Configures a <see cref="ILoggerRepository"/> using an Xml tree.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
[Obsolete("Use XmlConfigurator instead of DOMConfigurator")]
public sealed class DOMConfigurator
{
#region Private Instance Constructors
/// <summary>
/// Private constructor
/// </summary>
private DOMConfigurator()
{
}
#endregion Protected Instance Constructors
#region Configure static methods
/// <summary>
/// Automatically configures the Ctrip system based on the
/// application's configuration settings.
/// </summary>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// Each application has a configuration file. This has the
/// same name as the application with '.config' appended.
/// This file is XML and calling this function prompts the
/// configurator to look in that file for a section called
/// <c>Ctrip</c> that contains the configuration data.
/// </remarks>
[Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")]
static public void Configure()
{
XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()));
}
/// <summary>
/// Automatically configures the <see cref="ILoggerRepository"/> using settings
/// stored in the application's configuration file.
/// </summary>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// Each application has a configuration file. This has the
/// same name as the application with '.config' appended.
/// This file is XML and calling this function prompts the
/// configurator to look in that file for a section called
/// <c>Ctrip</c> that contains the configuration data.
/// </remarks>
/// <param name="repository">The repository to configure.</param>
[Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")]
static public void Configure(ILoggerRepository repository)
{
XmlConfigurator.Configure(repository);
}
/// <summary>
/// Configures Ctrip using a <c>Ctrip</c> element
/// </summary>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// Loads the Ctrip configuration from the XML element
/// supplied as <paramref name="element"/>.
/// </remarks>
/// <param name="element">The element to parse.</param>
[Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")]
static public void Configure(XmlElement element)
{
XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), element);
}
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the specified XML
/// element.
/// </summary>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// Loads the Ctrip configuration from the XML element
/// supplied as <paramref name="element"/>.
/// </remarks>
/// <param name="repository">The repository to configure.</param>
/// <param name="element">The element to parse.</param>
[Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")]
static public void Configure(ILoggerRepository repository, XmlElement element)
{
XmlConfigurator.Configure(repository, element);
}
/// <summary>
/// Configures Ctrip using the specified configuration file.
/// </summary>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>Ctrip</c> that holds
/// the Ctrip configuration data.
/// </para>
/// <para>
/// The Ctrip configuration file can possible be specified in the application's
/// configuration file (either <c>MyAppName.exe.config</c> for a
/// normal application on <c>Web.config</c> for an ASP.NET application).
/// </para>
/// <example>
/// The following example configures Ctrip using a configuration file, of which the
/// location is stored in the application's configuration file :
/// </example>
/// <code lang="C#">
/// using Ctrip.Config;
/// using System.IO;
/// using System.Configuration;
///
/// ...
///
/// DOMConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["Ctrip-config-file"]));
/// </code>
/// <para>
/// In the <c>.config</c> file, the path to the Ctrip can be specified like this :
/// </para>
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="Ctrip-config-file" value="log.config"/>
/// </appSettings>
/// </configuration>
/// </code>
/// </remarks>
[Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")]
static public void Configure(FileInfo configFile)
{
XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile);
}
/// <summary>
/// Configures Ctrip using the specified configuration file.
/// </summary>
/// <param name="configStream">A stream to load the XML configuration from.</param>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// <para>
/// The configuration data must be valid XML. It must contain
/// at least one element called <c>Ctrip</c> that holds
/// the Ctrip configuration data.
/// </para>
/// <para>
/// Note that this method will NOT close the stream parameter.
/// </para>
/// </remarks>
[Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")]
static public void Configure(Stream configStream)
{
XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configStream);
}
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the specified configuration
/// file.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>Ctrip</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// The Ctrip configuration file can possible be specified in the application's
/// configuration file (either <c>MyAppName.exe.config</c> for a
/// normal application on <c>Web.config</c> for an ASP.NET application).
/// </para>
/// <example>
/// The following example configures Ctrip using a configuration file, of which the
/// location is stored in the application's configuration file :
/// </example>
/// <code lang="C#">
/// using Ctrip.Config;
/// using System.IO;
/// using System.Configuration;
///
/// ...
///
/// DOMConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["Ctrip-config-file"]));
/// </code>
/// <para>
/// In the <c>.config</c> file, the path to the Ctrip can be specified like this :
/// </para>
/// <code lang="XML" escaped="true">
/// <configuration>
/// <appSettings>
/// <add key="Ctrip-config-file" value="log.config"/>
/// </appSettings>
/// </configuration>
/// </code>
/// </remarks>
[Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")]
static public void Configure(ILoggerRepository repository, FileInfo configFile)
{
XmlConfigurator.Configure(repository, configFile);
}
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the specified configuration
/// file.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configStream">The stream to load the XML configuration from.</param>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// <para>
/// The configuration data must be valid XML. It must contain
/// at least one element called <c>Ctrip</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// Note that this method will NOT close the stream parameter.
/// </para>
/// </remarks>
[Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")]
static public void Configure(ILoggerRepository repository, Stream configStream)
{
XmlConfigurator.Configure(repository, configStream);
}
#endregion Configure static methods
#region ConfigureAndWatch static methods
#if (!NETCF && !SSCLI)
/// <summary>
/// Configures Ctrip using the file specified, monitors the file for changes
/// and reloads the configuration if a change is detected.
/// </summary>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>Ctrip</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// The configuration file will be monitored using a <see cref="FileSystemWatcher"/>
/// and depends on the behavior of that class.
/// </para>
/// <para>
/// For more information on how to configure Ctrip using
/// a separate configuration file, see <see cref="M:Configure(FileInfo)"/>.
/// </para>
/// </remarks>
/// <seealso cref="M:Configure(FileInfo)"/>
[Obsolete("Use XmlConfigurator.ConfigureAndWatch instead of DOMConfigurator.ConfigureAndWatch")]
static public void ConfigureAndWatch(FileInfo configFile)
{
XmlConfigurator.ConfigureAndWatch(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile);
}
/// <summary>
/// Configures the <see cref="ILoggerRepository"/> using the file specified,
/// monitors the file for changes and reloads the configuration if a change
/// is detected.
/// </summary>
/// <param name="repository">The repository to configure.</param>
/// <param name="configFile">The XML file to load the configuration from.</param>
/// <remarks>
/// <para>
/// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b>
/// </para>
/// <para>
/// The configuration file must be valid XML. It must contain
/// at least one element called <c>Ctrip</c> that holds
/// the configuration data.
/// </para>
/// <para>
/// The configuration file will be monitored using a <see cref="FileSystemWatcher"/>
/// and depends on the behavior of that class.
/// </para>
/// <para>
/// For more information on how to configure Ctrip using
/// a separate configuration file, see <see cref="M:Configure(FileInfo)"/>.
/// </para>
/// </remarks>
/// <seealso cref="M:Configure(FileInfo)"/>
[Obsolete("Use XmlConfigurator.ConfigureAndWatch instead of DOMConfigurator.ConfigureAndWatch")]
static public void ConfigureAndWatch(ILoggerRepository repository, FileInfo configFile)
{
XmlConfigurator.ConfigureAndWatch(repository, configFile);
}
#endif
#endregion ConfigureAndWatch static methods
}
}
| |
// 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.Runtime.InteropServices;
internal partial class Interop
{
//
// These structures define the layout of CNG key blobs passed to NCryptImportKey
//
internal partial class BCrypt
{
/// <summary>
/// Append "value" to the data already in blob.
/// </summary>
internal static void Emit(byte[] blob, ref int offset, byte[] value)
{
Debug.Assert(blob != null);
Debug.Assert(offset >= 0);
Buffer.BlockCopy(value, 0, blob, offset, value.Length);
offset += value.Length;
}
/// <summary>
/// Append "value" to the data already in blob.
/// </summary>
internal static void EmitByte(byte[] blob, ref int offset, byte value, int count = 1)
{
Debug.Assert(blob != null);
Debug.Assert(offset >= 0);
Debug.Assert(count > 0);
int finalOffset = offset + count;
for (int i = offset; i < finalOffset; i++)
{
blob[i] = value;
}
offset = finalOffset;
}
/// <summary>
/// Append "value" in big Endian format to the data already in blob.
/// </summary>
internal static void EmitBigEndian(byte[] blob, ref int offset, int value)
{
Debug.Assert(blob != null);
Debug.Assert(offset >= 0);
unchecked
{
blob[offset++] = ((byte)(value >> 24));
blob[offset++] = ((byte)(value >> 16));
blob[offset++] = ((byte)(value >> 8));
blob[offset++] = ((byte)(value));
}
}
/// <summary>
/// Peel off the next "count" bytes in blob and return them in a byte array.
/// </summary>
internal static byte[] Consume(byte[] blob, ref int offset, int count)
{
byte[] value = new byte[count];
Buffer.BlockCopy(blob, offset, value, 0, count);
offset += count;
return value;
}
/// <summary>
/// Magic numbers identifying blob types
/// </summary>
internal enum KeyBlobMagicNumber : int
{
BCRYPT_DSA_PUBLIC_MAGIC = 0x42505344,
BCRYPT_DSA_PRIVATE_MAGIC = 0x56505344,
BCRYPT_DSA_PUBLIC_MAGIC_V2 = 0x32425044,
BCRYPT_DSA_PRIVATE_MAGIC_V2 = 0x32565044,
BCRYPT_ECDH_PUBLIC_P256_MAGIC = 0x314B4345,
BCRYPT_ECDH_PRIVATE_P256_MAGIC = 0x324B4345,
BCRYPT_ECDH_PUBLIC_P384_MAGIC = 0x334B4345,
BCRYPT_ECDH_PRIVATE_P384_MAGIC = 0x344B4345,
BCRYPT_ECDH_PUBLIC_P521_MAGIC = 0x354B4345,
BCRYPT_ECDH_PRIVATE_P521_MAGIC = 0x364B4345,
BCRYPT_ECDH_PUBLIC_GENERIC_MAGIC = 0x504B4345,
BCRYPT_ECDH_PRIVATE_GENERIC_MAGIC = 0x564B4345,
BCRYPT_ECDSA_PUBLIC_P256_MAGIC = 0x31534345,
BCRYPT_ECDSA_PRIVATE_P256_MAGIC = 0x32534345,
BCRYPT_ECDSA_PUBLIC_P384_MAGIC = 0x33534345,
BCRYPT_ECDSA_PRIVATE_P384_MAGIC = 0x34534345,
BCRYPT_ECDSA_PUBLIC_P521_MAGIC = 0x35534345,
BCRYPT_ECDSA_PRIVATE_P521_MAGIC = 0x36534345,
BCRYPT_ECDSA_PUBLIC_GENERIC_MAGIC = 0x50444345,
BCRYPT_ECDSA_PRIVATE_GENERIC_MAGIC = 0x56444345,
BCRYPT_RSAPUBLIC_MAGIC = 0x31415352,
BCRYPT_RSAPRIVATE_MAGIC = 0x32415352,
BCRYPT_RSAFULLPRIVATE_MAGIC = 0x33415352,
BCRYPT_KEY_DATA_BLOB_MAGIC = 0x4d42444b,
}
/// <summary>
/// Well known key blob types
/// </summary>
internal static class KeyBlobType
{
internal const string BCRYPT_PUBLIC_KEY_BLOB = "PUBLICBLOB";
internal const string BCRYPT_PRIVATE_KEY_BLOB = "PRIVATEBLOB";
internal const string BCRYPT_RSAFULLPRIVATE_BLOB = "RSAFULLPRIVATEBLOB";
internal const string BCRYPT_RSAPRIVATE_BLOB = "RSAPRIVATEBLOB";
internal const string BCRYPT_RSAPUBLIC_KEY_BLOB = "RSAPUBLICBLOB";
internal const string BCRYPT_DSA_PUBLIC_BLOB = "DSAPUBLICBLOB";
internal const string BCRYPT_DSA_PRIVATE_BLOB = "DSAPRIVATEBLOB";
internal const string LEGACY_DSA_V2_PUBLIC_BLOB = "V2CAPIDSAPUBLICBLOB";
internal const string LEGACY_DSA_V2_PRIVATE_BLOB = "V2CAPIDSAPRIVATEBLOB";
internal const string BCRYPT_ECCPUBLIC_BLOB = "ECCPUBLICBLOB";
internal const string BCRYPT_ECCPRIVATE_BLOB = "ECCPRIVATEBLOB";
internal const string BCRYPT_ECCFULLPUBLIC_BLOB = "ECCFULLPUBLICBLOB";
internal const string BCRYPT_ECCFULLPRIVATE_BLOB = "ECCFULLPRIVATEBLOB";
}
/// <summary>
/// The BCRYPT_RSAKEY_BLOB structure is used as a header for an RSA public key or private key BLOB in memory.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct BCRYPT_RSAKEY_BLOB
{
internal KeyBlobMagicNumber Magic;
internal int BitLength;
internal int cbPublicExp;
internal int cbModulus;
internal int cbPrime1;
internal int cbPrime2;
}
/// <summary>
/// The BCRYPT_DSA_KEY_BLOB structure is used as a v1 header for a DSA public key or private key BLOB in memory.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct BCRYPT_DSA_KEY_BLOB
{
internal KeyBlobMagicNumber Magic;
internal int cbKey;
internal fixed byte Count[4];
internal fixed byte Seed[20];
internal fixed byte q[20];
}
/// <summary>
/// The BCRYPT_DSA_KEY_BLOB structure is used as a v2 header for a DSA public key or private key BLOB in memory.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct BCRYPT_DSA_KEY_BLOB_V2
{
internal KeyBlobMagicNumber Magic;
internal int cbKey;
internal HASHALGORITHM_ENUM hashAlgorithm;
internal DSAFIPSVERSION_ENUM standardVersion;
internal int cbSeedLength;
internal int cbGroupSize;
internal fixed byte Count[4];
}
public enum HASHALGORITHM_ENUM
{
DSA_HASH_ALGORITHM_SHA1 = 0,
DSA_HASH_ALGORITHM_SHA256 = 1,
DSA_HASH_ALGORITHM_SHA512 = 2,
}
public enum DSAFIPSVERSION_ENUM
{
DSA_FIPS186_2 = 0,
DSA_FIPS186_3 = 1,
}
/// <summary>
/// The BCRYPT_ECCKEY_BLOB structure is used as a header for an ECC public key or private key BLOB in memory.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct BCRYPT_ECCKEY_BLOB
{
internal KeyBlobMagicNumber Magic;
internal int cbKey;
}
/// <summary>
/// Represents the type of curve.
/// </summary>
internal enum ECC_CURVE_TYPE_ENUM : int
{
BCRYPT_ECC_PRIME_SHORT_WEIERSTRASS_CURVE = 0x1,
BCRYPT_ECC_PRIME_TWISTED_EDWARDS_CURVE = 0x2,
BCRYPT_ECC_PRIME_MONTGOMERY_CURVE = 0x3,
}
/// <summary>
/// Represents the algorithm that was used with Seed to generate A and B.
/// </summary>
internal enum ECC_CURVE_ALG_ID_ENUM : int
{
BCRYPT_NO_CURVE_GENERATION_ALG_ID = 0x0,
}
/// <summary>
/// Used as a header to curve parameters including the public and potentially private key.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct BCRYPT_ECCFULLKEY_BLOB
{
internal KeyBlobMagicNumber Magic;
internal int Version; //Version of the structure
internal ECC_CURVE_TYPE_ENUM CurveType; //Supported curve types.
internal ECC_CURVE_ALG_ID_ENUM CurveGenerationAlgId; //For X.592 verification purposes, if we include Seed we will need to include the algorithm ID.
internal int cbFieldLength; //Byte length of the fields P, A, B, X, Y.
internal int cbSubgroupOrder; //Byte length of the subgroup.
internal int cbCofactor; //Byte length of cofactor of G in E.
internal int cbSeed; //Byte length of the seed used to generate the curve.
// The rest of the buffer contains the domain parameters
}
/// <summary>
/// NCrypt buffer descriptors
/// </summary>
internal enum NCryptBufferDescriptors : int
{
NCRYPTBUFFER_ECC_CURVE_NAME = 60,
}
/// <summary>
/// BCrypt buffer
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct BCryptBuffer
{
internal int cbBuffer; // Length of buffer, in bytes
internal NCryptBufferDescriptors BufferType; // Buffer type
internal IntPtr pvBuffer; // Pointer to buffer
}
/// <summary>
/// The version of BCryptBuffer
/// </summary>
internal const int BCRYPTBUFFER_VERSION = 0;
/// <summary>
/// Contains a set of generic CNG buffers.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct BCryptBufferDesc
{
internal int ulVersion; // Version number
internal int cBuffers; // Number of buffers
internal IntPtr pBuffers; // Pointer to array of BCryptBuffers
}
/// <summary>
/// The version of BCRYPT_ECC_PARAMETER_HEADER
/// </summary>
internal const int BCRYPT_ECC_PARAMETER_HEADER_V1 = 1;
/// <summary>
/// Used as a header to curve parameters.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct BCRYPT_ECC_PARAMETER_HEADER
{
internal int Version; //Version of the structure
internal ECC_CURVE_TYPE_ENUM CurveType; //Supported curve types.
internal ECC_CURVE_ALG_ID_ENUM CurveGenerationAlgId; //For X.592 verification purposes, if we include Seed we will need to include the algorithm ID.
internal int cbFieldLength; //Byte length of the fields P, A, B, X, Y.
internal int cbSubgroupOrder; //Byte length of the subgroup.
internal int cbCofactor; //Byte length of cofactor of G in E.
internal int cbSeed; //Byte length of the seed used to generate the curve.
// The rest of the buffer contains the domain parameters
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO
{
private int cbSize;
private uint dwInfoVersion;
internal byte* pbNonce;
internal int cbNonce;
internal byte* pbAuthData;
internal int cbAuthData;
internal byte* pbTag;
internal int cbTag;
internal byte* pbMacContext;
internal int cbMacContext;
internal int cbAAD;
internal ulong cbData;
internal uint dwFlags;
public static BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO Create()
{
BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO ret = new BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO();
ret.cbSize = sizeof(BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO);
const uint BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO_VERSION = 1;
ret.dwInfoVersion = BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO_VERSION;
return ret;
}
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// 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 the Outercurve Foundation 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.
namespace WebsitePanel.EnterpriseServer
{
public class Quotas
{
/*
select 'public const string ' + UPPER(REPLACE(q.QuotaName, '.', '_')) + ' = "' +
q.QuotaName + '"; // ' + q.QuotaDescription
from quotas as q
inner join ResourceGroups as rg on q.groupid = rg.groupid
order by rg.groupOrder
* */
public const string OS_ODBC = "OS.ODBC"; // ODBC DSNs
public const string OS_BANDWIDTH = "OS.Bandwidth"; // Bandwidth, MB
public const string OS_DISKSPACE = "OS.Diskspace"; // Disk space, MB
public const string OS_DOMAINS = "OS.Domains"; // Domains
public const string OS_SUBDOMAINS = "OS.SubDomains"; // Sub-Domains
public const string OS_DOMAINPOINTERS = "OS.DomainPointers"; // Domain Pointers
public const string OS_FILEMANAGER = "OS.FileManager"; // File Manager
public const string OS_SCHEDULEDTASKS = "OS.ScheduledTasks"; // Scheduled Tasks
public const string OS_SCHEDULEDINTERVALTASKS = "OS.ScheduledIntervalTasks"; // Interval Tasks Allowed
public const string OS_MINIMUMTASKINTERVAL = "OS.MinimumTaskInterval"; // Minimum Tasks Interval, minutes
public const string OS_APPINSTALLER = "OS.AppInstaller"; // Applications Installer
public const string OS_EXTRAAPPLICATIONS = "OS.ExtraApplications"; // Extra Application Packs
public const string OS_NOTALLOWTENANTCREATEDOMAINS = "OS.AllowTenantCreateDomains"; // Do not Allow tenant to create top level domains
public const string WEB_SITES = "Web.Sites"; // Web Sites
public const string WEB_ASPNET11 = "Web.AspNet11"; // ASP.NET 1.1
public const string WEB_ASPNET20 = "Web.AspNet20"; // ASP.NET 2.0
public const string WEB_ASPNET40 = "Web.AspNet40"; // ASP.NET 4.0
public const string WEB_ASP = "Web.Asp"; // ASP
public const string WEB_PHP4 = "Web.Php4"; // PHP 4.x
public const string WEB_PHP5 = "Web.Php5"; // PHP 5.x
public const string WEB_PERL = "Web.Perl"; // Perl
public const string WEB_PYTHON = "Web.Python"; // Python
public const string WEB_VIRTUALDIRS = "Web.VirtualDirs"; // Virtual Directories
public const string WEB_FRONTPAGE = "Web.FrontPage"; // FrontPage
public const string WEB_SECURITY = "Web.Security"; // Custom Security Settings
public const string WEB_DEFAULTDOCS = "Web.DefaultDocs"; // Custom Default Documents
public const string WEB_APPPOOLS = "Web.AppPools"; // Dedicated Application Pools
public const string WEB_APPPOOLSRESTART = "Web.AppPoolsRestart"; // Application Pools Restart
public const string WEB_HEADERS = "Web.Headers"; // Custom Headers
public const string WEB_ERRORS = "Web.Errors"; // Custom Errors
public const string WEB_MIME = "Web.Mime"; // Custom MIME Types
public const string WEB_CGIBIN = "Web.CgiBin"; // CGI-BIN Folder
public const string WEB_SECUREDFOLDERS = "Web.SecuredFolders"; // Secured Folders
public const string WEB_HTACCESS = "Web.Htaccess"; // Htaccess
public const string WEB_SHAREDSSL = "Web.SharedSSL"; // Shared SSL Folders
public const string WEB_REDIRECTIONS = "Web.Redirections"; // Web Sites Redirection
public const string WEB_HOMEFOLDERS = "Web.HomeFolders"; // Changing Sites Root Folders
public const string WEB_IP_ADDRESSES = "Web.IPAddresses"; // Dedicated IP Addresses
public const string WEB_COLDFUSION = "Web.ColdFusion"; // ColdFusion
public const string WEB_CFVIRTUALDIRS = "Web.CFVirtualDirectories"; //ColdFusion Virtual Directories
public const string WEB_REMOTEMANAGEMENT = "Web.RemoteManagement"; //IIS 7 Remote Management
public const string WEB_SSL = "Web.SSL"; //SSL
public const string WEB_ALLOWIPADDRESSMODESWITCH = "Web.AllowIPAddressModeSwitch"; //Allow to switch IP Address Mode
public const string WEB_ENABLEHOSTNAMESUPPORT = "Web.EnableHostNameSupport"; //Enable to specify hostnames upon site creation
public const string FTP_ACCOUNTS = "FTP.Accounts"; // FTP Accounts
public const string MAIL_ACCOUNTS = "Mail.Accounts"; // Mail Accounts
public const string MAIL_FORWARDINGS = "Mail.Forwardings"; // Mail Forwardings
public const string MAIL_LISTS = "Mail.Lists"; // Mail Lists
public const string MAIL_GROUPS = "Mail.Groups"; // Mail Groups
public const string MAIL_MAXBOXSIZE = "Mail.MaxBoxSize"; // Max Mailbox Size
public const string MAIL_MAXGROUPMEMBERS = "Mail.MaxGroupMembers"; // Max Group Recipients
public const string MAIL_MAXLISTMEMBERS = "Mail.MaxListMembers"; // Max List Recipients
public const string MAIL_DISABLESIZEEDIT = "Mail.DisableSizeEdit"; // Disable Mailbox Size Edit
public const string EXCHANGE2007_ORGANIZATIONS = "Exchange2007.Organizations"; // Exchange 2007 Organizations
public const string EXCHANGE2007_DISKSPACE = "Exchange2007.DiskSpace"; // Organization Disk Space, MB
public const string EXCHANGE2007_MAILBOXES = "Exchange2007.Mailboxes"; // Mailboxes per Organization
public const string EXCHANGE2007_CONTACTS = "Exchange2007.Contacts"; // Contacts per Organization
public const string EXCHANGE2007_DISTRIBUTIONLISTS = "Exchange2007.DistributionLists"; // Distribution Lists per Organization
public const string EXCHANGE2007_PUBLICFOLDERS = "Exchange2007.PublicFolders"; // Public Folders per Organization
public const string EXCHANGE2007_DOMAINS = "Exchange2007.Domains"; // Domains per Organization
public const string EXCHANGE2007_POP3ALLOWED = "Exchange2007.POP3Allowed"; // POP3 Access
public const string EXCHANGE2007_IMAPALLOWED = "Exchange2007.IMAPAllowed"; // IMAP Access
public const string EXCHANGE2007_OWAALLOWED = "Exchange2007.OWAAllowed"; // OWA/HTTP Access
public const string EXCHANGE2007_MAPIALLOWED = "Exchange2007.MAPIAllowed"; // MAPI Access
public const string EXCHANGE2007_ACTIVESYNCALLOWED = "Exchange2007.ActiveSyncAllowed"; // ActiveSync Access
public const string EXCHANGE2007_MAILENABLEDPUBLICFOLDERS = "Exchange2007.MailEnabledPublicFolders"; // Mail Enabled Public Folders Allowed
public const string EXCHANGE2007_POP3ENABLED = "Exchange2007.POP3Enabled"; // POP3 Enabled by default
public const string EXCHANGE2007_IMAPENABLED = "Exchange2007.IMAPEnabled"; // IMAP Enabled by default
public const string EXCHANGE2007_OWAENABLED = "Exchange2007.OWAEnabled"; // OWA Enabled by default
public const string EXCHANGE2007_MAPIENABLED = "Exchange2007.MAPIEnabled"; // MAPI Enabled by default
public const string EXCHANGE2007_ACTIVESYNCENABLED = "Exchange2007.ActiveSyncEnabled"; // ActiveSync Enabled by default
public const string EXCHANGE2007_KEEPDELETEDITEMSDAYS = "Exchange2007.KeepDeletedItemsDays"; // Keep deleted items
public const string EXCHANGE2007_MAXRECIPIENTS = "Exchange2007.MaxRecipients"; // Max Recipients
public const string EXCHANGE2007_MAXSENDMESSAGESIZEKB = "Exchange2007.MaxSendMessageSizeKB"; // Max Send Message Size
public const string EXCHANGE2007_MAXRECEIVEMESSAGESIZEKB = "Exchange2007.MaxReceiveMessageSizeKB"; // Max Receive Message Size
public const string EXCHANGE2007_ISCONSUMER = "Exchange2007.IsConsumer"; // Is Consumer Organization
public const string EXCHANGE2007_ENABLEDPLANSEDITING = "Exchange2007.EnablePlansEditing"; // Enabled plans editing
public const string EXCHANGE2007_ALLOWLITIGATIONHOLD = "Exchange2007.AllowLitigationHold";
public const string EXCHANGE2007_RECOVERABLEITEMSSPACE = "Exchange2007.RecoverableItemsSpace";
public const string EXCHANGE2007_DISCLAIMERSALLOWED = "Exchange2007.DisclaimersAllowed";
public const string EXCHANGE2013_ALLOWRETENTIONPOLICY = "Exchange2013.AllowRetentionPolicy"; // RetentionPolicy
public const string EXCHANGE2013_ARCHIVINGSTORAGE = "Exchange2013.ArchivingStorage"; // Archiving
public const string EXCHANGE2013_ARCHIVINGMAILBOXES = "Exchange2013.ArchivingMailboxes";
public const string EXCHANGE2013_SHAREDMAILBOXES = "Exchange2013.SharedMailboxes"; // Shared and resource mailboxes
public const string EXCHANGE2013_RESOURCEMAILBOXES = "Exchange2013.ResourceMailboxes";
public const string MSSQL2000_DATABASES = "MsSQL2000.Databases"; // Databases
public const string MSSQL2000_USERS = "MsSQL2000.Users"; // Users
public const string MSSQL2000_MAXDATABASESIZE = "MsSQL2000.MaxDatabaseSize"; // Max Database Size
public const string MSSQL2000_BACKUP = "MsSQL2000.Backup"; // Database Backups
public const string MSSQL2000_RESTORE = "MsSQL2000.Restore"; // Database Restores
public const string MSSQL2000_TRUNCATE = "MsSQL2000.Truncate"; // Database Truncate
public const string MSSQL2005_DATABASES = "MsSQL2005.Databases"; // Databases
public const string MSSQL2005_USERS = "MsSQL2005.Users"; // Users
public const string MSSQL2005_MAXDATABASESIZE = "MsSQL2005.MaxDatabaseSize"; // Max Database Size
public const string MSSQL2005_BACKUP = "MsSQL2005.Backup"; // Database Backups
public const string MSSQL2005_RESTORE = "MsSQL2005.Restore"; // Database Restores
public const string MSSQL2005_TRUNCATE = "MsSQL2005.Truncate"; // Database Truncate
public const string MYSQL4_DATABASES = "MySQL4.Databases"; // Databases
public const string MYSQL4_USERS = "MySQL4.Users"; // Users
public const string MYSQL4_BACKUP = "MySQL4.Backup"; // Database Backups
public const string MYSQL4_RESTORE = "MySQL4.Restore"; // Database Restores
public const string MYSQL4_MAXDATABASESIZE = "MySQL4.MaxDatabaseSize"; // Max Database Size
public const string MYSQL5_DATABASES = "MySQL5.Databases"; // Databases
public const string MYSQL5_USERS = "MySQL5.Users"; // Users
public const string MYSQL5_BACKUP = "MySQL5.Backup"; // Database Backups
public const string MYSQL5_RESTORE = "MySQL5.Restore"; // Database Restores
public const string MYSQL5_MAXDATABASESIZE = "MySQL5.MaxDatabaseSize"; // Max Database Size
public const string SHAREPOINT_USERS = "SharePoint.Users"; // SharePoint Users
public const string SHAREPOINT_GROUPS = "SharePoint.Groups"; // SharePoint Groups
public const string SHAREPOINT_SITES = "SharePoint.Sites"; // SharePoint Sites
public const string HOSTED_SHAREPOINT_SITES = "HostedSharePoint.Sites"; // Hosted SharePoint Sites
public const string HOSTED_SHAREPOINT_STORAGE_SIZE = "HostedSharePoint.MaxStorage"; // Hosted SharePoint storage size;
public const string HOSTED_SHAREPOINT_USESHAREDSSL = "HostedSharePoint.UseSharedSSL"; // Hosted SharePoint Use Shared SSL Root
public const string HOSTED_SHAREPOINT_ENTERPRISE_SITES = "HostedSharePointEnterprise.Sites"; // Hosted SharePoint Sites
public const string HOSTED_SHAREPOINT_ENTERPRISE_STORAGE_SIZE = "HostedSharePointEnterprise.MaxStorage"; // Hosted SharePoint storage size;
public const string HOSTED_SHAREPOINT_ENTERPRISE_USESHAREDSSL = "HostedSharePointEnterprise.UseSharedSSL"; // Hosted SharePoint Use Shared SSL Root
public const string DNS_EDITOR = "DNS.Editor"; // DNS Editor
public const string DNS_ZONES = "DNS.Zones"; // DNS Editor
public const string DNS_PRIMARY_ZONES = "DNS.PrimaryZones"; // DNS Editor
public const string DNS_SECONDARY_ZONES = "DNS.SecondaryZones"; // DNS Editor
public const string STATS_SITES = "Stats.Sites"; // Statistics Sites
public const string ORGANIZATIONS = "HostedSolution.Organizations";
public const string ORGANIZATION_USERS = "HostedSolution.Users";
public const string ORGANIZATION_DELETED_USERS = "HostedSolution.DeletedUsers";
public const string ORGANIZATION_DELETED_USERS_BACKUP_STORAGE_SPACE = "HostedSolution.DeletedUsersBackupStorageSpace";
public const string ORGANIZATION_DOMAINS = "HostedSolution.Domains";
public const string ORGANIZATION_ALLOWCHANGEUPN = "HostedSolution.AllowChangeUPN";
public const string ORGANIZATION_SECURITYGROUPS = "HostedSolution.SecurityGroups";
public const string CRM_USERS = "HostedCRM.Users";
public const string CRM_ORGANIZATION = "HostedCRM.Organization";
public const string CRM_LIMITEDUSERS = "HostedCRM.LimitedUsers";
public const string CRM_ESSUSERS = "HostedCRM.ESSUsers";
public const string CRM_MAXDATABASESIZE = "HostedCRM.MaxDatabaseSize";
public const string CRM2013_ORGANIZATION = "HostedCRM2013.Organization";
public const string CRM2013_MAXDATABASESIZE = "HostedCRM2013.MaxDatabaseSize";
public const string CRM2013_ESSENTIALUSERS = "HostedCRM2013.EssentialUsers";
public const string CRM2013_BASICUSERS = "HostedCRM2013.BasicUsers";
public const string CRM2013_PROFESSIONALUSERS = "HostedCRM2013.ProfessionalUsers";
public const string VPS_SERVERS_NUMBER = "VPS.ServersNumber"; // Number of VPS
public const string VPS_MANAGING_ALLOWED = "VPS.ManagingAllowed"; // Allow user to create VPS
public const string VPS_CPU_NUMBER = "VPS.CpuNumber"; // Number of CPU cores
public const string VPS_BOOT_CD_ALLOWED = "VPS.BootCdAllowed"; // Boot from CD allowed
public const string VPS_BOOT_CD_ENABLED = "VPS.BootCdEnabled"; // Boot from CD
public const string VPS_RAM = "VPS.Ram"; // RAM size, MB
public const string VPS_HDD = "VPS.Hdd"; // Hard Drive size, GB
public const string VPS_DVD_ENABLED = "VPS.DvdEnabled"; // DVD drive
public const string VPS_EXTERNAL_NETWORK_ENABLED = "VPS.ExternalNetworkEnabled"; // External Network
public const string VPS_EXTERNAL_IP_ADDRESSES_NUMBER = "VPS.ExternalIPAddressesNumber"; // Number of External IP addresses
public const string VPS_PRIVATE_NETWORK_ENABLED = "VPS.PrivateNetworkEnabled"; // Private Network
public const string VPS_PRIVATE_IP_ADDRESSES_NUMBER = "VPS.PrivateIPAddressesNumber"; // Number of Private IP addresses per VPS
public const string VPS_SNAPSHOTS_NUMBER = "VPS.SnapshotsNumber"; // Number of Snaphots
public const string VPS_START_SHUTDOWN_ALLOWED = "VPS.StartShutdownAllowed"; // Allow user to Start, Turn off and Shutdown VPS
public const string VPS_PAUSE_RESUME_ALLOWED = "VPS.PauseResumeAllowed"; // Allow user to Pause, Resume VPS
public const string VPS_REBOOT_ALLOWED = "VPS.RebootAllowed"; // Allow user to Reboot VPS
public const string VPS_RESET_ALOWED = "VPS.ResetAlowed"; // Allow user to Reset VPS
public const string VPS_REINSTALL_ALLOWED = "VPS.ReinstallAllowed"; // Allow user to Re-install VPS
public const string VPS_BANDWIDTH = "VPS.Bandwidth"; // Monthly bandwidth, GB
public const string VPS2012_SERVERS_NUMBER = "VPS2012.ServersNumber"; // Number of VPS
public const string VPS2012_MANAGING_ALLOWED = "VPS2012.ManagingAllowed"; // Allow user to create VPS
public const string VPS2012_CPU_NUMBER = "VPS2012.CpuNumber"; // Number of CPU cores
public const string VPS2012_BOOT_CD_ALLOWED = "VPS2012.BootCdAllowed"; // Boot from CD allowed
public const string VPS2012_BOOT_CD_ENABLED = "VPS2012.BootCdEnabled"; // Boot from CD
public const string VPS2012_RAM = "VPS2012.Ram"; // RAM size, MB
public const string VPS2012_HDD = "VPS2012.Hdd"; // Hard Drive size, GB
public const string VPS2012_DVD_ENABLED = "VPS2012.DvdEnabled"; // DVD drive
public const string VPS2012_EXTERNAL_NETWORK_ENABLED = "VPS2012.ExternalNetworkEnabled"; // External Network
public const string VPS2012_EXTERNAL_IP_ADDRESSES_NUMBER = "VPS2012.ExternalIPAddressesNumber"; // Number of External IP addresses
public const string VPS2012_PRIVATE_NETWORK_ENABLED = "VPS2012.PrivateNetworkEnabled"; // Private Network
public const string VPS2012_PRIVATE_IP_ADDRESSES_NUMBER = "VPS2012.PrivateIPAddressesNumber"; // Number of Private IP addresses per VPS
public const string VPS2012_SNAPSHOTS_NUMBER = "VPS2012.SnapshotsNumber"; // Number of Snaphots
public const string VPS2012_START_SHUTDOWN_ALLOWED = "VPS2012.StartShutdownAllowed"; // Allow user to Start, Turn off and Shutdown VPS
public const string VPS2012_PAUSE_RESUME_ALLOWED = "VPS2012.PauseResumeAllowed"; // Allow user to Pause, Resume VPS
public const string VPS2012_REBOOT_ALLOWED = "VPS2012.RebootAllowed"; // Allow user to Reboot VPS
public const string VPS2012_RESET_ALOWED = "VPS2012.ResetAlowed"; // Allow user to Reset VPS
public const string VPS2012_REINSTALL_ALLOWED = "VPS2012.ReinstallAllowed"; // Allow user to Re-install VPS
public const string VPS2012_BANDWIDTH = "VPS2012.Bandwidth"; // Monthly bandwidth, GB
public const string VPS2012_REPLICATION_ENABLED = "VPS2012.ReplicationEnabled";
public const string VPSForPC_SERVERS_NUMBER = "VPSForPC.ServersNumber"; // Number of VPS
public const string VPSForPC_MANAGING_ALLOWED = "VPSForPC.ManagingAllowed"; // Allow user to create VPS
public const string VPSForPC_CPU_NUMBER = "VPSForPC.CpuNumber"; // Number of CPU cores
public const string VPSForPC_BOOT_CD_ALLOWED = "VPSForPC.BootCdAllowed"; // Boot from CD allowed
public const string VPSForPC_BOOT_CD_ENABLED = "VPSForPC.BootCdEnabled"; // Boot from CD
public const string VPSForPC_RAM = "VPSForPC.Ram"; // RAM size, MB
public const string VPSForPC_HDD = "VPSForPC.Hdd"; // Hard Drive size, GB
public const string VPSForPC_DVD_ENABLED = "VPSForPC.DvdEnabled"; // DVD drive
public const string VPSForPC_EXTERNAL_NETWORK_ENABLED = "VPSForPC.ExternalNetworkEnabled"; // External Network
public const string VPSForPC_EXTERNAL_IP_ADDRESSES_NUMBER = "VPSForPC.ExternalIPAddressesNumber"; // Number of External IP addresses
public const string VPSForPC_PRIVATE_NETWORK_ENABLED = "VPSForPC.PrivateNetworkEnabled"; // Private Network
public const string VPSForPC_PRIVATE_IP_ADDRESSES_NUMBER = "VPSForPC.PrivateIPAddressesNumber"; // Number of Private IP addresses per VPS
public const string VPSForPC_SNAPSHOTS_NUMBER = "VPSForPC.SnapshotsNumber"; // Number of Snaphots
public const string VPSForPC_START_SHUTDOWN_ALLOWED = "VPSForPC.StartShutdownAllowed"; // Allow user to Start, Turn off and Shutdown VPS
public const string VPSForPC_PAUSE_RESUME_ALLOWED = "VPSForPC.PauseResumeAllowed"; // Allow user to Pause, Resume VPS
public const string VPSForPC_REBOOT_ALLOWED = "VPSForPC.RebootAllowed"; // Allow user to Reboot VPS
public const string VPSForPC_RESET_ALOWED = "VPSForPC.ResetAlowed"; // Allow user to Reset VPS
public const string VPSForPC_REINSTALL_ALLOWED = "VPSForPC.ReinstallAllowed"; // Allow user to Re-install VPS
public const string VPSForPC_BANDWIDTH = "VPSForPC.Bandwidth"; // Monthly bandwidth, GB
public const string BLACKBERRY_USERS = "BlackBerry.Users";
public const string OCS_USERS = "OCS.Users";
public const string OCS_Federation = "OCS.Federation";
public const string OCS_FederationByDefault = "OCS.FederationByDefault";
public const string OCS_PublicIMConnectivity = "OCS.PublicIMConnectivity";
public const string OCS_PublicIMConnectivityByDefault = "OCS.PublicIMConnectivityByDefault";
public const string OCS_ArchiveIMConversation = "OCS.ArchiveIMConversation";
public const string OCS_ArchiveIMConversationByDefault = "OCS.ArchiveIMConvervationByDefault";
public const string OCS_ArchiveFederatedIMConversationByDefault = "OCS.ArchiveFederatedIMConversationByDefault";
public const string OCS_ArchiveFederatedIMConversation = "OCS.ArchiveFederatedIMConversation";
public const string OCS_PresenceAllowed = "OCS.PresenceAllowed";
public const string OCS_PresenceAllowedByDefault = "OCS.PresenceAllowedByDefault";
public const string LYNC_USERS = "Lync.Users";
public const string LYNC_FEDERATION = "Lync.Federation";
public const string LYNC_CONFERENCING = "Lync.Conferencing";
public const string LYNC_MAXPARTICIPANTS = "Lync.MaxParticipants";
public const string LYNC_ALLOWVIDEO = "Lync.AllowVideo";
public const string LYNC_ENTERPRISEVOICE = "Lync.EnterpriseVoice";
public const string LYNC_EVUSERS = "Lync.EVUsers";
public const string LYNC_EVNATIONAL = "Lync.EVNational";
public const string LYNC_EVMOBILE = "Lync.EVMobile";
public const string LYNC_EVINTERNATIONAL = "Lync.EVInternational";
public const string LYNC_ENABLEDPLANSEDITING = "Lync.EnablePlansEditing";
public const string LYNC_PHONE = "Lync.PhoneNumbers";
public const string HELICON_ZOO = "HeliconZoo.*";
public const string ENTERPRISESTORAGE_DISKSTORAGESPACE = "EnterpriseStorage.DiskStorageSpace";
public const string ENTERPRISESTORAGE_FOLDERS = "EnterpriseStorage.Folders";
public const string ENTERPRICESTORAGE_DRIVEMAPS = "EnterpriseStorage.DriveMaps";
public const string SERVICE_LEVELS = "ServiceLevel.";
public const string RDS_USERS = "RDS.Users";
public const string RDS_SERVERS = "RDS.Servers";
public const string RDS_COLLECTIONS = "RDS.Collections";
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CocosSharp;
using tests.Clipping;
using tests.FontTest;
using tests.Extensions;
using Box2D.TestBed;
namespace tests
{
public class TestController : CCLayer
{
const int MENU_ITEM_Z_ORDER = 10000;
static int LINE_SPACE = 70;
static CCPoint curPos = CCPoint.Zero;
int currentItemIndex = 0;
CCPoint homePosition;
CCPoint lastPosition;
CCPoint beginTouchPos;
CCSprite menuIndicator;
CCLabelTtf versionLabel;
CCMenu testListMenu;
List<CCMenuItem> testListMenuItems = new List<CCMenuItem>();
CCMenu closeMenu;
CCMenuItem closeMenuItem;
#region Constructors
public TestController()
{
// Add close menu
closeMenuItem = new CCMenuItemImage(TestResource.s_pPathClose, TestResource.s_pPathClose, CloseCallback);
closeMenu = new CCMenu(closeMenuItem);
CCMenuItemFont.FontName = "MarkerFelt";
CCMenuItemFont.FontSize = 22;
#if !PSM && !WINDOWS_PHONE
#if NETFX_CORE
versionLabel = new CCLabelTtf("v" + this.GetType().GetAssemblyName().Version.ToString(), "arial", 30);
#else
versionLabel = new CCLabelTtf("v" + this.GetType().Assembly.GetName().Version.ToString(), "arial", 30);
#endif
AddChild(versionLabel, 20000);
#endif
// Add test list menu
testListMenu = new CCMenu();
for (int i = 0; i < (int)(TestCases.TESTS_COUNT); ++i)
{
CCLabelTtf label = new CCLabelTtf(Tests.g_aTestNames[i], "arial", 50);
CCMenuItem menuItem = new CCMenuItemLabelTTF(label, MenuCallback);
testListMenu.AddChild(menuItem, i + MENU_ITEM_Z_ORDER);
testListMenuItems.Add(menuItem);
}
#if XBOX || OUYA
CCSprite sprite = new CCSprite("Images/aButton");
AddChild(sprite, 10001);
menuIndicator = sprite;
#endif
AddChild(testListMenu);
AddChild(closeMenu, 1);
}
#endregion Constructors
#region Setup content
public override void OnEnter()
{
base.OnEnter();
CCRect visibleBounds = Layer.VisibleBoundsWorldspace;
// Laying out content based on window size
closeMenu.Position = CCPoint.Zero;
closeMenuItem.Position = new CCPoint(visibleBounds.Size.Width - 40, visibleBounds.Size.Height - 40);
#if !PSM && !WINDOWS_PHONE
versionLabel.HorizontalAlignment = CCTextAlignment.Left;
versionLabel.Position = new CCPoint (10.0f, visibleBounds.Size.Height - 40);
#endif
testListMenu.ContentSize = new CCSize(visibleBounds.Size.Width, ((int)TestCases.TESTS_COUNT + 1) * LINE_SPACE);
int i = 0;
foreach (CCMenuItem testItem in testListMenuItems)
{
testItem.Position = new CCPoint(visibleBounds.Size.Width /2.0f, (visibleBounds.Size.Height - (i + 1) * LINE_SPACE));
i++;
}
#if XBOX || OUYA
// Center the menu on the first item so that it is
// in the center of the screen
homePosition = new CCPoint(0f, visibleBounds.Size.Height / 2f + LINE_SPACE / 2f);
lastPosition = new CCPoint(0f, homePosition.Y - (testListMenuItems.Count - 1) * LINE_SPACE);
#else
homePosition = curPos;
#endif
testListMenu.Position = homePosition;
// Add listeners
#if !XBOX && !OUYA
var touchListener = new CCEventListenerTouchOneByOne ();
touchListener.IsSwallowTouches = true;
touchListener.OnTouchBegan = OnTouchBegan;
touchListener.OnTouchMoved = OnTouchMoved;
AddEventListener(touchListener);
var mouseListener = new CCEventListenerMouse ();
mouseListener.OnMouseScroll = OnMouseScroll;
AddEventListener(mouseListener);
#endif
#if WINDOWS || WINDOWSGL || MACOS
EnableGamePad();
#endif
// set the first one to have the selection highlight
currentItemIndex = 0;
//SelectMenuItem();
}
#endregion Setup content
#region Menu item handling
void SelectMenuItem()
{
if (currentItemIndex < testListMenuItems.Count)
{
testListMenuItems [currentItemIndex].Selected = true;
if (menuIndicator != null) {
menuIndicator.Position = new CCPoint (
testListMenu.Position.X + testListMenuItems [currentItemIndex].Position.X
- testListMenuItems[currentItemIndex].ContentSize.Width / 2f - menuIndicator.ContentSize.Width / 2f - 5f,
testListMenu.Position.Y + testListMenuItems [currentItemIndex].Position.Y
);
}
}
}
void NextMenuItem()
{
testListMenuItems[currentItemIndex].Selected = false;
currentItemIndex = (currentItemIndex + 1) % testListMenuItems.Count;
CCSize winSize = Layer.VisibleBoundsWorldspace.Size;
testListMenu.Position = (new CCPoint(0, homePosition.Y + currentItemIndex * LINE_SPACE));
curPos = testListMenu.Position;
SelectMenuItem();
}
void PreviousMenuItem()
{
testListMenuItems[currentItemIndex].Selected = false;
currentItemIndex--;
if(currentItemIndex < 0) {
currentItemIndex = testListMenuItems.Count - 1;
}
CCSize winSize = Layer.VisibleBoundsWorldspace.Size;
testListMenu.Position = (new CCPoint(0, homePosition.Y + currentItemIndex * LINE_SPACE));
curPos = testListMenu.Position;
SelectMenuItem();
}
#endregion Menu item handling
void MenuCallback(object sender)
{
// get the userdata, it's the index of the menu item clicked
CCMenuItem menuItem = (CCMenuItem)sender;
var nIdx = menuItem.LocalZOrder - MENU_ITEM_Z_ORDER;
// create the test scene and run it
TestScene scene = CreateTestScene(nIdx);
if (scene != null)
{
scene.runThisTest();
}
}
void CloseCallback(object sender)
{
Application.ExitGame();
}
void EnableGamePad()
{
var AButtonWasPressed = false;
var gamePadListener = new CCEventListenerGamePad ();
gamePadListener.OnButtonStatus = (buttonStatus) =>
{
if (buttonStatus.A == CCGamePadButtonStatus.Pressed)
{
AButtonWasPressed = true;
}
else if (buttonStatus.A == CCGamePadButtonStatus.Released && AButtonWasPressed)
{
// Select the menu
testListMenuItems[currentItemIndex].Activate();
testListMenuItems[currentItemIndex].Selected = false;
}
};
long firstTicks = 0;
bool isDownPressed = false;
bool isUpPressed = false;
gamePadListener.OnDPadStatus = (dpadStatus) =>
{
// Down and Up only
if (dpadStatus.Down == CCGamePadButtonStatus.Pressed)
{
if (firstTicks == 0L)
{
firstTicks = DateTime.Now.Ticks;
isDownPressed = true;
}
}
else if (dpadStatus.Down == CCGamePadButtonStatus.Released && firstTicks > 0L && isDownPressed)
{
firstTicks = 0L;
NextMenuItem ();
isDownPressed = false;
}
if (dpadStatus.Up == CCGamePadButtonStatus.Pressed)
{
if (firstTicks == 0L) {
firstTicks = DateTime.Now.Ticks;
isUpPressed = true;
}
}
else if (dpadStatus.Up == CCGamePadButtonStatus.Released && firstTicks > 0L && isUpPressed)
{
firstTicks = 0L;
PreviousMenuItem ();
isUpPressed = false;
}
};
gamePadListener.OnConnectionStatus = (connectionStatus) =>
{
CCLog.Log("Player {0} is connected {1}", connectionStatus.Player, connectionStatus.IsConnected);
};
AddEventListener(gamePadListener);
}
#region Event handling
bool OnTouchBegan(CCTouch touch, CCEvent touchEvent)
{
beginTouchPos = touch.LocationOnScreen;
return true;
}
void OnTouchMoved(CCTouch touch, CCEvent touchEvent)
{
var touchLocation = touch.LocationOnScreen;
float nMoveY = touchLocation.Y - beginTouchPos.Y;
curPos = testListMenu.Position;
CCPoint nextPos = new CCPoint(curPos.X, curPos.Y - nMoveY);
CCRect visibleBounds = Layer.VisibleBoundsWorldspace;
if (nextPos.Y < 0.0f)
{
testListMenu.Position = new CCPoint(0, 0);
return;
}
if (nextPos.Y > (((int)TestCases.TESTS_COUNT + 1) * LINE_SPACE - visibleBounds.Size.Height))
{
testListMenu.Position = (new CCPoint(0, (((int)TestCases.TESTS_COUNT + 1) * LINE_SPACE - visibleBounds.Size.Height)));
return;
}
testListMenu.Position = nextPos;
beginTouchPos = touchLocation;
curPos = nextPos;
}
void OnMouseScroll(CCEventMouse mouseEvent)
{
// Due to a bug in MonoGame the menu will jump around on Mac when hitting the top element
// https://github.com/mono/MonoGame/issues/2276
var delta = mouseEvent.ScrollY;
CCRect visibleBounds = Layer.VisibleBoundsWorldspace;
curPos = testListMenu.Position;
var nextPos = curPos;
nextPos.Y -= (delta) / LINE_SPACE;
if (nextPos.Y < 0)
{
testListMenu.Position = CCPoint.Zero;
return;
}
if (nextPos.Y > (((int)TestCases.TESTS_COUNT + 1) * LINE_SPACE - visibleBounds.Size.Height))
{
testListMenu.Position = (new CCPoint(0, (((int)TestCases.TESTS_COUNT + 1) * LINE_SPACE - visibleBounds.Size.Height)));
return;
}
testListMenu.Position = nextPos;
curPos = nextPos;
}
#endregion Event handling
public static TestScene CreateTestScene(int index)
{
//Application.PurgeAllCachedData();
TestScene scene = null;
switch(index)
{
case (int)TestCases.TEST_ACTIONS:
scene = new ActionsTestScene(); break;
case (int)TestCases.TEST_TRANSITIONS:
scene = new TransitionsTestScene(); break;
case (int)TestCases.TEST_PROGRESS_ACTIONS:
scene = new ProgressActionsTestScene(); break;
case (int)TestCases.TEST_EFFECTS:
scene = new EffectTestScene(); break;
case (int)TestCases.TEST_CLICK_AND_MOVE:
scene = new ClickAndMoveTest(); break;
case (int)TestCases.TEST_ROTATE_WORLD:
scene = new RotateWorldTestScene(); break;
case (int)TestCases.TEST_PARTICLE:
scene = new ParticleTestScene(); break;
case (int)TestCases.TEST_EASE_ACTIONS:
scene = new EaseActionsTestScene(); break;
case (int)TestCases.TEST_MOTION_STREAK:
scene = new MotionStreakTestScene(); break;
case (int)TestCases.TEST_DRAW_PRIMITIVES:
scene = new DrawPrimitivesTestScene(); break;
case (int)TestCases.TEST_COCOSNODE:
scene = new CocosNodeTestScene(); break;
case (int)TestCases.TEST_TOUCHES:
scene = new PongScene(); break;
case (int)TestCases.TEST_MENU:
scene = new MenuTestScene(); break;
case (int)TestCases.TEST_ACTION_MANAGER:
scene = new ActionManagerTestScene(); break;
case (int)TestCases.TEST_LAYER:
scene = new LayerTestScene(); break;
case (int)TestCases.TEST_SCENE:
scene = new SceneTestScene(); break;
case (int)TestCases.TEST_PARALLAX:
scene = new ParallaxTestScene(); break;
case (int)TestCases.TEST_TILE_MAP:
scene = new TileMapTestScene(); break;
case (int)TestCases.TEST_INTERVAL:
scene = new IntervalTestScene(); break;
case (int)TestCases.TEST_LABEL:
scene = new AtlasTestScene(); break;
case (int)TestCases.TEST_TEXT_INPUT:
scene = new TextInputTestScene(); break;
case (int)TestCases.TEST_SPRITE:
scene = new SpriteTestScene(); break;
case (int)TestCases.TEST_SCHEDULER:
scene = new SchedulerTestScene(); break;
case (int)TestCases.TEST_RENDERTEXTURE:
scene = new RenderTextureScene(); break;
case (int)TestCases.TEST_TEXTURE2D:
scene = new TextureTestScene(); break;
case (int)TestCases.TEST_BOX2D:
scene = new Box2DTestScene(); break;
case (int)TestCases.TEST_BOX2DBED2:
scene = new Box2D.TestBed.Box2dTestBedScene(); break;
case (int)TestCases.TEST_EFFECT_ADVANCE:
scene = new EffectAdvanceScene(); break;
case (int)TestCases.TEST_ACCELEROMRTER:
scene = new AccelerometerTestScene(); break;
case (int)TestCases.TEST_COCOSDENSHION:
scene = new CocosDenshionTestScene(); break;
case (int)TestCases.TEST_PERFORMANCE:
scene = new PerformanceTestScene(); break;
case (int)TestCases.TEST_ZWOPTEX:
scene = new ZwoptexTestScene(); break;
case (int)TestCases.TEST_FONTS:
scene = new FontTestScene(); break;
#if IPHONE || IOS || MACOS || WINDOWSGL || WINDOWS || (ANDROID && !OUYA) || NETFX_CORE
case (int)TestCases.TEST_SYSTEM_FONTS:
scene = new SystemFontTestScene(); break;
#endif
case (int)TestCases.TEST_CLIPPINGNODE:
scene = new ClippingNodeTestScene();
break;
case (int)TestCases.TEST_EXTENSIONS:
scene = new ExtensionsTestScene();
break;
case (int)TestCases.TEST_ORIENTATION:
scene = new OrientationTestScene();
break;
case(int)TestCases.TEST_MULTITOUCH:
scene = new MultiTouchTestScene();
break;
case(int)TestCases.TEST_EVENTDISPATCHER:
scene = new EventDispatcherTestScene();
break;
default:
break;
}
return scene;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Agent.Sdk;
using Agent.Sdk.Knob;
using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines;
using Microsoft.VisualStudio.Services.Agent.Util;
namespace Agent.Plugins.Repository
{
public sealed class TfsVCSourceProvider : ISourceProvider
{
public async Task GetSourceAsync(
AgentTaskPluginExecutionContext executionContext,
Pipelines.RepositoryResource repository,
CancellationToken cancellationToken)
{
// Validate args.
ArgUtil.NotNull(executionContext, nameof(executionContext));
ArgUtil.NotNull(repository, nameof(repository));
// Validate .NET Framework 4.6 or higher is installed.
if (PlatformUtil.RunningOnWindows && !NetFrameworkUtil.Test(new Version(4, 6), executionContext))
{
throw new Exception(StringUtil.Loc("MinimumNetFramework46"));
}
// determine if we've been asked to suppress some checkout step output
bool reducedOutput = AgentKnobs.QuietCheckout.GetValue(executionContext).AsBoolean();
if (reducedOutput)
{
executionContext.Output(StringUtil.Loc("QuietCheckoutModeRequested"));
executionContext.SetTaskVariable(AgentKnobs.QuietCheckoutRuntimeVarName, Boolean.TrueString);
}
// Create the tf command manager.
ITfsVCCliManager tf;
if (PlatformUtil.RunningOnWindows)
{
tf = new TFCliManager();
}
else
{
tf = new TeeCliManager();
}
tf.CancellationToken = cancellationToken;
tf.Repository = repository;
tf.ExecutionContext = executionContext;
if (repository.Endpoint != null)
{
// the endpoint should either be the SystemVssConnection (id = guild.empty, name = SystemVssConnection)
// or a real service endpoint to external service which has a real id
var endpoint = executionContext.Endpoints.Single(
x => (repository.Endpoint.Id != Guid.Empty && x.Id == repository.Endpoint.Id) ||
(repository.Endpoint.Id == Guid.Empty && string.Equals(x.Name, repository.Endpoint.Name.ToString(), StringComparison.OrdinalIgnoreCase)));
ArgUtil.NotNull(endpoint, nameof(endpoint));
tf.Endpoint = endpoint;
}
// Setup proxy.
var agentProxy = executionContext.GetProxyConfiguration();
if (agentProxy != null && !string.IsNullOrEmpty(agentProxy.ProxyAddress) && !agentProxy.WebProxy.IsBypassed(repository.Url))
{
executionContext.Debug($"Configure '{tf.FilePath}' to work through proxy server '{agentProxy.ProxyAddress}'.");
tf.SetupProxy(agentProxy.ProxyAddress, agentProxy.ProxyUsername, agentProxy.ProxyPassword);
}
// Setup client certificate.
var agentCertManager = executionContext.GetCertConfiguration();
if (agentCertManager != null && agentCertManager.SkipServerCertificateValidation)
{
executionContext.Debug("TF does not support ignoring SSL certificate validation error.");
}
// prepare client cert, if the repository's endpoint url match the TFS/VSTS url
var systemConnection = executionContext.Endpoints.Single(x => string.Equals(x.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrEmpty(agentCertManager?.ClientCertificateFile) &&
Uri.Compare(repository.Url, systemConnection.Url, UriComponents.SchemeAndServer, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) == 0)
{
executionContext.Debug($"Configure '{tf.FilePath}' to work with client cert '{agentCertManager.ClientCertificateFile}'.");
tf.SetupClientCertificate(agentCertManager.ClientCertificateFile, agentCertManager.ClientCertificatePrivateKeyFile, agentCertManager.ClientCertificateArchiveFile, agentCertManager.ClientCertificatePassword);
}
// Add TF to the PATH.
string tfPath = tf.FilePath;
ArgUtil.File(tfPath, nameof(tfPath));
executionContext.Output(StringUtil.Loc("Prepending0WithDirectoryContaining1", PathUtil.PathVariable, Path.GetFileName(tfPath)));
executionContext.PrependPath(Path.GetDirectoryName(tfPath));
executionContext.Debug($"PATH: '{Environment.GetEnvironmentVariable("PATH")}'");
if (PlatformUtil.RunningOnWindows)
{
// Set TFVC_BUILDAGENT_POLICYPATH
string policyDllPath = Path.Combine(executionContext.Variables.GetValueOrDefault("Agent.HomeDirectory")?.Value, "externals", "tf", "Microsoft.TeamFoundation.VersionControl.Controls.dll");
ArgUtil.File(policyDllPath, nameof(policyDllPath));
const string policyPathEnvKey = "TFVC_BUILDAGENT_POLICYPATH";
executionContext.Output(StringUtil.Loc("SetEnvVar", policyPathEnvKey));
executionContext.SetVariable(policyPathEnvKey, policyDllPath);
}
// Check if the administrator accepted the license terms of the TEE EULA when configuring the agent.
if (tf.Features.HasFlag(TfsVCFeatures.Eula) && StringUtil.ConvertToBoolean(executionContext.Variables.GetValueOrDefault("Agent.AcceptTeeEula")?.Value))
{
// Check if the "tf eula -accept" command needs to be run for the current user.
bool skipEula = false;
try
{
skipEula = tf.TestEulaAccepted();
}
catch (Exception ex)
{
executionContext.Debug("Unexpected exception while testing whether the TEE EULA has been accepted for the current user.");
executionContext.Debug(ex.ToString());
}
if (!skipEula)
{
// Run the command "tf eula -accept".
try
{
await tf.EulaAsync();
}
catch (Exception ex)
{
executionContext.Debug(ex.ToString());
executionContext.Warning(ex.Message);
}
}
}
// Get the workspaces.
executionContext.Output(StringUtil.Loc("QueryingWorkspaceInfo"));
ITfsVCWorkspace[] tfWorkspaces = await tf.WorkspacesAsync();
// Determine the workspace name.
string buildDirectory = executionContext.Variables.GetValueOrDefault("agent.builddirectory")?.Value;
ArgUtil.NotNullOrEmpty(buildDirectory, nameof(buildDirectory));
string workspaceName = $"ws_{Path.GetFileName(buildDirectory)}_{executionContext.Variables.GetValueOrDefault("agent.id")?.Value}";
executionContext.SetVariable("build.repository.tfvc.workspace", workspaceName);
// Get the definition mappings.
var workspaceMappings = repository.Properties.Get<IList<Pipelines.WorkspaceMapping>>(Pipelines.RepositoryPropertyNames.Mappings);
DefinitionWorkspaceMapping[] definitionMappings = workspaceMappings.Select(x => new DefinitionWorkspaceMapping() { ServerPath = x.ServerPath, LocalPath = x.LocalPath, MappingType = x.Exclude ? DefinitionMappingType.Cloak : DefinitionMappingType.Map }).ToArray();
// Determine the sources directory.
string sourcesDirectory = repository.Properties.Get<string>(Pipelines.RepositoryPropertyNames.Path);
ArgUtil.NotNullOrEmpty(sourcesDirectory, nameof(sourcesDirectory));
// Attempt to re-use an existing workspace if the command manager supports scorch
// or if clean is not specified.
ITfsVCWorkspace existingTFWorkspace = null;
bool clean = StringUtil.ConvertToBoolean(executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Clean));
if (tf.Features.HasFlag(TfsVCFeatures.Scorch) || !clean)
{
existingTFWorkspace = WorkspaceUtil.MatchExactWorkspace(
executionContext: executionContext,
tfWorkspaces: tfWorkspaces,
name: workspaceName,
definitionMappings: definitionMappings,
sourcesDirectory: sourcesDirectory);
if (existingTFWorkspace != null)
{
if (tf.Features.HasFlag(TfsVCFeatures.GetFromUnmappedRoot))
{
// Undo pending changes.
ITfsVCStatus tfStatus = await tf.StatusAsync(localPath: sourcesDirectory);
if (tfStatus?.HasPendingChanges ?? false)
{
await tf.UndoAsync(localPath: sourcesDirectory);
// Cleanup remaining files/directories from pend adds.
tfStatus.AllAdds
.OrderByDescending(x => x.LocalItem) // Sort descending so nested items are deleted before their parent is deleted.
.ToList()
.ForEach(x =>
{
executionContext.Output(StringUtil.Loc("Deleting", x.LocalItem));
IOUtil.Delete(x.LocalItem, cancellationToken);
});
}
}
else
{
// Perform "undo" for each map.
foreach (DefinitionWorkspaceMapping definitionMapping in definitionMappings ?? new DefinitionWorkspaceMapping[0])
{
if (definitionMapping.MappingType == DefinitionMappingType.Map)
{
// Check the status.
string localPath = definitionMapping.GetRootedLocalPath(sourcesDirectory);
ITfsVCStatus tfStatus = await tf.StatusAsync(localPath: localPath);
if (tfStatus?.HasPendingChanges ?? false)
{
// Undo.
await tf.UndoAsync(localPath: localPath);
// Cleanup remaining files/directories from pend adds.
tfStatus.AllAdds
.OrderByDescending(x => x.LocalItem) // Sort descending so nested items are deleted before their parent is deleted.
.ToList()
.ForEach(x =>
{
executionContext.Output(StringUtil.Loc("Deleting", x.LocalItem));
IOUtil.Delete(x.LocalItem, cancellationToken);
});
}
}
}
}
// Scorch.
if (clean)
{
// Try to scorch.
try
{
await tf.ScorchAsync();
}
catch (ProcessExitCodeException ex)
{
// Scorch failed.
// Warn, drop the folder, and re-clone.
executionContext.Warning(ex.Message);
existingTFWorkspace = null;
}
}
}
}
// Create a new workspace.
if (existingTFWorkspace == null)
{
// Remove any conflicting workspaces.
await RemoveConflictingWorkspacesAsync(
tf: tf,
tfWorkspaces: tfWorkspaces,
name: workspaceName,
directory: sourcesDirectory);
// Remove any conflicting workspace from a different computer.
// This is primarily a hosted scenario where a registered hosted
// agent can land on a different computer each time.
tfWorkspaces = await tf.WorkspacesAsync(matchWorkspaceNameOnAnyComputer: true);
foreach (ITfsVCWorkspace tfWorkspace in tfWorkspaces ?? new ITfsVCWorkspace[0])
{
await tf.WorkspaceDeleteAsync(tfWorkspace);
}
// Recreate the sources directory.
executionContext.Debug($"Deleting: '{sourcesDirectory}'.");
IOUtil.DeleteDirectory(sourcesDirectory, cancellationToken);
Directory.CreateDirectory(sourcesDirectory);
// Create the workspace.
await tf.WorkspaceNewAsync();
// Remove the default mapping.
if (tf.Features.HasFlag(TfsVCFeatures.DefaultWorkfoldMap))
{
await tf.WorkfoldUnmapAsync("$/");
}
// Sort the definition mappings.
definitionMappings =
(definitionMappings ?? new DefinitionWorkspaceMapping[0])
.OrderBy(x => x.NormalizedServerPath?.Length ?? 0) // By server path length.
.ToArray() ?? new DefinitionWorkspaceMapping[0];
// Add the definition mappings to the workspace.
foreach (DefinitionWorkspaceMapping definitionMapping in definitionMappings)
{
switch (definitionMapping.MappingType)
{
case DefinitionMappingType.Cloak:
// Add the cloak.
await tf.WorkfoldCloakAsync(serverPath: definitionMapping.ServerPath);
break;
case DefinitionMappingType.Map:
// Add the mapping.
await tf.WorkfoldMapAsync(
serverPath: definitionMapping.ServerPath,
localPath: definitionMapping.GetRootedLocalPath(sourcesDirectory));
break;
default:
throw new NotSupportedException();
}
}
}
if (tf.Features.HasFlag(TfsVCFeatures.GetFromUnmappedRoot))
{
// Get.
await tf.GetAsync(localPath: sourcesDirectory, quiet: reducedOutput);
}
else
{
// Perform "get" for each map.
foreach (DefinitionWorkspaceMapping definitionMapping in definitionMappings ?? new DefinitionWorkspaceMapping[0])
{
if (definitionMapping.MappingType == DefinitionMappingType.Map)
{
await tf.GetAsync(localPath: definitionMapping.GetRootedLocalPath(sourcesDirectory), quiet: reducedOutput);
}
}
}
// Steps for shelveset/gated.
string shelvesetName = repository.Properties.Get<string>(Pipelines.RepositoryPropertyNames.Shelveset);
if (!string.IsNullOrEmpty(shelvesetName))
{
// Steps for gated.
ITfsVCShelveset tfShelveset = null;
string gatedShelvesetName = executionContext.Variables.GetValueOrDefault("build.gated.shelvesetname")?.Value;
if (!string.IsNullOrEmpty(gatedShelvesetName))
{
// Clean the last-saved-checkin-metadata for existing workspaces.
//
// A better long term fix is to add a switch to "tf unshelve" that completely overwrites
// the last-saved-checkin-metadata, instead of merging associated work items.
//
// The targeted workaround for now is to create a trivial change and "tf shelve /move",
// which will delete the last-saved-checkin-metadata.
if (existingTFWorkspace != null)
{
executionContext.Output("Cleaning last saved checkin metadata.");
// Find a local mapped directory.
string firstLocalDirectory =
(definitionMappings ?? new DefinitionWorkspaceMapping[0])
.Where(x => x.MappingType == DefinitionMappingType.Map)
.Select(x => x.GetRootedLocalPath(sourcesDirectory))
.FirstOrDefault(x => Directory.Exists(x));
if (firstLocalDirectory == null)
{
executionContext.Warning("No mapped folder found. Unable to clean last-saved-checkin-metadata.");
}
else
{
// Create a trival change and "tf shelve /move" to clear the
// last-saved-checkin-metadata.
string cleanName = "__tf_clean_wksp_metadata";
string tempCleanFile = Path.Combine(firstLocalDirectory, cleanName);
try
{
File.WriteAllText(path: tempCleanFile, contents: "clean last-saved-checkin-metadata", encoding: Encoding.UTF8);
await tf.AddAsync(tempCleanFile);
await tf.ShelveAsync(shelveset: cleanName, commentFile: tempCleanFile, move: true);
}
catch (Exception ex)
{
executionContext.Warning($"Unable to clean last-saved-checkin-metadata. {ex.Message}");
try
{
await tf.UndoAsync(tempCleanFile);
}
catch (Exception ex2)
{
executionContext.Warning($"Unable to undo '{tempCleanFile}'. {ex2.Message}");
}
}
finally
{
IOUtil.DeleteFile(tempCleanFile);
}
}
}
// Get the shelveset metadata.
tfShelveset = await tf.ShelvesetsAsync(shelveset: shelvesetName);
// The above command throws if the shelveset is not found,
// so the following assertion should never fail.
ArgUtil.NotNull(tfShelveset, nameof(tfShelveset));
}
// Unshelve.
bool unshelveErrorsAllowed = AgentKnobs.AllowTfvcUnshelveErrors.GetValue(executionContext).AsBoolean();
await tf.UnshelveAsync(shelveset: shelvesetName, unshelveErrorsAllowed);
// Ensure we undo pending changes for shelveset build at the end.
executionContext.SetTaskVariable("UndoShelvesetPendingChanges", bool.TrueString);
if (!string.IsNullOrEmpty(gatedShelvesetName))
{
// Create the comment file for reshelve.
StringBuilder comment = new StringBuilder(tfShelveset.Comment ?? string.Empty);
string runCi = executionContext.Variables.GetValueOrDefault("build.gated.runci")?.Value;
bool gatedRunCi = StringUtil.ConvertToBoolean(runCi, true);
if (!gatedRunCi)
{
if (comment.Length > 0)
{
comment.AppendLine();
}
comment.Append("***NO_CI***");
}
string commentFile = null;
try
{
commentFile = Path.GetTempFileName();
File.WriteAllText(path: commentFile, contents: comment.ToString(), encoding: Encoding.UTF8);
// Reshelve.
await tf.ShelveAsync(shelveset: gatedShelvesetName, commentFile: commentFile, move: false);
}
finally
{
// Cleanup the comment file.
if (File.Exists(commentFile))
{
File.Delete(commentFile);
}
}
}
}
// Cleanup proxy settings.
if (agentProxy != null && !string.IsNullOrEmpty(agentProxy.ProxyAddress) && !agentProxy.WebProxy.IsBypassed(repository.Url))
{
executionContext.Debug($"Remove proxy setting for '{tf.FilePath}' to work through proxy server '{agentProxy.ProxyAddress}'.");
tf.CleanupProxySetting();
}
// Set intra-task variable for post job cleanup
executionContext.SetTaskVariable("repository", repository.Alias);
}
public async Task PostJobCleanupAsync(AgentTaskPluginExecutionContext executionContext, Pipelines.RepositoryResource repository)
{
bool undoShelvesetPendingChanges = StringUtil.ConvertToBoolean(executionContext.TaskVariables.GetValueOrDefault("UndoShelvesetPendingChanges")?.Value);
if (undoShelvesetPendingChanges)
{
string shelvesetName = repository.Properties.Get<string>(Pipelines.RepositoryPropertyNames.Shelveset);
executionContext.Debug($"Undo pending changes left by shelveset '{shelvesetName}'.");
// Create the tf command manager.
ITfsVCCliManager tf;
if (PlatformUtil.RunningOnWindows)
{
tf = new TFCliManager();
}
else
{
tf = new TeeCliManager();
}
tf.CancellationToken = CancellationToken.None;
tf.Repository = repository;
tf.ExecutionContext = executionContext;
if (repository.Endpoint != null)
{
// the endpoint should either be the SystemVssConnection (id = guild.empty, name = SystemVssConnection)
// or a real service endpoint to external service which has a real id
var endpoint = executionContext.Endpoints.Single(
x => (repository.Endpoint.Id != Guid.Empty && x.Id == repository.Endpoint.Id) ||
(repository.Endpoint.Id == Guid.Empty && string.Equals(x.Name, repository.Endpoint.Name.ToString(), StringComparison.OrdinalIgnoreCase)));
ArgUtil.NotNull(endpoint, nameof(endpoint));
tf.Endpoint = endpoint;
}
// Get the definition mappings.
var workspaceMappings = repository.Properties.Get<IList<Pipelines.WorkspaceMapping>>(Pipelines.RepositoryPropertyNames.Mappings);
DefinitionWorkspaceMapping[] definitionMappings = workspaceMappings.Select(x => new DefinitionWorkspaceMapping() { ServerPath = x.ServerPath, LocalPath = x.LocalPath, MappingType = x.Exclude ? DefinitionMappingType.Cloak : DefinitionMappingType.Map }).ToArray();
// Determine the sources directory.
string sourcesDirectory = repository.Properties.Get<string>(Pipelines.RepositoryPropertyNames.Path);
ArgUtil.NotNullOrEmpty(sourcesDirectory, nameof(sourcesDirectory));
try
{
if (tf.Features.HasFlag(TfsVCFeatures.GetFromUnmappedRoot))
{
// Undo pending changes.
ITfsVCStatus tfStatus = await tf.StatusAsync(localPath: sourcesDirectory);
if (tfStatus?.HasPendingChanges ?? false)
{
await tf.UndoAsync(localPath: sourcesDirectory);
// Cleanup remaining files/directories from pend adds.
tfStatus.AllAdds
.OrderByDescending(x => x.LocalItem) // Sort descending so nested items are deleted before their parent is deleted.
.ToList()
.ForEach(x =>
{
executionContext.Output(StringUtil.Loc("Deleting", x.LocalItem));
IOUtil.Delete(x.LocalItem, CancellationToken.None);
});
}
}
else
{
// Perform "undo" for each map.
foreach (DefinitionWorkspaceMapping definitionMapping in definitionMappings ?? new DefinitionWorkspaceMapping[0])
{
if (definitionMapping.MappingType == DefinitionMappingType.Map)
{
// Check the status.
string localPath = definitionMapping.GetRootedLocalPath(sourcesDirectory);
ITfsVCStatus tfStatus = await tf.StatusAsync(localPath: localPath);
if (tfStatus?.HasPendingChanges ?? false)
{
// Undo.
await tf.UndoAsync(localPath: localPath);
// Cleanup remaining files/directories from pend adds.
tfStatus.AllAdds
.OrderByDescending(x => x.LocalItem) // Sort descending so nested items are deleted before their parent is deleted.
.ToList()
.ForEach(x =>
{
executionContext.Output(StringUtil.Loc("Deleting", x.LocalItem));
IOUtil.Delete(x.LocalItem, CancellationToken.None);
});
}
}
}
}
}
catch (Exception ex)
{
// We can't undo pending changes, log a warning and continue.
executionContext.Debug(ex.ToString());
executionContext.Warning(ex.Message);
}
}
}
private async Task RemoveConflictingWorkspacesAsync(ITfsVCCliManager tf, ITfsVCWorkspace[] tfWorkspaces, string name, string directory)
{
// Validate the args.
ArgUtil.NotNullOrEmpty(name, nameof(name));
ArgUtil.NotNullOrEmpty(directory, nameof(directory));
// Fixup the directory.
directory = directory.TrimEnd('/', '\\');
ArgUtil.NotNullOrEmpty(directory, nameof(directory));
string directorySlash = $"{directory}{Path.DirectorySeparatorChar}";
foreach (ITfsVCWorkspace tfWorkspace in tfWorkspaces ?? new ITfsVCWorkspace[0])
{
// Attempt to match the workspace by name.
if (string.Equals(tfWorkspace.Name, name, StringComparison.OrdinalIgnoreCase))
{
// Try deleting the workspace from the server.
if (!(await tf.TryWorkspaceDeleteAsync(tfWorkspace)))
{
// Otherwise fallback to deleting the workspace from the local computer.
await tf.WorkspacesRemoveAsync(tfWorkspace);
}
// Continue iterating over the rest of the workspaces.
continue;
}
// Attempt to match the workspace by local path.
foreach (ITfsVCMapping tfMapping in tfWorkspace.Mappings ?? new ITfsVCMapping[0])
{
// Skip cloaks.
if (tfMapping.Cloak)
{
continue;
}
if (string.Equals(tfMapping.LocalPath, directory, StringComparison.CurrentCultureIgnoreCase) ||
(tfMapping.LocalPath ?? string.Empty).StartsWith(directorySlash, StringComparison.CurrentCultureIgnoreCase))
{
// Try deleting the workspace from the server.
if (!(await tf.TryWorkspaceDeleteAsync(tfWorkspace)))
{
// Otherwise fallback to deleting the workspace from the local computer.
await tf.WorkspacesRemoveAsync(tfWorkspace);
}
// Break out of this nested for loop only.
// Continue iterating over the rest of the workspaces.
break;
}
}
}
}
public static class WorkspaceUtil
{
public static ITfsVCWorkspace MatchExactWorkspace(
AgentTaskPluginExecutionContext executionContext,
ITfsVCWorkspace[] tfWorkspaces,
string name,
DefinitionWorkspaceMapping[] definitionMappings,
string sourcesDirectory)
{
ArgUtil.NotNullOrEmpty(name, nameof(name));
ArgUtil.NotNullOrEmpty(sourcesDirectory, nameof(sourcesDirectory));
// Short-circuit early if the sources directory is empty.
//
// Consider the sources directory to be empty if it only contains a .tf directory exists. This can
// indicate the workspace is in a corrupted state and the tf commands (e.g. status) will not return
// reliable information. An easy way to reproduce this is to delete the workspace directory, then
// run "tf status" on that workspace. The .tf directory will be recreated but the contents will be
// in a corrupted state.
if (!Directory.Exists(sourcesDirectory) ||
!Directory.EnumerateFileSystemEntries(sourcesDirectory).Any(x => !x.EndsWith($"{Path.DirectorySeparatorChar}.tf")))
{
executionContext.Debug("Sources directory does not exist or is empty.");
return null;
}
string machineName = Environment.MachineName;
executionContext.Debug($"Attempting to find a workspace: '{name}'");
foreach (ITfsVCWorkspace tfWorkspace in tfWorkspaces ?? new ITfsVCWorkspace[0])
{
// Compare the workspace name.
if (!string.Equals(tfWorkspace.Name, name, StringComparison.Ordinal))
{
executionContext.Debug($"Skipping workspace: '{tfWorkspace.Name}'");
continue;
}
executionContext.Debug($"Candidate workspace: '{tfWorkspace.Name}'");
// Compare the machine name.
if (!string.Equals(tfWorkspace.Computer, machineName, StringComparison.Ordinal))
{
executionContext.Debug($"Expected computer name: '{machineName}'. Actual: '{tfWorkspace.Computer}'");
continue;
}
// Compare the number of mappings.
if ((tfWorkspace.Mappings?.Length ?? 0) != (definitionMappings?.Length ?? 0))
{
executionContext.Debug($"Expected number of mappings: '{definitionMappings?.Length ?? 0}'. Actual: '{tfWorkspace.Mappings?.Length ?? 0}'");
continue;
}
// Sort the definition mappings.
List<DefinitionWorkspaceMapping> sortedDefinitionMappings =
(definitionMappings ?? new DefinitionWorkspaceMapping[0])
.OrderBy(x => x.MappingType != DefinitionMappingType.Cloak) // Cloaks first
.ThenBy(x => !x.Recursive) // Then recursive maps
.ThenBy(x => x.NormalizedServerPath) // Then sort by the normalized server path
.ToList();
for (int i = 0; i < sortedDefinitionMappings.Count; i++)
{
DefinitionWorkspaceMapping mapping = sortedDefinitionMappings[i];
executionContext.Debug($"Definition mapping[{i}]: cloak '{mapping.MappingType == DefinitionMappingType.Cloak}', recursive '{mapping.Recursive}', server path '{mapping.NormalizedServerPath}', local path '{mapping.GetRootedLocalPath(sourcesDirectory)}'");
}
// Sort the TF mappings.
List<ITfsVCMapping> sortedTFMappings =
(tfWorkspace.Mappings ?? new ITfsVCMapping[0])
.OrderBy(x => !x.Cloak) // Cloaks first
.ThenBy(x => !x.Recursive) // Then recursive maps
.ThenBy(x => x.ServerPath) // Then sort by server path
.ToList();
for (int i = 0; i < sortedTFMappings.Count; i++)
{
ITfsVCMapping mapping = sortedTFMappings[i];
executionContext.Debug($"Found mapping[{i}]: cloak '{mapping.Cloak}', recursive '{mapping.Recursive}', server path '{mapping.ServerPath}', local path '{mapping.LocalPath}'");
}
// Compare the mappings.
bool allMatch = true;
List<string> matchTrace = new List<string>();
for (int i = 0; i < sortedTFMappings.Count; i++)
{
ITfsVCMapping tfMapping = sortedTFMappings[i];
DefinitionWorkspaceMapping definitionMapping = sortedDefinitionMappings[i];
// Compare the cloak flag.
bool expectedCloak = definitionMapping.MappingType == DefinitionMappingType.Cloak;
if (tfMapping.Cloak != expectedCloak)
{
matchTrace.Add(StringUtil.Loc("ExpectedMappingCloak", i, expectedCloak, tfMapping.Cloak));
allMatch = false;
break;
}
// Compare the recursive flag.
if (!expectedCloak && tfMapping.Recursive != definitionMapping.Recursive)
{
matchTrace.Add(StringUtil.Loc("ExpectedMappingRecursive", i, definitionMapping.Recursive, tfMapping.Recursive));
allMatch = false;
break;
}
// Compare the server path. Normalize the expected server path for a single-level map.
string expectedServerPath = definitionMapping.NormalizedServerPath;
if (!string.Equals(tfMapping.ServerPath, expectedServerPath, StringComparison.Ordinal))
{
matchTrace.Add(StringUtil.Loc("ExpectedMappingServerPath", i, expectedServerPath, tfMapping.ServerPath));
allMatch = false;
break;
}
// Compare the local path.
if (!expectedCloak)
{
string expectedLocalPath = definitionMapping.GetRootedLocalPath(sourcesDirectory);
if (!string.Equals(tfMapping.LocalPath, expectedLocalPath, StringComparison.Ordinal))
{
matchTrace.Add(StringUtil.Loc("ExpectedMappingLocalPath", i, expectedLocalPath, tfMapping.LocalPath));
allMatch = false;
break;
}
}
}
if (allMatch)
{
executionContext.Debug("Matching workspace found.");
return tfWorkspace;
}
else
{
executionContext.Output(StringUtil.Loc("WorkspaceMappingNotMatched", tfWorkspace.Name));
foreach (var trace in matchTrace)
{
executionContext.Output(trace);
}
}
}
executionContext.Debug("Matching workspace not found.");
return null;
}
}
public sealed class DefinitionWorkspaceMapping
{
public string LocalPath { get; set; }
public DefinitionMappingType MappingType { get; set; }
/// <summary>
/// Remove the trailing "/*" from the single-level mapping server path.
/// If the ServerPath is "$/*", then the normalized path is returned
/// as "$/" rather than "$".
/// </summary>
public string NormalizedServerPath
{
get
{
string path;
if (!Recursive)
{
// Trim the last two characters (i.e. "/*") from the single-level
// mapping server path.
path = ServerPath.Substring(0, ServerPath.Length - 2);
// Check if trimmed too much. This is important when comparing
// against workspaces on disk.
if (string.Equals(path, "$", StringComparison.Ordinal))
{
path = "$/";
}
}
else
{
path = ServerPath ?? string.Empty;
}
return path;
}
}
/// <summary>
/// Returns true if the path does not end with "/*".
/// </summary>
public bool Recursive => !(ServerPath ?? string.Empty).EndsWith("/*");
public string ServerPath { get; set; }
/// <summary>
/// Gets the rooted local path and normalizes slashes.
/// </summary>
public string GetRootedLocalPath(string sourcesDirectory)
{
// TEE normalizes all slashes in a workspace mapping to match the OS. It is not
// possible on OSX/Linux to have a workspace mapping with a backslash, even though
// backslash is a legal file name character.
string relativePath =
(LocalPath ?? string.Empty)
.Replace('/', Path.DirectorySeparatorChar)
.Replace('\\', Path.DirectorySeparatorChar)
.Trim(Path.DirectorySeparatorChar);
return Path.Combine(sourcesDirectory, relativePath);
}
}
public enum DefinitionMappingType
{
Cloak,
Map,
}
}
}
| |
using System;
using System.IO;
using System.Web.Mvc;
using MvcContrib.UI.Html;
namespace MvcContrib.UI.MenuBuilder
{
///<summary>
/// Used internally to create the menu, use MvcContrib.UI.MenuBuilder.Menu to create a menu.
///</summary>
public class MenuItem
{
public string Title { get; set; }
public string Icon { get; set; }
public string HelpText { get; set; }
public string ActionUrl { get; set; }
public string AnchorClass { get; set; }
public string IconClass { get; set; }
public string ItemClass { get; set; }
public string IconDirectory { get; set; }
public bool ShowWhenDisabled { get; set; }
public string DisabledClass { get; set; }
public bool Disabled { get; set; }
public string SelectedClass { get; set; }
//internal disabled allows for resetting of the disabled property on each render,
//when using Secure items
protected bool? internalDisabled;
protected bool ItemDisabled
{
get { return internalDisabled ?? Disabled; }
}
public bool HideItem
{
get { return ItemDisabled && ShowWhenDisabled == false; }
}
protected bool Prepared { get; set; }
public MenuItem()
{
Prepared = false;
}
protected virtual string RenderLink()
{
CleanTagBuilder anchor = new CleanTagBuilder("a");
if (ItemDisabled)
anchor.AddCssClass(DisabledClass);
else
anchor.Attributes["href"] = ActionUrl;
if(IsItemSelected())
anchor.AddCssClass(SelectedClass);
anchor.Attributes["title"] = HelpText;
anchor.InnerHtml += RenderIcon() + RenderTitle();
return anchor.ToString(TagRenderMode.Normal);
}
protected bool itemSelected;
public virtual bool IsItemSelected()
{
return itemSelected;
}
protected virtual string RenderIcon()
{
if (!string.IsNullOrEmpty(Icon))
{
string iconPath = (IconDirectory ?? "") + Icon;
CleanTagBuilder icon = new CleanTagBuilder("img");
icon.Attributes["border"] = "0";
icon.Attributes["src"] = iconPath;
icon.Attributes["alt"] = Title;
icon.AddCssClass(IconClass);
return icon.ToString(TagRenderMode.SelfClosing);
}
return string.Empty;
}
protected virtual string RenderTitle()
{
if (!string.IsNullOrEmpty(Title))
return Title;
return string.Empty;
}
/// <summary>
/// Renders the menu according to the current RequestContext to the specified TextWriter
/// </summary>
/// <param name="requestContext">The current RequestContext</param>
/// <param name="writer">The TextWriter for output</param>
public virtual void RenderHtml(ControllerContext requestContext, TextWriter writer)
{
Prepare(requestContext);
writer.Write(RenderHtml());
}
/// <summary>
/// Used internally to render the menu. Do not call this directly without first calling Prepare, or call RenderHtml(RequestContext ...)
/// </summary>
public virtual string RenderHtml()
{
if (!Prepared)
throw new InvalidOperationException("Must call Prepare before RenderHtml() or call RenderHtml(RequestContext, TextWriter)");
if (HideItem)
return string.Empty;
CleanTagBuilder li = new CleanTagBuilder("li");
li.AddCssClass(ItemClass);
li.InnerHtml = RenderLink();
return li.ToString(TagRenderMode.Normal);
}
/// <summary>
/// Called internally by RenderHtml(RequestContext, TextWriter) to remove empty items from lists and generate urls.
/// Can also be called externally to prepare the menu for serialization into Json/Xml
/// </summary>
/// <param name="controllerContext">The current RequestContext</param>
/// <returns>if this item should be rendered</returns>
public virtual void Prepare(ControllerContext controllerContext)
{
Prepared = true;
if(controllerContext.RequestContext.HttpContext.Request.Path == ActionUrl)
itemSelected = true;
}
public MenuItem SetTitle(string title)
{
Title = title;
return this;
}
public MenuItem SetIcon(string icon)
{
Icon = icon;
return this;
}
public MenuItem SetHelpText(string helpText)
{
HelpText = helpText;
return this;
}
public MenuItem SetActionUrl(string actionUrl)
{
ActionUrl = actionUrl;
return this;
}
public MenuItem SetAnchorClass(string anchorClass)
{
AnchorClass = anchorClass;
return this;
}
public MenuItem SetIconClass(string iconClas)
{
IconClass = iconClas;
return this;
}
public MenuItem SetItemClass(string itemClass)
{
ItemClass = itemClass;
return this;
}
public MenuItem SetIconDirectory(string iconDirectory)
{
IconDirectory = iconDirectory;
return this;
}
public MenuItem SetDisabled(bool disabled)
{
Disabled = disabled;
return this;
}
public MenuItem SetSelectedClass(string selectedClass)
{
SelectedClass = selectedClass;
return this;
}
/// <summary>
/// The class to use when displaying an insecure menu item, won't be used if hiding insecure items (default behavior)
/// </summary>
/// <param name="itemClass"></param>
/// <returns>this</returns>
public MenuItem SetDisabledMenuItemClass(string itemClass)
{
DisabledClass = itemClass;
return this;
}
/// <summary>
/// Should the menu item be hidden or display with limited functionality when disabled
/// </summary>
/// <param name="hide">Set to true to hide the item, false to show it in a disabled format</param>
/// <returns>this</returns>
public MenuItem SetShowWhenDisabled(bool hide)
{
ShowWhenDisabled = hide;
return this;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Xml.Linq;
namespace Signum.Utilities.DataStructures
{
public class DirectedGraph<T> : IEnumerable<T>
where T : notnull
{
readonly Dictionary<T, HashSet<T>> adjacency;
public IEqualityComparer<T> Comparer { get; private set; }
public DirectedGraph()
: this(EqualityComparer<T>.Default)
{
}
public DirectedGraph(IEqualityComparer<T> comparer)
{
this.Comparer = comparer;
this.adjacency = new Dictionary<T, HashSet<T>>(comparer);
}
public IEnumerable<T> Nodes
{
get { return adjacency.Keys; }
}
public IEnumerable<Edge<T>> Edges
{
get { return adjacency.SelectMany(k => k.Value.Select(n => new Edge<T>(k.Key, n))); }
}
public int Count
{
get { return adjacency.Count; }
}
public int EdgesCount
{
get { return adjacency.Sum(k => k.Value.Count); }
}
public bool Contains(T node)
{
return adjacency.ContainsKey(node);
}
public bool Connected(T from, T to)
{
return RelatedTo(from).Contains(to);
}
public bool TryConnected(T from, T to)
{
var hs = TryGet(from);
return hs != null && hs.Contains(to);
}
public void Add(T from)
{
TryGetOrAdd(from);
}
public void Add(T from, T to)
{
TryGetOrAdd(from).Add(to);
TryGetOrAdd(to);
}
public void Add(T from, params T[] elements)
{
var f = TryGetOrAdd(from);
foreach (var item in elements)
{
TryGetOrAdd(item);
f.Add(item);
}
}
public void Add(T from, IEnumerable<T> elements)
{
var f = TryGetOrAdd(from);
foreach (var item in elements)
{
TryGetOrAdd(item);
f.Add(item);
}
}
public bool RemoveEdge(T from, T to)
{
var hashSet = adjacency.TryGetC(from);
if (hashSet == null)
return false;
return hashSet.Remove(to);
}
public bool RemoveEdge(Edge<T> edge)
{
return RemoveEdge(edge.From, edge.To);
}
public void RemoveEdges(IEnumerable<Edge<T>> edges)
{
foreach (var edge in edges)
RemoveEdge(edge.From, edge.To);
}
public bool RemoveFullNode(T node)
{
if (!adjacency.ContainsKey(node))
return false;
return RemoveFullNode(node, InverseRelatedTo(node));
}
/// <summary>
/// Unsafer but faster
/// </summary>
public bool RemoveFullNode(T node, IEnumerable<T> inverseRelated)
{
if (!adjacency.ContainsKey(node))
return false;
adjacency.Remove(node);
foreach (var n in inverseRelated)
RemoveEdge(n, node);
return true;
}
public static void RemoveFullNodeSymetric(DirectedGraph<T> original, DirectedGraph<T> inverse, T node)
{
HashSet<T> from = inverse.RelatedTo(node);
HashSet<T> to = original.RelatedTo(node);
original.RemoveFullNode(node, from);
inverse.RemoveFullNode(node, to);
}
HashSet<T>? TryGet(T node)
{
return adjacency.TryGetC(node);
}
HashSet<T> TryGetOrAdd(T node)
{
if (adjacency.TryGetValue(node, out var result))
return result;
result = new HashSet<T>(Comparer);
adjacency.Add(node, result);
return result;
}
public HashSet<T> TryRelatedTo(T node)
{
return TryGet(node) ?? new HashSet<T>();
}
public HashSet<T> RelatedTo(T node)
{
var result = adjacency.TryGetC(node);
if (result == null)
throw new InvalidOperationException("The node {0} is not in the graph".FormatWith(node));
return result;
}
/// <summary>
/// Costly
/// </summary>
public IEnumerable<T> InverseRelatedTo(T node)
{
return this.Where(n => Connected(n, node));
}
public HashSet<T> IndirectlyRelatedTo(T node)
{
return IndirectlyRelatedTo(node, false);
}
public HashSet<T> IndirectlyRelatedTo(T node, bool includeInitialNode)
{
HashSet<T> set = new HashSet<T>();
if (includeInitialNode)
set.Add(node);
IndirectlyRelatedTo(node, set);
return set;
}
void IndirectlyRelatedTo(T node, HashSet<T> set)
{
foreach (var item in RelatedTo(node))
if (set.Add(item))
IndirectlyRelatedTo(item, set);
}
public HashSet<T> IndirectlyRelatedTo(T node, Func<T, bool> condition)
{
HashSet<T> set = new HashSet<T>();
IndirectlyRelatedTo(node, set, condition);
return set;
}
void IndirectlyRelatedTo(T node, HashSet<T> set, Func<T, bool> condition)
{
foreach (var item in RelatedTo(node).Where(condition))
if (set.Add(item))
IndirectlyRelatedTo(item, set, condition);
}
public void DepthExplore(T node, Func<T, bool>? condition, Action<T>? preAction, Action<T>? postAction)
{
if (condition != null && !condition(node))
return;
preAction?.Invoke(node);
foreach (T item in RelatedTo(node))
DepthExplore(item, condition, preAction, postAction);
postAction?.Invoke(node);
}
public void BreadthExplore(T root, Func<T, bool> condition, Action<T> action)
{
Queue<T> queue = new Queue<T>();
queue.Enqueue(root);
while (queue.Count > 0)
{
T node = queue.Dequeue();
if (!condition(node))
continue;
action(node);
queue.EnqueueRange(RelatedTo(node));
}
}
public DirectedGraph<T> Inverse()
{
DirectedGraph<T> result = new DirectedGraph<T>(Comparer);
foreach (var item in Nodes)
{
result.Add(item);
foreach (var related in RelatedTo(item))
{
result.Add(related, item);
}
}
return result;
}
public DirectedGraph<T> UndirectedGraph()
{
return this.Inverse().Do(g => g.UnionWith(this));
}
public DirectedGraph<T> RemoveAllNodes(DirectedGraph<T> graph)
{
var inv = this.Inverse();
foreach (var item in this.Where(a=>graph.Contains(a)).ToList())
{
this.RemoveFullNode(item, inv.RelatedTo(item));
}
return this;
}
public void UnionWith(DirectedGraph<T> other)
{
foreach (var item in other.Nodes)
Add(item, other.RelatedTo(item));
}
public DirectedGraph<T> Clone()
{
return new DirectedGraph<T>(Comparer).Do(g => g.UnionWith(this));
}
public static DirectedGraph<T> Generate(T root, Func<T, IEnumerable<T>> expandFunction)
{
return Generate(root, expandFunction, EqualityComparer<T>.Default);
}
public static DirectedGraph<T> Generate(T root, Func<T, IEnumerable<T>> expandFunction, IEqualityComparer<T> comparer)
{
DirectedGraph<T> result = new DirectedGraph<T>(comparer);
result.Expand(root, expandFunction);
return result;
}
public static DirectedGraph<T> Generate(IEnumerable<T> roots, Func<T, IEnumerable<T>> expandFunction)
{
return Generate(roots, expandFunction, EqualityComparer<T>.Default);
}
public static DirectedGraph<T> Generate(IEnumerable<T> roots, Func<T, IEnumerable<T>> expandFunction, IEqualityComparer<T> comparer)
{
DirectedGraph<T> result = new DirectedGraph<T>(comparer);
foreach (var root in roots)
result.Expand(root, expandFunction);
return result;
}
public void Expand(T node, Func<T, IEnumerable<T>> expandFunction)
{
if (adjacency.ContainsKey(node))
return;
var hs = new HashSet<T>(Comparer);
adjacency.Add(node, hs);
foreach (var item in expandFunction(node))
{
Expand(item, expandFunction);
hs.Add(item);
}
}
public override string ToString()
{
return adjacency.ToString(kvp => "{0}=>{1};".FormatWith(kvp.Key, kvp.Value.ToString(",")), "\r\n");
}
public string Graphviz()
{
return Graphviz("Graph", a => a.ToString()!);
}
public string Graphviz(string name, Func<T, string> getName)
{
int num = 0;
Dictionary<T, int> nodeDic = Nodes.ToDictionary(n => n, n => num++, Comparer);
string nodes = Nodes.ToString(e => " {0} [ label =\"{1}\"];".FormatWith(nodeDic[e], getName(e)), "\r\n");
string edges = Edges.ToString(e => " {0} -> {1};".FormatWith(nodeDic[e.From], nodeDic[e.To]), "\r\n");
return "digraph \"{0}\"\r\n{{\r\n{1}\r\n{2}\r\n}}".FormatWith(name, nodes, edges);
}
public XDocument ToDGML()
{
return ToDGML(a => a.ToString() ?? "[null]", a => ColorExtensions.ToHtmlColor(a.GetType().FullName!.GetHashCode()));
}
public XDocument ToDGML(Func<T, string> getNodeLabel, Func<T, string> getColor)
{
return ToDGML(n => new[]
{
new XAttribute("Label", getNodeLabel(n)),
new XAttribute("Background", getColor(n))
});
}
public XDocument ToDGML(Func<T, XAttribute[]> attributes)
{
int num = 0;
Dictionary<T, int> nodeDic = Nodes.ToDictionary(n => n, n => num++, Comparer);
XNamespace ns = "http://schemas.microsoft.com/vs/2009/dgml";
return new XDocument(
new XElement(ns + "DirectedGraph",
new XElement(ns + "Nodes",
Nodes.Select(n => new XElement(ns + "Node",
new XAttribute("Id", nodeDic[n]),
attributes(n)))),
new XElement(ns + "Links",
Edges.Select(e => new XElement(ns + "Link",
new XAttribute("Source", nodeDic[e.From]),
new XAttribute("Target", nodeDic[e.To]))))
)
);
}
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
return adjacency.Keys.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return adjacency.Keys.GetEnumerator();
}
#endregion
public IEnumerable<HashSet<T>> CompilationOrderGroups()
{
DirectedGraph<T> clone = this.Clone();
DirectedGraph<T> inv = this.Inverse();
while (clone.Count > 0)
{
var leaves = clone.Sinks();
foreach (var node in leaves)
clone.RemoveFullNode(node, inv.RelatedTo(node));
yield return leaves;
}
}
public IEnumerable<T> CompilationOrder()
{
return CompilationOrderGroups().SelectMany(e => e);
}
/// <summary>
/// A simple but effective linear-time heuristic constructs a vertex ordering,
/// just as in the topological sort heuristic above, and deletes any arc going from right to left.
///
/// This heuristic builds up the ordering from the outside in based on the in- and out-degrees of each vertex.
/// - Any vertex of in-degree 0 is a source and can be placed first in the ordering.
/// - Any vertex of out-degree 0 is a sink and can be placed last in the ordering, again without violating any constraints.
/// - If not, we find the vertex with the maximum difference between in- and out-degree,
/// and place it on the side of the permutation that will salvage the greatest number of constraints.
/// Delete any vertex from the DAG after positioning it and repeat until the graph is empty.
/// </summary>
/// <returns></returns>
public DirectedGraph<T> FeedbackEdgeSet()
{
DirectedGraph<T> result = new DirectedGraph<T>(Comparer);
DirectedGraph<T> clone = this.Clone();
DirectedGraph<T> inv = this.Inverse();
HashSet<T> head = new HashSet<T>(); // for sources
HashSet<T> tail = new HashSet<T>(); // for sinks
while (clone.Count > 0)
{
var sinks = clone.Sinks();
if (sinks.Count() != 0)
{
foreach (var sink in sinks)
{
DirectedGraph<T>.RemoveFullNodeSymetric(clone, inv, sink);
tail.Add(sink);
}
continue;
}
var sources = inv.Sinks();
if (sources.Count() != 0)
{
foreach (var source in sources)
{
DirectedGraph<T>.RemoveFullNodeSymetric(clone, inv, source);
head.Add(source);
}
continue;
}
int fanInOut(T n) => clone.RelatedTo(n).Count() - inv.RelatedTo(n).Count();
MinMax<T> mm = clone.WithMinMaxPair(fanInOut);
if (fanInOut(mm.Max) > -fanInOut(mm.Min))
{
T node = mm.Max;
foreach (var n in inv.RelatedTo(node))
result.Add(node, n);
DirectedGraph<T>.RemoveFullNodeSymetric(clone, inv, node);
head.Add(node);
}
else
{
T node = mm.Min;
foreach (var n in clone.RelatedTo(node))
result.Add(node, n);
DirectedGraph<T>.RemoveFullNodeSymetric(clone, inv, node);
head.Add(node);
}
}
return result;
}
public HashSet<T> Sinks()
{
return new HashSet<T>(adjacency.Where(a => a.Value.Count == 0).Select(a => a.Key));
}
public DirectedGraph<T> WhereEdges(Func<Edge<T>, bool> condition)
{
DirectedGraph<T> result = new DirectedGraph<T>(Comparer);
foreach (var item in Nodes)
result.Add(item, RelatedTo(item).Where(to => condition(new Edge<T>(item, to))));
return result;
}
public List<T>? ShortestPath(T from, T to)
{
//http://en.wikipedia.org/wiki/Dijkstra's_algorithm
Dictionary<T, int> distance = this.ToDictionary(e => e, e => int.MaxValue, Comparer);
Dictionary<T, T> previous = new Dictionary<T, T>(Comparer);
distance[from] = 0;
PriorityQueue<T> queue = new PriorityQueue<T>((a, b) => distance[a].CompareTo(distance[b]));
queue.PushAll(this);
while (queue.Count > 0)
{
T u = queue.Peek();
if (distance[u] == int.MaxValue)
return null;
int newDist = distance[u] + 1;
foreach (var v in RelatedTo(u))
{
if (newDist < distance[v])
{
distance[v] = newDist;
queue.Update(v);
previous[v] = u;
}
}
queue.Pop();
if (Comparer.Equals(u, to))
break;
}
return to.For(n => previous.ContainsKey(n), n => previous[n]).Reverse().ToList();
}
}
public struct Edge<T>
{
public readonly T From;
public readonly T To;
public Edge(T from, T to)
{
this.From = from;
this.To = to;
}
public override string ToString()
{
return "{0}->{1}".FormatWith(From, To);
}
};
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// 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 the Outercurve Foundation 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebsitePanel.Portal.VPSForPC {
public partial class VdcCreate {
/// <summary>
/// asyncTasks control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.EnableAsyncTasksSupport asyncTasks;
/// <summary>
/// breadcrumb control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.VPSForPC.UserControls.Breadcrumb breadcrumb;
/// <summary>
/// menu control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.VPSForPC.UserControls.Menu menu;
/// <summary>
/// imgIcon control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Image imgIcon;
/// <summary>
/// locTitle control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locTitle;
/// <summary>
/// messageBox control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.SimpleMessageBox messageBox;
/// <summary>
/// validatorsSummary control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ValidationSummary validatorsSummary;
/// <summary>
/// wizard control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Wizard wizard;
/// <summary>
/// stepName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.WizardStep stepName;
/// <summary>
/// locNameStepTitle control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locNameStepTitle;
/// <summary>
/// locOperatingSystem control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locOperatingSystem;
/// <summary>
/// listOperatingSystems control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList listOperatingSystems;
/// <summary>
/// OperatingSystemValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator OperatingSystemValidator;
/// <summary>
/// Localize3 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize Localize3;
/// <summary>
/// txtVmName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtVmName;
/// <summary>
/// vmNameValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator vmNameValidator;
/// <summary>
/// chkSendSummary control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkSendSummary;
/// <summary>
/// txtSummaryEmail control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtSummaryEmail;
/// <summary>
/// SummaryEmailValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator SummaryEmailValidator;
/// <summary>
/// stepConfig control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.WizardStep stepConfig;
/// <summary>
/// locConfigStepTitle control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locConfigStepTitle;
/// <summary>
/// secResources control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secResources;
/// <summary>
/// ResourcesPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel ResourcesPanel;
/// <summary>
/// lblCpu control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblCpu;
/// <summary>
/// ddlCpu control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddlCpu;
/// <summary>
/// locCores control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locCores;
/// <summary>
/// lblRam control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblRam;
/// <summary>
/// txtRam control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtRam;
/// <summary>
/// RequireRamValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator RequireRamValidator;
/// <summary>
/// locMB control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locMB;
/// <summary>
/// lblHdd control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblHdd;
/// <summary>
/// txtHdd control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtHdd;
/// <summary>
/// RequireHddValidator control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.RequiredFieldValidator RequireHddValidator;
/// <summary>
/// locGB control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locGB;
/// <summary>
/// secActions control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secActions;
/// <summary>
/// ActionsPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel ActionsPanel;
/// <summary>
/// chkStartShutdown control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkStartShutdown;
/// <summary>
/// chkReset control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkReset;
/// <summary>
/// chkPauseResume control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkPauseResume;
/// <summary>
/// chkReinstall control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkReinstall;
/// <summary>
/// chkReboot control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkReboot;
/// <summary>
/// stepPrivateNetwork control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.WizardStep stepPrivateNetwork;
/// <summary>
/// locPrivateNetwork control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locPrivateNetwork;
/// <summary>
/// chkPrivateNetworkEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkPrivateNetworkEnabled;
/// <summary>
/// pVLanListIsEmptyMessage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl pVLanListIsEmptyMessage;
/// <summary>
/// tablePrivateNetwork control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTable tablePrivateNetwork;
/// <summary>
/// lvPrivateVLanID control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize lvPrivateVLanID;
/// <summary>
/// ddlPrivateVLanID control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddlPrivateVLanID;
/// <summary>
/// stepExternalNetwork control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.WizardStep stepExternalNetwork;
/// <summary>
/// locExternalNetwork control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locExternalNetwork;
/// <summary>
/// chkExternalNetworkEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkExternalNetworkEnabled;
/// <summary>
/// EmptyExternalAddressesMessage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl EmptyExternalAddressesMessage;
/// <summary>
/// locNotEnoughExternalAddresses control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locNotEnoughExternalAddresses;
/// <summary>
/// stepSummary control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.WizardStep stepSummary;
/// <summary>
/// locSummary control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locSummary;
/// <summary>
/// locNameStepTitle2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locNameStepTitle2;
/// <summary>
/// Localize1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize Localize1;
/// <summary>
/// litHostname control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litHostname;
/// <summary>
/// Localize2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize Localize2;
/// <summary>
/// litOperatingSystem control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litOperatingSystem;
/// <summary>
/// SummSummaryEmailRow control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableRow SummSummaryEmailRow;
/// <summary>
/// locSendSummary control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locSendSummary;
/// <summary>
/// litSummaryEmail control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litSummaryEmail;
/// <summary>
/// locConfig2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locConfig2;
/// <summary>
/// locCpu control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locCpu;
/// <summary>
/// litCpu control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litCpu;
/// <summary>
/// locRam control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locRam;
/// <summary>
/// litRam control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litRam;
/// <summary>
/// locHdd control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locHdd;
/// <summary>
/// litHdd control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litHdd;
/// <summary>
/// locStartShutdownAllowed control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locStartShutdownAllowed;
/// <summary>
/// optionStartShutdown control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.CheckBoxOption optionStartShutdown;
/// <summary>
/// locPauseResumeAllowed control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locPauseResumeAllowed;
/// <summary>
/// optionPauseResume control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.CheckBoxOption optionPauseResume;
/// <summary>
/// locRebootAllowed control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locRebootAllowed;
/// <summary>
/// optionReboot control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.CheckBoxOption optionReboot;
/// <summary>
/// locResetAllowed control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locResetAllowed;
/// <summary>
/// optionReset control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.CheckBoxOption optionReset;
/// <summary>
/// locReinstallAllowed control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locReinstallAllowed;
/// <summary>
/// optionReinstall control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.CheckBoxOption optionReinstall;
/// <summary>
/// locExternalNetwork2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locExternalNetwork2;
/// <summary>
/// locExternalNetworkEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locExternalNetworkEnabled;
/// <summary>
/// optionExternalNetwork control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.CheckBoxOption optionExternalNetwork;
/// <summary>
/// locPrivateNetwork2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locPrivateNetwork2;
/// <summary>
/// locPrivateNetworkEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locPrivateNetworkEnabled;
/// <summary>
/// optionPrivateNetwork control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.CheckBoxOption optionPrivateNetwork;
/// <summary>
/// locPrivateNetworkVLanID control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locPrivateNetworkVLanID;
/// <summary>
/// litPrivateNetworkVLanID control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litPrivateNetworkVLanID;
/// <summary>
/// FormComments control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize FormComments;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace Lucene.Net.Analysis.Hunspell {
public class HunspellDictionary {
private static readonly HunspellWord NoFlags = new HunspellWord();
private static readonly String PREFIX_KEY = "PFX";
private static readonly String SUFFIX_KEY = "SFX";
private static readonly String FLAG_KEY = "FLAG";
private static readonly String AF_KEY = "AF";
private static readonly String NUM_FLAG_TYPE = "num";
private static readonly String UTF8_FLAG_TYPE = "UTF-8";
private static readonly String LONG_FLAG_TYPE = "long";
private static readonly String PREFIX_CONDITION_REGEX_PATTERN = @"^{0}";
private static readonly String SUFFIX_CONDITION_REGEX_PATTERN = @"{0}$";
private readonly Dictionary<String, List<HunspellAffix>> _prefixes = new Dictionary<String, List<HunspellAffix>>();
private readonly Dictionary<String, List<HunspellAffix>> _suffixes = new Dictionary<String, List<HunspellAffix>>();
private readonly Dictionary<String, List<HunspellWord>> _words = new Dictionary<String, List<HunspellWord>>();
private readonly Dictionary<String, Char[]> _aliases = new Dictionary<String, Char[]>();
private FlagParsingStrategy _flagParsingStrategy = new SimpleFlagParsingStrategy(); // Default flag parsing strategy
/// <summary>
/// Creates a new HunspellDictionary containing the information read from the provided streams to hunspell affix and dictionary file.
/// </summary>
/// <param name = "affix">Stream for reading the hunspell affix file.</param>
/// <param name = "dictionary">Stream for reading the hunspell dictionary file.</param>
/// <exception cref = "IOException">Can be thrown while reading from the streams.</exception>
/// <exception cref = "InvalidDataException">Can be thrown if the content of the files does not meet expected formats.</exception>
public HunspellDictionary(Stream affix, Stream dictionary)
: this(affix, new[] { dictionary }) {
}
/// <summary>
/// Creates a new HunspellDictionary containing the information read from the provided streams to hunspell affix and dictionary files.
/// </summary>
/// <param name = "affix">Stream for reading the hunspell affix file.</param>
/// <param name = "dictionaries">Streams for reading the hunspell dictionary file.</param>
/// <exception cref = "IOException">Can be thrown while reading from the streams.</exception>
/// <exception cref = "InvalidDataException">Can be thrown if the content of the files does not meet expected formats.</exception>
public HunspellDictionary(Stream affix, IEnumerable<Stream> dictionaries) {
if (affix == null) throw new ArgumentNullException("affix");
if (dictionaries == null) throw new ArgumentNullException("dictionaries");
var encodingName = ReadDictionaryEncoding(affix);
var encoding = Encoding.GetEncoding(encodingName);
ReadAffixFile(affix, encoding);
foreach (var dictionary in dictionaries)
ReadDictionaryFile(dictionary, encoding);
}
/// <summary>
/// Looks up HunspellWords that match the String created from the given char array, offset and length.
/// </summary>
public IEnumerable<HunspellWord> LookupWord(String word) {
if (word == null) throw new ArgumentNullException("word");
List<HunspellWord> list;
if (_words.TryGetValue(word, out list))
return list;
return null;
}
/// <summary>
/// Looks up HunspellAffix prefixes that have an append that matches the String created from the given char array, offset and length.
/// </summary>
/// <param name="word">Char array to generate the String from.</param>
/// <param name="offset">Offset in the char array that the String starts at.</param>
/// <param name="length">Length from the offset that the String is.</param>
/// <returns>List of HunspellAffix prefixes with an append that matches the String, or <c>null</c> if none are found.</returns>
public IEnumerable<HunspellAffix> LookupPrefix(char[] word, int offset, int length) {
if (word == null) throw new ArgumentNullException("word");
var key = new String(word, offset, length);
List<HunspellAffix> list;
if (_prefixes.TryGetValue(key, out list))
return list;
return null;
}
/// <summary>
/// Looks up HunspellAffix suffixes that have an append that matches the String created from the given char array, offset and length.
/// </summary>
/// <param name="word">Char array to generate the String from.</param>
/// <param name="offset">Offset in the char array that the String starts at.</param>
/// <param name="length">Length from the offset that the String is.</param>
/// <returns>List of HunspellAffix suffixes with an append that matches the String, or <c>null</c> if none are found</returns>
public IEnumerable<HunspellAffix> LookupSuffix(char[] word, int offset, int length) {
if (word == null) throw new ArgumentNullException("word");
var key = new String(word, offset, length);
List<HunspellAffix> list;
if (_suffixes.TryGetValue(key, out list))
return list;
return null;
}
/// <summary>
/// Reads the affix file through the provided Stream, building up the prefix and suffix maps.
/// </summary>
/// <param name="affixStream">Stream to read the content of the affix file from.</param>
/// <param name="encoding">Encoding to decode the content of the file.</param>
/// <exception cref="IOException">IOException Can be thrown while reading from the Stream.</exception>
private void ReadAffixFile(Stream affixStream, Encoding encoding) {
if (affixStream == null) throw new ArgumentNullException("affixStream");
if (encoding == null) throw new ArgumentNullException("encoding");
using (var reader = new StreamReader(affixStream, encoding)) {
String line;
while ((line = reader.ReadLine()) != null) {
if (line.StartsWith(PREFIX_KEY)) {
ParseAffix(_prefixes, line, reader, PREFIX_CONDITION_REGEX_PATTERN);
} else if (line.StartsWith(SUFFIX_KEY)) {
ParseAffix(_suffixes, line, reader, SUFFIX_CONDITION_REGEX_PATTERN);
} else if (line.StartsWith(FLAG_KEY)) {
// Assume that the FLAG line comes before any prefix or suffixes
// Store the strategy so it can be used when parsing the dic file
_flagParsingStrategy = GetFlagParsingStrategy(line);
} else if (line.StartsWith(AF_KEY)) {
// Parse Alias Flag
ParseAliasFlag(line, reader);
}
}
}
}
/// <summary>
/// Parse alias flag and put it in hash
/// </summary>
/// <param name="line"></param>
/// <param name="reader"></param>
private void ParseAliasFlag(String line, TextReader reader) {
if (reader == null) throw new ArgumentNullException("reader");
var args = Regex.Split(line, "\\s+");
var numLines = Int32.Parse(args[1]);
for (var i = 0; i < numLines; i++) {
line = reader.ReadLine();
var ruleArgs = Regex.Split(line, "\\s+");
if (ruleArgs[0] != "AF")
throw new Exception("File corrupted, should be AF directive : " + line);
var appendFlags = _flagParsingStrategy.ParseFlags(ruleArgs[1]);
_aliases.Add((i+1).ToString(CultureInfo.InvariantCulture), appendFlags);
}
}
/// <summary>
/// Parses a specific affix rule putting the result into the provided affix map.
/// </summary>
/// <param name="affixes">Map where the result of the parsing will be put.</param>
/// <param name="header">Header line of the affix rule.</param>
/// <param name="reader">TextReader to read the content of the rule from.</param>
/// <param name="conditionPattern">Pattern to be used to generate the condition regex pattern.</param>
private void ParseAffix(Dictionary<String, List<HunspellAffix>> affixes, String header, TextReader reader, String conditionPattern) {
if (affixes == null) throw new ArgumentNullException("affixes");
if (header == null) throw new ArgumentNullException("header");
if (reader == null) throw new ArgumentNullException("reader");
if (conditionPattern == null) throw new ArgumentNullException("conditionPattern");
var args = Regex.Split(header, "\\s+");
var crossProduct = args[2].Equals("Y");
var numLines = Int32.Parse(args[3]);
var hasAliases = _aliases.Count > 0;
for (var i = 0; i < numLines; i++) {
var line = reader.ReadLine();
var ruleArgs = Regex.Split(line, "\\s+");
var affix = new HunspellAffix();
affix.Flag = _flagParsingStrategy.ParseFlag(ruleArgs[1]);
affix.Strip = (ruleArgs[2] == "0") ? "" : ruleArgs[2];
var affixArg = ruleArgs[3];
var flagSep = affixArg.LastIndexOf('/');
if (flagSep != -1) {
var cflag = affixArg.Substring(flagSep + 1);
var appendFlags = hasAliases ? _aliases[cflag] : _flagParsingStrategy.ParseFlags(cflag);
Array.Sort(appendFlags);
affix.AppendFlags = appendFlags;
affix.Append = affixArg.Substring(0, flagSep);
} else {
affix.Append = affixArg;
}
var condition = ruleArgs[4];
affix.SetCondition(condition, String.Format(conditionPattern, condition));
affix.IsCrossProduct = crossProduct;
List<HunspellAffix> list;
if (!affixes.TryGetValue(affix.Append, out list))
affixes.Add(affix.Append, list = new List<HunspellAffix>());
list.Add(affix);
}
}
/// <summary>
/// Parses the encoding specificed in the affix file readable through the provided Stream.
/// </summary>
/// <param name="affix">Stream for reading the affix file.</param>
/// <returns>Encoding specified in the affix file.</returns>
/// <exception cref="InvalidDataException">
/// Thrown if the first non-empty non-comment line read from the file does not
/// adhere to the format <c>SET encoding</c>.
/// </exception>
private static String ReadDictionaryEncoding(Stream affix) {
if (affix == null) throw new ArgumentNullException("affix");
var builder = new StringBuilder();
for (; ; ) {
builder.Length = 0;
int ch;
while ((ch = affix.ReadByte()) >= 0) {
if (ch == '\n') {
break;
}
if (ch != '\r') {
builder.Append((char)ch);
}
}
if (builder.Length == 0 ||
builder[0] == '#' ||
// this test only at the end as ineffective but would allow lines only containing spaces:
builder.ToString().Trim().Length == 0
) {
if (ch < 0)
throw new InvalidDataException("Unexpected end of affix file.");
continue;
}
if ("SET ".Equals(builder.ToString(0, 4))) {
// cleanup the encoding string, too (whitespace)
return builder.ToString(4, builder.Length - 4).Trim();
}
throw new InvalidDataException("The first non-comment line in the affix file must " +
"be a 'SET charset', was: '" + builder + "'");
}
}
/// <summary>
/// Determines the appropriate {@link FlagParsingStrategy} based on the FLAG definiton line taken from the affix file.
/// </summary>
/// <param name="flagLine">Line containing the flag information</param>
/// <returns>FlagParsingStrategy that handles parsing flags in the way specified in the FLAG definition.</returns>
private static FlagParsingStrategy GetFlagParsingStrategy(String flagLine) {
if (flagLine == null) throw new ArgumentNullException("flagLine");
var flagType = flagLine.Substring(5);
if (NUM_FLAG_TYPE.Equals(flagType))
return new NumFlagParsingStrategy();
if (UTF8_FLAG_TYPE.Equals(flagType))
return new SimpleFlagParsingStrategy();
if (LONG_FLAG_TYPE.Equals(flagType))
return new DoubleASCIIFlagParsingStrategy();
throw new ArgumentException("Unknown flag type: " + flagType);
}
/// <summary>
/// Reads the dictionary file through the provided Stream, building up the words map.
/// </summary>
/// <param name="dictionary">Stream to read the dictionary file through.</param>
/// <param name="encoding">Encoding used to decode the contents of the file.</param>
/// <exception cref="IOException">Can be thrown while reading from the file.</exception>
private void ReadDictionaryFile(Stream dictionary, Encoding encoding) {
if (dictionary == null) throw new ArgumentNullException("dictionary");
if (encoding == null) throw new ArgumentNullException("encoding");
var reader = new StreamReader(dictionary, encoding);
// nocommit, don't create millions of strings.
var line = reader.ReadLine(); // first line is number of entries
var numEntries = Int32.Parse(line);
var hasAliases = _aliases.Count > 0;
// nocommit, the flags themselves can be double-chars (long) or also numeric
// either way the trick is to encode them as char... but they must be parsed differently
while ((line = reader.ReadLine()) != null) {
String entry;
HunspellWord wordForm;
var flagSep = line.LastIndexOf('/');
if (flagSep == -1) {
wordForm = NoFlags;
entry = line;
} else {
// note, there can be comments (morph description) after a flag.
// we should really look for any whitespace
var end = line.IndexOf('\t', flagSep);
var cflag = end == -1 ? line.Substring(flagSep + 1) : line.Substring(flagSep + 1, end - flagSep - 1);
wordForm = new HunspellWord(hasAliases ? _aliases[cflag] : _flagParsingStrategy.ParseFlags(cflag));
entry = line.Substring(0, flagSep);
}
List<HunspellWord> entries;
if (!_words.TryGetValue(entry, out entries))
_words.Add(entry, entries = new List<HunspellWord>());
entries.Add(wordForm);
}
}
#region Nested type: DoubleASCIIFlagParsingStrategy
/// <summary>
/// Implementation of {@link FlagParsingStrategy} that assumes each flag is encoded as
/// two ASCII characters whose codes must be combined into a single character.
/// </summary>
private class DoubleASCIIFlagParsingStrategy : FlagParsingStrategy {
public override Char[] ParseFlags(String rawFlags) {
if (rawFlags.Length == 0)
return new Char[0];
var builder = new StringBuilder();
for (var i = 0; i < rawFlags.Length; i += 2) {
var cookedFlag = (Char)(rawFlags[i] + rawFlags[i + 1]);
builder.Append(cookedFlag);
}
return builder.ToString().ToCharArray();
}
}
#endregion
#region Nested type: FlagParsingStrategy
/// <summary>
/// Abstraction of the process of parsing flags taken from the affix and dic files
/// </summary>
private abstract class FlagParsingStrategy {
/// <summary>
/// Parses the given String into a single flag.
/// </summary>
/// <param name="rawFlag">String to parse into a flag.</param>
/// <returns>Parsed flag.</returns>
public Char ParseFlag(String rawFlag) {
if (rawFlag == null)
throw new ArgumentNullException("rawFlag");
return ParseFlags(rawFlag)[0];
}
/// <summary>
/// Parses the given String into multiple flag.
/// </summary>
/// <param name="rawFlags">String to parse into a flags.</param>
/// <returns>Parsed flags.</returns>
public abstract Char[] ParseFlags(String rawFlags);
}
#endregion
#region Nested type: NumFlagParsingStrategy
/// <summary>
/// Implementation of {@link FlagParsingStrategy} that assumes each flag is encoded in its
/// numerical form. In the case of multiple flags, each number is separated by a comma.
/// </summary>
private class NumFlagParsingStrategy : FlagParsingStrategy {
public override Char[] ParseFlags(String rawFlags) {
var rawFlagParts = rawFlags.Trim().Split(',');
var flags = new Char[rawFlagParts.Length];
for (var i = 0; i < rawFlagParts.Length; i++) {
// note, removing the trailing X/leading I for nepali... what is the rule here?!
var replaced = Regex.Replace(rawFlagParts[i], "[^0-9]", "");
flags[i] = (Char)Int32.Parse(replaced);
}
return flags;
}
}
#endregion
#region Nested type: SimpleFlagParsingStrategy
/// <summary>
/// Simple implementation of {@link FlagParsingStrategy} that treats the chars in each
/// String as a individual flags. Can be used with both the ASCII and UTF-8 flag types.
/// </summary>
private class SimpleFlagParsingStrategy : FlagParsingStrategy {
public override Char[] ParseFlags(String rawFlags) {
return rawFlags.ToCharArray();
}
}
#endregion
}
}
| |
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2009 Jason Booth
Copyright (c) 2011-2012 openxlive.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace Cocos2D
{
public enum CCSAXState
{
None = 0,
Key,
Dict,
Int,
Real,
String,
Array
};
public class CCDictMaker : ICCSAXDelegator
{
public Dictionary<string, Object> m_pRootDict;
public Dictionary<string, Object> m_pCurDict;
public Stack<Dictionary<string, Object>> m_tDictStack=new Stack<Dictionary<string,object>>();
public string m_sCurKey;///< parsed key
public CCSAXState m_tState;
public List<Object> m_pArray;
Stack<List<Object>> m_tArrayStack = new Stack<List<object>>();
Stack<CCSAXState> m_tStateStack = new Stack<CCSAXState>();
public CCDictMaker()
{
m_tState = CCSAXState.None;
}
public Dictionary<string, Object> DictionaryWithContentsOfFile(string pFileName)
{
CCSAXParser parser = new CCSAXParser();
if (false == parser.Init("UTF-8"))
{
return null;
}
parser.SetDelegator(this);
parser.Parse(pFileName);
return m_pRootDict;
}
public List<Object> ArrayWithContentsOfFile(string pFileName)
{
CCSAXParser parser = new CCSAXParser();
if (false == parser.Init("UTF-8"))
{
return null;
}
parser.SetDelegator(this);
//byte[] root;
StartElement(parser, "dict", null);
StartElement(parser, "key", null);
TextHandler(parser, System.Text.UTF8Encoding.UTF8.GetBytes("root"), 4);
EndElement(parser, "key");
parser.Parse(pFileName);
EndElement(parser, "dict");
return m_pRootDict["root"] as List<Object>;
}
public void StartElement(object ctx, string name, string[] atts)
{
string sName = name;
if (sName == "dict")
{
m_pCurDict = new Dictionary<string, Object>();
if (m_pRootDict == null)
{
m_pRootDict = m_pCurDict;
}
m_tState = CCSAXState.Dict;
CCSAXState preState = CCSAXState.None;
if (m_tStateStack.Count != 0)
{
preState = m_tStateStack.FirstOrDefault();
}
if (CCSAXState.Array == preState)
{
// add the dictionary into the array
m_pArray.Add(m_pCurDict);
}
else if (CCSAXState.Dict == preState)
{
// add the dictionary into the pre dictionary
Debug.Assert(m_tDictStack.Count > 0, "The state is wrong!");
Dictionary<string, Object> pPreDict = m_tDictStack.FirstOrDefault();
pPreDict.Add(m_sCurKey, m_pCurDict);
}
//m_pCurDict->autorelease();
// record the dict state
m_tStateStack.Push(m_tState);
m_tDictStack.Push(m_pCurDict);
}
else if (sName == "key")
{
m_tState = CCSAXState.Key;
}
else if (sName == "integer")
{
m_tState = CCSAXState.Int;
}
else if (sName == "real")
{
m_tState = CCSAXState.Real;
}
else if (sName == "string")
{
m_tState = CCSAXState.String;
}
else if (sName == "array")
{
m_tState = CCSAXState.Array;
m_pArray = new List<Object>();
CCSAXState preState = m_tStateStack.Count == 0 ? CCSAXState.Dict : m_tStateStack.FirstOrDefault();
if (preState == CCSAXState.Dict)
{
m_pCurDict.Add(m_sCurKey, m_pArray);
}
else if (preState == CCSAXState.Array)
{
Debug.Assert(m_tArrayStack.Count > 0, "The state is worng!");
List<Object> pPreArray = m_tArrayStack.FirstOrDefault();
pPreArray.Add(m_pArray);
}
//m_pArray->release();
// record the array state
m_tStateStack.Push(m_tState);
m_tArrayStack.Push(m_pArray);
}
else
{
m_tState = CCSAXState.None;
}
}
public void EndElement(object ctx, string name)
{
CCSAXState curState = m_tStateStack.Count > 0 ? CCSAXState.Dict : m_tStateStack.FirstOrDefault();
string sName = name;
if (sName == "dict")
{
m_tStateStack.Pop();
m_tDictStack.Pop();
if (m_tDictStack.Count > 0)
{
m_pCurDict = m_tDictStack.FirstOrDefault();
}
}
else if (sName == "array")
{
m_tStateStack.Pop();
m_tArrayStack.Pop();
if (m_tArrayStack.Count > 0)
{
m_pArray = m_tArrayStack.FirstOrDefault();
}
}
else if (sName == "true")
{
string str = "1";
if (CCSAXState.Array == curState)
{
m_pArray.Add(str);
}
else if (CCSAXState.Dict == curState)
{
m_pCurDict.Add(m_sCurKey, str);
}
//str->release();
}
else if (sName == "false")
{
string str = "0";
if (CCSAXState.Array == curState)
{
m_pArray.Add(str);
}
else if (CCSAXState.Dict == curState)
{
m_pCurDict.Add(m_sCurKey, str);
}
//str->release();
}
m_tState = CCSAXState.None;
}
public void TextHandler(object ctx, byte[] s, int len)
{
if (m_tState == CCSAXState.None)
{
return;
}
CCSAXState curState = m_tStateStack.Count == 0 ? CCSAXState.Dict : m_tStateStack.FirstOrDefault();
string m_sString = string.Empty;
m_sString = System.Text.UTF8Encoding.UTF8.GetString(s, 0, len);
switch (m_tState)
{
case CCSAXState.Key:
m_sCurKey = m_sString;
break;
case CCSAXState.Int:
case CCSAXState.Real:
case CCSAXState.String:
Debug.Assert(m_sCurKey.Length > 0, "not found key : <integet/real>");
if (CCSAXState.Array == curState)
{
m_pArray.Add(m_sString);
}
else if (CCSAXState.Dict == curState)
{
m_pCurDict.Add(m_sCurKey, m_sString);
}
break;
default:
break;
}
//pText->release();
}
}
}
| |
//
// Mono.System.Xml.Serialization.SerializationCodeGeneratorConfiguration.cs:
//
// Author:
// Lluis Sanchez Gual (lluis@ximian.com)
//
// (C) 2002, 2003 Ximian, Inc. http://www.ximian.com
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using Mono.System.Xml.Serialization;
namespace Mono.System.Xml.Serialization
{
[XmlType ("configuration")]
internal class SerializationCodeGeneratorConfiguration
{
[XmlElement ("serializer")]
public SerializerInfo[] Serializers;
}
[XmlType ("serializer")]
internal class SerializerInfo
{
[XmlAttribute ("class")]
public string ClassName;
[XmlAttribute ("assembly")]
public string Assembly;
[XmlElement ("reader")]
public string ReaderClassName;
[XmlElement ("writer")]
public string WriterClassName;
[XmlElement ("baseSerializer")]
public string BaseSerializerClassName;
[XmlElement ("implementation")]
public string ImplementationClassName;
[XmlElement ("noreader")]
public bool NoReader;
[XmlElement ("nowriter")]
public bool NoWriter;
[XmlElement ("generateAsInternal")]
public bool GenerateAsInternal;
[XmlElement ("namespace")]
public string Namespace;
[XmlArray ("namespaceImports")]
[XmlArrayItem ("namespaceImport")]
public string [] NamespaceImports;
[global::System.ComponentModel.DefaultValue (SerializationFormat.Literal)]
public SerializationFormat SerializationFormat = SerializationFormat.Literal;
[XmlElement ("outFileName")]
public string OutFileName;
[XmlArray ("readerHooks")]
public Hook[] ReaderHooks;
[XmlArray ("writerHooks")]
public Hook[] WriterHooks;
public ArrayList GetHooks (HookType hookType, XmlMappingAccess dir, HookAction action, Type type, string member)
{
if ((dir & XmlMappingAccess.Read) != 0)
return FindHook (ReaderHooks, hookType, action, type, member);
if ((dir & XmlMappingAccess.Write) != 0)
return FindHook (WriterHooks, hookType, action, type, member);
else
throw new Exception ("INTERNAL ERROR");
}
ArrayList FindHook (Hook[] hooks, HookType hookType, HookAction action, Type type, string member)
{
ArrayList foundHooks = new ArrayList ();
if (hooks == null) return foundHooks;
foreach (Hook hook in hooks)
{
if (action == HookAction.InsertBefore && (hook.InsertBefore == null || hook.InsertBefore == ""))
continue;
else if (action == HookAction.InsertAfter && (hook.InsertAfter == null || hook.InsertAfter == ""))
continue;
else if (action == HookAction.Replace && (hook.Replace == null || hook.Replace == ""))
continue;
if (hook.HookType != hookType)
continue;
if (hook.Select != null)
{
if (hook.Select.TypeName != null && hook.Select.TypeName != "")
if (hook.Select.TypeName != type.FullName) continue;
if (hook.Select.TypeMember != null && hook.Select.TypeMember != "")
if (hook.Select.TypeMember != member) continue;
if (hook.Select.TypeAttributes != null && hook.Select.TypeAttributes.Length > 0)
{
object[] ats = type.GetCustomAttributes (true);
bool found = false;
foreach (object at in ats)
if (Array.IndexOf (hook.Select.TypeAttributes, at.GetType().FullName) != -1) { found = true; break; }
if (!found) continue;
}
}
foundHooks.Add (hook);
}
return foundHooks;
}
}
[XmlType ("hook")]
internal class Hook
{
[XmlAttribute ("type")]
public HookType HookType;
[XmlElement ("select")]
public Select Select;
[XmlElement ("insertBefore")]
public string InsertBefore;
[XmlElement ("insertAfter")]
public string InsertAfter;
[XmlElement ("replace")]
public string Replace;
public string GetCode (HookAction action)
{
if (action == HookAction.InsertBefore)
return InsertBefore;
else if (action == HookAction.InsertAfter)
return InsertAfter;
else
return Replace;
}
}
[XmlType ("select")]
internal class Select
{
[XmlElement ("typeName")]
public string TypeName;
[XmlElement("typeAttribute")]
public string[] TypeAttributes;
[XmlElement ("typeMember")]
public string TypeMember;
}
internal enum HookAction
{
InsertBefore,
InsertAfter,
Replace
}
[XmlType ("hookType")]
internal enum HookType
{
attributes,
elements,
unknownAttribute,
unknownElement,
member,
type
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// AvailablePhoneNumberCountryResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.Api.V2010.Account
{
public class AvailablePhoneNumberCountryResource : Resource
{
private static Request BuildReadRequest(ReadAvailablePhoneNumberCountryOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Api,
"/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/AvailablePhoneNumbers.json",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read AvailablePhoneNumberCountry parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of AvailablePhoneNumberCountry </returns>
public static ResourceSet<AvailablePhoneNumberCountryResource> Read(ReadAvailablePhoneNumberCountryOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<AvailablePhoneNumberCountryResource>.FromJson("countries", response.Content);
return new ResourceSet<AvailablePhoneNumberCountryResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read AvailablePhoneNumberCountry parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of AvailablePhoneNumberCountry </returns>
public static async System.Threading.Tasks.Task<ResourceSet<AvailablePhoneNumberCountryResource>> ReadAsync(ReadAvailablePhoneNumberCountryOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<AvailablePhoneNumberCountryResource>.FromJson("countries", response.Content);
return new ResourceSet<AvailablePhoneNumberCountryResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathAccountSid"> The SID of the Account requesting the available phone number Country resources
/// </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of AvailablePhoneNumberCountry </returns>
public static ResourceSet<AvailablePhoneNumberCountryResource> Read(string pathAccountSid = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadAvailablePhoneNumberCountryOptions(){PathAccountSid = pathAccountSid, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathAccountSid"> The SID of the Account requesting the available phone number Country resources
/// </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of AvailablePhoneNumberCountry </returns>
public static async System.Threading.Tasks.Task<ResourceSet<AvailablePhoneNumberCountryResource>> ReadAsync(string pathAccountSid = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadAvailablePhoneNumberCountryOptions(){PathAccountSid = pathAccountSid, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<AvailablePhoneNumberCountryResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<AvailablePhoneNumberCountryResource>.FromJson("countries", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<AvailablePhoneNumberCountryResource> NextPage(Page<AvailablePhoneNumberCountryResource> page,
ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<AvailablePhoneNumberCountryResource>.FromJson("countries", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<AvailablePhoneNumberCountryResource> PreviousPage(Page<AvailablePhoneNumberCountryResource> page,
ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<AvailablePhoneNumberCountryResource>.FromJson("countries", response.Content);
}
private static Request BuildFetchRequest(FetchAvailablePhoneNumberCountryOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Api,
"/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/AvailablePhoneNumbers/" + options.PathCountryCode + ".json",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch AvailablePhoneNumberCountry parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of AvailablePhoneNumberCountry </returns>
public static AvailablePhoneNumberCountryResource Fetch(FetchAvailablePhoneNumberCountryOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch AvailablePhoneNumberCountry parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of AvailablePhoneNumberCountry </returns>
public static async System.Threading.Tasks.Task<AvailablePhoneNumberCountryResource> FetchAsync(FetchAvailablePhoneNumberCountryOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="pathCountryCode"> The ISO country code of the country to fetch available phone number information
/// about </param>
/// <param name="pathAccountSid"> The SID of the Account requesting the available phone number Country resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of AvailablePhoneNumberCountry </returns>
public static AvailablePhoneNumberCountryResource Fetch(string pathCountryCode,
string pathAccountSid = null,
ITwilioRestClient client = null)
{
var options = new FetchAvailablePhoneNumberCountryOptions(pathCountryCode){PathAccountSid = pathAccountSid};
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="pathCountryCode"> The ISO country code of the country to fetch available phone number information
/// about </param>
/// <param name="pathAccountSid"> The SID of the Account requesting the available phone number Country resource </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of AvailablePhoneNumberCountry </returns>
public static async System.Threading.Tasks.Task<AvailablePhoneNumberCountryResource> FetchAsync(string pathCountryCode,
string pathAccountSid = null,
ITwilioRestClient client = null)
{
var options = new FetchAvailablePhoneNumberCountryOptions(pathCountryCode){PathAccountSid = pathAccountSid};
return await FetchAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a AvailablePhoneNumberCountryResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> AvailablePhoneNumberCountryResource object represented by the provided JSON </returns>
public static AvailablePhoneNumberCountryResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<AvailablePhoneNumberCountryResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The ISO-3166-1 country code of the country.
/// </summary>
[JsonProperty("country_code")]
public string CountryCode { get; private set; }
/// <summary>
/// The name of the country
/// </summary>
[JsonProperty("country")]
public string Country { get; private set; }
/// <summary>
/// The URI of the Country resource, relative to `https://api.twilio.com`
/// </summary>
[JsonProperty("uri")]
public Uri Uri { get; private set; }
/// <summary>
/// Whether all phone numbers available in the country are new to the Twilio platform.
/// </summary>
[JsonProperty("beta")]
public bool? Beta { get; private set; }
/// <summary>
/// A list of related resources identified by their relative URIs
/// </summary>
[JsonProperty("subresource_uris")]
public Dictionary<string, string> SubresourceUris { get; private set; }
private AvailablePhoneNumberCountryResource()
{
}
}
}
| |
#pragma warning disable 109, 114, 219, 429, 168, 162
public class List<T> : global::haxe.lang.HxObject, global::List
{
public List(global::haxe.lang.EmptyObject empty)
{
unchecked
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
{
}
}
#line default
}
public List()
{
unchecked
{
#line 40 "C:\\HaxeToolkit\\haxe\\std/List.hx"
global::List<object>.__hx_ctor__List<T>(this);
}
#line default
}
public static void __hx_ctor__List<T_c>(global::List<T_c> __temp_me8)
{
unchecked
{
#line 41 "C:\\HaxeToolkit\\haxe\\std/List.hx"
__temp_me8.length = 0;
}
#line default
}
public static object __hx_cast<T_c_c>(global::List me)
{
unchecked
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return ( (( me != default(global::List) )) ? (me.List_cast<T_c_c>()) : (default(global::List)) );
}
#line default
}
public static new object __hx_createEmpty()
{
unchecked
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return new global::List<object>(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
}
#line default
}
public static new object __hx_create(global::Array arr)
{
unchecked
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return new global::List<object>();
}
#line default
}
public virtual object List_cast<T_c>()
{
unchecked
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
if (global::haxe.lang.Runtime.eq(typeof(T), typeof(T_c)))
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return this;
}
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
global::List<T_c> new_me = new global::List<T_c>(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
object __temp_iterator131 = global::Reflect.fields(this).iterator();
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
while (((bool) (global::haxe.lang.Runtime.callField(__temp_iterator131, "hasNext", 407283053, default(global::Array))) ))
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
string field = global::haxe.lang.Runtime.toString(global::haxe.lang.Runtime.callField(__temp_iterator131, "next", 1224901875, default(global::Array)));
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
switch (field)
{
default:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
global::Reflect.setField(new_me, field, ((object) (global::Reflect.field(this, field)) ));
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
break;
}
}
}
}
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return new_me;
}
#line default
}
public global::Array h;
public global::Array q;
public int length;
public virtual void @add(T item)
{
unchecked
{
#line 50 "C:\\HaxeToolkit\\haxe\\std/List.hx"
global::Array x = new global::Array<object>(new object[]{item});
if (( this.h == default(global::Array) ))
{
this.h = x;
}
else
{
#line 54 "C:\\HaxeToolkit\\haxe\\std/List.hx"
this.q[1] = x;
}
this.q = x;
this.length++;
}
#line default
}
public virtual void push(T item)
{
unchecked
{
#line 68 "C:\\HaxeToolkit\\haxe\\std/List.hx"
global::Array x = new global::Array<object>(new object[]{item, this.h});
#line 70 "C:\\HaxeToolkit\\haxe\\std/List.hx"
this.h = x;
if (( this.q == default(global::Array) ))
{
this.q = x;
}
this.length++;
}
#line default
}
public virtual global::haxe.lang.Null<T> pop()
{
unchecked
{
#line 101 "C:\\HaxeToolkit\\haxe\\std/List.hx"
if (( this.h == default(global::Array) ))
{
return default(global::haxe.lang.Null<T>);
}
global::haxe.lang.Null<T> x = global::haxe.lang.Null<object>.ofDynamic<T>(this.h[0]);
this.h = ((global::Array) (this.h[1]) );
if (( this.h == default(global::Array) ))
{
this.q = default(global::Array);
}
this.length--;
return x;
}
#line default
}
public virtual void clear()
{
unchecked
{
#line 125 "C:\\HaxeToolkit\\haxe\\std/List.hx"
this.h = default(global::Array);
this.q = default(global::Array);
this.length = 0;
}
#line default
}
public virtual bool @remove(T v)
{
unchecked
{
#line 139 "C:\\HaxeToolkit\\haxe\\std/List.hx"
global::Array prev = default(global::Array);
global::Array l = this.h;
while (( l != default(global::Array) ))
{
if (global::haxe.lang.Runtime.eq(l[0], v))
{
if (( prev == default(global::Array) ))
{
this.h = ((global::Array) (l[1]) );
}
else
{
#line 146 "C:\\HaxeToolkit\\haxe\\std/List.hx"
prev[1] = l[1];
}
if (( this.q == l ))
{
this.q = prev;
}
this.length--;
return true;
}
#line 152 "C:\\HaxeToolkit\\haxe\\std/List.hx"
prev = l;
l = ((global::Array) (l[1]) );
}
#line 155 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return false;
}
#line default
}
public virtual object iterator()
{
unchecked
{
#line 163 "C:\\HaxeToolkit\\haxe\\std/List.hx"
global::Array<object> h = new global::Array<object>(new object[]{this.h});
object __temp_stmt242 = default(object);
#line 164 "C:\\HaxeToolkit\\haxe\\std/List.hx"
{
global::haxe.lang.Function __temp_odecl240 = new global::List_iterator_165__Fun(((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (h) ))) ));
#line 168 "C:\\HaxeToolkit\\haxe\\std/List.hx"
global::haxe.lang.Function __temp_odecl241 = new global::List_iterator_168__Fun(((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (h) ))) ));
#line 164 "C:\\HaxeToolkit\\haxe\\std/List.hx"
__temp_stmt242 = new global::haxe.lang.DynamicObject(new global::Array<int>(new int[]{407283053, 1224901875}), new global::Array<object>(new object[]{__temp_odecl240, __temp_odecl241}), new global::Array<int>(new int[]{}), new global::Array<double>(new double[]{}));
}
#line 164 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return ((object) (__temp_stmt242) );
}
#line default
}
public override double __hx_setField_f(string field, int hash, double @value, bool handleProperties)
{
unchecked
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
switch (hash)
{
case 520590566:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
this.length = ((int) (@value) );
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return @value;
}
default:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return base.__hx_setField_f(field, hash, @value, handleProperties);
}
}
}
#line default
}
public override object __hx_setField(string field, int hash, object @value, bool handleProperties)
{
unchecked
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
switch (hash)
{
case 520590566:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
this.length = ((int) (global::haxe.lang.Runtime.toInt(@value)) );
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return @value;
}
case 113:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
this.q = ((global::Array) (@value) );
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return @value;
}
case 104:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
this.h = ((global::Array) (@value) );
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return @value;
}
default:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return base.__hx_setField(field, hash, @value, handleProperties);
}
}
}
#line default
}
public override object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties)
{
unchecked
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
switch (hash)
{
case 328878574:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("iterator"), ((int) (328878574) ))) );
}
case 76061764:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("remove"), ((int) (76061764) ))) );
}
case 1213952397:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("clear"), ((int) (1213952397) ))) );
}
case 5594513:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("pop"), ((int) (5594513) ))) );
}
case 1247875546:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("push"), ((int) (1247875546) ))) );
}
case 4846113:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("add"), ((int) (4846113) ))) );
}
case 520590566:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return this.length;
}
case 113:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return this.q;
}
case 104:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return this.h;
}
default:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return base.__hx_getField(field, hash, throwErrors, isCheck, handleProperties);
}
}
}
#line default
}
public override double __hx_getField_f(string field, int hash, bool throwErrors, bool handleProperties)
{
unchecked
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
switch (hash)
{
case 520590566:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return ((double) (this.length) );
}
default:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return base.__hx_getField_f(field, hash, throwErrors, handleProperties);
}
}
}
#line default
}
public override object __hx_invokeField(string field, int hash, global::Array dynargs)
{
unchecked
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
switch (hash)
{
case 328878574:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return this.iterator();
}
case 76061764:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return this.@remove(global::haxe.lang.Runtime.genericCast<T>(dynargs[0]));
}
case 1213952397:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
this.clear();
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
break;
}
case 5594513:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return (this.pop()).toDynamic();
}
case 1247875546:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
this.push(global::haxe.lang.Runtime.genericCast<T>(dynargs[0]));
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
break;
}
case 4846113:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
this.@add(global::haxe.lang.Runtime.genericCast<T>(dynargs[0]));
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
break;
}
default:
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return base.__hx_invokeField(field, hash, dynargs);
}
}
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return default(object);
}
#line default
}
public override void __hx_getFields(global::Array<object> baseArr)
{
unchecked
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
baseArr.push("length");
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
baseArr.push("q");
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
baseArr.push("h");
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
{
#line 27 "C:\\HaxeToolkit\\haxe\\std/List.hx"
base.__hx_getFields(baseArr);
}
}
#line default
}
}
#pragma warning disable 109, 114, 219, 429, 168, 162
public class List_iterator_165__Fun : global::haxe.lang.Function
{
public List_iterator_165__Fun(global::Array<object> h) : base(0, 0)
{
unchecked
{
#line 166 "C:\\HaxeToolkit\\haxe\\std/List.hx"
this.h = h;
}
#line default
}
public override object __hx_invoke0_o()
{
unchecked
{
#line 166 "C:\\HaxeToolkit\\haxe\\std/List.hx"
return ( ((global::Array) (this.h[0]) ) != default(global::Array) );
}
#line default
}
public global::Array<object> h;
}
#pragma warning disable 109, 114, 219, 429, 168, 162
public class List_iterator_168__Fun : global::haxe.lang.Function
{
public List_iterator_168__Fun(global::Array<object> h) : base(0, 0)
{
unchecked
{
#line 169 "C:\\HaxeToolkit\\haxe\\std/List.hx"
this.h = h;
}
#line default
}
public override object __hx_invoke0_o()
{
unchecked
{
#line 170 "C:\\HaxeToolkit\\haxe\\std/List.hx"
if (( ((global::Array) (this.h[0]) ) == default(global::Array) ))
{
return default(object);
}
object x = ((global::Array) (this.h[0]) )[0];
this.h[0] = ((global::Array) (this.h[0]) )[1];
return x;
}
#line default
}
public global::Array<object> h;
}
#pragma warning disable 109, 114, 219, 429, 168, 162
public interface List : global::haxe.lang.IHxObject, global::haxe.lang.IGenericObject
{
object List_cast<T_c>();
}
| |
function AssetBrowser_editAsset::saveAsset(%this)
{
%file = AssetDatabase.getAssetFilePath(%this.editedAssetId);
%success = TamlWrite(AssetBrowser_editAsset.editedAsset, %file);
AssetBrowser.loadFilters();
Canvas.popDialog(AssetBrowser_editAsset);
}
function AssetBrowser::editAsset(%this)
{
//Find out what type it is
%assetDef = AssetDatabase.acquireAsset(EditAssetPopup.assetId);
%assetType = %assetDef.getClassName();
if(%assetType $= "MaterialAsset")
{
//if(EditorSettings.materialEditMode $= "MaterialEditor")
//{
%assetDef.materialDefinitionName.reload();
EditorGui.setEditor(MaterialEditorPlugin);
MaterialEditorGui.currentMaterial = %assetDef.materialDefinitionName;
MaterialEditorGui.setActiveMaterial( %assetDef.materialDefinitionName );
AssetBrowser.hideDialog();
/*}
else
{
Canvas.pushDialog(ShaderEditor);
ShaderEditorGraph.loadGraph(%assetDef.shaderGraph);
$ShaderGen::targetShaderFile = filePath(%assetDef.shaderGraph) @"/"@fileBase(%assetDef.shaderGraph);
}*/
}
else if(%assetType $= "StateMachineAsset")
{
eval("AssetBrowser.tempAsset = new " @ %assetDef.getClassName() @ "();");
AssetBrowser.tempAsset.assignFieldsFrom(%assetDef);
SMAssetEditInspector.inspect(AssetBrowser.tempAsset);
AssetBrowser_editAsset.editedAssetId = EditAssetPopup.assetId;
AssetBrowser_editAsset.editedAsset = AssetBrowser.tempAsset;
//remove some of the groups we don't need:
for(%i=0; %i < SMAssetEditInspector.getCount(); %i++)
{
%caption = SMAssetEditInspector.getObject(%i).caption;
if(%caption $= "Ungrouped" || %caption $= "Object" || %caption $= "Editing"
|| %caption $= "Persistence" || %caption $= "Dynamic Fields")
{
SMAssetEditInspector.remove(SMAssetEditInspector.getObject(%i));
%i--;
}
}
Canvas.pushDialog(StateMachineEditor);
StateMachineEditor.loadStateMachineAsset(EditAssetPopup.assetId);
StateMachineEditor-->Window.text = "State Machine Editor ("@EditAssetPopup.assetId@")";
}
else if(%assetType $= "ComponentAsset")
{
%assetDef = AssetDatabase.acquireAsset(EditAssetPopup.assetId);
%scriptFile = %assetDef.scriptFile;
EditorOpenFileInTorsion(makeFullPath(%scriptFile), 0);
}
else if(%assetType $= "GameObjectAsset")
{
%assetDef = AssetDatabase.acquireAsset(EditAssetPopup.assetId);
%scriptFile = %assetDef.scriptFilePath;
EditorOpenFileInTorsion(makeFullPath(%scriptFile), 0);
}
else if(%assetType $= "ScriptAsset")
{
%assetDef = AssetDatabase.acquireAsset(EditAssetPopup.assetId);
%scriptFile = %assetDef.scriptFilePath;
EditorOpenFileInTorsion(makeFullPath(%scriptFile), 0);
}
else if(%assetType $= "ShapeAsset")
{
%this.hideDialog();
ShapeEditorPlugin.openShapeAsset(EditAssetPopup.assetId);
}
else if(%assetType $= "ShapeAnimationAsset")
{
%this.hideDialog();
ShapeEditorPlugin.openShapeAsset(EditAssetPopup.assetId);
}
else if(%assetType $= "LevelAsset")
{
schedule( 1, 0, "EditorOpenMission", %assetDef.LevelFile);
}
else if(%assetType $= "GUIAsset")
{
if(!isObject(%assetDef.assetName))
{
exec(%assetDef.GUIFilePath);
exec(%assetDef.mScriptFilePath);
}
GuiEditContent(%assetDef.assetName);
}
}
function AssetBrowser::editAssetInfo(%this)
{
Canvas.pushDialog(AssetBrowser_editAsset);
%assetDef = AssetDatabase.acquireAsset(EditAssetPopup.assetId);
eval("AssetBrowser.tempAsset = new " @ %assetDef.getClassName() @ "();");
AssetBrowser.tempAsset.assignFieldsFrom(%assetDef);
AssetEditInspector.inspect(AssetBrowser.tempAsset);
AssetBrowser_editAsset.editedAssetId = EditAssetPopup.assetId;
AssetBrowser_editAsset.editedAsset = AssetBrowser.tempAsset;
//remove some of the groups we don't need:
for(%i=0; %i < AssetEditInspector.getCount(); %i++)
{
%caption = AssetEditInspector.getObject(%i).caption;
if(%caption $= "Ungrouped" || %caption $= "Object" || %caption $= "Editing"
|| %caption $= "Persistence" || %caption $= "Dynamic Fields")
{
AssetEditInspector.remove(AssetEditInspector.getObject(%i));
%i--;
}
}
}
//------------------------------------------------------------
function AssetBrowser::refreshAsset(%this, %assetId)
{
if(%assetId $= "")
{
//if we have no passed-in asset ID, we're probably going through the popup menu, so get our edit popup id
%assetId = EditAssetPopup.assetId;
}
AssetDatabase.refreshAsset(%assetId);
AssetBrowser.refreshPreviews();
}
//------------------------------------------------------------
function AssetBrowser::renameAsset(%this)
{
//Find out what type it is
%assetDef = AssetDatabase.acquireAsset(EditAssetPopup.assetId);
%curFirstResponder = AssetBrowser.getFirstResponder();
if(%curFirstResponder != 0)
%curFirstResponder.clearFirstResponder();
AssetBrowser.selectedAssetPreview-->AssetNameLabel.setActive(true);
AssetBrowser.selectedAssetPreview-->AssetNameLabel.setFirstResponder();
}
function AssetNameField::onReturn(%this)
{
//if the name is different to the asset's original name, rename it!
%newName = %this.getText();
if(%this.originalAssetName !$= %this.getText())
{
%moduleName = AssetBrowser.selectedModule;
//do a rename!
%success = AssetDatabase.renameDeclaredAsset(%moduleName @ ":" @ %this.originalAssetName, %moduleName @ ":" @ %this.getText());
if(%success)
{
%newAssetId = %moduleName @ ":" @ %this.getText();
%assetPath = AssetDatabase.getAssetFilePath(%newAssetId);
//Rename any associated files as well
%assetDef = AssetDatabase.acquireAsset(%newAssetId);
%assetType = %assetDef.getClassName();
//rename the file to match
%path = filePath(%assetPath);
if(%assetType $= "ComponentAsset")
{
%oldScriptFilePath = %assetDef.scriptFile;
%scriptFilePath = filePath(%assetDef.scriptFile);
%scriptExt = fileExt(%assetDef.scriptFile);
%newScriptFileName = %scriptFilePath @ "/" @ %newName @ %scriptExt;
%newAssetFile = %path @ "/" @ %this.getText() @ ".asset.taml";
%assetDef.componentName = %newName;
%assetDef.scriptFile = %newScriptFileName;
TamlWrite(%assetDef, %newAssetFile);
fileDelete(%assetPath);
pathCopy(%oldScriptFilePath, %newScriptFileName);
fileDelete(%oldScriptFilePath);
//Go through our scriptfile and replace the old namespace with the new
%editedFileContents = "";
%file = new FileObject();
if ( %file.openForRead( %newScriptFileName ) )
{
while ( !%file.isEOF() )
{
%line = %file.readLine();
%line = trim( %line );
%editedFileContents = %editedFileContents @ strreplace(%line, %this.originalAssetName, %newName) @ "\n";
}
%file.close();
}
if(%editedFileContents !$= "")
{
%file.openForWrite(%newScriptFileName);
%file.writeline(%editedFileContents);
%file.close();
}
exec(%newScriptFileName);
}
else if(%assetType $= "StateMachineAsset")
{
%oldScriptFilePath = %assetDef.stateMachineFile;
%scriptFilePath = filePath(%assetDef.stateMachineFile);
%scriptExt = fileExt(%assetDef.stateMachineFile);
%newScriptFileName = %scriptFilePath @ "/" @ %newName @ %scriptExt;
%newAssetFile = %path @ "/" @ %this.getText() @ ".asset.taml";
%assetDef.stateMachineFile = %newScriptFileName;
TamlWrite(%assetDef, %newAssetFile);
fileDelete(%assetPath);
pathCopy(%oldScriptFilePath, %newScriptFileName);
fileDelete(%oldScriptFilePath);
}
else if(%assetType $= "GameObjectAsset")
{
%oldScriptFilePath = %assetDef.scriptFilePath;
%scriptFilePath = filePath(%assetDef.scriptFilePath);
%scriptExt = fileExt(%assetDef.scriptFilePath);
%oldGOFilePath = %assetDef.TAMLFilePath;
%newScriptFileName = %scriptFilePath @ "/" @ %newName @ %scriptExt;
%newAssetFile = %path @ "/" @ %this.getText() @ ".asset.taml";
%newGOFile = %path @ "/" @ %this.getText() @ ".taml";
%assetDef.gameObjectName = %newName;
%assetDef.scriptFilePath = %newScriptFileName;
%assetDef.TAMLFilePath = %newGOFile;
TamlWrite(%assetDef, %newAssetFile);
fileDelete(%assetPath);
pathCopy(%oldScriptFilePath, %newScriptFileName);
fileDelete(%oldScriptFilePath);
pathCopy(%oldGOFilePath, %newGOFile);
fileDelete(%oldGOFilePath);
//Go through our scriptfile and replace the old namespace with the new
%editedFileContents = "";
%file = new FileObject();
if ( %file.openForRead( %newScriptFileName ) )
{
while ( !%file.isEOF() )
{
%line = %file.readLine();
%line = trim( %line );
%editedFileContents = %editedFileContents @ strreplace(%line, %this.originalAssetName, %newName) @ "\n";
}
%file.close();
}
if(%editedFileContents !$= "")
{
%file.openForWrite(%newScriptFileName);
%file.writeline(%editedFileContents);
%file.close();
}
exec(%newScriptFileName);
//Rename in the TAML file as well
%file = new FileObject();
if ( %file.openForRead( %newGOFile ) )
{
while ( !%file.isEOF() )
{
%line = %file.readLine();
%line = trim( %line );
%editedFileContents = %editedFileContents @ strreplace(%line, %this.originalAssetName, %newName) @ "\n";
}
%file.close();
}
if(%editedFileContents !$= "")
{
%file.openForWrite(%newGOFile);
%file.writeline(%editedFileContents);
%file.close();
}
}
}
}
%this.clearFirstResponder();
%this.setActive(false);
}
//------------------------------------------------------------
function AssetBrowser::duplicateAsset(%this)
{
%assetDef = AssetDatabase.acquireAsset(EditAssetPopup.assetId);
%this.setupCreateNewAsset(%assetDef.getClassName(), AssetBrowser.selectedModule);
}
function AssetBrowser::deleteAsset(%this)
{
//Find out what type it is
%assetDef = AssetDatabase.acquireAsset(EditAssetPopup.assetId);
%assetType = %assetDef.getClassName();
MessageBoxOKCancel("Warning!", "This will delete the selected asset and the files associated to it, do you wish to continue?",
"AssetBrowser.confirmDeleteAsset();", "");
}
function AssetBrowser::confirmDeleteAsset(%this)
{
%currentSelectedItem = AssetBrowserFilterTree.getSelectedItem();
%currentItemParent = AssetBrowserFilterTree.getParentItem(%currentSelectedItem);
AssetDatabase.deleteAsset(EditAssetPopup.assetId, false);
%this.loadFilters();
if(!AssetBrowserFilterTree.selectItem(%currentSelectedItem))
{
//if it failed, that means we deleted the last item in that category, and we need to do the parent
AssetBrowserFilterTree.selectItem(%currentItemParent);
AssetBrowserFilterTree.expandItem(%currentItemParent);
}
}
| |
//KKM4 added this comment for testing
using System;
using System.Collections.Generic;
using System.Data;
using Epi.DataSets;
using Epi.Fields;
using VariableCollection = Epi.Collections.NamedObjectCollection<Epi.IVariable>;
namespace Epi
{
/// <summary>
/// Class MemoryRegion
/// </summary>
public class MemoryRegion : IMemoryRegion
{
private class LocalBlockVariableCollection : VariableCollection
{
}
/// <summary>
/// syncLock
/// </summary>
protected static object syncLock = new object();
private static bool staticInitalized = false;
private static VariableCollection systemVariables;
private static VariableCollection permanentVariables;
/// <summary>
/// Global Variables
/// </summary>
protected VariableCollection globalVariables;
/// <summary>
/// Local Variable Stack
/// </summary>
protected Stack<VariableCollection> localVariableStack;
/// <summary>
/// Configuration Updated EventHandler
/// </summary>
protected EventHandler configurationUpdated;
/// <summary>
/// Constructor
/// </summary>
public MemoryRegion()
{
lock (syncLock)
{
if (!staticInitalized)
{
LoadPermanentVariables();
//LoadSystemVariables();
configurationUpdated = new EventHandler(MemoryRegion.ConfigurationUpdated);
staticInitalized = true;
}
}
localVariableStack = new Stack<VariableCollection>();
globalVariables = new VariableCollection();
PushLocalRegion();
}
private static void DeletePermanentVariable(string variableName)
{
Configuration config = Configuration.GetNewInstance();
DataRow[] result = config.PermanentVariables.Select("Name='" + variableName + "'");
if (result.Length != 1)
{
throw new ConfigurationException(ConfigurationException.ConfigurationIssue.ContentsInvalid);
}
result[0].Delete();
Configuration.Save(config);
}
public static void UpdatePermanentVariable(IVariable variable)
{
Configuration config = Configuration.GetNewInstance();
DataRow[] result = config.PermanentVariables.Select("Name='" + variable.Name + "'");
if (result.Length < 1)
{
config.PermanentVariables.AddPermanentVariableRow(
variable.Name,
variable.Expression ?? "",
(int)variable.DataType,
config.ParentRowPermanentVariables);
}
else if (result.Length == 1)
{
((DataSets.Config.PermanentVariableRow)result[0]).DataValue = variable.Expression ?? "";
((DataSets.Config.PermanentVariableRow)result[0]).DataType = (int)variable.DataType;
}
else
{
throw new ConfigurationException(ConfigurationException.ConfigurationIssue.ContentsInvalid, "Duplicate permanent variable rows encountered.");
}
Configuration.Save(config);
}
/// <summary>
/// GetVariablesInScope()
/// </summary>
/// <param name="scopeCombination">The logically ORed scopes to be included</param>
/// <returns>VariableCollection</returns>
public VariableCollection GetVariablesInScope(VariableType scopeCombination)
{
VariableCollection shortList = new VariableCollection();
VariableCollection masterList = GetVariablesInScope();
foreach (IVariable variable in masterList)
{
if ((variable.VarType & scopeCombination) > 0)
{
shortList.Add(variable);
}
}
return shortList;
}
/// <summary>
/// Returns a list of all standard variables.
/// </summary>
/// <returns></returns>
public List<ISetBasedVariable> GetStandardVariables()
{
List<ISetBasedVariable> vars = new List<ISetBasedVariable>();
VariableCollection varsInScope = GetVariablesInScope(VariableType.Standard);
foreach (IVariable var in varsInScope)
{
vars.Add(var as ISetBasedVariable);
}
return vars;
}
/// <summary>
/// Returns a list of all data source variables.
/// </summary>
/// <returns></returns>
public List<ISetBasedVariable> GetDataSourceVariables()
{
List<ISetBasedVariable> vars = new List<ISetBasedVariable>();
VariableCollection varsInScope = GetVariablesInScope(VariableType.DataSource);
foreach (IVariable var in varsInScope)
{
vars.Add(var as ISetBasedVariable);
}
return vars;
}
/// <summary>
/// Returns a list of all Data source redefined variables.
/// </summary>
/// <returns></returns>
public List<ISetBasedVariable> GetDataSourceRedefinedVariables()
{
List<ISetBasedVariable> vars = new List<ISetBasedVariable>();
VariableCollection varsInScope = GetVariablesInScope(VariableType.DataSourceRedefined);
foreach (IVariable var in varsInScope)
{
vars.Add(var as ISetBasedVariable);
}
return vars;
}
/// <summary>
/// Returns a list of all standard variables.
/// </summary>
/// <returns></returns>
public List<IScalarVariable> GetGlobalVariables()
{
List<IScalarVariable> vars = new List<IScalarVariable>();
VariableCollection varsInScope = GetVariablesInScope(VariableType.Global);
foreach (IVariable var in varsInScope)
{
vars.Add(var as IScalarVariable);
}
return vars;
}
/// <summary>
/// Returns a list of all standard variables.
/// </summary>
/// <returns></returns>
public List<IScalarVariable> GetPermanentVariables()
{
List<IScalarVariable> vars = new List<IScalarVariable>();
VariableCollection varsInScope = GetVariablesInScope(VariableType.Permanent);
foreach (IVariable var in varsInScope)
{
vars.Add(var as IScalarVariable);
}
return vars;
}
/// <summary>
/// GetVariablesInScope()
/// </summary>
/// <remarks> Returns all variables, regardless of scope or type</remarks>
/// <returns>VariableCollection</returns>
public VariableCollection GetVariablesInScope()
{
VariableCollection result;
lock (syncLock)
{
VariableCollection localVariables = new VariableCollection();
if (localVariableStack.Peek() is LocalBlockVariableCollection)
{
VariableCollection[] locals = new VariableCollection[localVariableStack.Count];
localVariableStack.CopyTo(locals, 0);
for (int i = 0; i < locals.Length; i++)
{
localVariables = CombineCollections(localVariables, locals[i]);
if (!(locals[i] is LocalBlockVariableCollection))
{
break;
}
}
}
else
{
localVariables = localVariableStack.Peek();
}
result = CombineCollections(systemVariables, permanentVariables, globalVariables, localVariables);
}
return result;
}
/// <summary>
/// dcs0 8/9/2007
/// Gets all the variables as a datatable
/// </summary>
/// <returns>Newly constructed DataTable with appropriate columns</returns>
private DataTable CreateAllVariablesTable()
{
DataTable dt = new DataTable();
dt.Columns.Add(ColumnNames.NAME, typeof(string));
dt.Columns.Add(ColumnNames.VARIABLE_SCOPE, typeof(Int16));
dt.Columns.Add(ColumnNames.DATA_TABLE_NAME, typeof(string));
dt.Columns.Add(ColumnNames.FIELD_TYPE_ID, typeof(Int16));
dt.Columns.Add(ColumnNames.DATA_TYPE, typeof(Int16));
dt.Columns.Add(ColumnNames.VARIABLE_VALUE, typeof(string));
dt.Columns.Add(ColumnNames.ADDITIONAL_INFO, typeof(string));
dt.Columns.Add(ColumnNames.PROMPT, typeof(string));
return dt;
}
private DataRow AddRow(DataTable table, IVariable var)
{
DataRow row = table.NewRow();
row[ColumnNames.NAME] = var.Name;
row[ColumnNames.DATA_TYPE] = var.DataType;
row[ColumnNames.VARIABLE_SCOPE] = var.VarType;
row[ColumnNames.VARIABLE_VALUE] = var.Expression;
row[ColumnNames.ADDITIONAL_INFO] = string.Empty;
row[ColumnNames.PROMPT] = string.Empty;
// Data source variables have an extra piece of information: Table name
if (var is IDataSourceVariable)
{
IDataSourceVariable dataSourceVar = var as IDataSourceVariable;
row[ColumnNames.DATA_TABLE_NAME] = dataSourceVar.TableName;
}
// Data field variables know the field type.
if (var is IDataField)
{
IDataField dataField = var as IDataField;
row[ColumnNames.FIELD_TYPE_ID] = dataField.FieldType;
}
table.Rows.Add(row);
return row;
}
/// <summary>
/// GetVariablesAsDataTable()
/// </summary>
/// <param name="scopeCombination"></param>
/// <returns>DataTable</returns>
public DataTable GetVariablesAsDataTable(VariableType scopeCombination)
{
//TODO: HERE
VariableCollection allVariables = GetVariablesInScope(scopeCombination);
DataTable variablesDataTable = CreateAllVariablesTable();
DataRow newRow = null;
foreach (IVariable variable in allVariables)
{
if (variable.IsVarType(scopeCombination))
{
newRow = AddRow(variablesDataTable, variable);
if (variable.IsVarType(VariableType.DataSource))
{
string tableName = ((IDataSourceVariable)variable).TableName;
tableName = (tableName == null) ? string.Empty : tableName;
newRow[ColumnNames.DATA_TABLE_NAME] = tableName;
}
else
{
newRow[ColumnNames.DATA_TABLE_NAME] = SharedStrings.DEFINED_VARIABLE;
}
}
}
return variablesDataTable;
}
/// <summary>
/// IsVariableInScope()
/// </summary>
/// <param name="varName"></param>
/// <returns>bool</returns>
public bool IsVariableInScope(string varName)
{
return GetVariablesInScope().Contains(varName);
}
/// <summary>
/// UndefineVariable()
/// </summary>
/// <param name="varName"></param>
public void UndefineVariable(string varName)
{
if (localVariableStack.Peek().Contains(varName))
{
localVariableStack.Peek().Remove(varName);
}
else if (globalVariables.Contains(varName))
{
globalVariables.Remove(varName);
}
else
{
lock (syncLock)
{
if (permanentVariables.Contains(varName))
{
DeletePermanentVariable(varName);
permanentVariables.Remove(varName);
}
//else if (systemVariables.Contains(varName))
//{
// throw new GeneralException(string.Format("System variable '{0}' cannot be undefined.", varName));
//}
//else
//{
// throw new GeneralException(string.Format("Variable '{0}' is not defined.", varName));
//}
}
}
}
/// <summary>
/// DefineVariable()
/// </summary>
/// <param name="variable"></param>
public void DefineVariable(IVariable variable)
{
if (IsVariableInScope(variable.Name))
{
//throw new GeneralException(string.Format("Variable '{0}' is already defined.", variable.Name));
}
else
{
if (variable.VarType == VariableType.Permanent)
{
DefinePermanentVariable(variable);
LoadPermanentVariables();
}
else if (variable.VarType == VariableType.System)
{
DefineSystemVariable(variable);
}
else if (variable.VarType == VariableType.Global)
{
globalVariables.Add(variable);
}
else // Standard, DataSource or DataSourceRedefined variables
{
VariableCollection localVariables = localVariableStack.Peek();
localVariables.Add(variable);
}
}
}
private static void DefinePermanentVariable(IVariable variable)
{
lock (syncLock)
{
UpdatePermanentVariable(variable);
permanentVariables.Add(variable);
}
}
private static void DefineSystemVariable(IVariable variable)
{
lock (syncLock)
{
systemVariables.Add(variable);
}
}
/// <summary>
/// Removes all variables of the given types.
/// </summary>
/// <param name="varTypes"></param>
public void RemoveVariablesInScope(VariableType varTypes)
{
VariableCollection vars = GetVariablesInScope(varTypes);
foreach (IVariable var in vars)
{
UndefineVariable(var.Name);
}
}
/// <summary>
/// Try to get a given variable
/// </summary>
/// <param name="varName">The name of the variable</param>
/// <param name="var">The variable</param>
/// <returns>bool</returns>
public bool TryGetVariable(string varName, out IVariable var)
{
var = null;
try
{
if (localVariableStack.Peek().Contains(varName))
{
var = localVariableStack.Peek()[varName];
}
else if (globalVariables.Contains(varName))
{
var = globalVariables[varName];
}
else
{
lock (syncLock)
{
if (permanentVariables.Contains(varName))
{
var = permanentVariables[varName];
}
else /*if (systemVariables.Contains(varName))
{
var = systemVariables[varName];
}
else*/
{
return false;
}
}
}
}
catch
{
return false;
}
return true;
}
/// <summary>
/// Get a given variable
/// </summary>
/// <param name="varName">The name of the variable</param>
/// <returns>IVariable</returns>
public IVariable GetVariable(string varName)
{
IVariable var = null;
if (localVariableStack.Peek().Contains(varName))
{
return localVariableStack.Peek()[varName];
}
else if (globalVariables.Contains(varName))
{
var = globalVariables[varName];
}
else
{
lock (syncLock)
{
if (permanentVariables.Contains(varName))
{
var = permanentVariables[varName];
}
else if (systemVariables != null && systemVariables.Contains(varName))
{
var = systemVariables[varName];
}
else
{
// throw new GeneralException(string.Format("Variable '{0}' is not defined.", varName));
}
}
}
return var;
}
/// <summary>
/// CombineCollections
/// </summary>
/// <remarks>
/// Null parameters are allowed
/// </remarks>
/// <param name="collections">Collections</param>
/// <returns>VariableCollection</returns>
private static VariableCollection CombineCollections(params VariableCollection[] collections)
{
VariableCollection combinedCollection = new VariableCollection();
foreach (VariableCollection col in collections)
{
if (col != null)
{
combinedCollection.Add(col);
}
}
return combinedCollection;
}
/// <summary>
/// Push the Local Region onto the stack
/// </summary>
public void PushLocalRegion()
{
localVariableStack.Push(new VariableCollection());
}
/// <summary>
/// Push the Local Block Region onto the stack
/// </summary>
public void PushLocalBlockRegion()
{
localVariableStack.Push(new LocalBlockVariableCollection());
}
/// <summary>
/// PopRegion()
/// </summary>
/// <remarks>
/// Pop the region off the stack
/// </remarks>
public void PopRegion()
{
if (localVariableStack.Count > 1)
{
localVariableStack.Pop();
}
else
{
throw new GeneralException("Root local variable stack cannot be popped off the local memory stack.");
}
}
private static void ConfigurationUpdated(object sender, EventArgs e)
{
LoadPermanentVariables();
}
private static void LoadPermanentVariables()
{
lock (syncLock)
{
MemoryRegion.permanentVariables = new VariableCollection();
Configuration config = Configuration.GetNewInstance();
foreach (Config.PermanentVariableRow row in config.PermanentVariables)
{
DefinePermanentVariable(new PermanentVariable(row));
}
}
}
private static void LoadSystemVariables()
{
lock (syncLock)
{
MemoryRegion.systemVariables = new VariableCollection();
foreach (IVariable variable in GetSystemVariables())
{
DefineSystemVariable(variable);
}
}
}
private static VariableCollection GetSystemVariables()
{
VariableCollection list = new VariableCollection();
string[] names = Enum.GetNames(typeof(SystemVariables));
foreach (string variableName in names)
{
list.Add(GetSystemVariable(variableName));
}
return list;
}
private static IVariable GetSystemVariable(string variableName)
{
IVariable target = null;
if (Enum.IsDefined(typeof(SystemVariables), variableName))
{
SystemVariables targetType = (SystemVariables)Enum.Parse(typeof(SystemVariables), variableName);
Type type = typeof(MemoryRegion).GetNestedType(variableName, System.Reflection.BindingFlags.NonPublic);
target = (IVariable)Activator.CreateInstance(type);
}
else
{
// look up from plugin =)
}
return target;
}
/*
#region SYSTEMDATE
private class SYSTEMDATE : VariableBase, ISystemVariable
{
public SYSTEMDATE()
: base("SYSTEMDATE", DataType.Date, VariableType.System)
{
}
public string Value
{
get
{
return DateTime.Now.ToShortDateString();
}
}
}
#endregion
#region SYSTEMTIME
private class SYSTEMTIME : VariableBase, ISystemVariable
{
public SYSTEMTIME()
: base("SYSTEMTIME", DataType.Date, VariableType.System)
{
}
public override string Expression
{
get
{
return DateTime.Now.ToShortTimeString();
}
set
{
throw new NotSupportedException();
}
}
public string Value
{
get
{
return Expression;
}
}
}
#endregion*/
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
// ERROR: Not supported in C#: OptionDeclaration
namespace _4PosBackOffice.NET
{
internal partial class frmPricelistFilterItem : System.Windows.Forms.Form
{
int gID;
List<Button> cmdClick = new List<Button>();
int[,] dataArray;
private void loadLanguage()
{
//frmPricelistFilterItem = No Code [Allocate Stock Items to Pricelist]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then frmPricelistFilterItem.Caption = rsLang("LanguageLayoutLnk_Description"): frmPricelistFilterItem.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//lblHeading = No Code/Dynamic!
//TOOLBAR CODE NOT DONE!!!
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1080;
//Search|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|Checked
if (modRecordSet.rsLang.RecordCount){cmdExit.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdExit.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmPricelistFilterItem.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
private void cmdClick_Click(System.Object eventSender, System.EventArgs eventArgs)
{
//Dim Index As Short = cmdClick.GetIndex(eventSender)
int Index = 0;
Button n = new Button();
n = (Button)eventSender;
Index = GetIndex.GetIndexer(ref n, ref cmdClick);
tbStockItem_ButtonClick(this.tbStockItem.Items[Index], new System.EventArgs());
lstStockItem.Focus();
}
private void cmdExit_Click(System.Object eventSender, System.EventArgs eventArgs)
{
this.Close();
}
public void loadItem(ref int id)
{
short x = 0;
ADODB.Recordset rs = default(ADODB.Recordset);
gID = id;
rs = modRecordSet.getRS(ref "SELECT Pricelist_Name FROM PricelistFilter WHERE PricelistID = " + gID);
if (rs.BOF | rs.EOF) {
} else {
lblHeading.Text = rs.Fields("Pricelist_Name").Value;
rs = modRecordSet.getRS(ref "SELECT TOP 100 PERCENT StockItem.StockItemID, StockItem.StockItem_Name FROM StockItem ORDER BY StockItem_Name;");
dataArray = new int[rs.RecordCount + 1, 3];
x = -1;
while (!(rs.EOF)) {
x = x + 1;
dataArray[x, 0] = rs.Fields("StockItemID").Value;
//UPGRADE_WARNING: Couldn't resolve default property of object x. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
//UPGRADE_WARNING: Couldn't resolve default property of object dataArray(x, 1). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
dataArray[x, 1] = rs.Fields("StockItem_Name").Value;
dataArray[x, 2] = false;
rs.moveNext();
}
rs = modRecordSet.getRS(ref "SELECT PricelistFilterStockItemLnk.PricelistStockItemLnk_StockItemID From PricelistFilterStockItemLnk WHERE (((PricelistFilterStockItemLnk.PricelistStockItemLnk_PricelistID)=" + gID + "));");
while (!(rs.EOF)) {
for (x = Information.LBound(dataArray); x <= Information.UBound(dataArray); x++) {
if (dataArray[x, 0] == rs.Fields("PricelistStockItemLnk_StockItemID").Value) {
dataArray[x, 2] = true;
}
}
rs.moveNext();
}
doLoad();
loadLanguage();
ShowDialog();
}
}
private void doLoad()
{
short x = 0;
bool loading = false;
string tmpString = null;
loading = true;
lstStockItem.Visible = false;
this.lstStockItem.Items.Clear();
int m = 0;
switch (this.tbStockItem.Tag) {
case Convert.ToString(1):
for (x = 0; x <= Information.UBound(dataArray) - 1; x++) {
if (dataArray[x, 2]) {
if (Strings.InStr(Strings.UCase(dataArray[x, 1]), Strings.UCase(this.txtSearch.Text))) {
tmpString = dataArray[x, 1] + " " + x.ToString();
m = lstStockItem.Items.Add(tmpString);
lstStockItem.SetItemChecked(m, dataArray[x, 2]);
}
}
}
break;
case Convert.ToString(2):
for (x = 0; x <= Information.UBound(dataArray) - 1; x++) {
if (dataArray[x, 2]) {
} else {
if (Strings.InStr(Strings.UCase(dataArray[x, 1]), Strings.UCase(this.txtSearch.Text))) {
tmpString = dataArray[x, 1] + " " + x.ToString();
m = lstStockItem.Items.Add(tmpString);
lstStockItem.SetItemChecked(m, dataArray[x, 2]);
}
}
}
break;
default:
for (x = 0; x <= Information.UBound(dataArray) - 1; x++) {
if (Strings.InStr(Strings.UCase(dataArray[x, 1]), Strings.UCase(this.txtSearch.Text))) {
tmpString = dataArray[x, 1] + " " + x.ToString();
m = lstStockItem.Items.Add(tmpString);
lstStockItem.SetItemChecked(m, dataArray[x, 2]);
}
}
break;
}
if (lstStockItem.SelectedIndex)
lstStockItem.SelectedIndex = 0;
lstStockItem.Visible = true;
loading = false;
}
private void frmPricelistFilterItem_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
switch (KeyAscii) {
case System.Windows.Forms.Keys.Escape:
KeyAscii = 0;
cmdExit_Click(cmdExit, new System.EventArgs());
break;
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void lstStockItem_SelectedIndexChanged(System.Object eventSender, System.EventArgs eventArgs)
{
bool loading = false;
string sql = null;
if (loading)
return;
short x = 0;
x = Convert.ToInt64(lstStockItem.SelectedIndex);
if (lstStockItem.SelectedIndex != -1) {
dataArray[x, 2] = Convert.ToInt16(lstStockItem.GetItemChecked(lstStockItem.SelectedIndex));
sql = "DELETE PricelistFilterStockItemLnk.* From PricelistFilterStockItemLnk WHERE (((PricelistFilterStockItemLnk.PricelistStockitemLnk_PricelistID)=" + gID + ") AND ((PricelistFilterStockItemLnk.PricelistStockitemLnk_StockitemID)=" + dataArray[x, 0] + "));";
modRecordSet.cnnDB.Execute(sql);
if (dataArray[x, 2]) {
sql = "INSERT INTO PricelistFilterStockItemLnk ( PricelistStockitemLnk_PricelistID, PricelistStockitemLnk_StockitemID ) SELECT " + gID + " AS pricelist, " + dataArray[x, 0] + " AS stock;";
modRecordSet.cnnDB.Execute(sql);
}
}
}
private void tbStockItem_ButtonClick(System.Object eventSender, System.EventArgs eventArgs)
{
System.Windows.Forms.ToolStrip Button = (System.Windows.Forms.ToolStrip)eventSender;
short x = 0;
for (x = 0; x <= tbStockItem.Items.Count; x++) {
((ToolStripButton)tbStockItem.Items[x]).Checked = false;
}
tbStockItem.Tag = Button.Items.IndexOf(Button.Tag) - 1;
// buildDepartment
//Button.Checked = True
doLoad();
}
private void txtSearch_KeyDown(System.Object eventSender, System.Windows.Forms.KeyEventArgs eventArgs)
{
short KeyCode = eventArgs.KeyCode;
short Shift = eventArgs.KeyData / 0x10000;
if (KeyCode == 40) {
this.lstStockItem.Focus();
KeyCode = 0;
}
}
private void txtSearch_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
switch (KeyAscii) {
case 13:
doLoad();
KeyAscii = 0;
break;
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void frmPricelistFilterItem_Load(object sender, System.EventArgs e)
{
cmdClick.AddRange(new Button[] {
_cmdClick_1,
_cmdClick_2,
_cmdClick_3
});
Button bt = new Button();
foreach (Button bt_loopVariable in cmdClick) {
bt = bt_loopVariable;
bt.Click += cmdClick_Click;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Text;
using System.Threading;
using System.Security.Cryptography.X509Certificates;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Mono.Addins;
using Amib.Threading;
/*****************************************************
*
* ScriptsHttpRequests
*
* Implements the llHttpRequest and http_response
* callback.
*
* Some stuff was already in LSLLongCmdHandler, and then
* there was this file with a stub class in it. So,
* I am moving some of the objects and functions out of
* LSLLongCmdHandler, such as the HttpRequestClass, the
* start and stop methods, and setting up pending and
* completed queues. These are processed in the
* LSLLongCmdHandler polling loop. Similiar to the
* XMLRPCModule, since that seems to work.
*
* //TODO
*
* This probably needs some throttling mechanism but
* it's wide open right now. This applies to both
* number of requests and data volume.
*
* Linden puts all kinds of header fields in the requests.
* Not doing any of that:
* User-Agent
* X-SecondLife-Shard
* X-SecondLife-Object-Name
* X-SecondLife-Object-Key
* X-SecondLife-Region
* X-SecondLife-Local-Position
* X-SecondLife-Local-Velocity
* X-SecondLife-Local-Rotation
* X-SecondLife-Owner-Name
* X-SecondLife-Owner-Key
*
* HTTPS support
*
* Configurable timeout?
* Configurable max response size?
* Configurable
*
* **************************************************/
namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HttpRequestModule")]
public class HttpRequestModule : ISharedRegionModule, IHttpRequestModule
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private object HttpListLock = new object();
private int httpTimeout = 30000;
private string m_name = "HttpScriptRequests";
private OutboundUrlFilter m_outboundUrlFilter;
private string m_proxyurl = "";
private string m_proxyexcepts = "";
// <request id, HttpRequestClass>
private Dictionary<UUID, HttpRequestClass> m_pendingRequests;
private Scene m_scene;
// private Queue<HttpRequestClass> rpcQueue = new Queue<HttpRequestClass>();
public static SmartThreadPool ThreadPool = null;
public HttpRequestModule()
{
ServicePointManager.ServerCertificateValidationCallback +=ValidateServerCertificate;
}
public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
// If this is a web request we need to check the headers first
// We may want to ignore SSL
if (sender is HttpWebRequest)
{
HttpWebRequest Request = (HttpWebRequest)sender;
ServicePoint sp = Request.ServicePoint;
// We don't case about encryption, get out of here
if (Request.Headers.Get("NoVerifyCert") != null)
{
return true;
}
// If there was an upstream cert verification error, bail
if ((((int)sslPolicyErrors) & ~4) != 0)
return false;
// Check for policy and execute it if defined
#pragma warning disable 0618
if (ServicePointManager.CertificatePolicy != null)
{
return ServicePointManager.CertificatePolicy.CheckValidationResult (sp, certificate, Request, 0);
}
#pragma warning restore 0618
return true;
}
// If it's not HTTP, trust .NET to check it
if ((((int)sslPolicyErrors) & ~4) != 0)
return false;
return true;
}
#region IHttpRequestModule Members
public UUID MakeHttpRequest(string url, string parameters, string body)
{
return UUID.Zero;
}
public UUID StartHttpRequest(
uint localID, UUID itemID, string url, List<string> parameters, Dictionary<string, string> headers, string body,
out HttpInitialRequestStatus status)
{
UUID reqID = UUID.Random();
HttpRequestClass htc = new HttpRequestClass();
// Partial implementation: support for parameter flags needed
// see http://wiki.secondlife.com/wiki/LlHTTPRequest
//
// Parameters are expected in {key, value, ... , key, value}
if (parameters != null)
{
string[] parms = parameters.ToArray();
for (int i = 0; i < parms.Length; i += 2)
{
switch (Int32.Parse(parms[i]))
{
case (int)HttpRequestConstants.HTTP_METHOD:
htc.HttpMethod = parms[i + 1];
break;
case (int)HttpRequestConstants.HTTP_MIMETYPE:
htc.HttpMIMEType = parms[i + 1];
break;
case (int)HttpRequestConstants.HTTP_BODY_MAXLENGTH:
int len;
if(int.TryParse(parms[i + 1], out len))
{
if(len > HttpRequestClass.HttpBodyMaxLenMAX)
len = HttpRequestClass.HttpBodyMaxLenMAX;
else if(len < 64) //???
len = 64;
htc.HttpBodyMaxLen = len;
}
break;
case (int)HttpRequestConstants.HTTP_VERIFY_CERT:
htc.HttpVerifyCert = (int.Parse(parms[i + 1]) != 0);
break;
case (int)HttpRequestConstants.HTTP_VERBOSE_THROTTLE:
// TODO implement me
break;
case (int)HttpRequestConstants.HTTP_CUSTOM_HEADER:
//Parameters are in pairs and custom header takes
//arguments in pairs so adjust for header marker.
++i;
//Maximum of 8 headers are allowed based on the
//Second Life documentation for llHTTPRequest.
for (int count = 1; count <= 8; ++count)
{
//Not enough parameters remaining for a header?
if (parms.Length - i < 2)
break;
if (htc.HttpCustomHeaders == null)
htc.HttpCustomHeaders = new List<string>();
htc.HttpCustomHeaders.Add(parms[i]);
htc.HttpCustomHeaders.Add(parms[i+1]);
int nexti = i + 2;
if (nexti >= parms.Length || Char.IsDigit(parms[nexti][0]))
break;
i = nexti;
}
break;
case (int)HttpRequestConstants.HTTP_PRAGMA_NO_CACHE:
htc.HttpPragmaNoCache = (int.Parse(parms[i + 1]) != 0);
break;
}
}
}
htc.RequestModule = this;
htc.LocalID = localID;
htc.ItemID = itemID;
htc.Url = url;
htc.ReqID = reqID;
htc.HttpTimeout = httpTimeout;
htc.OutboundBody = body;
htc.ResponseHeaders = headers;
htc.proxyurl = m_proxyurl;
htc.proxyexcepts = m_proxyexcepts;
// Same number as default HttpWebRequest.MaximumAutomaticRedirections
htc.MaxRedirects = 50;
if (StartHttpRequest(htc))
{
status = HttpInitialRequestStatus.OK;
return htc.ReqID;
}
else
{
status = HttpInitialRequestStatus.DISALLOWED_BY_FILTER;
return UUID.Zero;
}
}
/// <summary>
/// Would a caller to this module be allowed to make a request to the given URL?
/// </summary>
/// <returns></returns>
public bool CheckAllowed(Uri url)
{
return m_outboundUrlFilter.CheckAllowed(url);
}
public bool StartHttpRequest(HttpRequestClass req)
{
if (!CheckAllowed(new Uri(req.Url)))
return false;
lock (HttpListLock)
{
m_pendingRequests.Add(req.ReqID, req);
}
req.Process();
return true;
}
public void StopHttpRequest(uint m_localID, UUID m_itemID)
{
if (m_pendingRequests != null)
{
lock (HttpListLock)
{
HttpRequestClass tmpReq;
if (m_pendingRequests.TryGetValue(m_itemID, out tmpReq))
{
tmpReq.Stop();
m_pendingRequests.Remove(m_itemID);
}
}
}
}
/*
* TODO
* Not sure how important ordering is is here - the next first
* one completed in the list is returned, based soley on its list
* position, not the order in which the request was started or
* finished. I thought about setting up a queue for this, but
* it will need some refactoring and this works 'enough' right now
*/
public IServiceRequest GetNextCompletedRequest()
{
lock (HttpListLock)
{
foreach (UUID luid in m_pendingRequests.Keys)
{
HttpRequestClass tmpReq;
if (m_pendingRequests.TryGetValue(luid, out tmpReq))
{
if (tmpReq.Finished)
{
return tmpReq;
}
}
}
}
return null;
}
public void RemoveCompletedRequest(UUID id)
{
lock (HttpListLock)
{
HttpRequestClass tmpReq;
if (m_pendingRequests.TryGetValue(id, out tmpReq))
{
tmpReq.Stop();
tmpReq = null;
m_pendingRequests.Remove(id);
}
}
}
#endregion
#region ISharedRegionModule Members
public void Initialise(IConfigSource config)
{
m_proxyurl = config.Configs["Startup"].GetString("HttpProxy");
m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions");
HttpRequestClass.HttpBodyMaxLenMAX = config.Configs["Network"].GetInt("HttpBodyMaxLenMAX", 16384);
m_outboundUrlFilter = new OutboundUrlFilter("Script HTTP request module", config);
int maxThreads = 15;
IConfig httpConfig = config.Configs["HttpRequestModule"];
if (httpConfig != null)
{
maxThreads = httpConfig.GetInt("MaxPoolThreads", maxThreads);
}
m_pendingRequests = new Dictionary<UUID, HttpRequestClass>();
// First instance sets this up for all sims
if (ThreadPool == null)
{
STPStartInfo startInfo = new STPStartInfo();
startInfo.IdleTimeout = 20000;
startInfo.MaxWorkerThreads = maxThreads;
startInfo.MinWorkerThreads = 1;
startInfo.ThreadPriority = ThreadPriority.BelowNormal;
startInfo.StartSuspended = true;
startInfo.ThreadPoolName = "ScriptsHttpReq";
ThreadPool = new SmartThreadPool(startInfo);
ThreadPool.Start();
}
}
public void AddRegion(Scene scene)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IHttpRequestModule>(this);
}
public void RemoveRegion(Scene scene)
{
scene.UnregisterModuleInterface<IHttpRequestModule>(this);
if (scene == m_scene)
m_scene = null;
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
}
public void Close()
{
ThreadPool.Shutdown();
}
public string Name
{
get { return m_name; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
}
public class HttpRequestClass : IServiceRequest
{
// Constants for parameters
// public const int HTTP_BODY_MAXLENGTH = 2;
// public const int HTTP_METHOD = 0;
// public const int HTTP_MIMETYPE = 1;
// public const int HTTP_VERIFY_CERT = 3;
// public const int HTTP_VERBOSE_THROTTLE = 4;
// public const int HTTP_CUSTOM_HEADER = 5;
// public const int HTTP_PRAGMA_NO_CACHE = 6;
/// <summary>
/// Module that made this request.
/// </summary>
public HttpRequestModule RequestModule { get; set; }
private bool _finished;
public bool Finished
{
get { return _finished; }
}
public static int HttpBodyMaxLenMAX = 16384;
// Parameter members and default values
public int HttpBodyMaxLen = 2048;
public string HttpMethod = "GET";
public string HttpMIMEType = "text/plain;charset=utf-8";
public int HttpTimeout;
public bool HttpVerifyCert = true;
public IWorkItemResult WorkItem = null;
//public bool HttpVerboseThrottle = true; // not implemented
public List<string> HttpCustomHeaders = null;
public bool HttpPragmaNoCache = true;
// Request info
private UUID _itemID;
public UUID ItemID
{
get { return _itemID; }
set { _itemID = value; }
}
private uint _localID;
public uint LocalID
{
get { return _localID; }
set { _localID = value; }
}
public DateTime Next;
public string proxyurl;
public string proxyexcepts;
/// <summary>
/// Number of HTTP redirects that this request has been through.
/// </summary>
public int Redirects { get; private set; }
/// <summary>
/// Maximum number of HTTP redirects allowed for this request.
/// </summary>
public int MaxRedirects { get; set; }
public string OutboundBody;
private UUID _reqID;
public UUID ReqID
{
get { return _reqID; }
set { _reqID = value; }
}
public HttpWebRequest Request;
public string ResponseBody;
public List<string> ResponseMetadata;
public Dictionary<string, string> ResponseHeaders;
public int Status;
public string Url;
public void Process()
{
_finished = false;
lock (HttpRequestModule.ThreadPool)
WorkItem = HttpRequestModule.ThreadPool.QueueWorkItem(new WorkItemCallback(StpSendWrapper), null);
}
private object StpSendWrapper(object o)
{
SendRequest();
return null;
}
/*
* TODO: More work on the response codes. Right now
* returning 200 for success or 499 for exception
*/
public void SendRequest()
{
HttpWebResponse response = null;
Stream resStream = null;
byte[] buf = new byte[HttpBodyMaxLenMAX + 16];
string tempString = null;
int count = 0;
try
{
Request = (HttpWebRequest)WebRequest.Create(Url);
Request.AllowAutoRedirect = false;
Request.KeepAlive = false;
//This works around some buggy HTTP Servers like Lighttpd
Request.ServicePoint.Expect100Continue = false;
Request.Method = HttpMethod;
Request.ContentType = HttpMIMEType;
if (!HttpVerifyCert)
{
// We could hijack Connection Group Name to identify
// a desired security exception. But at the moment we'll use a dummy header instead.
Request.Headers.Add("NoVerifyCert", "true");
}
// else
// {
// Request.ConnectionGroupName="Verify";
// }
if (!HttpPragmaNoCache)
{
Request.Headers.Add("Pragma", "no-cache");
}
if (HttpCustomHeaders != null)
{
for (int i = 0; i < HttpCustomHeaders.Count; i += 2)
Request.Headers.Add(HttpCustomHeaders[i],
HttpCustomHeaders[i+1]);
}
if (!string.IsNullOrEmpty(proxyurl))
{
if (!string.IsNullOrEmpty(proxyexcepts))
{
string[] elist = proxyexcepts.Split(';');
Request.Proxy = new WebProxy(proxyurl, true, elist);
}
else
{
Request.Proxy = new WebProxy(proxyurl, true);
}
}
foreach (KeyValuePair<string, string> entry in ResponseHeaders)
if (entry.Key.ToLower().Equals("user-agent"))
Request.UserAgent = entry.Value;
else
Request.Headers[entry.Key] = entry.Value;
// Encode outbound data
if (!string.IsNullOrEmpty(OutboundBody))
{
byte[] data = Util.UTF8.GetBytes(OutboundBody);
Request.ContentLength = data.Length;
using (Stream bstream = Request.GetRequestStream())
bstream.Write(data, 0, data.Length);
}
Request.Timeout = HttpTimeout;
try
{
// execute the request
response = (HttpWebResponse) Request.GetResponse();
}
catch (WebException e)
{
if (e.Status != WebExceptionStatus.ProtocolError)
{
throw;
}
response = (HttpWebResponse)e.Response;
}
Status = (int)response.StatusCode;
resStream = response.GetResponseStream();
int totalBodyBytes = 0;
int maxBytes = HttpBodyMaxLen;
if(maxBytes > buf.Length)
maxBytes = buf.Length;
// we need to read all allowed or UFT8 conversion may fail
do
{
// fill the buffer with data
count = resStream.Read(buf, totalBodyBytes, maxBytes - totalBodyBytes);
totalBodyBytes += count;
if (totalBodyBytes >= maxBytes)
break;
} while (count > 0); // any more data to read?
if(totalBodyBytes > 0)
{
tempString = Util.UTF8.GetString(buf, 0, totalBodyBytes);
ResponseBody = tempString.Replace("\r", "");
}
else
ResponseBody = "";
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
HttpWebResponse webRsp = (HttpWebResponse)((WebException)e).Response;
Status = (int)webRsp.StatusCode;
try
{
using (Stream responseStream = webRsp.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
ResponseBody = reader.ReadToEnd();
}
}
catch
{
ResponseBody = webRsp.StatusDescription;
}
}
else
{
Status = (int)OSHttpStatusCode.ClientErrorJoker;
ResponseBody = e.Message;
}
}
catch (Exception e)
{
// Don't crash on anything else
}
finally
{
if (resStream != null)
resStream.Close();
if (response != null)
response.Close();
// We need to resubmit
if (
(Status == (int)HttpStatusCode.MovedPermanently
|| Status == (int)HttpStatusCode.Found
|| Status == (int)HttpStatusCode.SeeOther
|| Status == (int)HttpStatusCode.TemporaryRedirect))
{
if (Redirects >= MaxRedirects)
{
Status = (int)OSHttpStatusCode.ClientErrorJoker;
ResponseBody = "Number of redirects exceeded max redirects";
_finished = true;
}
else
{
string location = response.Headers["Location"];
if (location == null)
{
Status = (int)OSHttpStatusCode.ClientErrorJoker;
ResponseBody = "HTTP redirect code but no location header";
_finished = true;
}
else if (!RequestModule.CheckAllowed(new Uri(location)))
{
Status = (int)OSHttpStatusCode.ClientErrorJoker;
ResponseBody = "URL from HTTP redirect blocked: " + location;
_finished = true;
}
else
{
Status = 0;
Url = response.Headers["Location"];
Redirects++;
ResponseBody = null;
// m_log.DebugFormat("Redirecting to [{0}]", Url);
Process();
}
}
}
else
{
_finished = true;
if (ResponseBody == null)
ResponseBody = String.Empty;
}
}
}
public void Stop()
{
try
{
if (!WorkItem.Cancel())
{
WorkItem.Cancel(true);
}
}
catch (Exception)
{
}
}
}
}
| |
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
/*
test cases
complex boundaries
complex boundaries complex holes
overlapping complex everything
single complex boundary with some holes (no edge case testing, just standard stuff)
common edge case all in one
try cutting a triangulated hole into a triangulated polygon (just start with two triangles, move up from there)
try merging two polygons:
cut poly1 with poly2's edges
cut poly2 with poly1's edges
remove poly1 triangles contained in poly2
remove poly2 triangles contained in poly1*/
// TODO
// Make edge cases tests
// Closed boundary
// Closed hole
// Degenerate
// Self intersecting
// Too small
// Colinear overlap
// Intersect through vertices
// Colinear
namespace Rx
{
[CustomEditor( typeof( NewNavMesh2 ), true )]
public class NewNavMesh2Editor : Editor
{
#region Data Members
private NavMesh2Builder builder = new NavMesh2Builder();
//private bool hideDebugShapes = false;
//private bool drawInputBoundaries = false;
//private bool drawInputHoles = false;
//private bool drawGroups = false;
//private bool drawBoundaryTriangles = false;
//private bool drawHoleTriangles = false;
private bool drawPolygonIndices = false;
private bool drawVertexIndices = false;
private bool drawVertexPositions = false;
private int previousBuildStep = -1;
private int buildStep = 0;
#endregion
#region Build
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
NewNavMesh2 selectedNavMesh = (NewNavMesh2)target;
GUILayout.BeginVertical();
//hideDebugShapes = GUILayout.Toggle( hideDebugShapes, "Hide Debug Shapes" );
//drawInputBoundaries = GUILayout.Toggle( drawInputBoundaries, "Draw Input Boundaries" );
//drawInputHoles = GUILayout.Toggle( drawInputHoles, "Draw Input Holes" );
//drawGroups = GUILayout.Toggle( drawGroups, "Draw Groups" );
//drawBoundaryTriangles = GUILayout.Toggle( drawBoundaryTriangles, "Draw Boundary Triangles" );
//drawHoleTriangles = GUILayout.Toggle( drawHoleTriangles, "Draw Hole Triangles" );
drawPolygonIndices = GUILayout.Toggle( drawPolygonIndices, "Draw Polygon Indices" );
drawVertexIndices = GUILayout.Toggle( drawVertexIndices, "Draw Vertex Indices" );
drawVertexPositions = GUILayout.Toggle( drawVertexPositions, "Draw Vertex Positions" );
buildStep = (int)GUILayout.HorizontalSlider( (float)buildStep, 0.0f, 10.0f );
switch ( buildStep )
{
case 0:
{
GUILayout.Label( "Build Step: None" );
}
break;
case 1:
{
GUILayout.Label( "Build Step: Fuse Boundaries" );
}
break;
case 2:
{
GUILayout.Label( "Build Step: Fuse Holes" );
}
break;
case 3:
{
GUILayout.Label( "Build Step: Clip Holes" );
}
break;
case 4:
{
GUILayout.Label( "Build Step: Generate Convex" );
}
break;
}
bool build = GUILayout.Button( "Build" );
GUILayout.EndVertical();
EditorUtility.SetDirty( selectedNavMesh );
if ( build || buildStep != previousBuildStep )
{
Build();
}
DebugShape2.hackHide = true;
}
// private void Build()
// {
// builder.Clear();
//
// CollectBoundaries();
// CollectHoles();
//
// builder.Build();
// }
private void CollectBoundaries()
{
DebugBoundary2[] boundaries = Object.FindObjectsOfType( typeof(DebugBoundary2) ) as DebugBoundary2[];
foreach ( DebugBoundary2 boundary in boundaries )
{
builder.AddBoundary( boundary.GetWorldVertices() );
}
}
private void CollectHoles()
{
DebugHole2[] holes = Object.FindObjectsOfType( typeof(DebugHole2) ) as DebugHole2[];
foreach ( DebugHole2 hole in holes )
{
builder.AddHole( hole.GetWorldVertices() );
}
}
private void Build()
{
builder.Clear();
CollectBoundaries();
CollectHoles();
builder.Build( buildStep );
}
#endregion
#region Debug Drawing
public void OnSceneGUI()
{
Draw();
// if ( drawBoundaryTriangles )
// {
// DrawBoundaryTriangles();
// }
//
// if ( drawHoleTriangles )
// {
// DrawHoleTriangles();
// }
//
// if ( drawInputBoundaries )
// {
// DrawInputBoundaries();
// }
//
// if ( drawInputHoles )
// {
// DrawInputHoles();
// }
//
// if ( drawGroups )
// {
// DrawGroups();
// }
}
private void Draw()
{
if ( buildStep == 0 )
{
DrawPolygons( builder.boundaries, Color.white );
DrawPolygons( builder.holes, Color.blue );
}
else if ( buildStep == 1 )
{
DrawPolygons( builder.boundaries, Color.white );
DrawPolygons( builder.holes, Color.blue );
}
else if ( buildStep == 2 )
{
DrawPolygons( builder.boundaries, Color.white );
DrawPolygons( builder.holes, Color.blue );
}
else if ( buildStep == 3 )
{
DrawPolygons( builder.boundaries, Color.white );
DrawPolygons( builder.holes, Color.blue );
}
}
private void DrawPolygons( List<NavMesh2Builder.PolygonProcessingInfo> polygons, Color color )
{
int polygonIndex = 0;
foreach ( NavMesh2Builder.PolygonProcessingInfo polygon in polygons )
{
DrawPolygon( polygon.vertices, color, polygonIndex );
++polygonIndex;
}
}
// private void DrawInputBoundaries()
// {
// foreach ( List<Vector2> polygon in builder.inputBoundaries )
// {
// DrawPolygon( polygon, Color.white );
// }
// }
//
// private void DrawInputHoles()
// {
// foreach ( List<Vector2> polygon in builder.inputHoles )
// {
// DrawPolygon( polygon, Color.black );
// }
// }
//
// private void DrawGroups()
// {
// if ( ( builder.meshData == null ) || ( builder.meshData.Count == 0 ) )
// {
// return;
// }
//
// Color boundaryColor = new Color( 0.0f, 1.0f, 0.0f, 0.2f );
// Color holeColor = new Color( 0.0f, 0.0f, 1.0f, 0.2f );
//
// float colorStep = 0.8f / builder.meshData.Count;
//
// foreach ( NavMesh2Builder.MeshProcessingInfo mesh in builder.meshData )
// {
// foreach ( List<Vector2> boundary in mesh.boundaries )
// {
// DrawPolygon( boundary, boundaryColor );
// }
//
// foreach ( List<Vector2> hole in mesh.holes )
// {
// DrawPolygon( hole, holeColor );
// }
//
// boundaryColor.a += colorStep;
// holeColor.a += colorStep;
// }
// }
//
// private void DrawBoundaryTriangles()
// {
// foreach ( NavMesh2Builder.MeshProcessingInfo meshInfo in builder.meshData )
// {
// if ( meshInfo.boundaries.Count != meshInfo.triangulatedBoundaries.Count )
// {
// Debug.LogError( "Encountered a MeshProcessingInfo with " + meshInfo.boundaries.Count + " boundaries and " + meshInfo.triangulatedBoundaries.Count + " triangulated boundaries." );
// }
//
// for ( int boundaryIndex = 0; boundaryIndex < meshInfo.boundaries.Count; ++boundaryIndex )
// {
// DrawIndexedTriangle( meshInfo.boundaries[boundaryIndex], meshInfo.triangulatedBoundaries[boundaryIndex], Color.cyan );
// }
// }
// }
//
// private void DrawHoleTriangles()
// {
// foreach ( NavMesh2Builder.MeshProcessingInfo meshInfo in builder.meshData )
// {
// if ( meshInfo.holes.Count != meshInfo.triangulatedHoles.Count )
// {
// Debug.LogError( "Encountered a MeshProcessingInfo with " + meshInfo.holes.Count + " holes and " + meshInfo.triangulatedHoles.Count + " triangulated holes." );
// }
//
// for ( int holeIndex = 0; holeIndex < meshInfo.holes.Count; ++holeIndex )
// {
// DrawIndexedTriangle( meshInfo.holes[holeIndex], meshInfo.triangulatedHoles[holeIndex], Color.blue );
// }
// }
// }
//
// private void DrawIndexedTriangle( List<Vector2> vertices, List<int> triangles, Color color )
// {
// for ( int a = 0; a < triangles.Count; a += 3 )
// {
// int b = a + 1;
// int c = a + 2;
//
// DrawLine( vertices[ triangles[a] ], vertices[ triangles[b] ], color );
// DrawLine( vertices[ triangles[b] ], vertices[ triangles[c] ], color );
// DrawLine( vertices[ triangles[c] ], vertices[ triangles[a] ], color );
// }
// }
private void DrawPolygon( List<Vector2> polygon, Color color, int polygonIndex )
{
for ( int edgeStartIndex = 0; edgeStartIndex < polygon.Count; ++edgeStartIndex )
{
string vertString = "";
if ( drawPolygonIndices )
{
vertString += polygonIndex;
}
if ( vertString.Length > 0 )
{
vertString += ":";
}
if ( drawVertexIndices )
{
vertString += edgeStartIndex;
}
if ( vertString.Length > 0 )
{
vertString += ":";
}
if ( drawVertexPositions )
{
vertString += polygon[edgeStartIndex].x + "," + polygon[edgeStartIndex].y;
}
Handles.Label( polygon[edgeStartIndex], vertString );
int edgeEndIndex = (edgeStartIndex+1) % polygon.Count;
DrawLine( polygon[edgeStartIndex], polygon[edgeEndIndex], color );
}
}
private void DrawLine( Vector2 start, Vector2 end, Color color )
{
Handles.color = color;
Handles.DrawLine( new Vector3( start.x, start.y, 0.0f ), new Vector3( end.x, end.y, 0.0f ) );
}
#endregion
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace HostWebEventsWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using ServiceStack.Text;
namespace ServiceStack.Script
{
public class JsMemberExpression : JsExpression
{
public JsToken Object { get; }
public JsToken Property { get; }
public bool Computed { get; } //indexer
public JsMemberExpression(JsToken @object, JsToken property) : this(@object, property, false) { }
public JsMemberExpression(JsToken @object, JsToken property, bool computed)
{
Object = @object;
Property = property;
Computed = computed;
}
public override string ToRawString()
{
var sb = StringBuilderCache.Allocate();
sb.Append(Object.ToRawString());
if (Computed)
{
sb.Append("[");
sb.Append(Property.ToRawString());
sb.Append("]");
}
else
{
sb.Append(".");
sb.Append(Property.ToRawString());
}
return StringBuilderCache.ReturnAndFree(sb);
}
public override Dictionary<string, object> ToJsAst()
{
var to = new Dictionary<string, object>
{
["type"] = ToJsAstType(),
["computed"] = Computed,
["object"] = Object.ToJsAst(),
["property"] = Property.ToJsAst(),
};
return to;
}
public override object Evaluate(ScriptScopeContext scope)
{
var targetValue = Object.Evaluate(scope);
var ret = GetValue(targetValue, scope);
return Equals(ret, JsNull.Value)
? null
: ret;
}
private static object PropValue(object targetValue, Type targetType, string name)
{
var memberFn = TypeProperties.Get(targetType).GetPublicGetter(name)
?? TypeFields.Get(targetType).GetPublicGetter(name);
if (memberFn != null)
{
return memberFn(targetValue);
}
var methods = targetType.GetInstanceMethods();
var indexerMethod =
methods.FirstOrDefault(x => x.Name == "get_Item" && x.GetParameters().Any(p => p.ParameterType == typeof(string))) ??
methods.FirstOrDefault(x => x.Name == "get_Item" && x.GetParameters().Any(p => p.ParameterType != typeof(string)));
if (indexerMethod != null)
{
var fn = indexerMethod.GetInvoker();
var ret = fn(targetValue, name);
return ret;
}
throw new ArgumentException($"'{targetType.Name}' does not have a '{name}' property or field");
}
private object GetValue(object targetValue, ScriptScopeContext scope)
{
if (targetValue == null || targetValue == JsNull.Value)
return JsNull.Value;
var targetType = targetValue.GetType();
try
{
if (!Computed)
{
if (Property is JsIdentifier identifier)
{
var ret = PropValue(targetValue, targetType, identifier.Name);
// Don't emit member expression on null KeyValuePair
if (ret == null && targetType.Name == "KeyValuePair`2")
return JsNull.Value;
return ret;
}
}
else
{
var indexValue = Property.Evaluate(scope);
if (indexValue == null)
return JsNull.Value;
if (targetType.IsArray)
{
var array = (Array) targetValue;
if (indexValue is long l)
return array.GetValue(l);
var intValue = indexValue.ConvertTo<int>();
return array.GetValue(intValue);
}
if (targetValue is IDictionary dict)
{
var ret = dict[indexValue];
return ret ?? JsNull.Value;
}
if (indexValue is string propName)
{
return PropValue(targetValue, targetType, propName);
}
if (targetValue is IList list)
{
var intValue = indexValue.ConvertTo<int>();
return list[intValue];
}
if (targetValue is IEnumerable e)
{
var intValue = indexValue.ConvertTo<int>();
var i = 0;
foreach (var item in e)
{
if (i++ == intValue)
return item;
}
return null;
}
if (DynamicNumber.IsNumber(indexValue.GetType()))
{
var indexerMethod = targetType.GetInstanceMethod("get_Item");
if (indexerMethod != null)
{
var fn = indexerMethod.GetInvoker();
var ret = fn(targetValue, indexValue);
return ret ?? JsNull.Value;
}
}
}
}
catch (KeyNotFoundException)
{
return JsNull.Value;
}
catch (Exception ex)
{
var exResult = scope.PageResult.Format.OnExpressionException(scope.PageResult, ex);
if (exResult != null)
return exResult;
var expr = ToRawString();
throw new BindingExpressionException($"Could not evaluate expression '{expr}'", null, expr, ex);
}
throw new NotSupportedException($"'{targetValue.GetType()}' does not support access by '{Property}'");
}
protected bool Equals(JsMemberExpression other)
{
return Equals(Object, other.Object) &&
Equals(Property, other.Property) &&
Computed == other.Computed;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((JsMemberExpression) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = (Object != null ? Object.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (Property != null ? Property.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ Computed.GetHashCode();
return hashCode;
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//#define TRACK_TIMING
//#define TRACK_TIMING_LEVEL2
//#define TRACK_TIMING_LEVEL3
//#define TRACK_TIMING_LEVEL4
namespace Microsoft.Zelig.CodeGeneration.IR.Transformations
{
using System;
using System.Collections.Generic;
using Microsoft.Zelig.Runtime.TypeSystem;
#if TRACK_TIMING
internal class ExecutionTiming : IDisposable
{
[ThreadStatic] static int s_nesting;
string m_text;
PerformanceCounters.Timing m_counter;
internal ExecutionTiming( string text ,
params object[] args )
{
m_text = string.Format( text, args );
s_nesting++;
m_counter.Start();
}
public void Dispose()
{
m_counter.Stop( true );
Console.WriteLine( "Execution time {0,8}usec : {1}{2}", m_counter.TotalInclusiveMicroSeconds, new string( ' ', (--s_nesting) * 3 ), m_text );
}
}
#else
internal class ExecutionTiming : IDisposable
{
internal ExecutionTiming( string text ,
params object[] args )
{
}
public void Dispose()
{
}
}
#endif
//--//
internal class PerformClassExtension : ScanTypeSystem
{
internal struct Duplicate
{
//
// State
//
internal object From;
internal object To;
//
// Constructor Methods
//
internal Duplicate( object from, object to )
{
this.From = from;
this.To = to;
}
}
//
// State
//
ReverseIndexTypeSystem m_reverseIndex;
GrowOnlySet< object > m_newObjectsForReverseIndex;
List< Duplicate > m_duplicates;
TypeRepresentation m_overridingTD;
TypeRepresentation m_overriddenTD;
bool m_fNoConstructors;
bool m_fSameExtends;
GrowOnlyHashTable< object, object > m_remapAliases;
LocateUsageInCode m_inlineCandidates;
GrowOnlyHashTable< MethodRepresentation, MethodRepresentation > m_substitutionTable;
object m_activeContext;
object m_replaceFrom;
object m_replaceTo;
//
// Constructor Methods
//
internal PerformClassExtension( TypeSystemForCodeTransformation typeSystem ,
ReverseIndexTypeSystem reverseIndex ,
List< Duplicate > duplicates ) : base( typeSystem, typeof(PerformClassExtension) )
{
m_reverseIndex = reverseIndex;
m_duplicates = duplicates;
//--//
m_newObjectsForReverseIndex = SetFactory.New< object >();
m_remapAliases = HashTableFactory.New< object, object >();
m_inlineCandidates = new LocateUsageInCode( typeSystem );
m_substitutionTable = HashTableFactory.New< MethodRepresentation, MethodRepresentation >();
}
internal PerformClassExtension( TypeSystemForCodeTransformation typeSystem ,
ReverseIndexTypeSystem reverseIndex ,
List< Duplicate > duplicates ,
TypeRepresentation overridingTD ,
TypeRepresentation overriddenTD ,
bool fNoConstructors ) : this( typeSystem, reverseIndex, duplicates )
{
m_overridingTD = overridingTD;
m_overriddenTD = overriddenTD;
m_fNoConstructors = fNoConstructors;
//--//
m_fSameExtends = (overridingTD.Extends == overriddenTD.Extends);
//
// Either the two classes have the same super-class, or the overridding one derives from Object.
//
if(!m_fSameExtends)
{
if(overridingTD.Extends != typeSystem.WellKnownTypes.System_Object)
{
throw TypeConsistencyErrorException.Create( "Cannot extend '{0}' with '{1}', their superclasses are incompatible", overriddenTD, overridingTD );
}
}
}
//--//
//
// Helper Methods
//
internal static GrowOnlyHashTable< MethodRepresentation, MethodRepresentation > Hack_GetSubstitutionTable( TypeSystemForCodeTransformation typeSystem ,
TypeRepresentation overridingTD ,
TypeRepresentation overriddenTD )
{
var pce = new PerformClassExtension( typeSystem, null, null );
pce.m_overridingTD = overridingTD;
pce.m_overriddenTD = overriddenTD;
EquivalenceSet set = new EquivalenceSet( delegate( BaseRepresentation context1,
BaseRepresentation br1 ,
BaseRepresentation context2,
BaseRepresentation br2 )
{
DelayedMethodParameterTypeRepresentation td1 = context1 as DelayedMethodParameterTypeRepresentation;
DelayedMethodParameterTypeRepresentation td2 = context2 as DelayedMethodParameterTypeRepresentation;
if(td1 != null && td2 != null)
{
MethodRepresentation md1 = br1 as MethodRepresentation;
MethodRepresentation md2 = br2 as MethodRepresentation;
if(md1 != null && md2 != null)
{
if(md1.IsOpenMethod && md2.IsOpenMethod)
{
if(md1.GenericParametersDefinition[td1.ParameterNumber].IsCompatible( ref md2.GenericParametersDefinition[td2.ParameterNumber] ))
{
return true;
}
}
}
}
return false;
} );
set.AddEquivalencePair( overridingTD, overriddenTD );
foreach(MethodRepresentation md in pce.m_overridingTD.Methods)
{
pce.m_substitutionTable[md] = pce.FindTargetMethod( md, set );
}
return pce.m_substitutionTable;
}
//--//
internal void Execute()
{
#if GENERICS_DEBUG
if(m_overridingTD.ToString() == "AbstractReferenceTypeRepresentation(Microsoft.Zelig.Runtime.InterlockedImpl)")
{
}
#endif
//
// 1) We need to deal with Generic Types and Methods.
//
// For generic types, we need to ensure we have as many specialization of the overridding type as those of the overridden one.
//
// For generic methods, we need to ensure that the overriding generic method is instantiated as many times as the overridden one.
//
#if TRACK_TIMING_LEVEL2
using(new ExecutionTiming( "InstantiateGenericTypesAndMethods for {0}", m_overridingTD ))
#endif
//// HACK: We performed the instantiation at metadata import time.
//// {
//// InstantiateGenericTypesAndMethods();
//// }
//
// 2) Go through all the whole type system and replace references from overridingTD to overriddenTD.
//
#if TRACK_TIMING_LEVEL2
using(new ExecutionTiming( "PrepareFieldAliasing for {0}", m_overridingTD ))
#endif
{
PrepareFieldAliasing();
}
#if TRACK_TIMING_LEVEL2
using(new ExecutionTiming( "PrepareMethodAliasing for {0}", m_overridingTD ))
#endif
{
PrepareMethodAliasing();
}
#if TRACK_TIMING_LEVEL2
using(new ExecutionTiming( "RemapTypesFromOverridingToOverridden for {0}", m_overridingTD ))
#endif
{
RemapTypesFromOverridingToOverridden();
}
#if TRACK_TIMING_LEVEL2
using(new ExecutionTiming( "ProcessMethodAliasing for {0}", m_overridingTD ))
#endif
{
ProcessMethodAliasing();
}
//
// 3) Move fields and methods from overriding type to overridden one:
// a) fields should not collide,
//
GrowOnlyHashTable< object, object > remap = HashTableFactory.New< object, object >();
#if TRACK_TIMING_LEVEL2
using(new ExecutionTiming( "MoveFields for {0}", m_overridingTD ))
#endif
{
MoveFields( remap );
}
#if TRACK_TIMING_LEVEL2
using(new ExecutionTiming( "MoveMethods for {0}", m_overridingTD ))
#endif
{
MoveMethods( remap );
}
#if TRACK_TIMING_LEVEL2
using(new ExecutionTiming( "ProcessTypeSystem for {0}", m_overridingTD ))
#endif
{
ProcessRemaps( remap );
}
FlushNewObjects();
}
//--//
private void InstantiateGenericTypesAndMethods()
{
GrowOnlyHashTable< MethodRepresentation, List< MethodRepresentation > > ht = null;
if(m_overridingTD.IsOpenType || m_overridingTD.Generic != null ||
m_overriddenTD.IsOpenType || m_overriddenTD.Generic != null )
{
throw TypeConsistencyErrorException.Create( "Class Extension for generic types not supported yet: '{0}' => '{1}'", m_overridingTD, m_overriddenTD );
}
foreach(MethodRepresentation md in m_overridingTD.Methods)
{
if(md.IsOpenMethod)
{
EquivalenceSet set = new EquivalenceSet( delegate( BaseRepresentation context1,
BaseRepresentation br1 ,
BaseRepresentation context2,
BaseRepresentation br2 )
{
DelayedMethodParameterTypeRepresentation td1 = context1 as DelayedMethodParameterTypeRepresentation;
DelayedMethodParameterTypeRepresentation td2 = context2 as DelayedMethodParameterTypeRepresentation;
if(td1 != null && td2 != null)
{
MethodRepresentation md1 = br1 as MethodRepresentation;
MethodRepresentation md2 = br2 as MethodRepresentation;
if(md1 != null && md2 != null)
{
if(md1.IsOpenMethod && md2.IsOpenMethod)
{
if(md1.GenericParametersDefinition[td1.ParameterNumber].IsCompatible( ref md2.GenericParametersDefinition[td2.ParameterNumber] ))
{
return true;
}
}
}
}
return false;
} );
set.AddEquivalencePair( m_overridingTD, m_overriddenTD );
MethodRepresentation overriddenMD = FindTargetMethod( md, set );
if(overriddenMD != null)
{
if(ht == null)
{
m_typeSystem.BuildHierarchyTables();
ht = m_typeSystem.GenericMethodInstantiations;
}
if(ht.ContainsKey( overriddenMD ))
{
foreach(MethodRepresentation overriddenInstantiationMD in ht[overriddenMD])
{
if(m_overridingTD.FindMatch( overriddenInstantiationMD, set ) == null)
{
InstantiationContext ic;
MethodRepresentation instantiatedMD = m_typeSystem.InstantiateMethod( md, null, overriddenInstantiationMD.GenericParameters, out ic );
ControlFlowGraphStateForCodeTransformation cfg = TypeSystemForCodeTransformation.GetCodeForMethod( md );
if(cfg != null)
{
instantiatedMD.Code = cfg.Clone( ic );
}
}
}
}
}
}
}
}
private void PrepareFieldAliasing()
{
//
// AliasForBaseField should only act as a placeholder for a field on the target class.
//
foreach(FieldRepresentation fd in m_overridingTD.Fields)
{
FieldRepresentation aliasedFD;
aliasedFD = FindAliasedField( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_AliasForBaseFieldAttribute, fd, m_overriddenTD );
if(aliasedFD != null)
{
foreach(CustomAttributeAssociationRepresentation caa in fd.CustomAttributes)
{
aliasedFD.CopyCustomAttribute( caa );
}
m_remapAliases[fd] = aliasedFD;
m_overridingTD.RemoveField( fd );
m_typeSystem.ProhibitUse( fd );
continue;
}
}
}
private static FieldRepresentation FindAliasedField( TypeRepresentation customAttribute ,
FieldRepresentation fd ,
TypeRepresentation targetType )
{
CustomAttributeRepresentation ca = fd.FindCustomAttribute( customAttribute );
if(ca != null)
{
fd.RemoveCustomAttribute( ca );
string targetField;
if(ca.FixedArgsValues.Length == 0)
{
targetField = fd.Name;
}
else
{
targetField = (string)ca.FixedArgsValues[0];
}
FieldRepresentation aliasedFD = targetType.FindField( targetField );
if(aliasedFD == null)
{
throw TypeConsistencyErrorException.Create( "Field '{0}' is aliased to non-existing or incompatible field {1}", fd, targetField );
}
return aliasedFD;
}
return null;
}
//--//
private void PrepareMethodAliasing()
{
//
// AliasForBaseMethod should only act as a placeholder for a call to another method.
// AliasForSuperMethod should only act as a placeholder for a call to another method.
// Both should not be invoked from any other class other than this one.
// Implementation should be empty.
//
foreach(MethodRepresentation md in m_overridingTD.Methods)
{
MethodRepresentation aliasedMD;
aliasedMD = FindAliasedMethod( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_AliasForBaseMethodAttribute, md, m_overriddenTD );
if(aliasedMD != null)
{
//
// Any call to this method should be inlined, if the target method is going to be overridden.
//
m_inlineCandidates.AddLookup( md );
m_remapAliases[md] = aliasedMD;
m_overridingTD.RemoveMethod( md );
m_typeSystem.ProhibitUse( md );
continue;
}
aliasedMD = FindAliasedMethod( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_AliasForSuperMethodAttribute, md, m_overriddenTD.Extends );
if(aliasedMD != null)
{
m_remapAliases[md] = aliasedMD;
m_overridingTD.RemoveMethod( md );
m_typeSystem.ProhibitUse( md );
continue;
}
}
}
private static MethodRepresentation FindAliasedMethod( TypeRepresentation customAttribute ,
MethodRepresentation md ,
TypeRepresentation targetType )
{
CustomAttributeRepresentation ca = md.FindCustomAttribute( customAttribute );
if(ca != null)
{
string targetMethod = (string)ca.FixedArgsValues[0];
MethodRepresentation aliasedMD = targetType.FindMatch( targetMethod, md, null );
if(aliasedMD == null)
{
throw TypeConsistencyErrorException.Create( "Method '{0}' is aliased to non-existing or incompatible method {1}", md, targetMethod );
}
if(TypeSystemForCodeTransformation.GetCodeForMethod( md ) != null)
{
throw TypeConsistencyErrorException.Create( "Method '{0}' cannot be an alias for a base method and have an implementation", md );
}
if(md.MemberAccess != MethodRepresentation.Attributes.Private && !(md is VirtualMethodRepresentation))
{
throw TypeConsistencyErrorException.Create( "Alias Method '{0}' has to be marked 'private'", md );
}
return aliasedMD;
}
return null;
}
//--//
private void RemapTypesFromOverridingToOverridden()
{
//
// Remove the type from the list and process it unconditionally.
//
m_typeSystem.Types.Remove( m_overridingTD );
ProcessRemap( m_overridingTD , m_overriddenTD );
ProcessRemap( m_overridingTD.VirtualTable, m_overriddenTD.VirtualTable );
//--//
m_remapAliases .RefreshHashCodes();
m_inlineCandidates.RefreshHashCodes();
}
//--//
private void ProcessMethodAliasing()
{
foreach(MethodRepresentation md in m_overridingTD.Methods)
{
m_substitutionTable[md] = FindTargetMethod( md, null );
}
//
// If any of the overriding methods has a call to one of the aliased method, the calls have to be inlined.
//
if(m_inlineCandidates.Entries.Count > 0)
{
m_inlineCandidates.ProcessType( m_overridingTD );
foreach(List< Operator > lst in m_inlineCandidates.Entries.Values)
{
foreach(Operator op in lst)
{
CallOperator call = (CallOperator)op;
if(call != null)
{
MethodRepresentation md = call.TargetMethod;
MethodRepresentation mdRemapped = (MethodRepresentation)m_remapAliases[md];
//
// If the aliased method is going to be overridden, we need to inline it.
//
if(m_substitutionTable.ContainsValue( mdRemapped ))
{
call.TargetMethod = mdRemapped;
Transformations.InlineCall.Execute( call, NotifyNewObjects );
}
}
}
}
}
ProcessRemaps( m_remapAliases );
}
private MethodRepresentation FindTargetMethod( MethodRepresentation md ,
EquivalenceSet set )
{
string targetMethod;
CustomAttributeRepresentation ca = md.FindCustomAttribute( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_AliasForTargetMethodAttribute );
if(ca != null)
{
targetMethod = (string)ca.FixedArgsValues[0];
}
else
{
targetMethod = md.Name;
}
MethodRepresentation overriddenMD;
if(md.HasCustomAttribute( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_InjectAtEntryPointAttribute ))
{
TypeRepresentation[] tdThisPlusArguments = md.ThisPlusArguments;
if(md.ReturnType != m_typeSystem.WellKnownTypes.System_Void)
{
throw TypeConsistencyErrorException.Create( "Method '{0}' cannot have a return value because it's marked as InjectAtEntryPoint", md );
}
overriddenMD = null;
foreach(MethodRepresentation md2 in m_overriddenTD.Methods)
{
if(md2.Name == targetMethod)
{
//
// Don't compare the first argument, a method signature does not include any 'this' pointer.
//
if(BaseRepresentation.ArrayEqualsThroughEquivalence( tdThisPlusArguments, md2.ThisPlusArguments, 1, -1, set ))
{
overriddenMD = md2;
break;
}
}
}
if(overriddenMD == null)
{
throw TypeConsistencyErrorException.Create( "Type '{0}' doesn't have a method compatible for injection of '{0}'", m_overriddenTD.FullNameWithAbbreviation, md.ToShortString() );
}
}
else if(md.HasCustomAttribute( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_InjectAtExitPointAttribute ))
{
TypeRepresentation[] tdThisPlusArguments = md.ThisPlusArguments;
int numThisPlusArguments = tdThisPlusArguments.Length;
overriddenMD = null;
foreach(MethodRepresentation md2 in m_overriddenTD.Methods)
{
if(md2.Name == targetMethod)
{
TypeRepresentation[] td2ThisPlusArguments = md2.ThisPlusArguments;
int num2ThisPlusArguments = td2ThisPlusArguments.Length;
if(BaseRepresentation.EqualsThroughEquivalence( md.ReturnType, md2.ReturnType, set ))
{
//
// There' an extra parameter in the overriding method, for the result value.
//
if(numThisPlusArguments == num2ThisPlusArguments + 1)
{
//
// Make sure the extra parameter is compatible with the return type.
//
if(BaseRepresentation.EqualsThroughEquivalence( tdThisPlusArguments[numThisPlusArguments-1], md2.ReturnType, set ))
{
//
// Don't compare the first argument, a method signature does not include any 'this' pointer.
//
if(BaseRepresentation.ArrayEqualsThroughEquivalence( tdThisPlusArguments, td2ThisPlusArguments, 1, num2ThisPlusArguments - 1, set ))
{
overriddenMD = md2;
break;
}
}
}
}
}
}
if(overriddenMD == null)
{
throw TypeConsistencyErrorException.Create( "Type '{0}' doesn't have a method compatible for injection of '{0}'", m_overriddenTD.FullNameWithAbbreviation, md.ToShortString() );
}
}
else
{
overriddenMD = m_overriddenTD.FindMatch( targetMethod, md, set );
}
if(ca != null)
{
if(overriddenMD == null)
{
throw TypeConsistencyErrorException.Create( "Method '{0}' is aliased to non-existing method {1}", md, targetMethod );
}
}
else
{
if(overriddenMD != null)
{
if((overriddenMD is ConstructorMethodRepresentation) != (md is ConstructorMethodRepresentation))
{
throw TypeConsistencyErrorException.Create( "Method '{0}' cannot override incompatible method '{1}'", md, overriddenMD );
}
}
}
return overriddenMD;
}
//--//
private void MoveFields( GrowOnlyHashTable< object, object > remap )
{
foreach(FieldRepresentation overridingFD in m_overridingTD.Fields)
{
m_overriddenTD.AddField( overridingFD );
}
}
//--//
private void MoveMethods( GrowOnlyHashTable< object, object > remap )
{
ConstructorMethodRepresentation overiddenDefaultConstructor = m_overriddenTD.FindDefaultConstructor();
foreach(MethodRepresentation overridingMD in m_substitutionTable.Keys)
{
CHECKS.ASSERT(overridingMD.OwnerType == m_overriddenTD, "Remapping from {0} to {1} failed on method {2}", m_overridingTD, m_overriddenTD, overridingMD );
MethodRepresentation overriddenMD = m_substitutionTable[overridingMD];
ControlFlowGraphStateForCodeTransformation overridingCFG = TypeSystemForCodeTransformation.GetCodeForMethod( overridingMD );
ControlFlowGraphStateForCodeTransformation overriddenCFG = overriddenMD != null ? TypeSystemForCodeTransformation.GetCodeForMethod( overriddenMD ) : null;
bool fAddToOverridden = false;
bool fSubstituteToOverridden = false;
bool fRemoveOverriding = false;
bool fMigrateMethodImpl = false;
if(overridingMD is ConstructorMethodRepresentation ||
overridingMD is StaticConstructorMethodRepresentation )
{
bool fDiscard = overridingMD.HasCustomAttribute( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_DiscardTargetImplementationAttribute );
bool fMerge = overridingMD.HasCustomAttribute( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_MergeWithTargetImplementationAttribute );
if(overridingCFG == null && fMerge)
{
throw TypeConsistencyErrorException.Create( "Constructor method '{0}' cannot be an internal call and be decorated with the MergeWithTargetImplementation attribute", overridingMD );
}
if(overridingMD is ConstructorMethodRepresentation)
{
if(m_fNoConstructors) continue;
if(!fDiscard && !fMerge)
{
throw TypeConsistencyErrorException.Create( "Constructor method '{0}' should be decorated with DiscardTargetImplementation or MergeWithTargetImplementation", overridingMD );
}
////
//// When extending a type, constructors have to be merged, and the first thing to check is whether or not oldTD and newTD share the same super class:
////
//// 1) Same Extends?
//// Yes)
//// 2) New Constructor?
//// Yes)
//// Just add newMD to the list of methods on oldTD.
//// DONE)
////
//// No)
//// [Either Merge or Discard should be set at this point]
//// Check Merge and Discard flags (for merge, only same super class calls are allowed, single operator, just forward arguments).
//// Substitute oldMD for newMD.
//// DONE)
////
//// No)
//// [In this case, newTD should extend System.Object, nothing else is allowed.]
//// 3) New Constructor?
//// Yes)
//// 4) Does oldTD have a default constructor?
//// Yes)
//// Remove call to newTD super constructor, inline in its place the default constructor.
//// Substitute oldMD for newMD.
//// DONE)
////
//// No)
//// Just add newMD to the list of methods on oldTD.
//// DONE)
////
//// No)
//// [Either Merge or Discard should be set at this point]
////
//// 5) Is Merge?
//// Yes)
//// Remove call to newTD super constructor, inline in its place the old constructor.
//// Substitute oldMD for newMD.
//// DONE)
////
//// No) [Then it's Discard]
//// Unless base() in oldMD is a call to the default constructor, fail.
//// Change call to object() with oldTD.super()
//// Substitute oldMD for newMD.
//// DONE)
////
if(m_fSameExtends) // 1)
{
if(overriddenMD == null) // 2)
{
if(fMerge)
{
if(overiddenDefaultConstructor == null)
{
throw TypeConsistencyErrorException.Create( "Overriding constructor '{0}' cannot be merged, neither a matching nor a default constructor could be found", overridingMD );
}
CallOperator oldCall = FindSuperConstructorCall( overridingCFG );
CallOperator newCall = InstanceCallOperator.New( oldCall.DebugInfo, oldCall.CallType, overiddenDefaultConstructor, new Expression[] { oldCall.FirstArgument }, true );
NotifyNewObjects( null, newCall );
oldCall.AddOperatorAfter( newCall );
overridingCFG.TraceToFile( "InlineCall" );
Transformations.InlineCall.Execute( newCall, NotifyNewObjects );
overridingCFG.TraceToFile( "InlineCall-Post" );
//
// Now we are left with two calls to the base constructor, we have to remove the second one.
//
bool fGotGoodOne = false;
foreach(Operator op in oldCall.BasicBlock.Operators)
{
CallOperator call = op as CallOperator;
if(call != null && call.TargetMethod is ConstructorMethodRepresentation)
{
if(fGotGoodOne == false)
{
fGotGoodOne = true;
}
else
{
call.Delete();
break;
}
}
}
}
fAddToOverridden = true;
}
else
{
if(fMerge)
{
// TODO: Check that the prologues of the two methods are the same.
//
// Create a proper invocation list.
//
VariableExpression[] args = overridingCFG.Arguments;
Expression[] rhs = new Expression[args.Length];
for(int i = 0; i < args.Length; i++)
{
rhs[i] = args[i];
}
//
// Substitute old call to overridden constructor, then inline the whole thing.
//
CallOperator oldCall = FindSuperConstructorCall( overridingCFG );
CallOperator newCall = InstanceCallOperator.New( oldCall.DebugInfo, oldCall.CallType, overriddenMD, rhs, true );
NotifyNewObjects( null, newCall );
oldCall.SubstituteWithOperator( newCall, Operator.SubstitutionFlags.CopyAnnotations );
overridingCFG.TraceToFile( "InlineCall" );
Transformations.InlineCall.Execute( newCall, NotifyNewObjects );
overridingCFG.TraceToFile( "InlineCall-Post" );
}
fSubstituteToOverridden = true;
}
}
else // Different super class
{
if(overriddenMD == null) // 3)
{
if(overiddenDefaultConstructor != null) // 4)
{
CallOperator call = FindSuperConstructorCall( overridingCFG );
call.TargetMethod = overiddenDefaultConstructor;
overridingCFG.TraceToFile( "InlineCall" );
Transformations.InlineCall.Execute( call, NotifyNewObjects );
overridingCFG.TraceToFile( "InlineCall-Post" );
}
fAddToOverridden = true;
}
else
{
if(fMerge) // 5)
{
// TODO: Check that the prologues of the two methods are the same.
CallOperator oldCall = FindSuperConstructorCall( overridingCFG );
CallOperator newCall = InstanceCallOperator.New( oldCall.DebugInfo, oldCall.CallType, overriddenMD, oldCall.Arguments, true );
NotifyNewObjects( null, newCall );
oldCall.SubstituteWithOperator( newCall, Operator.SubstitutionFlags.CopyAnnotations );
overridingCFG.TraceToFile( "InlineCall" );
Transformations.InlineCall.Execute( newCall, NotifyNewObjects );
overridingCFG.TraceToFile( "InlineCall-Post" );
}
fSubstituteToOverridden = true;
}
}
}
else
{
if(overriddenMD == null)
{
fAddToOverridden = true;
}
else
{
//
// Inline the other static constructor.
//
Expression[] rhs = new Expression[] { overriddenCFG.Arguments[0] };
CallOperator call = InstanceCallOperator.New( null, CallOperator.CallKind.Direct, overriddenMD, rhs, true );
NotifyNewObjects( null, call );
BasicBlock bb = overridingCFG.NormalizedEntryBasicBlock;
bb.FirstOperator.AddOperatorBefore( call );
overridingCFG.TraceToFile( "InlineCall" );
Transformations.InlineCall.Execute( call, NotifyNewObjects );
overridingCFG.TraceToFile( "InlineCall-Post" );
//--//
fSubstituteToOverridden = true;
}
}
}
else
{
//
// Non-constructor case.
//
bool fInsertPre = overridingMD.HasCustomAttribute( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_InjectAtEntryPointAttribute );
bool fInsertPost = overridingMD.HasCustomAttribute( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_InjectAtExitPointAttribute );
if(fInsertPre && fInsertPost)
{
throw TypeConsistencyErrorException.Create( "Method '{0}' cannot be decorated with both InjectAtEntryPoint and InjectAtExitPoint", overridingMD );
}
if(fInsertPre || fInsertPost)
{
if(overriddenMD == null)
{
throw TypeConsistencyErrorException.Create( "Method '{0}' cannot be injected into target because target is missing", overridingMD );
}
if(overriddenCFG == null)
{
throw TypeConsistencyErrorException.Create( "Method '{0}' cannot be injected into target because target doesn't have an implementation", overridingMD );
}
}
if(fInsertPre)
{
BasicBlock injectBasicBlock = overriddenCFG.GetInjectionPoint( BasicBlock.Qualifier.EntryInjectionEnd );
//
// Create a proper invocation list.
//
VariableExpression[] args = overriddenCFG.Arguments;
Expression[] rhs = new Expression[args.Length];
for(int i = 0; i < args.Length; i++)
{
rhs[i] = args[i];
}
CallOperator newCall = InstanceCallOperator.New( null, CallOperator.CallKind.Direct, overridingMD, rhs, true );
NotifyNewObjects( null, newCall );
injectBasicBlock.AddOperator( newCall );
overriddenCFG.TraceToFile( "InjectCall" );
Transformations.InlineCall.Execute( newCall, NotifyNewObjects );
overriddenCFG.TraceToFile( "InjectCall-Post" );
fRemoveOverriding = true;
}
else if(fInsertPost)
{
BasicBlock injectBasicBlock = overriddenCFG.GetInjectionPoint( BasicBlock.Qualifier.ExitInjectionStart );
//
// Create a proper invocation list.
//
VariableExpression[] args = overriddenCFG.Arguments;
Expression[] rhs = new Expression[args.Length + 1];
for(int i = 0; i < args.Length; i++)
{
rhs[i] = args[i];
}
rhs[args.Length] = overriddenCFG.ReturnValue;
CallOperator newCall = InstanceCallOperator.New( null, CallOperator.CallKind.Direct, overridingMD, VariableExpression.ToArray( overriddenCFG.ReturnValue ), rhs, true );
NotifyNewObjects( null, newCall );
injectBasicBlock.AddOperator( newCall );
overriddenCFG.TraceToFile( "InjectCall" );
Transformations.InlineCall.Execute( newCall, NotifyNewObjects );
overriddenCFG.TraceToFile( "InjectCall-Post" );
fRemoveOverriding = true;
}
else
{
//
// The default case is very simple, either add or substitute.
//
if(overriddenMD == null)
{
fAddToOverridden = true;
}
else
{
fSubstituteToOverridden = true;
}
}
}
if(fAddToOverridden)
{
m_overriddenTD.AddMethod( overridingMD );
fMigrateMethodImpl = true;
}
if(fSubstituteToOverridden)
{
m_overriddenTD.Substituite( overriddenMD, overridingMD );
remap[overriddenMD] = overridingMD;
fMigrateMethodImpl = true;
}
if(fRemoveOverriding)
{
m_overridingTD.RemoveMethod( overridingMD );
remap[overridingMD] = overriddenMD;
}
if(fMigrateMethodImpl)
{
MigrateMethodImpl( m_overriddenTD, m_overridingTD, overridingMD );
}
}
}
//--//
private void NotifyNewObjects( object from, object to )
{
m_newObjectsForReverseIndex.Insert( to );
}
private static CallOperator FindSuperConstructorCall( ControlFlowGraphStateForCodeTransformation cfg )
{
var bb = cfg.NormalizedEntryBasicBlock;
while(true)
{
Operator[] ops = bb.Operators;
CallOperator call = ops[0] as CallOperator;
if(call != null && call.TargetMethod is ConstructorMethodRepresentation)
{
return call;
}
var ctrl = bb.FlowControl as UnconditionalControlOperator;
if(ctrl == null)
{
break;
}
bb = ctrl.TargetBranch;
}
throw TypeConsistencyErrorException.Create( "Cannot find call to constructor in '{0}'", cfg.Method );
}
private static void MigrateMethodImpl( TypeRepresentation overriddenTD ,
TypeRepresentation overridingTD ,
MethodRepresentation overridingMD )
{
foreach(MethodImplRepresentation mi in overridingTD.MethodImpls)
{
if(mi.Body == overridingMD)
{
overriddenTD.AddMethodImpl( new MethodImplRepresentation( overridingMD, mi.Declaration ) );
}
}
}
//--//
internal void ProcessDuplicates()
{
while(m_duplicates.Count > 0)
{
Duplicate[] duplicates = m_duplicates.ToArray();
m_duplicates.Clear();
foreach(Duplicate duplicate in duplicates)
{
object from = duplicate.From;
object to = duplicate.To;
if(m_typeSystem.ReachabilitySet.IsProhibited( from ) == false &&
m_typeSystem.ReachabilitySet.IsProhibited( to ) == false )
{
if(Object.Equals( from, to ))
{
//
// Types are kept in a list, which doesn't shrink when we process remaps.
// We'll have to manually force an update.
//
if(from is TypeRepresentation)
{
var tdFrom = (TypeRepresentation)from;
m_typeSystem.RemoveDuplicateType( tdFrom );
}
//
// Fields are kept in an array, which doesn't shrink when we process remaps.
// We'll have to manually force an update.
//
if(from is FieldRepresentation)
{
var fdFrom = (FieldRepresentation)from;
var fdTo = (FieldRepresentation)to;
var td = fdFrom.OwnerType;
if(ArrayUtility.FindReferenceInNotNullArray( td.Fields, fdFrom ) >= 0 &&
ArrayUtility.FindReferenceInNotNullArray( td.Fields, fdTo ) >= 0)
{
td.RemoveField( fdFrom );
}
}
//
// Methods are kept in an array, which doesn't shrink when we process remaps.
// We'll have to manually force an update.
//
if(from is MethodRepresentation)
{
var mdFrom = (MethodRepresentation)from;
var mdTo = (MethodRepresentation)to;
var td = mdFrom.OwnerType;
if(ArrayUtility.FindReferenceInNotNullArray( td.Methods, mdFrom ) >= 0 &&
ArrayUtility.FindReferenceInNotNullArray( td.Methods, mdTo ) >= 0)
{
td.RemoveMethod( mdFrom );
}
}
ProcessRemap( from, to );
}
}
}
}
}
private void ProcessRemaps( GrowOnlyHashTable< object, object > remap )
{
object[] keys = remap.KeysToArray();
object[] values = remap.ValuesToArray();
for(int i = 0; i < keys.Length; i++)
{
#if TRACK_TIMING_LEVEL3
using(new ExecutionTiming( "Remap from {0} to {1} : {2}", keys[i], values[i], m_newObjectsForReverseIndex.Count ))
#endif
{
ProcessRemap( keys[i], values[i] );
}
}
}
private void ProcessRemap( object from ,
object to )
{
m_replaceFrom = from;
m_replaceTo = to;
object[] arrayFrom = null;
object[] arrayTo = null;
if(m_reverseIndex.CanBeTracked( from ) == false)
{
throw TypeConsistencyErrorException.Create( "Got unexpected source object to remap: {0}", from );
}
if(m_reverseIndex.CanBeTracked( to ) == false)
{
throw TypeConsistencyErrorException.Create( "Got unexpected destination object to remap: {0}", to );
}
//// List< object[] > pre = null;
////
//// {
//// pre = CollectUsageContext.Execute( m_typeSystem, from );
//// }
FlushNewObjects();
GrowOnlySet< object > setFrom = m_reverseIndex[from];
if(setFrom != null)
{
foreach(object context in setFrom)
{
m_activeContext = context;
this.Reset();
object obj = context; Transform( ref obj );
}
GrowOnlySet< object > setTo = m_reverseIndex[to];
if(setTo != null)
{
arrayFrom = setFrom.ToArray();
arrayTo = setTo.ToArray();
}
m_reverseIndex.Merge( from, to );
}
m_typeSystem.ProhibitUse( from );
//// if(pre != null)
//// {
//// List< object[] > post = CollectUsageContext.Execute( m_typeSystem, from );
//// }
if(arrayTo != null)
{
GrowOnlySet< object > set = SetFactory.New< object >();
foreach(object obj in arrayTo)
{
CheckForDuplicates( obj, set );
}
foreach(object obj in arrayFrom)
{
CheckForDuplicates( obj, set );
}
}
}
private void FlushNewObjects()
{
if(m_newObjectsForReverseIndex.Count > 0)
{
foreach(object obj in m_newObjectsForReverseIndex)
{
#if TRACK_TIMING_LEVEL4
using(new ExecutionTiming( "Update for {0}", obj ))
#endif
{
m_reverseIndex.Update( obj );
}
}
m_newObjectsForReverseIndex.Clear();
}
}
private void CheckForDuplicates( object obj ,
GrowOnlySet< object > set )
{
object objOld;
if(set.Contains( obj, out objOld ) == true)
{
if(Object.ReferenceEquals( obj, objOld ) == false)
{
m_duplicates.Add( new Duplicate( obj, objOld ) );
}
}
else
{
set.Insert( obj );
}
}
//--//
protected override object ShouldSubstitute( object target ,
out SubstitutionAction result )
{
object context = this.TopContext();
if(context == null)
{
result = SubstitutionAction.Unknown;
return null;
}
if(Object.ReferenceEquals( context, m_activeContext ))
{
if(Object.ReferenceEquals( m_replaceFrom, target ))
{
result = SubstitutionAction.Substitute;
return m_replaceTo;
}
else
{
result = SubstitutionAction.Unknown;
return null;
}
}
result = SubstitutionAction.Keep;
return null;
}
}
}
| |
// 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.Xml.Schema
{
using System;
using System.IO;
using System.Text;
using System.Resources;
using System.Runtime.Serialization;
using System.Globalization;
using System.Diagnostics;
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException"]/*' />
[Serializable]
public class XmlSchemaException : SystemException
{
private string _res;
private string[] _args;
private string _sourceUri;
private int _lineNumber;
private int _linePosition;
[NonSerialized]
private XmlSchemaObject _sourceSchemaObject;
// message != null for V1 exceptions deserialized in Whidbey
// message == null for V2 or higher exceptions; the exception message is stored on the base class (Exception._message)
private string _message;
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.XmlSchemaException5"]/*' />
protected XmlSchemaException(SerializationInfo info, StreamingContext context) : base(info, context)
{
_res = (string)info.GetValue("res", typeof(string));
_args = (string[])info.GetValue("args", typeof(string[]));
_sourceUri = (string)info.GetValue("sourceUri", typeof(string));
_lineNumber = (int)info.GetValue("lineNumber", typeof(int));
_linePosition = (int)info.GetValue("linePosition", typeof(int));
// deserialize optional members
string version = null;
foreach (SerializationEntry e in info)
{
if (e.Name == "version")
{
version = (string)e.Value;
}
}
if (version == null)
{
// deserializing V1 exception
_message = CreateMessage(_res, _args);
}
else
{
// deserializing V2 or higher exception -> exception message is serialized by the base class (Exception._message)
_message = null;
}
}
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.GetObjectData"]/*' />
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("res", _res);
info.AddValue("args", _args);
info.AddValue("sourceUri", _sourceUri);
info.AddValue("lineNumber", _lineNumber);
info.AddValue("linePosition", _linePosition);
info.AddValue("version", "2.0");
}
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.XmlSchemaException1"]/*' />
public XmlSchemaException() : this(null)
{
}
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.XmlSchemaException2"]/*' />
public XmlSchemaException(String message) : this(message, ((Exception)null), 0, 0)
{
#if DEBUG
Debug.Assert(message == null || !message.StartsWith("Sch_", StringComparison.Ordinal), "Do not pass a resource here!");
#endif
}
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.XmlSchemaException0"]/*' />
public XmlSchemaException(String message, Exception innerException) : this(message, innerException, 0, 0)
{
}
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.XmlSchemaException3"]/*' />
public XmlSchemaException(String message, Exception innerException, int lineNumber, int linePosition) :
this((message == null ? SR.Sch_DefaultException : SR.Xml_UserException), new string[] { message }, innerException, null, lineNumber, linePosition, null)
{
}
internal XmlSchemaException(string res, string[] args) :
this(res, args, null, null, 0, 0, null)
{ }
internal XmlSchemaException(string res, string arg) :
this(res, new string[] { arg }, null, null, 0, 0, null)
{ }
internal XmlSchemaException(string res, string arg, string sourceUri, int lineNumber, int linePosition) :
this(res, new string[] { arg }, null, sourceUri, lineNumber, linePosition, null)
{ }
internal XmlSchemaException(string res, string sourceUri, int lineNumber, int linePosition) :
this(res, (string[])null, null, sourceUri, lineNumber, linePosition, null)
{ }
internal XmlSchemaException(string res, string[] args, string sourceUri, int lineNumber, int linePosition) :
this(res, args, null, sourceUri, lineNumber, linePosition, null)
{ }
internal XmlSchemaException(string res, XmlSchemaObject source) :
this(res, (string[])null, source)
{ }
internal XmlSchemaException(string res, string arg, XmlSchemaObject source) :
this(res, new string[] { arg }, source)
{ }
internal XmlSchemaException(string res, string[] args, XmlSchemaObject source) :
this(res, args, null, source.SourceUri, source.LineNumber, source.LinePosition, source)
{ }
internal XmlSchemaException(string res, string[] args, Exception innerException, string sourceUri, int lineNumber, int linePosition, XmlSchemaObject source) :
base(CreateMessage(res, args), innerException)
{
HResult = HResults.XmlSchema;
_res = res;
_args = args;
_sourceUri = sourceUri;
_lineNumber = lineNumber;
_linePosition = linePosition;
_sourceSchemaObject = source;
}
internal static string CreateMessage(string res, string[] args)
{
try
{
if (args == null)
{
return res;
}
return string.Format(res, args);
}
catch (MissingManifestResourceException)
{
return "UNKNOWN(" + res + ")";
}
}
internal string GetRes
{
get
{
return _res;
}
}
internal string[] Args
{
get
{
return _args;
}
}
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.SourceUri"]/*' />
public string SourceUri
{
get { return _sourceUri; }
}
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.LineNumber"]/*' />
public int LineNumber
{
get { return _lineNumber; }
}
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.LinePosition"]/*' />
public int LinePosition
{
get { return _linePosition; }
}
/// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.SourceObject"]/*' />
public XmlSchemaObject SourceSchemaObject
{
get { return _sourceSchemaObject; }
}
/*internal static XmlSchemaException Create(string res) { //Since internal overload with res string will clash with public constructor that takes in a message
return new XmlSchemaException(res, (string[])null, null, null, 0, 0, null);
}*/
internal void SetSource(string sourceUri, int lineNumber, int linePosition)
{
_sourceUri = sourceUri;
_lineNumber = lineNumber;
_linePosition = linePosition;
}
internal void SetSchemaObject(XmlSchemaObject source)
{
_sourceSchemaObject = source;
}
internal void SetSource(XmlSchemaObject source)
{
_sourceSchemaObject = source;
_sourceUri = source.SourceUri;
_lineNumber = source.LineNumber;
_linePosition = source.LinePosition;
}
public override string Message
{
get
{
return (_message == null) ? base.Message : _message;
}
}
};
} // namespace System.Xml.Schema
| |
using System;
using System.Collections;
using Server;
using Server.HuePickers;
namespace Knives.Chat3
{
public class SendMessageGump : GumpPlus
{
#region Class Definitions
private Mobile c_From, c_To;
private Message c_Reply;
private string c_Text, c_Subject;
private MsgType c_MsgType;
#endregion
#region Constructors
public SendMessageGump(Mobile from, Mobile to, string txt, Message reply, MsgType type)
: base(from, 200, 200)
{
from.CloseGump(typeof(SendMessageGump));
Override = true;
c_From = from;
c_To = to;
c_Text = txt;
c_Subject = "";
c_Reply = reply;
c_MsgType = type;
if (c_Reply != null)
{
if (c_Reply.Subject.IndexOf("RE:") != 0)
c_Subject = "RE: " + c_Reply.Subject;
else
c_Subject = c_Reply.Subject;
}
}
#endregion
#region Methods
protected override void BuildGump()
{
int width = Data.GetData(Owner).ExtraPm ? 400 : 300;
int y = 10;
int field = Data.GetData(Owner).ExtraPm ? 300 : 150;
if (c_MsgType == MsgType.System)
AddHtml(0, y, width, "<CENTER>" + General.Local(94));
else if (c_MsgType == MsgType.Staff)
AddHtml(0, y, width, "<CENTER>" + General.Local(256));
else
AddHtml(0, y, width, "<CENTER>" + General.Local(62) + " " + c_To.RawName);
AddImage(width / 2 - 120, y + 2, 0x39);
AddImage(width / 2 + 90, y + 2, 0x3B);
if (Data.GetData(Owner).Recording == this)
{
AddHtml(30, y+=20, width-60, 25, c_Subject, true, false);
AddHtml(20, y+=30, width-40, field, c_Text, true, true);
AddHtml(0, y+=(field+20), width, "<CENTER>" + General.Local(63));
}
else
{
AddTextField(30, y+=20, width - 60, 21, Data.GetData(Owner).MsgC, 0xBBC, "Subject", c_Subject);
AddTextField(20, y+=30, width - 40, field, Data.GetData(Owner).MsgC, 0xBBC, "Text", c_Text);
y+=(field+15);
if(Data.GetData(Owner).ExtraPm)
AddButton(20, y, 0x2333, "Record", new GumpCallback(Record));
AddButton(50, y, Data.GetData(Owner).ExtraPm ? 0x25E4 : 0x25E8, Data.GetData(Owner).ExtraPm ? 0x25E5 : 0x25E9, "ExtraPm", new GumpCallback(ExtraPm));
}
AddImage(width / 2 - 10, y, 0x2342, Data.GetData(Owner).MsgC);
AddButton(width / 2 - 6, y + 4, 0x2716, "Channel Color", new GumpCallback(Color));
AddHtml(width - 85, y, 50, General.Local(252));
AddButton(width-100, y+3, 0x2716, "Send", new GumpCallback(Send));
AddBackgroundZero(0, 0, width, y + 30, Data.GetData(Owner).DefaultBack);
}
#endregion
#region Responses
private void ExtraPm()
{
Data.GetData(Owner).ExtraPm = !Data.GetData(Owner).ExtraPm;
NewGump();
}
public void AddText(string txt)
{
c_Text += txt;
NewGump();
}
private void Save()
{
c_Subject = GetTextField("Subject");
c_Text = GetTextField("Text");
}
private void Record()
{
Save();
if (c_Subject.Trim() == "")
c_Subject = "No Subject";
Data.GetData(Owner).Recording = this;
Owner.SendMessage(Data.GetData(Owner).SystemC, General.Local(65));
NewGump();
}
private void Send()
{
if( Data.GetData(Owner).Recording == null )
Save();
if (c_Text.Trim() == "")
{
Owner.SendMessage(Data.GetData(Owner).SystemC, General.Local(66));
NewGump();
return;
}
if (c_Subject.Trim() == "")
c_Subject = "No subject";
if (!TrackSpam.LogSpam(Owner, "Message", TimeSpan.FromSeconds(Data.MsgSpam)))
{
Owner.SendMessage(Data.GetData(Owner).SystemC, General.Local(97));
NewGump();
return;
}
if (Data.GetData(Owner).Recording == this)
Data.GetData(Owner).Recording = null;
if (Data.FilterMsg)
{
c_Text = Filter.FilterText(Owner, c_Text, false);
c_Subject = Filter.FilterText(Owner, c_Subject, false);
}
if (c_MsgType == MsgType.System)
{
foreach (Data data in Data.Datas.Values)
{
data.AddMessage(new Message(Owner, c_Subject, c_Text, MsgType.System));
General.PmNotify(data.Mobile);
}
}
else if (c_MsgType == MsgType.Staff)
{
foreach (Data data in Data.Datas.Values)
{
if (data.Mobile.AccessLevel != AccessLevel.Player)
{
data.AddMessage(new Message(Owner, c_Subject, c_Text, MsgType.Staff));
General.PmNotify(data.Mobile);
}
}
}
else
{
Data.GetData(c_To).AddMessage(new Message(Owner, c_Subject, c_Text, MsgType.Normal));
General.PmNotify(c_To);
Owner.SendMessage(Data.GetData(Owner).SystemC, General.Local(67) + " " + c_To.RawName);
if (Data.GetData(c_To).Status != OnlineStatus.Online)
Owner.SendMessage(Data.GetData(Owner).SystemC, c_To.RawName + ": " + Data.GetData(c_To).AwayMsg);
}
if (Data.LogPms)
Logging.LogPm(String.Format(DateTime.Now + " <Mail> {0} to {1}: {2}", Owner.RawName, (c_To == null ? "All" : c_To.RawName), c_Text));
foreach( Data data in Data.Datas.Values)
if (data.Mobile.AccessLevel >= c_From.AccessLevel && ((data.GlobalM && !data.GIgnores.Contains(c_From)) || data.GListens.Contains(c_From)))
data.Mobile.SendMessage(data.GlobalMC, String.Format("(Global) <Mail> {0} to {1}: {2}", Owner.RawName, (c_To == null ? "All" : c_To.RawName), c_Text ));
}
private void Color()
{
Owner.SendHuePicker(new InternalPicker(this));
}
#endregion
#region Internal Classes
private class InternalPicker : HuePicker
{
private GumpPlus c_Gump;
public InternalPicker(GumpPlus g)
: base(0x1018)
{
c_Gump = g;
}
public override void OnResponse(int hue)
{
Data.GetData(c_Gump.Owner).MsgC = hue;
c_Gump.NewGump();
}
}
#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.ComponentModel;
using System.Diagnostics;
using System.Runtime;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Dispatcher;
using System.Threading;
namespace System.ServiceModel
{
public abstract class ClientBase<TChannel> : ICommunicationObject, IDisposable
where TChannel : class
{
private TChannel _channel;
private ChannelFactoryRef<TChannel> _channelFactoryRef;
private EndpointTrait<TChannel> _endpointTrait;
// Determine whether the proxy can share factory with others. It is false only if the public getters
// are invoked.
private bool _canShareFactory = true;
// Determine whether the proxy is currently holding a cached factory
private bool _useCachedFactory;
// Determine whether we have locked down sharing for this proxy. This is turned on only when the channel
// is created.
private bool _sharingFinalized;
// Determine whether the ChannelFactoryRef has been released. We should release it only once per proxy
private bool _channelFactoryRefReleased;
// Determine whether we have released the last ref count of the ChannelFactory so that we could abort it when it was closing.
private bool _releasedLastRef;
private object finalizeLock = new object();
// Cache at most 32 ChannelFactories
private const int MaxNumChannelFactories = 32;
private static ChannelFactoryRefCache<TChannel> s_factoryRefCache = new ChannelFactoryRefCache<TChannel>(MaxNumChannelFactories);
private static object s_staticLock = new object();
private static object s_cacheLock = new object();
private static CacheSetting s_cacheSetting = CacheSetting.Default;
private static bool s_isCacheSettingReadOnly;
private static AsyncCallback s_onAsyncCallCompleted = Fx.ThunkCallback(new AsyncCallback(OnAsyncCallCompleted));
protected ClientBase()
{
throw new PlatformNotSupportedException(SR.ConfigurationFilesNotSupported);
}
protected ClientBase(string endpointConfigurationName)
{
throw new PlatformNotSupportedException(SR.ConfigurationFilesNotSupported);
}
protected ClientBase(string endpointConfigurationName, string remoteAddress)
{
throw new PlatformNotSupportedException(SR.ConfigurationFilesNotSupported);
}
protected ClientBase(string endpointConfigurationName, EndpointAddress remoteAddress)
{
throw new PlatformNotSupportedException(SR.ConfigurationFilesNotSupported);
}
protected ClientBase(Binding binding, EndpointAddress remoteAddress)
{
if (binding == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(binding));
}
if (remoteAddress == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(remoteAddress));
}
MakeCacheSettingReadOnly();
if (s_cacheSetting == CacheSetting.AlwaysOn)
{
_endpointTrait = new ProgrammaticEndpointTrait<TChannel>(binding, remoteAddress, null);
InitializeChannelFactoryRef();
}
else
{
_channelFactoryRef = new ChannelFactoryRef<TChannel>(new ChannelFactory<TChannel>(binding, remoteAddress));
_channelFactoryRef.ChannelFactory.TraceOpenAndClose = false;
TryDisableSharing();
}
}
protected ClientBase(ServiceEndpoint endpoint)
{
if (endpoint == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(endpoint));
}
MakeCacheSettingReadOnly();
if (s_cacheSetting == CacheSetting.AlwaysOn)
{
_endpointTrait = new ServiceEndpointTrait<TChannel>(endpoint, null);
InitializeChannelFactoryRef();
}
else
{
_channelFactoryRef = new ChannelFactoryRef<TChannel>(new ChannelFactory<TChannel>(endpoint));
_channelFactoryRef.ChannelFactory.TraceOpenAndClose = false;
TryDisableSharing();
}
}
protected ClientBase(InstanceContext callbackInstance, Binding binding, EndpointAddress remoteAddress)
{
if (callbackInstance == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(callbackInstance));
}
if (binding == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(binding));
}
if (remoteAddress == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(remoteAddress));
}
MakeCacheSettingReadOnly();
if (s_cacheSetting == CacheSetting.AlwaysOn)
{
_endpointTrait = new ProgrammaticEndpointTrait<TChannel>(binding, remoteAddress, callbackInstance);
InitializeChannelFactoryRef();
}
else
{
_channelFactoryRef = new ChannelFactoryRef<TChannel>(
new DuplexChannelFactory<TChannel>(callbackInstance, binding, remoteAddress));
_channelFactoryRef.ChannelFactory.TraceOpenAndClose = false;
TryDisableSharing();
}
}
protected T GetDefaultValueForInitialization<T>()
{
return default(T);
}
private object ThisLock { get; } = new object();
protected TChannel Channel
{
get
{
// created on demand, so that Mort can modify .Endpoint before calling methods on the client
if (_channel == null)
{
lock (ThisLock)
{
if (_channel == null)
{
using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null)
{
if (DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity.Start(activity, SR.Format(SR.ActivityOpenClientBase, typeof(TChannel).FullName), ActivityType.OpenClient);
}
if (_useCachedFactory)
{
try
{
CreateChannelInternal();
}
catch (Exception ex)
{
if (_useCachedFactory &&
(ex is CommunicationException ||
ex is ObjectDisposedException ||
ex is TimeoutException))
{
DiagnosticUtility.TraceHandledException(ex, TraceEventType.Warning);
InvalidateCacheAndCreateChannel();
}
else
{
throw;
}
}
}
else
{
CreateChannelInternal();
}
}
}
}
}
return _channel;
}
}
public static CacheSetting CacheSetting
{
get
{
return s_cacheSetting;
}
set
{
lock (s_cacheLock)
{
if (s_isCacheSettingReadOnly && s_cacheSetting != value)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxImmutableClientBaseCacheSetting, typeof(TChannel).ToString())));
}
else
{
s_cacheSetting = value;
}
}
}
}
public ChannelFactory<TChannel> ChannelFactory
{
get
{
if (s_cacheSetting == CacheSetting.Default)
{
TryDisableSharing();
}
return GetChannelFactory();
}
}
public ClientCredentials ClientCredentials
{
get
{
return ChannelFactory.Credentials;
}
}
public CommunicationState State
{
get
{
IChannel channel = (IChannel)_channel;
if (channel != null)
{
return channel.State;
}
else
{
// we may have failed to create the channel under open, in which case we our factory wouldn't be open
if (!_useCachedFactory)
{
return GetChannelFactory().State;
}
else
{
return CommunicationState.Created;
}
}
}
}
public IClientChannel InnerChannel
{
get
{
return (IClientChannel)Channel;
}
}
public ServiceEndpoint Endpoint
{
get
{
return ChannelFactory.Endpoint;
}
}
public void Open()
{
((ICommunicationObject)this).Open(GetChannelFactory().InternalOpenTimeout);
}
public void Abort()
{
IChannel channel = (IChannel)_channel;
if (channel != null)
{
channel.Abort();
}
if (!_channelFactoryRefReleased)
{
lock (s_staticLock)
{
if (!_channelFactoryRefReleased)
{
if (_channelFactoryRef.Release())
{
_releasedLastRef = true;
}
_channelFactoryRefReleased = true;
}
}
}
// Abort the ChannelFactory if we released the last one. We should be able to abort it when another thread is closing it.
if (_releasedLastRef)
{
_channelFactoryRef.Abort();
}
}
public void Close()
{
((ICommunicationObject)this).Close(GetChannelFactory().InternalCloseTimeout);
}
// This ensures that the cachesetting (on, off or default) cannot be modified by
// another ClientBase instance of matching TChannel after the first instance is created.
private void MakeCacheSettingReadOnly()
{
if (s_isCacheSettingReadOnly)
{
return;
}
lock (s_cacheLock)
{
s_isCacheSettingReadOnly = true;
}
}
void CreateChannelInternal()
{
try
{
_channel = CreateChannel();
if (_sharingFinalized)
{
if (_canShareFactory && !_useCachedFactory)
{
// It is OK to add ChannelFactory to the cache now.
TryAddChannelFactoryToCache();
}
}
}
finally
{
if (!_sharingFinalized && s_cacheSetting == CacheSetting.Default)
{
// this.CreateChannel() is not called. For safety, we disable sharing.
TryDisableSharing();
}
}
}
protected virtual TChannel CreateChannel()
{
if (_sharingFinalized)
{
return GetChannelFactory().CreateChannel();
}
lock (finalizeLock)
{
_sharingFinalized = true;
return GetChannelFactory().CreateChannel();
}
}
void IDisposable.Dispose()
{
Close();
}
void ICommunicationObject.Open(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (!_useCachedFactory)
{
GetChannelFactory().Open(timeoutHelper.RemainingTime());
}
InnerChannel.Open(timeoutHelper.RemainingTime());
}
void ICommunicationObject.Close(TimeSpan timeout)
{
using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null)
{
if (DiagnosticUtility.ShouldUseActivity)
{
ServiceModelActivity.Start(activity, SR.Format(SR.ActivityCloseClientBase, typeof(TChannel).FullName), ActivityType.Close);
}
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (_channel != null)
{
InnerChannel.Close(timeoutHelper.RemainingTime());
}
if (!_channelFactoryRefReleased)
{
lock (s_staticLock)
{
if (!_channelFactoryRefReleased)
{
if (_channelFactoryRef.Release())
{
_releasedLastRef = true;
}
_channelFactoryRefReleased = true;
}
}
// Close the factory outside of the lock so that we can abort from a different thread.
if (_releasedLastRef)
{
if (_useCachedFactory)
{
_channelFactoryRef.Abort();
}
else
{
_channelFactoryRef.Close(timeoutHelper.RemainingTime());
}
}
}
}
}
event EventHandler ICommunicationObject.Closed
{
add
{
InnerChannel.Closed += value;
}
remove
{
InnerChannel.Closed -= value;
}
}
event EventHandler ICommunicationObject.Closing
{
add
{
InnerChannel.Closing += value;
}
remove
{
InnerChannel.Closing -= value;
}
}
event EventHandler ICommunicationObject.Faulted
{
add
{
InnerChannel.Faulted += value;
}
remove
{
InnerChannel.Faulted -= value;
}
}
event EventHandler ICommunicationObject.Opened
{
add
{
InnerChannel.Opened += value;
}
remove
{
InnerChannel.Opened -= value;
}
}
event EventHandler ICommunicationObject.Opening
{
add
{
InnerChannel.Opening += value;
}
remove
{
InnerChannel.Opening -= value;
}
}
IAsyncResult ICommunicationObject.BeginClose(AsyncCallback callback, object state)
{
return ((ICommunicationObject)this).BeginClose(GetChannelFactory().InternalCloseTimeout, callback, state);
}
IAsyncResult ICommunicationObject.BeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return new ChainedAsyncResult(timeout, callback, state, BeginChannelClose, EndChannelClose, BeginFactoryClose, EndFactoryClose);
}
void ICommunicationObject.EndClose(IAsyncResult result)
{
ChainedAsyncResult.End(result);
}
IAsyncResult ICommunicationObject.BeginOpen(AsyncCallback callback, object state)
{
return ((ICommunicationObject)this).BeginOpen(GetChannelFactory().InternalOpenTimeout, callback, state);
}
IAsyncResult ICommunicationObject.BeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return new ChainedAsyncResult(timeout, callback, state, BeginFactoryOpen, EndFactoryOpen, BeginChannelOpen, EndChannelOpen);
}
void ICommunicationObject.EndOpen(IAsyncResult result)
{
ChainedAsyncResult.End(result);
}
//ChainedAsyncResult methods for opening and closing ChannelFactory<T>
internal IAsyncResult BeginFactoryOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
if (_useCachedFactory)
{
return new CompletedAsyncResult(callback, state);
}
else
{
return GetChannelFactory().BeginOpen(timeout, callback, state);
}
}
internal void EndFactoryOpen(IAsyncResult result)
{
if (_useCachedFactory)
{
CompletedAsyncResult.End(result);
}
else
{
GetChannelFactory().EndOpen(result);
}
}
internal IAsyncResult BeginChannelOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return InnerChannel.BeginOpen(timeout, callback, state);
}
internal void EndChannelOpen(IAsyncResult result)
{
InnerChannel.EndOpen(result);
}
internal IAsyncResult BeginFactoryClose(TimeSpan timeout, AsyncCallback callback, object state)
{
if (_useCachedFactory)
{
return new CompletedAsyncResult(callback, state);
}
else
{
return GetChannelFactory().BeginClose(timeout, callback, state);
}
}
internal void EndFactoryClose(IAsyncResult result)
{
if (typeof(CompletedAsyncResult).IsAssignableFrom(result.GetType()))
{
CompletedAsyncResult.End(result);
}
else
{
GetChannelFactory().EndClose(result);
}
}
internal IAsyncResult BeginChannelClose(TimeSpan timeout, AsyncCallback callback, object state)
{
if (_channel != null)
{
return InnerChannel.BeginClose(timeout, callback, state);
}
else
{
return new CompletedAsyncResult(callback, state);
}
}
internal void EndChannelClose(IAsyncResult result)
{
if (typeof(CompletedAsyncResult).IsAssignableFrom(result.GetType()))
{
CompletedAsyncResult.End(result);
}
else
{
InnerChannel.EndClose(result);
}
}
ChannelFactory<TChannel> GetChannelFactory()
{
return _channelFactoryRef.ChannelFactory;
}
void InitializeChannelFactoryRef()
{
Fx.Assert(_channelFactoryRef == null, "The channelFactory should have never been assigned");
Fx.Assert(_canShareFactory, "GetChannelFactoryFromCache can be called only when canShareFactory is true");
lock (s_staticLock)
{
ChannelFactoryRef<TChannel> factoryRef;
if (s_factoryRefCache.TryGetValue(_endpointTrait, out factoryRef))
{
if (factoryRef.ChannelFactory.State != CommunicationState.Opened)
{
// Remove the bad ChannelFactory.
s_factoryRefCache.Remove(_endpointTrait);
}
else
{
_channelFactoryRef = factoryRef;
_channelFactoryRef.AddRef();
_useCachedFactory = true;
if (WcfEventSource.Instance.ClientBaseChannelFactoryCacheHitIsEnabled())
{
WcfEventSource.Instance.ClientBaseChannelFactoryCacheHit(this);
}
return;
}
}
}
if (_channelFactoryRef == null)
{
// Creating the ChannelFactory at initial time to catch configuration exception earlier.
_channelFactoryRef = CreateChannelFactoryRef(_endpointTrait);
}
}
static ChannelFactoryRef<TChannel> CreateChannelFactoryRef(EndpointTrait<TChannel> endpointTrait)
{
Fx.Assert(endpointTrait != null, "The endpointTrait should not be null when the factory can be shared.");
ChannelFactory<TChannel> channelFactory = endpointTrait.CreateChannelFactory();
channelFactory.TraceOpenAndClose = false;
return new ChannelFactoryRef<TChannel>(channelFactory);
}
// Once the channel is created, we can't disable caching.
// This method can be called safely multiple times.
// this.sharingFinalized is set the first time the method is called.
// Subsequent calls are essentially no-ops.
void TryDisableSharing()
{
if (_sharingFinalized)
{
return;
}
lock (finalizeLock)
{
if (_sharingFinalized)
{
return;
}
_canShareFactory = false;
_sharingFinalized = true;
if (_useCachedFactory)
{
ChannelFactoryRef<TChannel> pendingFactoryRef = _channelFactoryRef;
_channelFactoryRef = CreateChannelFactoryRef(_endpointTrait);
_useCachedFactory = false;
lock (s_staticLock)
{
if (!pendingFactoryRef.Release())
{
pendingFactoryRef = null;
}
}
if (pendingFactoryRef != null)
{
pendingFactoryRef.Abort();
}
}
}
// can be done outside the lock since the lines below do not access shared data.
// also the use of this.sharingFinalized in the lines above ensures that tracing
// happens only once and only when needed.
if (WcfEventSource.Instance.ClientBaseUsingLocalChannelFactoryIsEnabled())
{
WcfEventSource.Instance.ClientBaseUsingLocalChannelFactory(this);
}
}
void TryAddChannelFactoryToCache()
{
Fx.Assert(_canShareFactory, "This should be called only when this proxy can share ChannelFactory.");
Fx.Assert(_channelFactoryRef.ChannelFactory.State == CommunicationState.Opened,
"The ChannelFactory must be in Opened state for caching.");
// Lock the cache and add the item to synchronize with lookup.
lock (s_staticLock)
{
ChannelFactoryRef<TChannel> cfRef;
if (!s_factoryRefCache.TryGetValue(_endpointTrait, out cfRef))
{
// Increment the ref count before adding to the cache.
_channelFactoryRef.AddRef();
s_factoryRefCache.Add(_endpointTrait, _channelFactoryRef);
_useCachedFactory = true;
if (WcfEventSource.Instance.ClientBaseCachedChannelFactoryCountIsEnabled())
{
WcfEventSource.Instance.ClientBaseCachedChannelFactoryCount(s_factoryRefCache.Count, MaxNumChannelFactories, this);
}
}
}
}
// NOTE: This should be called inside ThisLock
void InvalidateCacheAndCreateChannel()
{
RemoveFactoryFromCache();
TryDisableSharing();
CreateChannelInternal();
}
void RemoveFactoryFromCache()
{
lock (s_staticLock)
{
ChannelFactoryRef<TChannel> factoryRef;
if (s_factoryRefCache.TryGetValue(_endpointTrait, out factoryRef))
{
if (object.ReferenceEquals(_channelFactoryRef, factoryRef))
{
s_factoryRefCache.Remove(_endpointTrait);
}
}
}
}
// WARNING: changes in the signature/name of the following delegates must be applied to the
// ClientClassGenerator.cs as well, otherwise the ClientClassGenerator would generate wrong code.
protected delegate IAsyncResult BeginOperationDelegate(object[] inValues, AsyncCallback asyncCallback, object state);
protected delegate object[] EndOperationDelegate(IAsyncResult result);
// WARNING: Any changes in the signature/name of the following type and its ctor must be applied to the
// ClientClassGenerator.cs as well, otherwise the ClientClassGenerator would generate wrong code.
protected class InvokeAsyncCompletedEventArgs : AsyncCompletedEventArgs
{
internal InvokeAsyncCompletedEventArgs(object[] results, Exception error, bool cancelled, object userState)
: base(error, cancelled, userState)
{
Results = results;
}
public object[] Results { get; }
}
// WARNING: Any changes in the signature/name of the following method ctor must be applied to the
// ClientClassGenerator.cs as well, otherwise the ClientClassGenerator would generate wrong code.
protected void InvokeAsync(BeginOperationDelegate beginOperationDelegate, object[] inValues,
EndOperationDelegate endOperationDelegate, SendOrPostCallback operationCompletedCallback, object userState)
{
if (beginOperationDelegate == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(beginOperationDelegate));
}
if (endOperationDelegate == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(endOperationDelegate));
}
AsyncOperation asyncOperation = AsyncOperationManager.CreateOperation(userState);
AsyncOperationContext context = new AsyncOperationContext(asyncOperation, endOperationDelegate, operationCompletedCallback);
Exception error = null;
object[] results = null;
IAsyncResult result = null;
try
{
result = beginOperationDelegate(inValues, s_onAsyncCallCompleted, context);
if (result.CompletedSynchronously)
{
results = endOperationDelegate(result);
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
error = e;
}
if (error != null || result.CompletedSynchronously) /* result cannot be null if error == null */
{
CompleteAsyncCall(context, results, error);
}
}
private static void OnAsyncCallCompleted(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
AsyncOperationContext context = (AsyncOperationContext)result.AsyncState;
Exception error = null;
object[] results = null;
try
{
results = context.EndDelegate(result);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
error = e;
}
CompleteAsyncCall(context, results, error);
}
private static void CompleteAsyncCall(AsyncOperationContext context, object[] results, Exception error)
{
if (context.CompletionCallback != null)
{
InvokeAsyncCompletedEventArgs e = new InvokeAsyncCompletedEventArgs(results, error, false, context.AsyncOperation.UserSuppliedState);
context.AsyncOperation.PostOperationCompleted(context.CompletionCallback, e);
}
else
{
context.AsyncOperation.OperationCompleted();
}
}
protected class AsyncOperationContext
{
private SendOrPostCallback _completionCallback;
internal AsyncOperationContext(AsyncOperation asyncOperation, EndOperationDelegate endDelegate, SendOrPostCallback completionCallback)
{
AsyncOperation = asyncOperation;
EndDelegate = endDelegate;
_completionCallback = completionCallback;
}
internal AsyncOperation AsyncOperation { get; }
internal EndOperationDelegate EndDelegate { get; }
internal SendOrPostCallback CompletionCallback
{
get
{
return _completionCallback;
}
}
}
protected class ChannelBase<T> : IClientChannel, IOutputChannel, IRequestChannel, IChannelBaseProxy
where T : class
{
private ServiceChannel _channel;
private ImmutableClientRuntime _runtime;
protected ChannelBase(ClientBase<T> client)
{
if (client.Endpoint.Address == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxChannelFactoryEndpointAddressUri));
}
ChannelFactory<T> cf = client.ChannelFactory;
cf.EnsureOpened(); // to prevent the NullReferenceException that is thrown if the ChannelFactory is not open when cf.ServiceChannelFactory is accessed.
_channel = cf.ServiceChannelFactory.CreateServiceChannel(client.Endpoint.Address, client.Endpoint.Address.Uri);
_channel.InstanceContext = cf.CallbackInstance;
_runtime = _channel.ClientRuntime.GetRuntime();
}
protected IAsyncResult BeginInvoke(string methodName, object[] args, AsyncCallback callback, object state)
{
object[] inArgs = new object[args.Length + 2];
Array.Copy(args, inArgs, args.Length);
inArgs[inArgs.Length - 2] = callback;
inArgs[inArgs.Length - 1] = state;
MethodCall methodCall = new MethodCall(inArgs);
ProxyOperationRuntime op = GetOperationByName(methodName);
object[] ins = op.MapAsyncBeginInputs(methodCall, out callback, out state);
return _channel.BeginCall(op.Action, op.IsOneWay, op, ins, callback, state);
}
protected object EndInvoke(string methodName, object[] args, IAsyncResult result)
{
object[] inArgs = new object[args.Length + 1];
Array.Copy(args, inArgs, args.Length);
inArgs[inArgs.Length - 1] = result;
MethodCall methodCall = new MethodCall(inArgs);
ProxyOperationRuntime op = GetOperationByName(methodName);
object[] outs;
op.MapAsyncEndInputs(methodCall, out result, out outs);
object ret = _channel.EndCall(op.Action, outs, result);
object[] retArgs = op.MapAsyncOutputs(methodCall, outs, ref ret);
if (retArgs != null)
{
Fx.Assert(retArgs.Length == inArgs.Length, "retArgs.Length should be equal to inArgs.Length");
Array.Copy(retArgs, args, args.Length);
}
return ret;
}
private ProxyOperationRuntime GetOperationByName(string methodName)
{
ProxyOperationRuntime op = _runtime.GetOperationByName(methodName);
if (op == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SFxMethodNotSupported1, methodName)));
}
return op;
}
bool IClientChannel.AllowInitializationUI
{
get { return ((IClientChannel)_channel).AllowInitializationUI; }
set { ((IClientChannel)_channel).AllowInitializationUI = value; }
}
bool IClientChannel.DidInteractiveInitialization
{
get { return ((IClientChannel)_channel).DidInteractiveInitialization; }
}
Uri IClientChannel.Via
{
get { return ((IClientChannel)_channel).Via; }
}
event EventHandler<UnknownMessageReceivedEventArgs> IClientChannel.UnknownMessageReceived
{
add { ((IClientChannel)_channel).UnknownMessageReceived += value; }
remove { ((IClientChannel)_channel).UnknownMessageReceived -= value; }
}
void IClientChannel.DisplayInitializationUI()
{
((IClientChannel)_channel).DisplayInitializationUI();
}
IAsyncResult IClientChannel.BeginDisplayInitializationUI(AsyncCallback callback, object state)
{
return ((IClientChannel)_channel).BeginDisplayInitializationUI(callback, state);
}
void IClientChannel.EndDisplayInitializationUI(IAsyncResult result)
{
((IClientChannel)_channel).EndDisplayInitializationUI(result);
}
bool IContextChannel.AllowOutputBatching
{
get { return ((IContextChannel)_channel).AllowOutputBatching; }
set { ((IContextChannel)_channel).AllowOutputBatching = value; }
}
IInputSession IContextChannel.InputSession
{
get { return ((IContextChannel)_channel).InputSession; }
}
EndpointAddress IContextChannel.LocalAddress
{
get { return ((IContextChannel)_channel).LocalAddress; }
}
TimeSpan IContextChannel.OperationTimeout
{
get { return ((IContextChannel)_channel).OperationTimeout; }
set { ((IContextChannel)_channel).OperationTimeout = value; }
}
IOutputSession IContextChannel.OutputSession
{
get { return ((IContextChannel)_channel).OutputSession; }
}
EndpointAddress IContextChannel.RemoteAddress
{
get { return ((IContextChannel)_channel).RemoteAddress; }
}
string IContextChannel.SessionId
{
get { return ((IContextChannel)_channel).SessionId; }
}
TProperty IChannel.GetProperty<TProperty>()
{
return ((IChannel)_channel).GetProperty<TProperty>();
}
CommunicationState ICommunicationObject.State
{
get { return ((ICommunicationObject)_channel).State; }
}
event EventHandler ICommunicationObject.Closed
{
add { ((ICommunicationObject)_channel).Closed += value; }
remove { ((ICommunicationObject)_channel).Closed -= value; }
}
event EventHandler ICommunicationObject.Closing
{
add { ((ICommunicationObject)_channel).Closing += value; }
remove { ((ICommunicationObject)_channel).Closing -= value; }
}
event EventHandler ICommunicationObject.Faulted
{
add { ((ICommunicationObject)_channel).Faulted += value; }
remove { ((ICommunicationObject)_channel).Faulted -= value; }
}
event EventHandler ICommunicationObject.Opened
{
add { ((ICommunicationObject)_channel).Opened += value; }
remove { ((ICommunicationObject)_channel).Opened -= value; }
}
event EventHandler ICommunicationObject.Opening
{
add { ((ICommunicationObject)_channel).Opening += value; }
remove { ((ICommunicationObject)_channel).Opening -= value; }
}
void ICommunicationObject.Abort()
{
((ICommunicationObject)_channel).Abort();
}
void ICommunicationObject.Close()
{
((ICommunicationObject)_channel).Close();
}
void ICommunicationObject.Close(TimeSpan timeout)
{
((ICommunicationObject)_channel).Close(timeout);
}
IAsyncResult ICommunicationObject.BeginClose(AsyncCallback callback, object state)
{
return ((ICommunicationObject)_channel).BeginClose(callback, state);
}
IAsyncResult ICommunicationObject.BeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return ((ICommunicationObject)_channel).BeginClose(timeout, callback, state);
}
void ICommunicationObject.EndClose(IAsyncResult result)
{
((ICommunicationObject)_channel).EndClose(result);
}
void ICommunicationObject.Open()
{
((ICommunicationObject)_channel).Open();
}
void ICommunicationObject.Open(TimeSpan timeout)
{
((ICommunicationObject)_channel).Open(timeout);
}
IAsyncResult ICommunicationObject.BeginOpen(AsyncCallback callback, object state)
{
return ((ICommunicationObject)_channel).BeginOpen(callback, state);
}
IAsyncResult ICommunicationObject.BeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return ((ICommunicationObject)_channel).BeginOpen(timeout, callback, state);
}
void ICommunicationObject.EndOpen(IAsyncResult result)
{
((ICommunicationObject)_channel).EndOpen(result);
}
IExtensionCollection<IContextChannel> IExtensibleObject<IContextChannel>.Extensions
{
get { return ((IExtensibleObject<IContextChannel>)_channel).Extensions; }
}
void IDisposable.Dispose()
{
((IDisposable)_channel).Dispose();
}
Uri IOutputChannel.Via
{
get { return ((IOutputChannel)_channel).Via; }
}
EndpointAddress IOutputChannel.RemoteAddress
{
get { return ((IOutputChannel)_channel).RemoteAddress; }
}
void IOutputChannel.Send(Message message)
{
((IOutputChannel)_channel).Send(message);
}
void IOutputChannel.Send(Message message, TimeSpan timeout)
{
((IOutputChannel)_channel).Send(message, timeout);
}
IAsyncResult IOutputChannel.BeginSend(Message message, AsyncCallback callback, object state)
{
return ((IOutputChannel)_channel).BeginSend(message, callback, state);
}
IAsyncResult IOutputChannel.BeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state)
{
return ((IOutputChannel)_channel).BeginSend(message, timeout, callback, state);
}
void IOutputChannel.EndSend(IAsyncResult result)
{
((IOutputChannel)_channel).EndSend(result);
}
Uri IRequestChannel.Via
{
get { return ((IRequestChannel)_channel).Via; }
}
EndpointAddress IRequestChannel.RemoteAddress
{
get { return ((IRequestChannel)_channel).RemoteAddress; }
}
Message IRequestChannel.Request(Message message)
{
return ((IRequestChannel)_channel).Request(message);
}
Message IRequestChannel.Request(Message message, TimeSpan timeout)
{
return ((IRequestChannel)_channel).Request(message, timeout);
}
IAsyncResult IRequestChannel.BeginRequest(Message message, AsyncCallback callback, object state)
{
return ((IRequestChannel)_channel).BeginRequest(message, callback, state);
}
IAsyncResult IRequestChannel.BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, object state)
{
return ((IRequestChannel)_channel).BeginRequest(message, timeout, callback, state);
}
Message IRequestChannel.EndRequest(IAsyncResult result)
{
return ((IRequestChannel)_channel).EndRequest(result);
}
ServiceChannel IChannelBaseProxy.GetServiceChannel()
{
return _channel;
}
}
}
}
| |
using System.Net;
using System.Reflection;
using FluentAssertions;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Resources;
using JsonApiDotNetCore.Serialization.Objects;
using Microsoft.Extensions.DependencyInjection;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.IntegrationTests.ReadWrite.Creating;
public sealed class CreateResourceWithClientGeneratedIdTests : IClassFixture<IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext>>
{
private readonly IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> _testContext;
private readonly ReadWriteFakers _fakers = new();
public CreateResourceWithClientGeneratedIdTests(IntegrationTestContext<TestableStartup<ReadWriteDbContext>, ReadWriteDbContext> testContext)
{
_testContext = testContext;
testContext.UseController<WorkItemGroupsController>();
testContext.UseController<RgbColorsController>();
testContext.ConfigureServicesAfterStartup(services =>
{
services.AddResourceDefinition<ImplicitlyChangingWorkItemGroupDefinition>();
});
var options = (JsonApiOptions)testContext.Factory.Services.GetRequiredService<IJsonApiOptions>();
options.AllowClientGeneratedIds = true;
}
[Fact]
public async Task Can_create_resource_with_client_generated_guid_ID_having_side_effects()
{
// Arrange
WorkItemGroup newGroup = _fakers.WorkItemGroup.Generate();
newGroup.Id = Guid.NewGuid();
var requestBody = new
{
data = new
{
type = "workItemGroups",
id = newGroup.StringId,
attributes = new
{
name = newGroup.Name
}
}
};
const string route = "/workItemGroups";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Created);
string groupName = $"{newGroup.Name}{ImplicitlyChangingWorkItemGroupDefinition.Suffix}";
responseDocument.Data.SingleValue.ShouldNotBeNull();
responseDocument.Data.SingleValue.Type.Should().Be("workItemGroups");
responseDocument.Data.SingleValue.Id.Should().Be(newGroup.StringId);
responseDocument.Data.SingleValue.Attributes.ShouldContainKey("name").With(value => value.Should().Be(groupName));
responseDocument.Data.SingleValue.Relationships.ShouldNotBeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItemGroup groupInDatabase = await dbContext.Groups.FirstWithIdAsync(newGroup.Id);
groupInDatabase.Name.Should().Be(groupName);
});
PropertyInfo? property = typeof(WorkItemGroup).GetProperty(nameof(Identifiable<object>.Id));
property.ShouldNotBeNull();
property.PropertyType.Should().Be(typeof(Guid));
}
[Fact]
public async Task Can_create_resource_with_client_generated_guid_ID_having_side_effects_with_fieldset()
{
// Arrange
WorkItemGroup newGroup = _fakers.WorkItemGroup.Generate();
newGroup.Id = Guid.NewGuid();
var requestBody = new
{
data = new
{
type = "workItemGroups",
id = newGroup.StringId,
attributes = new
{
name = newGroup.Name
}
}
};
const string route = "/workItemGroups?fields[workItemGroups]=name";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Created);
string groupName = $"{newGroup.Name}{ImplicitlyChangingWorkItemGroupDefinition.Suffix}";
responseDocument.Data.SingleValue.ShouldNotBeNull();
responseDocument.Data.SingleValue.Type.Should().Be("workItemGroups");
responseDocument.Data.SingleValue.Id.Should().Be(newGroup.StringId);
responseDocument.Data.SingleValue.Attributes.ShouldHaveCount(1);
responseDocument.Data.SingleValue.Attributes.ShouldContainKey("name").With(value => value.Should().Be(groupName));
responseDocument.Data.SingleValue.Relationships.Should().BeNull();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
WorkItemGroup groupInDatabase = await dbContext.Groups.FirstWithIdAsync(newGroup.Id);
groupInDatabase.Name.Should().Be(groupName);
});
PropertyInfo? property = typeof(WorkItemGroup).GetProperty(nameof(Identifiable<object>.Id));
property.ShouldNotBeNull();
property.PropertyType.Should().Be(typeof(Guid));
}
[Fact]
public async Task Can_create_resource_with_client_generated_string_ID_having_no_side_effects()
{
// Arrange
RgbColor newColor = _fakers.RgbColor.Generate();
var requestBody = new
{
data = new
{
type = "rgbColors",
id = newColor.StringId,
attributes = new
{
displayName = newColor.DisplayName
}
}
};
const string route = "/rgbColors";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
RgbColor colorInDatabase = await dbContext.RgbColors.FirstWithIdAsync(newColor.Id);
colorInDatabase.DisplayName.Should().Be(newColor.DisplayName);
});
PropertyInfo? property = typeof(RgbColor).GetProperty(nameof(Identifiable<object>.Id));
property.ShouldNotBeNull();
property.PropertyType.Should().Be(typeof(string));
}
[Fact]
public async Task Can_create_resource_with_client_generated_string_ID_having_no_side_effects_with_fieldset()
{
// Arrange
RgbColor newColor = _fakers.RgbColor.Generate();
var requestBody = new
{
data = new
{
type = "rgbColors",
id = newColor.StringId,
attributes = new
{
displayName = newColor.DisplayName
}
}
};
const string route = "/rgbColors?fields[rgbColors]=id";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
RgbColor colorInDatabase = await dbContext.RgbColors.FirstWithIdAsync(newColor.Id);
colorInDatabase.DisplayName.Should().Be(newColor.DisplayName);
});
PropertyInfo? property = typeof(RgbColor).GetProperty(nameof(Identifiable<object>.Id));
property.ShouldNotBeNull();
property.PropertyType.Should().Be(typeof(string));
}
[Fact]
public async Task Cannot_create_resource_for_existing_client_generated_ID()
{
// Arrange
RgbColor existingColor = _fakers.RgbColor.Generate();
RgbColor colorToCreate = _fakers.RgbColor.Generate();
colorToCreate.Id = existingColor.Id;
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.RgbColors.Add(existingColor);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "rgbColors",
id = colorToCreate.StringId,
attributes = new
{
displayName = colorToCreate.DisplayName
}
}
};
const string route = "/rgbColors";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Conflict);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.Conflict);
error.Title.Should().Be("Another resource with the specified ID already exists.");
error.Detail.Should().Be($"Another resource of type 'rgbColors' with ID '{existingColor.StringId}' already exists.");
error.Source.Should().BeNull();
error.Meta.Should().NotContainKey("requestBody");
}
}
| |
#region CopyrightHeader
//
// Copyright by Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0.txt
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Xml;
using System.Reflection;
using gov.va.medora.utils;
namespace gov.va.medora.mdo.dao.vista
{
public class VistaSystemFileHandler : ISystemFileHandler
{
AbstractConnection myCxn;
Hashtable fileDefs;
Hashtable files;
Hashtable lookupTables;
public VistaSystemFileHandler(AbstractConnection cxn)
{
myCxn = cxn;
getFileDefs();
files = new Hashtable();
lookupTables = new Hashtable();
}
public Dictionary<string, object> getFile(string fileNum)
{
if (!files.ContainsKey(fileNum))
{
VistaFile theFile = (VistaFile)fileDefs[fileNum];
DdrLister query = buildFileQuery(theFile);
string[] response = query.execute();
files.Add(fileNum, toMdo(response, theFile));
}
return (Dictionary<string, object>)files[fileNum];
}
public StringDictionary getLookupTable(string fileNum)
{
if (!lookupTables.ContainsKey(fileNum))
{
DdrLister query = buildIenNameQuery(fileNum);
string[] response = query.execute();
lookupTables.Add(fileNum, VistaUtils.toStringDictionary(response));
}
return (StringDictionary)lookupTables[fileNum];
}
internal DdrLister buildFileQuery(VistaFile file)
{
DdrLister query = new DdrLister(myCxn);
query.File = file.FileNumber;
query.Fields = file.getFieldString();
query.Flags = "IP";
query.Xref = "#";
return query;
}
internal void getFileDefs()
{
VistaFile currentFile = null;
VistaField currentFld = null;
fileDefs = new Hashtable();
XmlReader reader = new XmlTextReader(VistaConstants.VISTA_FILEDEFS_PATH);
while (reader.Read())
{
switch ((int)reader.NodeType)
{
case (int)XmlNodeType.Element:
string name = reader.Name;
if (name == "File")
{
currentFile = new VistaFile();
currentFile.FileName = reader.GetAttribute("name");
currentFile.FileNumber = reader.GetAttribute("number");
currentFile.Global = reader.GetAttribute("global");
currentFile.MdoName = reader.GetAttribute("mdo");
}
else if (name == "fields")
{
currentFile.Fields = new DictionaryHashList();
}
else if (name == "field")
{
currentFld = new VistaField();
currentFld.Pos = Convert.ToInt16(reader.GetAttribute("pos"));
}
else if (name == "vista")
{
currentFld.VistaName = reader.GetAttribute("name");
currentFld.VistaNumber = reader.GetAttribute("number");
currentFld.VistaNode = reader.GetAttribute("node");
currentFld.VistaPiece = reader.GetAttribute("piece");
currentFile.Fields.Add(currentFld.Pos.ToString(), currentFld);
}
else if (name == "mdo")
{
currentFld.MdoName = reader.GetAttribute("name");
currentFld.MdoType = reader.GetAttribute("type");
}
else if (name == "mapping")
{
string mappingType = reader.GetAttribute("type");
currentFld.Mapping = new VistaFieldMapping(mappingType);
if (currentFld.Mapping.Type == "pointer")
{
currentFld.Mapping.VistaFileNumber = reader.GetAttribute("file");
}
else if (currentFld.Mapping.Type == "decode")
{
currentFld.Mapping.DecodeMap = new StringDictionary();
}
}
else if (name == "map")
{
currentFld.Mapping.DecodeMap.Add(reader.GetAttribute("code"), reader.GetAttribute("value"));
}
break;
case (int)XmlNodeType.EndElement:
name = reader.Name;
if (name == "File")
{
fileDefs.Add(currentFile.FileNumber, currentFile);
}
else if (name == "fields")
{
}
else if (name == "field")
{
}
else if (name == "vista")
{
}
else if (name == "mdo")
{
}
else if (name == "mapping")
{
}
else if (name == "map")
{
}
break;
}
}
}
internal DdrLister buildIenNameQuery(string fileNum)
{
DdrLister query = new DdrLister(myCxn);
query.File = fileNum;
query.Fields = ".01";
query.Flags = "IP";
query.Xref = "#";
return query;
}
internal Dictionary<string, object> toMdo(string[] response, VistaFile theFile)
{
if (response == null || response.Length == 0)
{
return null;
}
Dictionary<string, object> result = new Dictionary<string, object>(response.Length);
for (int lineIdx = 0; lineIdx < response.Length; lineIdx++)
{
//Need to instantiate the mdo here
Object theMdo = Activator.CreateInstance(Type.GetType(theFile.MdoName), new object[] { });
Type theClass = theMdo.GetType();
string[] flds = StringUtils.split(response[lineIdx], StringUtils.CARET);
for (int fldIdx = 0; fldIdx < flds.Length; fldIdx++)
{
VistaField vf = (VistaField)((DictionaryEntry)theFile.Fields[fldIdx]).Value;
FieldInfo theField = theClass.GetField(vf.MdoName, BindingFlags.NonPublic | BindingFlags.Instance);
if (vf.MdoType == "string")
{
if (vf.Mapping != null && vf.Mapping.Type == "decode")
{
if (vf.Mapping.DecodeMap.ContainsKey(flds[fldIdx]))
{
theField.SetValue(theMdo, vf.Mapping.DecodeMap[flds[fldIdx]]);
}
else
{
theField.SetValue(theMdo, flds[fldIdx]);
}
}
else
{
theField.SetValue(theMdo, flds[fldIdx]);
}
}
else if (vf.MdoType == "kvp")
{
string key = flds[fldIdx];
string value = "";
if (vf.Mapping != null && vf.Mapping.Type == "decode")
{
value = vf.Mapping.DecodeMap[key];
}
else
{
StringDictionary lookupTbl = getLookupTable(vf.Mapping.VistaFileNumber);
if (lookupTbl.ContainsKey(key))
{
value = lookupTbl[key];
}
}
theField.SetValue(theMdo, new KeyValuePair<string, string>(key, value));
//KeyValuePair<string, string> kvp = new KeyValuePair<string, string>(key, value);
}
}
result.Add(flds[0], theMdo);
}
return result;
}
public Hashtable LookupTables()
{
return lookupTables;
}
public Hashtable Files()
{
return files;
}
}
}
| |
//
// CustomizableMockHttpClient.cs
//
// Author:
// Zachary Gramana <zack@xamarin.com>
//
// Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
/**
* Original iOS version by Jens Alfke
* Ported to Android by Marty Schoch, Traun Leyden
*
* Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Couchbase.Lite;
using Couchbase.Lite.Replicator;
using Sharpen;
using System.Net.Http;
namespace Couchbase.Lite.Replicator
{
public class CustomizableMockHttpClient : HttpMessageInvoker
{
private IDictionary<string, CustomizableMockHttpClient.Responder> responders;
private IList<HttpWebRequest> capturedRequests = Sharpen.Collections.SynchronizedList
(new AList<HttpWebRequest>());
public CustomizableMockHttpClient() : base(new HttpClientHandler())
{
// tests can register custom responders per url. the key is the URL pattern to match,
// the value is the responder that should handle that request.
// capture all request so that the test can verify expected requests were received.
responders = new Dictionary<string, CustomizableMockHttpClient.Responder>();
AddDefaultResponders();
}
public virtual void SetResponder(string urlPattern, CustomizableMockHttpClient.Responder
responder)
{
responders[urlPattern] = responder;
}
public virtual void AddDefaultResponders()
{
responders.Put("_revs_diff", new _Responder_49());
responders.Put("_bulk_docs", new _Responder_56());
responders.Put("_local", new _Responder_63());
}
private sealed class _Responder_49 : CustomizableMockHttpClient.Responder
{
public _Responder_49()
{
}
/// <exception cref="System.IO.IOException"></exception>
public HttpResponse Execute(HttpRequestMessage httpUriRequest)
{
return Couchbase.Lite.Replicator.CustomizableMockHttpClient.FakeRevsDiff(httpUriRequest
);
}
}
private sealed class _Responder_56 : CustomizableMockHttpClient.Responder
{
public _Responder_56()
{
}
/// <exception cref="System.IO.IOException"></exception>
public HttpResponse Execute(HttpRequestMessage httpUriRequest)
{
return Couchbase.Lite.Replicator.CustomizableMockHttpClient.FakeBulkDocs(httpUriRequest
);
}
}
private sealed class _Responder_63 : CustomizableMockHttpClient.Responder
{
public _Responder_63()
{
}
/// <exception cref="System.IO.IOException"></exception>
public HttpResponse Execute(HttpRequestMessage httpUriRequest)
{
return Couchbase.Lite.Replicator.CustomizableMockHttpClient.FakeLocalDocumentUpdate
(httpUriRequest);
}
}
public virtual void AddResponderFailAllRequests(int statusCode)
{
SetResponder("*", new _Responder_73(statusCode));
}
private sealed class _Responder_73 : CustomizableMockHttpClient.Responder
{
public _Responder_73(int statusCode)
{
this.statusCode = statusCode;
}
/// <exception cref="System.IO.IOException"></exception>
public HttpResponse Execute(HttpRequestMessage httpUriRequest)
{
return Couchbase.Lite.Replicator.CustomizableMockHttpClient.EmptyResponseWithStatusCode
(statusCode);
}
private readonly int statusCode;
}
public virtual void AddResponderThrowExceptionAllRequests()
{
SetResponder("*", new _Responder_82());
}
private sealed class _Responder_82 : CustomizableMockHttpClient.Responder
{
public _Responder_82()
{
}
/// <exception cref="System.IO.IOException"></exception>
public HttpResponse Execute(HttpRequestMessage httpUriRequest)
{
throw new IOException("Test IOException");
}
}
public virtual IList<HttpWebRequest> GetCapturedRequests()
{
return capturedRequests;
}
public virtual HttpParams GetParams()
{
return null;
}
public virtual ClientConnectionManager GetConnectionManager()
{
return null;
}
/// <exception cref="System.IO.IOException"></exception>
public virtual HttpResponse Execute(HttpRequestMessage httpUriRequest)
{
capturedRequests.AddItem(httpUriRequest);
foreach (string urlPattern in responders.Keys)
{
if (urlPattern.Equals("*") || httpUriRequest.GetURI().GetPath().Contains(urlPattern
))
{
CustomizableMockHttpClient.Responder responder = responders[urlPattern];
return responder.Execute(httpUriRequest);
}
}
throw new RuntimeException("No responders matched for url pattern: " + httpUriRequest
.GetURI().GetPath());
}
/// <exception cref="System.IO.IOException"></exception>
/// <exception cref="Apache.Http.Client.ClientProtocolException"></exception>
public static HttpResponse FakeLocalDocumentUpdate(HttpRequestMessage httpUriRequest
)
{
throw new IOException("Throw exception on purpose for purposes of testSaveRemoteCheckpointNoResponse()"
);
}
/// <exception cref="System.IO.IOException"></exception>
/// <exception cref="Apache.Http.Client.ClientProtocolException"></exception>
public static HttpResponse FakeBulkDocs(HttpRequestMessage httpUriRequest)
{
IDictionary<string, object> jsonMap = GetJsonMapFromRequest((HttpPost)httpUriRequest
);
IList<IDictionary<string, object>> responseList = new AList<IDictionary<string, object
>>();
AList<IDictionary<string, object>> docs = (ArrayList)jsonMap["docs"];
foreach (IDictionary<string, object> doc in docs)
{
IDictionary<string, object> responseListItem = new Dictionary<string, object>();
responseListItem.Put("id", doc["_id"]);
responseListItem.Put("rev", doc["_rev"]);
responseList.AddItem(responseListItem);
}
HttpResponse response = GenerateHttpResponseObject(responseList);
return response;
}
/// <exception cref="System.IO.IOException"></exception>
public static HttpResponse FakeRevsDiff(HttpRequestMessage httpUriRequest)
{
IDictionary<string, object> jsonMap = GetJsonMapFromRequest((HttpPost)httpUriRequest
);
IDictionary<string, object> responseMap = new Dictionary<string, object>();
foreach (string key in jsonMap.Keys)
{
ArrayList value = (ArrayList)jsonMap[key];
IDictionary<string, object> missingMap = new Dictionary<string, object>();
missingMap["missing"] = value;
responseMap[key] = missingMap;
}
HttpResponse response = GenerateHttpResponseObject(responseMap);
return response;
}
/// <exception cref="System.IO.IOException"></exception>
public static HttpResponse GenerateHttpResponseObject(object o)
{
DefaultHttpResponseFactory responseFactory = new DefaultHttpResponseFactory();
BasicStatusLine statusLine = new BasicStatusLine(HttpVersion.Http11, 200, "OK");
HttpResponse response = responseFactory.NewHttpResponse(statusLine, null);
byte[] responseBytes = Manager.GetObjectMapper().WriteValueAsBytes(o);
response.SetEntity(new ByteArrayEntity(responseBytes));
return response;
}
/// <exception cref="System.IO.IOException"></exception>
public static HttpResponse GenerateHttpResponseObject(string responseJson)
{
DefaultHttpResponseFactory responseFactory = new DefaultHttpResponseFactory();
BasicStatusLine statusLine = new BasicStatusLine(HttpVersion.Http11, 200, "OK");
HttpResponse response = responseFactory.NewHttpResponse(statusLine, null);
byte[] responseBytes = Sharpen.Runtime.GetBytesForString(responseJson);
response.SetEntity(new ByteArrayEntity(responseBytes));
return response;
}
public static HttpResponse EmptyResponseWithStatusCode(int statusCode)
{
DefaultHttpResponseFactory responseFactory = new DefaultHttpResponseFactory();
BasicStatusLine statusLine = new BasicStatusLine(HttpVersion.Http11, statusCode,
string.Empty);
HttpResponse response = responseFactory.NewHttpResponse(statusLine, null);
return response;
}
/// <exception cref="System.IO.IOException"></exception>
private static IDictionary<string, object> GetJsonMapFromRequest(HttpPost httpUriRequest
)
{
HttpPost post = (HttpPost)httpUriRequest;
InputStream @is = post.GetEntity().GetContent();
return Manager.GetObjectMapper().ReadValue<IDictionary>(@is);
}
/// <exception cref="System.IO.IOException"></exception>
public virtual HttpResponse Execute(HttpRequestMessage httpUriRequest, HttpContext
httpContext)
{
throw new RuntimeException("Mock Http Client does not know how to handle this request. It should be fixed"
);
}
/// <exception cref="System.IO.IOException"></exception>
public virtual HttpResponse Execute(HttpHost httpHost, HttpWebRequest httpRequest
)
{
throw new RuntimeException("Mock Http Client does not know how to handle this request. It should be fixed"
);
}
/// <exception cref="System.IO.IOException"></exception>
public virtual HttpResponse Execute(HttpHost httpHost, HttpWebRequest httpRequest
, HttpContext httpContext)
{
throw new RuntimeException("Mock Http Client does not know how to handle this request. It should be fixed"
);
}
/// <exception cref="System.IO.IOException"></exception>
public virtual T Execute<T, _T1>(HttpRequestMessage httpUriRequest, ResponseHandler
<_T1> responseHandler) where _T1:T
{
throw new RuntimeException("Mock Http Client does not know how to handle this request. It should be fixed"
);
}
/// <exception cref="System.IO.IOException"></exception>
public virtual T Execute<T, _T1>(HttpRequestMessage httpUriRequest, ResponseHandler
<_T1> responseHandler, HttpContext httpContext) where _T1:T
{
throw new RuntimeException("Mock Http Client does not know how to handle this request. It should be fixed"
);
}
/// <exception cref="System.IO.IOException"></exception>
public virtual T Execute<T, _T1>(HttpHost httpHost, HttpWebRequest httpRequest, ResponseHandler
<_T1> responseHandler) where _T1:T
{
throw new RuntimeException("Mock Http Client does not know how to handle this request. It should be fixed"
);
}
/// <exception cref="System.IO.IOException"></exception>
public virtual T Execute<T, _T1>(HttpHost httpHost, HttpWebRequest httpRequest, ResponseHandler
<_T1> responseHandler, HttpContext httpContext) where _T1:T
{
throw new RuntimeException("Mock Http Client does not know how to handle this request. It should be fixed"
);
}
internal interface Responder
{
/// <exception cref="System.IO.IOException"></exception>
HttpResponse Execute(HttpRequestMessage httpUriRequest);
}
}
}
| |
using System;
using System.Diagnostics;
using System.Linq;
using Mono.Cecil;
using Xunit;
// ReSharper disable UnusedMember.Global
// ReSharper disable ConvertToAutoPropertyWhenPossible
// ReSharper disable UnusedVariable
// ReSharper disable ValueParameterNotUsed
public class HasEqualityCheckerTests
{
Mono.Collections.Generic.Collection<PropertyDefinition> properties;
Mono.Collections.Generic.Collection<FieldDefinition> fields;
public HasEqualityCheckerTests()
{
var moduleDefinition = ModuleDefinition.ReadModule(GetType().Assembly.Location);
var typeDefinition = moduleDefinition.Types.First(definition => definition.Name == "HasEqualityCheckerTests");
properties = typeDefinition.Properties;
fields = typeDefinition.Fields;
}
[Fact]
public void EqualityShortCutTest()
{
var instructions = GetInstructions("EqualityShortCut");
var field = GetField("intField");
Assert.True(HasEqualityChecker.AlreadyHasEquality(instructions, field));
}
[Fact]
public void EqualsNoFieldTest()
{
var instructions = GetInstructions("EqualsNoField");
var field = GetField("intField");
Assert.True(HasEqualityChecker.AlreadyHasEquality(instructions, null));
}
[Fact]
public void NoEqualsNoFieldTest()
{
var instructions = GetInstructions("NoEqualsNoField");
var field = GetField("intField");
Assert.False(HasEqualityChecker.AlreadyHasEquality(instructions, null));
}
[Fact]
public void EqualityShortCutInverseTest()
{
var instructions = GetInstructions("EqualityShortCutInverse");
var field = GetField("intField");
Assert.True(HasEqualityChecker.AlreadyHasEquality(instructions, field));
}
[Fact]
public void EqualityNestedTest()
{
var instructions = GetInstructions("EqualityNested");
var field = GetField("intField");
Assert.True(HasEqualityChecker.AlreadyHasEquality(instructions, field));
}
[Fact]
public void EqualityNestedInverseTest()
{
var instructions = GetInstructions("EqualityNestedInverse");
var field = GetField("intField");
Assert.True(HasEqualityChecker.AlreadyHasEquality(instructions, field));
}
[Fact]
public void EqualsShortCutTest()
{
var instructions = GetInstructions("EqualsShortCut");
var field = GetField("stringField");
Assert.True(HasEqualityChecker.AlreadyHasEquality(instructions, field));
}
[Fact]
public void EqualsShortCutInverseTest()
{
var instructions = GetInstructions("EqualsShortCutInverse");
var field = GetField("stringField");
Assert.True(HasEqualityChecker.AlreadyHasEquality(instructions, field));
}
[Fact]
public void EqualsNestedInverseTest()
{
var instructions = GetInstructions("EqualsNestedInverse");
var field = GetField("stringField");
Assert.True(HasEqualityChecker.AlreadyHasEquality(instructions, field));
}
[Fact]
public void EqualsNestedTest()
{
var instructions = GetInstructions("EqualsNested");
var field = GetField("stringField");
Assert.True(HasEqualityChecker.AlreadyHasEquality(instructions, field));
}
[Fact]
public void StringEqualsShortCutTest()
{
var instructions = GetInstructions("StringEqualsShortCut");
var field = GetField("stringField");
Assert.True(HasEqualityChecker.AlreadyHasEquality(instructions, field));
}
[Fact]
public void StringEqualsShortCutInverseTest()
{
var instructions = GetInstructions("StringEqualsShortCutInverse");
var field = GetField("stringField");
Assert.True(HasEqualityChecker.AlreadyHasEquality(instructions, field));
}
[Fact]
public void StringEqualsNestedTest()
{
var instructions = GetInstructions("StringEqualsNested");
var field = GetField("stringField");
Assert.True(HasEqualityChecker.AlreadyHasEquality(instructions, field));
}
[Fact]
public void StringEqualsOrdinalTest()
{
var instructions = GetInstructions("StringEqualsOrdinal");
var field = GetField("stringField");
Assert.True(HasEqualityChecker.AlreadyHasEquality(instructions, field));
}
[Fact]
public void StringEqualsNestedInverseTest()
{
var instructions = GetInstructions("StringEqualsNestedInverse");
var field = GetField("stringField");
Assert.True(HasEqualityChecker.AlreadyHasEquality(instructions, field));
}
[Fact]
public void NoEqualityTest()
{
var instructions = GetInstructions("NoEquality");
var field = GetField("stringField");
Assert.False(HasEqualityChecker.AlreadyHasEquality(instructions, field));
}
PropertyDefinition GetInstructions(string equalityShortcut)
{
return properties.First(definition => definition.Name == equalityShortcut);
}
FieldDefinition GetField(string equalityShortcut)
{
return fields.First(x => x.Name == equalityShortcut);
}
int intField;
string stringField;
public int EqualityShortCut
{
get => intField;
set
{
if (value == intField)
{
return;
}
intField = value;
}
}
public int EqualityShortCutInverse
{
get => intField;
set
{
if (intField == value)
{
return;
}
intField = value;
}
}
public int EqualityNested
{
get => intField;
set
{
if (value != intField)
{
intField = value;
}
}
}
public int EqualityNestedInverse
{
get => intField;
set
{
if (intField != value)
{
intField = value;
}
}
}
public string EqualsShortCut
{
get => stringField;
set
{
if (Equals(value, stringField))
{
return;
}
stringField = value;
}
}
public string EqualsShortCutInverse
{
get => stringField;
set
{
if (Equals(stringField, value))
{
return;
}
stringField = value;
}
}
public string EqualsNested
{
get => stringField;
set
{
if (!Equals(value, stringField))
{
stringField = value;
}
}
}
public string EqualsNestedInverse
{
get => stringField;
set
{
if (!Equals(stringField, value))
{
stringField = value;
}
}
}
public string NoEqualsNoField
{
get => "";
set { }
}
public string EqualsNoField
{
get => "";
set
{
if (EqualsNoField == value)
{
// ReSharper disable once RedundantJumpStatement
return;
}
Debug.WriteLine(value);
}
}
public string StringEqualsShortCut
{
get => stringField;
set
{
if (string.Equals(value, stringField))
{
return;
}
stringField = value;
}
}
public string StringEqualsShortCutInverse
{
get => stringField;
set
{
if (string.Equals(stringField, value))
{
return;
}
stringField = value;
}
}
public string StringEqualsNested
{
get => stringField;
set
{
if (!string.Equals(value, stringField))
{
stringField = value;
}
}
}
public string StringEqualsNestedInverse
{
get => stringField;
set
{
if (!string.Equals(stringField, value))
{
stringField = value;
}
}
}
public string StringEqualsOrdinal
{
get => stringField;
set
{
if (!string.Equals(stringField, value, StringComparison.Ordinal))
{
stringField = value;
}
}
}
public string NoEquality
{
get => stringField;
set => stringField = value;
}
}
| |
/*******************************************************************************
INTEL CORPORATION PROPRIETARY INFORMATION
This software is supplied under the terms of a license agreement or nondisclosure
agreement with Intel Corporation and may not be copied or disclosed except in
accordance with the terms of that agreement
Copyright(c) 2012-2014 Intel Corporation. All Rights Reserved.
*******************************************************************************/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using RSUnityToolkit;
/// <summary>
/// Scale action: This action implements object scaling
/// </summary>
public class ScaleAction : BaseAction {
#region Public Fields
/// <summary>
/// The min/max/freeze scale constraints
/// </summary>
public ScaleConstraints Constraints = new ScaleConstraints();
/// <summary>
/// When enabled the object will continue to scale in a constant speed (set in the Continuous Scale Speed parameter) as long as the Scale Trigger is fired
/// </summary>
public bool ContinuousScale = false;
/// <summary>
/// Sets the continuous scale speed when enabled
/// </summary>
public float ContinuousScaleSpeed = 0f;
/// <summary>
/// The scale dumping factor. More means less scaling.
/// </summary>
public float ScaleDumpingFactor = 10f;
#endregion
#region Private Fields
private float _scale = 0f;
private float _lastScale = 0f;
private bool _actionTriggered = false;
#endregion
#region Public Methods
/// <summary>
/// Determines whether this instance is support custom triggers.
/// </summary>
public override bool IsSupportCustomTriggers()
{
return false;
}
/// <summary>
/// Returns the actions's description for GUI purposes.
/// </summary>
/// <returns>
/// The action description.
/// </returns>
public override string GetActionDescription()
{
return "This Action changes the scale of the game object";
}
/// <summary>
/// Sets the default trigger values (for the triggers set in SetDefaultTriggers() )
/// </summary>
/// <param name='index'>
/// Index of the trigger.
/// </param>
/// <param name='trigger'>
/// A pointer to the trigger for which you can set the default rules.
/// </param>
public override void SetDefaultTriggerValues(int index, Trigger trigger)
{
switch (index)
{
case 0:
trigger.FriendlyName = "Start Event";
((EventTrigger)trigger).Rules = new BaseRule[1] { AddHiddenComponent<GestureDetectedRule>() };
((GestureDetectedRule)(trigger.Rules[0])).Gesture = MCTTypes.RSUnityToolkitGestures.Grab;
break;
case 1:
((ScaleTrigger)trigger).Rules = new BaseRule[1] { AddHiddenComponent<TwoHandsInteractionRule>() };
break;
case 2:
trigger.FriendlyName = "Stop Event";
((EventTrigger)trigger).Rules = new BaseRule[1] { AddHiddenComponent<GestureLostRule>() };
((GestureLostRule)(trigger.Rules[0])).Gesture = MCTTypes.RSUnityToolkitGestures.Grab;
break;
}
}
#endregion
#region Protected Methods
/// <summary>
/// Sets the default triggers for that action.
/// </summary>
protected override void SetDefaultTriggers()
{
SupportedTriggers = new Trigger[3]{
AddHiddenComponent<EventTrigger>(),
AddHiddenComponent<ScaleTrigger>(),
AddHiddenComponent<EventTrigger>()};
}
#endregion
#region Private Methods
/// <summary>
/// Update is called once per frame.
/// </summary>
void Update ()
{
ProcessAllTriggers();
//Start Event
if ( !_actionTriggered && SupportedTriggers[0].Success )
{
_actionTriggered = true;
((ScaleTrigger)SupportedTriggers[1]).Restart = true;
return;
}
//Stop Event
if ( _actionTriggered && SupportedTriggers[2].Success )
{
_actionTriggered = false;
}
if ( !_actionTriggered )
{
return;
}
ScaleTrigger trgr = (ScaleTrigger)SupportedTriggers[1];
if( trgr.Success )
{
_scale = trgr.Scale / ScaleDumpingFactor;
//Keep it relative - for each axis, if rotation angle is 0 or if this is the first "frame" after a rotation angle is detected, save the data for next frame
if (!ContinuousScale)
{
if (_scale == 0 || _lastScale == 0)
{
_lastScale = _scale;
}
else
{
_scale = _scale - _lastScale;
}
}
if (ContinuousScale && ContinuousScaleSpeed != 0)
{
_scale = Mathf.Sign(_scale) * ContinuousScaleSpeed;
}
Vector3 scaleVector = this.gameObject.transform.localScale;
float _scaleX = _scale;
float _scaleY = _scale;
float _scaleZ = _scale;
//Make sure we didn't pass the max / min Scale
if (Constraints.XScale.Max != 0) {
if ((_scale + scaleVector.x) > Constraints.XScale.Max) {
_scaleX = Constraints.XScale.Max - scaleVector.x;
}
}
if (Constraints.YScale.Max != 0) {
if ((_scale + scaleVector.y) > Constraints.YScale.Max) {
_scaleY = Constraints.YScale.Max - scaleVector.y;
}
}
if (Constraints.ZScale.Max != 0) {
if ((_scale + scaleVector.z) > Constraints.ZScale.Max) {
_scaleZ = Constraints.ZScale.Max - scaleVector.z;
}
}
if (Constraints.XScale.Min != 0) {
if ((_scale + scaleVector.x) < Constraints.XScale.Min) {
_scaleX = Constraints.XScale.Min - scaleVector.x;
}
}
if (Constraints.YScale.Min != 0) {
if ((_scale + scaleVector.y) < Constraints.YScale.Min) {
_scaleY = Constraints.YScale.Min - scaleVector.y;
}
}
if (Constraints.ZScale.Min != 0) {
if ((_scale + scaleVector.z) < Constraints.ZScale.Min) {
_scaleZ = Constraints.ZScale.Min - scaleVector.z;
}
}
//Enable / Disable Axis
_scaleX = !Constraints.Freeze.X ? scaleVector.x + _scaleX : scaleVector.x;
_scaleY = !Constraints.Freeze.Y ? scaleVector.y + _scaleY : scaleVector.y;
_scaleZ = !Constraints.Freeze.Z ? scaleVector.z + _scaleZ : scaleVector.z;
//Scale
this.gameObject.transform.localScale = new Vector3(_scaleX, _scaleY, _scaleZ);
if (ScaleDumpingFactor==0)
{
Debug.LogError("ScaleDumpingFactor must not be zero. Changing it to 1");
ScaleDumpingFactor = 1;
}
//Update last scaling
_lastScale = trgr.Scale / ScaleDumpingFactor;
}
}
#endregion
#region Menu
#if UNITY_EDITOR
/// <summary>
/// Adds the action to the Toolkit menu.
/// </summary>
[UnityEditor.MenuItem ("Toolkit/Add Action/Scale")]
static void AddThisAction ()
{
AddAction<ScaleAction>();
}
#endif
#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.
#pragma warning disable 1634 // Stops compiler from warning about unknown warnings (for Presharp)
using System.IO;
using System.Text;
using System.Xml;
namespace System.Runtime.Serialization.Json
{
// This wrapper does not support seek.
// Supports: UTF-8, Unicode, BigEndianUnicode
// ASSUMPTION (Microsoft): This class will only be used for EITHER reading OR writing. It can be done, it would just mean more buffers.
internal class JsonEncodingStreamWrapper : Stream
{
private static readonly UnicodeEncoding s_validatingBEUTF16 = new UnicodeEncoding(true, false, true);
private static readonly UnicodeEncoding s_validatingUTF16 = new UnicodeEncoding(false, false, true);
private static readonly UTF8Encoding s_validatingUTF8 = new UTF8Encoding(false, true);
private const int BufferLength = 128;
private byte[] _byteBuffer = new byte[1];
private int _byteCount;
private int _byteOffset;
private byte[] _bytes;
private char[] _chars;
private Decoder _dec;
private Encoder _enc;
private Encoding _encoding;
private SupportedEncoding _encodingCode;
private bool _isReading;
private Stream _stream;
public JsonEncodingStreamWrapper(Stream stream, Encoding encoding, bool isReader)
{
_isReading = isReader;
if (isReader)
{
InitForReading(stream, encoding);
}
else
{
if (encoding == null)
{
throw new ArgumentNullException("encoding");
}
InitForWriting(stream, encoding);
}
}
private enum SupportedEncoding
{
UTF8,
UTF16LE,
UTF16BE,
None
}
// This stream wrapper does not support duplex
public override bool CanRead
{
get
{
if (!_isReading)
{
return false;
}
return _stream.CanRead;
}
}
// The encoding conversion and buffering breaks seeking.
public override bool CanSeek
{
get { return false; }
}
// Delegate properties
public override bool CanTimeout
{
get { return _stream.CanTimeout; }
}
// This stream wrapper does not support duplex
public override bool CanWrite
{
get
{
if (_isReading)
{
return false;
}
return _stream.CanWrite;
}
}
public override long Length
{
get { return _stream.Length; }
}
// The encoding conversion and buffering breaks seeking.
public override long Position
{
get
{
#pragma warning suppress 56503 // The contract for non seekable stream is to throw exception
throw new NotSupportedException();
}
set { throw new NotSupportedException(); }
}
public override int ReadTimeout
{
get { return _stream.ReadTimeout; }
set { _stream.ReadTimeout = value; }
}
public override int WriteTimeout
{
get { return _stream.WriteTimeout; }
set { _stream.WriteTimeout = value; }
}
public static ArraySegment<byte> ProcessBuffer(byte[] buffer, int offset, int count, Encoding encoding)
{
try
{
SupportedEncoding expectedEnc = GetSupportedEncoding(encoding);
SupportedEncoding dataEnc;
if (count < 2)
{
dataEnc = SupportedEncoding.UTF8;
}
else
{
dataEnc = ReadEncoding(buffer[offset], buffer[offset + 1]);
}
if ((expectedEnc != SupportedEncoding.None) && (expectedEnc != dataEnc))
{
ThrowExpectedEncodingMismatch(expectedEnc, dataEnc);
}
// Fastpath: UTF-8
if (dataEnc == SupportedEncoding.UTF8)
{
return new ArraySegment<byte>(buffer, offset, count);
}
// Convert to UTF-8
return
new ArraySegment<byte>(s_validatingUTF8.GetBytes(GetEncoding(dataEnc).GetChars(buffer, offset, count)));
}
catch (DecoderFallbackException e)
{
throw new XmlException(SR.JsonInvalidBytes, e);
}
}
protected override void Dispose(bool disposing)
{
Flush();
_stream.Dispose();
base.Dispose(disposing);
}
public override void Flush()
{
_stream.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
try
{
if (_byteCount == 0)
{
if (_encodingCode == SupportedEncoding.UTF8)
{
return _stream.Read(buffer, offset, count);
}
// No more bytes than can be turned into characters
_byteOffset = 0;
_byteCount = _stream.Read(_bytes, _byteCount, (_chars.Length - 1) * 2);
// Check for end of stream
if (_byteCount == 0)
{
return 0;
}
// Fix up incomplete chars
CleanupCharBreak();
// Change encoding
int charCount = _encoding.GetChars(_bytes, 0, _byteCount, _chars, 0);
_byteCount = Encoding.UTF8.GetBytes(_chars, 0, charCount, _bytes, 0);
}
// Give them bytes
if (_byteCount < count)
{
count = _byteCount;
}
Buffer.BlockCopy(_bytes, _byteOffset, buffer, offset, count);
_byteOffset += count;
_byteCount -= count;
return count;
}
catch (DecoderFallbackException ex)
{
throw new XmlException(SR.JsonInvalidBytes, ex);
}
}
public override int ReadByte()
{
if (_byteCount == 0 && _encodingCode == SupportedEncoding.UTF8)
{
return _stream.ReadByte();
}
if (Read(_byteBuffer, 0, 1) == 0)
{
return -1;
}
return _byteBuffer[0];
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
// Delegate methods
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
// Optimize UTF-8 case
if (_encodingCode == SupportedEncoding.UTF8)
{
_stream.Write(buffer, offset, count);
return;
}
while (count > 0)
{
int size = _chars.Length < count ? _chars.Length : count;
int charCount = _dec.GetChars(buffer, offset, size, _chars, 0, false);
_byteCount = _enc.GetBytes(_chars, 0, charCount, _bytes, 0, false);
_stream.Write(_bytes, 0, _byteCount);
offset += size;
count -= size;
}
}
public override void WriteByte(byte b)
{
if (_encodingCode == SupportedEncoding.UTF8)
{
_stream.WriteByte(b);
return;
}
_byteBuffer[0] = b;
Write(_byteBuffer, 0, 1);
}
private static Encoding GetEncoding(SupportedEncoding e)
{
switch (e)
{
case SupportedEncoding.UTF8:
return s_validatingUTF8;
case SupportedEncoding.UTF16LE:
return s_validatingUTF16;
case SupportedEncoding.UTF16BE:
return s_validatingBEUTF16;
default:
throw new XmlException(SR.JsonEncodingNotSupported);
}
}
private static string GetEncodingName(SupportedEncoding enc)
{
switch (enc)
{
case SupportedEncoding.UTF8:
return "utf-8";
case SupportedEncoding.UTF16LE:
return "utf-16LE";
case SupportedEncoding.UTF16BE:
return "utf-16BE";
default:
throw new XmlException(SR.JsonEncodingNotSupported);
}
}
private static SupportedEncoding GetSupportedEncoding(Encoding encoding)
{
if (encoding == null)
{
return SupportedEncoding.None;
}
if (encoding.WebName == s_validatingUTF8.WebName)
{
return SupportedEncoding.UTF8;
}
else if (encoding.WebName == s_validatingUTF16.WebName)
{
return SupportedEncoding.UTF16LE;
}
else if (encoding.WebName == s_validatingBEUTF16.WebName)
{
return SupportedEncoding.UTF16BE;
}
else
{
throw new XmlException(SR.JsonEncodingNotSupported);
}
}
private static SupportedEncoding ReadEncoding(byte b1, byte b2)
{
if (b1 == 0x00 && b2 != 0x00)
{
return SupportedEncoding.UTF16BE;
}
else if (b1 != 0x00 && b2 == 0x00)
{
// 857 It's possible to misdetect UTF-32LE as UTF-16LE, but that's OK.
return SupportedEncoding.UTF16LE;
}
else if (b1 == 0x00 && b2 == 0x00)
{
// UTF-32BE not supported
throw new XmlException(SR.JsonInvalidBytes);
}
else
{
return SupportedEncoding.UTF8;
}
}
private static void ThrowExpectedEncodingMismatch(SupportedEncoding expEnc, SupportedEncoding actualEnc)
{
throw new XmlException(SR.Format(SR.JsonExpectedEncoding, GetEncodingName(expEnc), GetEncodingName(actualEnc)));
}
private void CleanupCharBreak()
{
int max = _byteOffset + _byteCount;
// Read on 2 byte boundaries
if ((_byteCount % 2) != 0)
{
int b = _stream.ReadByte();
if (b < 0)
{
throw new XmlException(SR.JsonUnexpectedEndOfFile);
}
_bytes[max++] = (byte)b;
_byteCount++;
}
// Don't cut off a surrogate character
int w;
if (_encodingCode == SupportedEncoding.UTF16LE)
{
w = _bytes[max - 2] + (_bytes[max - 1] << 8);
}
else
{
w = _bytes[max - 1] + (_bytes[max - 2] << 8);
}
if ((w & 0xDC00) != 0xDC00 && w >= 0xD800 && w <= 0xDBFF) // First 16-bit number of surrogate pair
{
int b1 = _stream.ReadByte();
int b2 = _stream.ReadByte();
if (b2 < 0)
{
throw new XmlException(SR.JsonUnexpectedEndOfFile);
}
_bytes[max++] = (byte)b1;
_bytes[max++] = (byte)b2;
_byteCount += 2;
}
}
private void EnsureBuffers()
{
EnsureByteBuffer();
if (_chars == null)
{
_chars = new char[BufferLength];
}
}
private void EnsureByteBuffer()
{
if (_bytes != null)
{
return;
}
_bytes = new byte[BufferLength * 4];
_byteOffset = 0;
_byteCount = 0;
}
private void FillBuffer(int count)
{
count -= _byteCount;
while (count > 0)
{
int read = _stream.Read(_bytes, _byteOffset + _byteCount, count);
if (read == 0)
{
break;
}
_byteCount += read;
count -= read;
}
}
private void InitForReading(Stream inputStream, Encoding expectedEncoding)
{
try
{
//this.stream = new BufferedStream(inputStream);
_stream = inputStream;
SupportedEncoding expectedEnc = GetSupportedEncoding(expectedEncoding);
SupportedEncoding dataEnc = ReadEncoding();
if ((expectedEnc != SupportedEncoding.None) && (expectedEnc != dataEnc))
{
ThrowExpectedEncodingMismatch(expectedEnc, dataEnc);
}
// Fastpath: UTF-8 (do nothing)
if (dataEnc != SupportedEncoding.UTF8)
{
// Convert to UTF-8
EnsureBuffers();
FillBuffer((BufferLength - 1) * 2);
_encodingCode = dataEnc;
_encoding = GetEncoding(dataEnc);
CleanupCharBreak();
int count = _encoding.GetChars(_bytes, _byteOffset, _byteCount, _chars, 0);
_byteOffset = 0;
_byteCount = s_validatingUTF8.GetBytes(_chars, 0, count, _bytes, 0);
}
}
catch (DecoderFallbackException ex)
{
throw new XmlException(SR.JsonInvalidBytes, ex);
}
}
private void InitForWriting(Stream outputStream, Encoding writeEncoding)
{
_encoding = writeEncoding;
//this.stream = new BufferedStream(outputStream);
_stream = outputStream;
// Set the encoding code
_encodingCode = GetSupportedEncoding(writeEncoding);
if (_encodingCode != SupportedEncoding.UTF8)
{
EnsureBuffers();
_dec = s_validatingUTF8.GetDecoder();
_enc = _encoding.GetEncoder();
}
}
private SupportedEncoding ReadEncoding()
{
int b1 = _stream.ReadByte();
int b2 = _stream.ReadByte();
EnsureByteBuffer();
SupportedEncoding e;
if (b1 == -1)
{
e = SupportedEncoding.UTF8;
_byteCount = 0;
}
else if (b2 == -1)
{
e = SupportedEncoding.UTF8;
_bytes[0] = (byte)b1;
_byteCount = 1;
}
else
{
e = ReadEncoding((byte)b1, (byte)b2);
_bytes[0] = (byte)b1;
_bytes[1] = (byte)b2;
_byteCount = 2;
}
return e;
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="ComponentInfo.cs" company="Microsoft Corporation">
// Copyright (c) 1999, Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Part of the Deployment Tools Foundation project.
// </summary>
//---------------------------------------------------------------------
namespace Microsoft.PackageManagement.Msi.Internal.Deployment.WindowsInstaller
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// Accessor for information about components within the context of an installation session.
/// </summary>
internal sealed class ComponentInfoCollection : ICollection<ComponentInfo>
{
private Session session;
internal ComponentInfoCollection(Session session)
{
this.session = session;
}
/// <summary>
/// Gets information about a component within the context of an installation session.
/// </summary>
/// <param name="component">name of the component</param>
/// <returns>component object</returns>
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public ComponentInfo this[string component]
{
get
{
return new ComponentInfo(this.session, component);
}
}
void ICollection<ComponentInfo>.Add(ComponentInfo item)
{
throw new InvalidOperationException();
}
void ICollection<ComponentInfo>.Clear()
{
throw new InvalidOperationException();
}
/// <summary>
/// Checks if the collection contains a component.
/// </summary>
/// <param name="component">name of the component</param>
/// <returns>true if the component is in the collection, else false</returns>
public bool Contains(string component)
{
return this.session.Database.CountRows(
"Component", "`Component` = '" + component + "'") == 1;
}
bool ICollection<ComponentInfo>.Contains(ComponentInfo item)
{
return item != null && this.Contains(item.Name);
}
/// <summary>
/// Copies the features into an array.
/// </summary>
/// <param name="array">array that receives the features</param>
/// <param name="arrayIndex">offset into the array</param>
public void CopyTo(ComponentInfo[] array, int arrayIndex)
{
if (array == null) {
throw new ArgumentNullException("array");
}
foreach (ComponentInfo component in this)
{
array[arrayIndex++] = component;
}
}
/// <summary>
/// Gets the number of components defined for the product.
/// </summary>
public int Count
{
get
{
return this.session.Database.CountRows("Component");
}
}
bool ICollection<ComponentInfo>.IsReadOnly
{
get
{
return true;
}
}
bool ICollection<ComponentInfo>.Remove(ComponentInfo item)
{
throw new InvalidOperationException();
}
/// <summary>
/// Enumerates the components in the collection.
/// </summary>
/// <returns>an enumerator over all features in the collection</returns>
public IEnumerator<ComponentInfo> GetEnumerator()
{
using (View compView = this.session.Database.OpenView(
"SELECT `Component` FROM `Component`"))
{
compView.Execute();
foreach (Record compRec in compView) using (compRec)
{
string comp = compRec.GetString(1);
yield return new ComponentInfo(this.session, comp);
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
/// <summary>
/// Provides access to information about a component within the context of an installation session.
/// </summary>
internal class ComponentInfo
{
private Session session;
private string name;
internal ComponentInfo(Session session, string name)
{
this.session = session;
this.name = name;
}
/// <summary>
/// Gets the name of the component (primary key in the Component table).
/// </summary>
public string Name
{
get
{
return this.name;
}
}
/// <summary>
/// Gets the current install state of the designated Component.
/// </summary>
/// <exception cref="InvalidHandleException">the Session handle is invalid</exception>
/// <exception cref="ArgumentException">an unknown Component was requested</exception>
/// <remarks><p>
/// Win32 MSI API:
/// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigetcomponentstate.asp">MsiGetComponentState</a>
/// </p></remarks>
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public InstallState CurrentState
{
get
{
int installedState, actionState;
uint ret = RemotableNativeMethods.MsiGetComponentState((int) this.session.Handle, this.name, out installedState, out actionState);
if (ret != 0)
{
if (ret == (uint) NativeMethods.Error.UNKNOWN_COMPONENT)
{
throw InstallerException.ExceptionFromReturnCode(ret, this.name);
}
else
{
throw InstallerException.ExceptionFromReturnCode(ret);
}
}
return (InstallState) installedState;
}
}
/// <summary>
/// Gets or sets the action state of the designated Component.
/// </summary>
/// <exception cref="InvalidHandleException">the Session handle is invalid</exception>
/// <exception cref="ArgumentException">an unknown Component was requested</exception>
/// <exception cref="InstallCanceledException">the user exited the installation</exception>
/// <remarks><p>
/// Win32 MSI APIs:
/// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigetcomponentstate.asp">MsiGetComponentState</a>,
/// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msisetcomponentstate.asp">MsiSetComponentState</a>
/// </p></remarks>
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public InstallState RequestState
{
get
{
int installedState, actionState;
uint ret = RemotableNativeMethods.MsiGetComponentState((int) this.session.Handle, this.name, out installedState, out actionState);
if (ret != 0)
{
if (ret == (uint) NativeMethods.Error.UNKNOWN_COMPONENT)
{
throw InstallerException.ExceptionFromReturnCode(ret, this.name);
}
else
{
throw InstallerException.ExceptionFromReturnCode(ret);
}
}
return (InstallState) actionState;
}
set
{
uint ret = RemotableNativeMethods.MsiSetComponentState((int) this.session.Handle, this.name, (int) value);
if (ret != 0)
{
if (ret == (uint) NativeMethods.Error.UNKNOWN_COMPONENT)
{
throw InstallerException.ExceptionFromReturnCode(ret, this.name);
}
else
{
throw InstallerException.ExceptionFromReturnCode(ret);
}
}
}
}
/// <summary>
/// Gets disk space per drive required to install a component.
/// </summary>
/// <param name="installState">Requested component state</param>
/// <returns>A list of InstallCost structures, specifying the cost for each drive for the component</returns>
/// <remarks><p>
/// Win32 MSI API:
/// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msienumcomponentcosts.asp">MsiEnumComponentCosts</a>
/// </p></remarks>
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public IList<InstallCost> GetCost(InstallState installState)
{
IList<InstallCost> costs = new List<InstallCost>();
StringBuilder driveBuf = new StringBuilder(20);
for (uint i = 0; true; i++)
{
int cost, tempCost;
uint driveBufSize = (uint) driveBuf.Capacity;
uint ret = RemotableNativeMethods.MsiEnumComponentCosts(
(int) this.session.Handle,
this.name,
i,
(int) installState,
driveBuf,
ref driveBufSize,
out cost,
out tempCost);
if (ret == (uint) NativeMethods.Error.NO_MORE_ITEMS) break;
if (ret == (uint) NativeMethods.Error.MORE_DATA)
{
driveBuf.Capacity = (int) ++driveBufSize;
ret = RemotableNativeMethods.MsiEnumComponentCosts(
(int) this.session.Handle,
this.name,
i,
(int) installState,
driveBuf,
ref driveBufSize,
out cost,
out tempCost);
}
if (ret != 0)
{
throw InstallerException.ExceptionFromReturnCode(ret);
}
costs.Add(new InstallCost(driveBuf.ToString(), cost * 512L, tempCost * 512L));
}
return costs;
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !SILVERLIGHT
namespace NLog.Internal.FileAppenders
{
using System;
using System.IO;
using System.Security;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Threading;
using NLog.Common;
/// <summary>
/// Provides a multiprocess-safe atomic file appends while
/// keeping the files open.
/// </summary>
/// <remarks>
/// On Unix you can get all the appends to be atomic, even when multiple
/// processes are trying to write to the same file, because setting the file
/// pointer to the end of the file and appending can be made one operation.
/// On Win32 we need to maintain some synchronization between processes
/// (global named mutex is used for this)
/// </remarks>
[SecuritySafeCritical]
internal class MutexMultiProcessFileAppender : BaseFileAppender
{
public static readonly IFileAppenderFactory TheFactory = new Factory();
private FileStream fileStream;
private Mutex mutex;
/// <summary>
/// Initializes a new instance of the <see cref="MutexMultiProcessFileAppender" /> class.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="parameters">The parameters.</param>
public MutexMultiProcessFileAppender(string fileName, ICreateFileParameters parameters) : base(fileName, parameters)
{
try
{
this.mutex = CreateSharableMutex(GetMutexName(fileName));
this.fileStream = CreateFileStream(true);
}
catch
{
if (this.mutex != null)
{
this.mutex.Close();
this.mutex = null;
}
if (this.fileStream != null)
{
this.fileStream.Close();
this.fileStream = null;
}
throw;
}
}
/// <summary>
/// Writes the specified bytes.
/// </summary>
/// <param name="bytes">The bytes to be written.</param>
public override void Write(byte[] bytes)
{
if (this.mutex == null)
{
return;
}
try
{
this.mutex.WaitOne();
}
catch (AbandonedMutexException)
{
// ignore the exception, another process was killed without properly releasing the mutex
// the mutex has been acquired, so proceed to writing
// See: http://msdn.microsoft.com/en-us/library/system.threading.abandonedmutexexception.aspx
}
try
{
this.fileStream.Seek(0, SeekOrigin.End);
this.fileStream.Write(bytes, 0, bytes.Length);
this.fileStream.Flush();
if (CaptureLastWriteTime)
{
FileTouched();
}
}
finally
{
this.mutex.ReleaseMutex();
}
}
/// <summary>
/// Closes this instance.
/// </summary>
public override void Close()
{
InternalLogger.Trace("Closing '{0}'", FileName);
if (this.mutex != null)
{
this.mutex.Close();
}
if (this.fileStream != null)
{
this.fileStream.Close();
}
this.mutex = null;
this.fileStream = null;
FileTouched();
}
/// <summary>
/// Flushes this instance.
/// </summary>
public override void Flush()
{
// do nothing, the stream is always flushed
}
public override DateTime? GetFileCreationTimeUtc()
{
var fileChars = GetFileCharacteristics();
return fileChars.CreationTimeUtc;
}
public override DateTime? GetFileLastWriteTimeUtc()
{
var fileChars = GetFileCharacteristics();
return fileChars.LastWriteTimeUtc;
}
public override long? GetFileLength()
{
var fileChars = GetFileCharacteristics();
return fileChars.FileLength;
}
private FileCharacteristics GetFileCharacteristics()
{
//todo not efficient to read all the whole FileCharacteristics and then using one property
return FileCharacteristicsHelper.Helper.GetFileCharacteristics(FileName, this.fileStream.SafeFileHandle.DangerousGetHandle());
}
private static Mutex CreateSharableMutex(string name)
{
// Creates a mutex sharable by more than one process
var mutexSecurity = new MutexSecurity();
var everyoneSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
mutexSecurity.AddAccessRule(new MutexAccessRule(everyoneSid, MutexRights.FullControl, AccessControlType.Allow));
// The constructor will either create new mutex or open
// an existing one, in a thread-safe manner
bool createdNew;
return new Mutex(false, name, out createdNew, mutexSecurity);
}
private static string GetMutexName(string fileName)
{
// The global kernel object namespace is used so the mutex
// can be shared among processes in all sessions
const string mutexNamePrefix = @"Global\NLog-FileLock-";
const int maxMutexNameLength = 260;
string canonicalName = Path.GetFullPath(fileName).ToLowerInvariant();
// Mutex names must not contain a backslash, it's the namespace separator,
// but all other are OK
canonicalName = canonicalName.Replace('\\', '/');
// A mutex name must not exceed MAX_PATH (260) characters
if (mutexNamePrefix.Length + canonicalName.Length <= maxMutexNameLength)
{
return mutexNamePrefix + canonicalName;
}
// The unusual case of the path being too long; let's hash the canonical name,
// so it can be safely shortened and still remain unique
string hash;
using (MD5 md5 = MD5.Create())
{
byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(canonicalName));
hash = Convert.ToBase64String(bytes);
}
// The hash makes the name unique, but also add the end of the path,
// so the end of the name tells us which file it is (for debugging)
int cutOffIndex = canonicalName.Length - (maxMutexNameLength - mutexNamePrefix.Length - hash.Length);
return mutexNamePrefix + hash + canonicalName.Substring(cutOffIndex);
}
/// <summary>
/// Factory class.
/// </summary>
private class Factory : IFileAppenderFactory
{
/// <summary>
/// Opens the appender for given file name and parameters.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="parameters">Creation parameters.</param>
/// <returns>
/// Instance of <see cref="BaseFileAppender"/> which can be used to write to the file.
/// </returns>
BaseFileAppender IFileAppenderFactory.Open(string fileName, ICreateFileParameters parameters)
{
return new MutexMultiProcessFileAppender(fileName, parameters);
}
}
}
}
#endif
| |
// 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.Data.SqlClient;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Threading;
using System.Transactions;
namespace System.Data.SqlClient
{
sealed internal partial class SqlDelegatedTransaction : IPromotableSinglePhaseNotification
{
private static int _objectTypeCount;
private readonly int _objectID = Interlocked.Increment(ref _objectTypeCount);
private const int _globalTransactionsTokenVersionSizeInBytes = 4; // the size of the version in the PromotedDTCToken for Global Transactions
internal int ObjectID
{
get
{
return _objectID;
}
}
// WARNING!!! Multithreaded object!
// Locking strategy: Any potentailly-multithreaded operation must first lock the associated connection, then
// validate this object's active state. Locked activities should ONLY include Sql-transaction state altering activities
// or notifications of same. Updates to the connection's association with the transaction or to the connection pool
// may be initiated here AFTER the connection lock is released, but should NOT fall under this class's locking strategy.
private SqlInternalConnection _connection; // the internal connection that is the root of the transaction
private IsolationLevel _isolationLevel; // the IsolationLevel of the transaction we delegated to the server
private SqlInternalTransaction _internalTransaction; // the SQL Server transaction we're delegating to
private Transaction _atomicTransaction;
private bool _active; // Is the transaction active?
internal SqlDelegatedTransaction(SqlInternalConnection connection, Transaction tx)
{
Debug.Assert(null != connection, "null connection?");
_connection = connection;
_atomicTransaction = tx;
_active = false;
Transactions.IsolationLevel systxIsolationLevel = (Transactions.IsolationLevel)tx.IsolationLevel;
// We need to map the System.Transactions IsolationLevel to the one
// that System.Data uses and communicates to SqlServer. We could
// arguably do that in Initialize when the transaction is delegated,
// however it is better to do this before we actually begin the process
// of delegation, in case System.Transactions adds another isolation
// level we don't know about -- we can throw the exception at a better
// place.
switch (systxIsolationLevel)
{
case Transactions.IsolationLevel.ReadCommitted:
_isolationLevel = IsolationLevel.ReadCommitted;
break;
case Transactions.IsolationLevel.ReadUncommitted:
_isolationLevel = IsolationLevel.ReadUncommitted;
break;
case Transactions.IsolationLevel.RepeatableRead:
_isolationLevel = IsolationLevel.RepeatableRead;
break;
case Transactions.IsolationLevel.Serializable:
_isolationLevel = IsolationLevel.Serializable;
break;
case Transactions.IsolationLevel.Snapshot:
_isolationLevel = IsolationLevel.Snapshot;
break;
default:
throw SQL.UnknownSysTxIsolationLevel(systxIsolationLevel);
}
}
internal Transaction Transaction
{
get { return _atomicTransaction; }
}
public void Initialize()
{
// if we get here, then we know for certain that we're the delegated
// transaction.
SqlInternalConnection connection = _connection;
SqlConnection usersConnection = connection.Connection;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
if (connection.IsEnlistedInTransaction)
{ // defect first
connection.EnlistNull();
}
_internalTransaction = new SqlInternalTransaction(connection, TransactionType.Delegated, null);
connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Begin, null, _isolationLevel, _internalTransaction, true);
// Handle case where ExecuteTran didn't produce a new transaction, but also didn't throw.
if (null == connection.CurrentTransaction)
{
connection.DoomThisConnection();
throw ADP.InternalError(ADP.InternalErrorCode.UnknownTransactionFailure);
}
_active = true;
}
catch (System.OutOfMemoryException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.StackOverflowException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.Threading.ThreadAbortException e)
{
usersConnection.Abort(e);
throw;
}
}
internal bool IsActive
{
get
{
return _active;
}
}
public byte[] Promote()
{
// Operations that might be affected by multi-threaded use MUST be done inside the lock.
// Don't read values off of the connection outside the lock unless it doesn't really matter
// from an operational standpoint (i.e. logging connection's ObjectID should be fine,
// but the PromotedDTCToken can change over calls. so that must be protected).
SqlInternalConnection connection = GetValidConnection();
Exception promoteException;
byte[] returnValue = null;
if (null != connection)
{
SqlConnection usersConnection = connection.Connection;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
lock (connection)
{
try
{
// Now that we've acquired the lock, make sure we still have valid state for this operation.
ValidateActiveOnConnection(connection);
connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Promote, null, IsolationLevel.Unspecified, _internalTransaction, true);
returnValue = _connection.PromotedDTCToken;
// For Global Transactions, we need to set the Transaction Id since we use a Non-MSDTC Promoter type.
if (_connection.IsGlobalTransaction)
{
if (SysTxForGlobalTransactions.SetDistributedTransactionIdentifier == null)
{
throw SQL.UnsupportedSysTxForGlobalTransactions();
}
if (!_connection.IsGlobalTransactionsEnabledForServer)
{
throw SQL.GlobalTransactionsNotEnabled();
}
SysTxForGlobalTransactions.SetDistributedTransactionIdentifier.Invoke(_atomicTransaction, new object[] { this, GetGlobalTxnIdentifierFromToken() });
}
promoteException = null;
}
catch (SqlException e)
{
promoteException = e;
// Doom the connection, to make sure that the transaction is
// eventually rolled back.
// VSTS 144562: doom the connection while having the lock on it to prevent race condition with "Transaction Ended" Event
connection.DoomThisConnection();
}
catch (InvalidOperationException e)
{
promoteException = e;
connection.DoomThisConnection();
}
}
}
catch (System.OutOfMemoryException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.StackOverflowException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.Threading.ThreadAbortException e)
{
usersConnection.Abort(e);
throw;
}
// Throw exception only if Transaction is still active and not yet aborted.
if (promoteException != null && Transaction.TransactionInformation.Status != TransactionStatus.Aborted)
{
throw SQL.PromotionFailed(promoteException);
}
}
return returnValue;
}
// Called by transaction to initiate abort sequence
public void Rollback(SinglePhaseEnlistment enlistment)
{
Debug.Assert(null != enlistment, "null enlistment?");
SqlInternalConnection connection = GetValidConnection();
if (null != connection)
{
SqlConnection usersConnection = connection.Connection;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
lock (connection)
{
try
{
// Now that we've acquired the lock, make sure we still have valid state for this operation.
ValidateActiveOnConnection(connection);
_active = false; // set to inactive first, doesn't matter how the execute completes, this transaction is done.
_connection = null; // Set prior to ExecuteTransaction call in case this initiates a TransactionEnd event
// If we haven't already rolled back (or aborted) then tell the SQL Server to roll back
if (!_internalTransaction.IsAborted)
{
connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Rollback, null, IsolationLevel.Unspecified, _internalTransaction, true);
}
}
catch (SqlException)
{
// Doom the connection, to make sure that the transaction is
// eventually rolled back.
// VSTS 144562: doom the connection while having the lock on it to prevent race condition with "Transaction Ended" Event
connection.DoomThisConnection();
// Unlike SinglePhaseCommit, a rollback is a rollback, regardless
// of how it happens, so SysTx won't throw an exception, and we
// don't want to throw an exception either, because SysTx isn't
// handling it and it may create a fail fast scenario. In the end,
// there is no way for us to communicate to the consumer that this
// failed for more serious reasons than usual.
//
// This is a bit like "should you throw if Close fails", however,
// it only matters when you really need to know. In that case,
// we have the tracing that we're doing to fallback on for the
// investigation.
}
catch (InvalidOperationException)
{
connection.DoomThisConnection();
}
}
// it doesn't matter whether the rollback succeeded or not, we presume
// that the transaction is aborted, because it will be eventually.
connection.CleanupConnectionOnTransactionCompletion(_atomicTransaction);
enlistment.Aborted();
}
catch (System.OutOfMemoryException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.StackOverflowException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.Threading.ThreadAbortException e)
{
usersConnection.Abort(e);
throw;
}
}
else
{
// The transaction was aborted, report that to SysTx.
enlistment.Aborted();
}
}
// Called by the transaction to initiate commit sequence
public void SinglePhaseCommit(SinglePhaseEnlistment enlistment)
{
Debug.Assert(null != enlistment, "null enlistment?");
SqlInternalConnection connection = GetValidConnection();
if (null != connection)
{
SqlConnection usersConnection = connection.Connection;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
lock (connection)
{
// If the connection is doomed, we can be certain that the
// transaction will eventually be rolled back or is externally aborted, and we shouldn't
// attempt to commit it.
if (connection.IsConnectionDoomed)
{
_active = false; // set to inactive first, doesn't matter how the rest completes, this transaction is done.
_connection = null;
enlistment.Aborted(SQL.ConnectionDoomed());
}
else
{
Exception commitException;
try
{
// Now that we've acquired the lock, make sure we still have valid state for this operation.
ValidateActiveOnConnection(connection);
_active = false; // set to inactive first, doesn't matter how the rest completes, this transaction is done.
_connection = null; // Set prior to ExecuteTransaction call in case this initiates a TransactionEnd event
connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Commit, null, IsolationLevel.Unspecified, _internalTransaction, true);
commitException = null;
}
catch (SqlException e)
{
commitException = e;
// Doom the connection, to make sure that the transaction is
// eventually rolled back.
// VSTS 144562: doom the connection while having the lock on it to prevent race condition with "Transaction Ended" Event
connection.DoomThisConnection();
}
catch (InvalidOperationException e)
{
commitException = e;
connection.DoomThisConnection();
}
if (commitException != null)
{
// connection.ExecuteTransaction failed with exception
if (_internalTransaction.IsCommitted)
{
// Even though we got an exception, the transaction
// was committed by the server.
enlistment.Committed();
}
else if (_internalTransaction.IsAborted)
{
// The transaction was aborted, report that to
// SysTx.
enlistment.Aborted(commitException);
}
else
{
// The transaction is still active, we cannot
// know the state of the transaction.
enlistment.InDoubt(commitException);
}
// We eat the exception. This is called on the SysTx
// thread, not the applications thread. If we don't
// eat the exception an UnhandledException will occur,
// causing the process to FailFast.
}
connection.CleanupConnectionOnTransactionCompletion(_atomicTransaction);
if (commitException == null)
{
// connection.ExecuteTransaction succeeded
enlistment.Committed();
}
}
}
}
catch (System.OutOfMemoryException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.StackOverflowException e)
{
usersConnection.Abort(e);
throw;
}
catch (System.Threading.ThreadAbortException e)
{
usersConnection.Abort(e);
throw;
}
}
else
{
// The transaction was aborted before we could commit, report that to SysTx.
enlistment.Aborted();
}
}
// Event notification that transaction ended. This comes from the subscription to the Transaction's
// ended event via the internal connection. If it occurs without a prior Rollback or SinglePhaseCommit call,
// it indicates the transaction was ended externally (generally that one of the DTC participants aborted
// the transaction).
internal void TransactionEnded(Transaction transaction)
{
SqlInternalConnection connection = _connection;
if (connection != null)
{
lock (connection)
{
if (_atomicTransaction.Equals(transaction))
{
// No need to validate active on connection, this operation can be called on completed transactions
_active = false;
_connection = null;
}
// Safest approach is to doom this connection, whose transaction has been aborted externally.
// If we want to avoid dooming the connection for performance, state needs to be properly restored. (future TODO)
connection.DoomThisConnection();
}
}
}
// Check for connection validity
private SqlInternalConnection GetValidConnection()
{
SqlInternalConnection connection = _connection;
if (null == connection && Transaction.TransactionInformation.Status != TransactionStatus.Aborted)
{
throw ADP.ObjectDisposed(this);
}
return connection;
}
// Dooms connection and throws and error if not a valid, active, delegated transaction for the given
// connection. Designed to be called AFTER a lock is placed on the connection, otherwise a normal return
// may not be trusted.
private void ValidateActiveOnConnection(SqlInternalConnection connection)
{
bool valid = _active && (connection == _connection) && (connection.DelegatedTransaction == this);
if (!valid)
{
// Invalid indicates something BAAAD happened (Commit after TransactionEnded, for instance)
// Doom anything remotely involved.
if (null != connection)
{
connection.DoomThisConnection();
}
if (connection != _connection && null != _connection)
{
_connection.DoomThisConnection();
}
throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasWrongOwner); //TODO: Create a new code
}
}
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Abp.Collections.Extensions;
using Abp.Dependency;
using Abp.Localization;
using Abp.Threading;
namespace Abp.Authorization
{
/// <summary>
/// Extension methods for <see cref="IPermissionChecker"/>
/// </summary>
public static class PermissionCheckerExtensions
{
/// <summary>
/// Checks if current user is granted for a permission.
/// </summary>
/// <param name="permissionChecker">Permission checker</param>
/// <param name="permissionName">Name of the permission</param>
public static bool IsGranted(this IPermissionChecker permissionChecker, string permissionName)
{
return AsyncHelper.RunSync(() => permissionChecker.IsGrantedAsync(permissionName));
}
/// <summary>
/// Checks if a user is granted for a permission.
/// </summary>
/// <param name="permissionChecker">Permission checker</param>
/// <param name="user">User to check</param>
/// <param name="permissionName">Name of the permission</param>
public static bool IsGranted(this IPermissionChecker permissionChecker, UserIdentifier user, string permissionName)
{
return AsyncHelper.RunSync(() => permissionChecker.IsGrantedAsync(user, permissionName));
}
/// <summary>
/// Checks if given user is granted for given permission.
/// </summary>
/// <param name="permissionChecker">Permission checker</param>
/// <param name="user">User</param>
/// <param name="requiresAll">True, to require all given permissions are granted. False, to require one or more.</param>
/// <param name="permissionNames">Name of the permissions</param>
public static bool IsGranted(this IPermissionChecker permissionChecker, UserIdentifier user, bool requiresAll, params string[] permissionNames)
{
return AsyncHelper.RunSync(() => IsGrantedAsync(permissionChecker, user, requiresAll, permissionNames));
}
/// <summary>
/// Checks if given user is granted for given permission.
/// </summary>
/// <param name="permissionChecker">Permission checker</param>
/// <param name="user">User</param>
/// <param name="requiresAll">True, to require all given permissions are granted. False, to require one or more.</param>
/// <param name="permissionNames">Name of the permissions</param>
public static async Task<bool> IsGrantedAsync(this IPermissionChecker permissionChecker, UserIdentifier user, bool requiresAll, params string[] permissionNames)
{
if (permissionNames.IsNullOrEmpty())
{
return true;
}
if (requiresAll)
{
foreach (var permissionName in permissionNames)
{
if (!(await permissionChecker.IsGrantedAsync(user, permissionName)))
{
return false;
}
}
return true;
}
else
{
foreach (var permissionName in permissionNames)
{
if (await permissionChecker.IsGrantedAsync(user, permissionName))
{
return true;
}
}
return false;
}
}
/// <summary>
/// Checks if current user is granted for given permission.
/// </summary>
/// <param name="permissionChecker">Permission checker</param>
/// <param name="requiresAll">True, to require all given permissions are granted. False, to require one or more.</param>
/// <param name="permissionNames">Name of the permissions</param>
public static bool IsGranted(this IPermissionChecker permissionChecker, bool requiresAll, params string[] permissionNames)
{
return AsyncHelper.RunSync(() => IsGrantedAsync(permissionChecker, requiresAll, permissionNames));
}
/// <summary>
/// Checks if current user is granted for given permission.
/// </summary>
/// <param name="permissionChecker">Permission checker</param>
/// <param name="requiresAll">True, to require all given permissions are granted. False, to require one or more.</param>
/// <param name="permissionNames">Name of the permissions</param>
public static async Task<bool> IsGrantedAsync(this IPermissionChecker permissionChecker, bool requiresAll, params string[] permissionNames)
{
if (permissionNames.IsNullOrEmpty())
{
return true;
}
if (requiresAll)
{
foreach (var permissionName in permissionNames)
{
if (!(await permissionChecker.IsGrantedAsync(permissionName)))
{
return false;
}
}
return true;
}
else
{
foreach (var permissionName in permissionNames)
{
if (await permissionChecker.IsGrantedAsync(permissionName))
{
return true;
}
}
return false;
}
}
/// <summary>
/// Authorizes current user for given permission or permissions,
/// throws <see cref="AbpAuthorizationException"/> if not authorized.
/// User it authorized if any of the <see cref="permissionNames"/> are granted.
/// </summary>
/// <param name="permissionChecker">Permission checker</param>
/// <param name="permissionNames">Name of the permissions to authorize</param>
/// <exception cref="AbpAuthorizationException">Throws authorization exception if</exception>
public static void Authorize(this IPermissionChecker permissionChecker, params string[] permissionNames)
{
Authorize(permissionChecker, false, permissionNames);
}
/// <summary>
/// Authorizes current user for given permission or permissions,
/// throws <see cref="AbpAuthorizationException"/> if not authorized.
/// User it authorized if any of the <see cref="permissionNames"/> are granted.
/// </summary>
/// <param name="permissionChecker">Permission checker</param>
/// <param name="requireAll">
/// If this is set to true, all of the <see cref="permissionNames"/> must be granted.
/// If it's false, at least one of the <see cref="permissionNames"/> must be granted.
/// </param>
/// <param name="permissionNames">Name of the permissions to authorize</param>
/// <exception cref="AbpAuthorizationException">Throws authorization exception if</exception>
public static void Authorize(this IPermissionChecker permissionChecker, bool requireAll, params string[] permissionNames)
{
AsyncHelper.RunSync(() => AuthorizeAsync(permissionChecker, requireAll, permissionNames));
}
/// <summary>
/// Authorizes current user for given permission or permissions,
/// throws <see cref="AbpAuthorizationException"/> if not authorized.
/// User it authorized if any of the <see cref="permissionNames"/> are granted.
/// </summary>
/// <param name="permissionChecker">Permission checker</param>
/// <param name="permissionNames">Name of the permissions to authorize</param>
/// <exception cref="AbpAuthorizationException">Throws authorization exception if</exception>
public static Task AuthorizeAsync(this IPermissionChecker permissionChecker, params string[] permissionNames)
{
return AuthorizeAsync(permissionChecker, false, permissionNames);
}
/// <summary>
/// Authorizes current user for given permission or permissions,
/// throws <see cref="AbpAuthorizationException"/> if not authorized.
/// </summary>
/// <param name="permissionChecker">Permission checker</param>
/// <param name="requireAll">
/// If this is set to true, all of the <see cref="permissionNames"/> must be granted.
/// If it's false, at least one of the <see cref="permissionNames"/> must be granted.
/// </param>
/// <param name="permissionNames">Name of the permissions to authorize</param>
/// <exception cref="AbpAuthorizationException">Throws authorization exception if</exception>
public static async Task AuthorizeAsync(this IPermissionChecker permissionChecker, bool requireAll, params string[] permissionNames)
{
if (await IsGrantedAsync(permissionChecker, requireAll, permissionNames))
{
return;
}
var localizedPermissionNames = LocalizePermissionNames(permissionChecker, permissionNames);
if (requireAll)
{
throw new AbpAuthorizationException(
string.Format(
L(
permissionChecker,
"AllOfThesePermissionsMustBeGranted",
"Required permissions are not granted. All of these permissions must be granted: {0}"
),
string.Join(", ", localizedPermissionNames)
)
);
}
else
{
throw new AbpAuthorizationException(
string.Format(
L(
permissionChecker,
"AtLeastOneOfThesePermissionsMustBeGranted",
"Required permissions are not granted. At least one of these permissions must be granted: {0}"
),
string.Join(", ", localizedPermissionNames)
)
);
}
}
public static string L(IPermissionChecker permissionChecker, string name, string defaultValue)
{
if (!(permissionChecker is IIocManagerAccessor))
{
return defaultValue;
}
var iocManager = (permissionChecker as IIocManagerAccessor).IocManager;
using (var localizationManager = iocManager.ResolveAsDisposable<ILocalizationManager>())
{
return localizationManager.Object.GetString(AbpConsts.LocalizationSourceName, name);
}
}
public static string[] LocalizePermissionNames(IPermissionChecker permissionChecker, string[] permissionNames)
{
if (!(permissionChecker is IIocManagerAccessor))
{
return permissionNames;
}
var iocManager = (permissionChecker as IIocManagerAccessor).IocManager;
using (var localizationContext = iocManager.ResolveAsDisposable<ILocalizationContext>())
{
using (var permissionManager = iocManager.ResolveAsDisposable<IPermissionManager>())
{
return permissionNames.Select(permissionName =>
{
var permission = permissionManager.Object.GetPermissionOrNull(permissionName);
return permission?.DisplayName == null
? permissionName
: permission.DisplayName.Localize(localizationContext.Object);
}).ToArray();
}
}
}
}
}
| |
/*
Copyright (c) 2004-2006 Tomas Matousek and Ladislav Prosek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Collections;
using System.Diagnostics;
using PHP.Core.Reflection;
using System.Collections.Generic;
using System.Reflection.Emit;
using System.Reflection;
using System.Linq;
using PHP.Core.Emit;
#if SILVERLIGHT
using PHP.CoreCLR;
#endif
namespace PHP.Core
{
#region Assemblies
[Serializable]
public abstract class DAssemblyAttribute : Attribute
{
internal static DAssemblyAttribute Reflect(Assembly/*!*/ assembly)
{
#if !SILVERLIGHT
Debug.Assert(!assembly.ReflectionOnly);
#endif
object[] attrs = assembly.GetCustomAttributes(typeof(DAssemblyAttribute), false);
return (attrs.Length == 1) ? (DAssemblyAttribute)attrs[0] : null;
}
}
[Serializable]
public abstract class PhpAssemblyAttribute : DAssemblyAttribute
{
}
/// <summary>
/// Identifies PHP library assembly or extension.
/// </summary>
[Serializable]
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
public class PhpLibraryAttribute : DAssemblyAttribute
{
/// <summary>
/// Name of the type describing the assembly.
/// Either a name of the type in the declaring assembly, a fully qualified name containing an assembly name
/// or a <B>null</B> reference if a default descriptor can be used.
/// </summary>
public Type Descriptor { get { return descriptor; } }
private readonly Type descriptor;
public bool IsPure { get { return isPure; } }
private readonly bool isPure;
public bool ContainsDynamicStubs { get { return containsDynamicStubs; } }
private readonly bool containsDynamicStubs;
public string/*!*/ Name { get { return name; } }
private readonly string/*!*/ name;
public string[]/*!*/ ImplementsExtensions { get { return implementsExtensions; } }
private readonly string[]/*!*/ implementsExtensions;
/// <summary>
/// Used by hand-written libraries in PHP.
/// </summary>
/// <param name="descriptor">The type derived from <c>PhpLibraryDescriptor</c> class. Can be null to use default implementation.</param>
/// <param name="name">The human readable name of the extension.</param>
/// <remarks>List of implemented extensions <c>ImplementsExtensions</c> is an empty array. Extensions using
/// this attribute does not populate any list of implemented PHP extensions.</remarks>
public PhpLibraryAttribute(Type descriptor, string/*!*/ name)
: this(descriptor, name, ArrayUtils.EmptyStrings, false, false)
{
}
/// <summary>
/// Used by hand-written libraries.
/// </summary>
public PhpLibraryAttribute(Type descriptor, string/*!*/ name, string[]/*!*/implementsExtensions)
: this(descriptor, name, implementsExtensions, false, false)
{
}
/// <summary>
/// Used by hand-written libraries.
/// </summary>
public PhpLibraryAttribute(Type descriptor, string/*!*/ name, string[]/*!*/implementsExtensions, bool isPure, bool containsDynamicStubs)
{
// descriptor can be null, default descriptor is used then, needed at least for the Extension PHP project
//if (descriptor == null)
// throw new ArgumentNullException("descriptorName");
if (descriptor != null && !typeof(PhpLibraryDescriptor).IsAssignableFrom(descriptor))
throw new ArgumentNullException("descriptor", "The type must be derived from PHP.Core.PhpLibraryDescriptor class.");
if (name == null)
throw new ArgumentNullException("name");
if (implementsExtensions == null)
throw new ArgumentNullException("implementsExtensions");
this.descriptor = descriptor;
this.isPure = isPure;
this.containsDynamicStubs = containsDynamicStubs;
this.name = name;
this.implementsExtensions = implementsExtensions;
}
/*
* TODO: Not needed???
*
public static PhpLibraryAttribute/*!* / Reflect(CustomAttributeData/*!* / data)
{
if (data == null)
throw new ArgumentNullException("data");
switch (data.ConstructorArguments.Count)
{
case 2: return new PhpLibraryAttribute(
(Type)data.ConstructorArguments[0].Value,
(string)data.ConstructorArguments[1].Value);
case 3: return new PhpLibraryAttribute(
(Type)data.ConstructorArguments[0].Value,
(string)data.ConstructorArguments[1].Value,
(bool)data.ConstructorArguments[2].Value,
(bool)data.ConstructorArguments[3].Value);
}
throw new ArgumentException();
}*/
}
/// <summary>
/// Identifies PHP extension written in PHP pure mode.
/// It has only PHP literals as parameters and it has dynamic stubs contained already.
/// </summary>
[Serializable]
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
public class PhpExtensionAttribute : PhpLibraryAttribute
{
public PhpExtensionAttribute(string/*!*/name)
:base(null, name, ArrayUtils.EmptyStrings, false, true)
{
}
}
/// <summary>
/// Marks Phalanger compiled PHP script assemblies.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
public sealed class ScriptAssemblyAttribute : PhpAssemblyAttribute
{
/// <summary>
/// Determines whether there are multiple scripts stored in the assembly.
/// </summary>
public bool IsMultiScript { get { return isMultiScript; } }
private readonly bool isMultiScript;
/// <summary>
/// <see cref="Type"/> of a <c><Script></c> class in case of SingleScriptAssembly.
/// </summary>
public Type SSAScriptType { get { return ssaScriptType; } }
private readonly Type ssaScriptType;
public ScriptAssemblyAttribute(bool isMultiScript, Type ssaScriptType)
{
this.isMultiScript = isMultiScript;
this.ssaScriptType = ssaScriptType;
}
internal new static ScriptAssemblyAttribute Reflect(Assembly/*!*/ assembly)
{
#if !SILVERLIGHT
Debug.Assert(!assembly.ReflectionOnly);
#endif
object[] attrs = assembly.GetCustomAttributes(typeof(ScriptAssemblyAttribute), false);
return (attrs.Length == 1) ? (ScriptAssemblyAttribute)attrs[0] : null;
}
}
/// <summary>
/// Marks Phalanger compiled pure assemblies.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
public sealed class PurePhpAssemblyAttribute : PhpAssemblyAttribute
{
public string[]/*!*/ ReferencedAssemblies { get { return referencedAssemblies; } }
private string[]/*!*/ referencedAssemblies;
public PurePhpAssemblyAttribute(string[]/*!*/ referencedAssemblies)
{
this.referencedAssemblies = referencedAssemblies;
}
/* TODO: Not needed?
public static PurePhpAssemblyAttribute/*!* / Reflect(CustomAttributeData/*!* / data)
{
if (data == null)
throw new ArgumentNullException("data");
switch (data.ConstructorArguments.Count)
{
case 1: return new PurePhpAssemblyAttribute((string[])data.ConstructorArguments[0].Value);
}
throw new ArgumentException();
}*/
internal new static PurePhpAssemblyAttribute Reflect(Assembly/*!*/ assembly)
{
#if !SILVERLIGHT
Debug.Assert(!assembly.ReflectionOnly);
#endif
object[] attrs = assembly.GetCustomAttributes(typeof(PurePhpAssemblyAttribute), false);
return (attrs.Length == 1) ? (PurePhpAssemblyAttribute)attrs[0] : null;
}
}
#endregion
#region Language
/// <summary>
/// Marks types of the Class Library which should be viewed as PHP classes or interfaces.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false, Inherited = false)]
public sealed class ImplementsTypeAttribute : Attribute
{
/// <summary>
/// If not <c>null</c>, defines the PHP type name instead of the reflected name. CLR notation of namespaces.
/// </summary>
public readonly string PHPTypeName;
/// <summary>
/// Initialized new instance of <see cref="ImplementsTypeAttribute"/> specifying that
/// the type is visible in PHP code and the type is named using the reflected <see cref="Type.FullName"/>.
/// </summary>
public ImplementsTypeAttribute()
{
}
/// <summary>
/// Initialized new instance of <see cref="ImplementsTypeAttribute"/> with PHP type name specified.
/// </summary>
/// <param name="PHPTypeName">If not <c>null</c>, defines the PHP type name instead of the reflected name. Uses CLR notation of namespaces.</param>
/// <remarks>This overload is only valid within class library types.</remarks>
public ImplementsTypeAttribute(string PHPTypeName)
{
Debug.Assert(!string.IsNullOrWhiteSpace(PHPTypeName));
Debug.Assert(!PHPTypeName.Contains(QualifiedName.Separator));
this.PHPTypeName = PHPTypeName;
}
internal static ImplementsTypeAttribute Reflect(Type/*!*/type)
{
Debug.Assert(type != null);
var attrs = type.GetCustomAttributes(typeof(ImplementsTypeAttribute), false);
return (attrs != null && attrs.Length == 1) ? (ImplementsTypeAttribute)attrs[0] : null;
}
}
/// <summary>
/// An attibute storing PHP formal argument type hints.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
public sealed class DTypeSpecAttribute : Attribute
{
internal DTypeSpec TypeSpec { get { return typeSpec; } }
private DTypeSpec typeSpec;
public DTypeSpecAttribute(int data0, int data1)
{
typeSpec = new DTypeSpec(new int[] { data0, data1 });
}
public DTypeSpecAttribute(int[]/*!*/ data)
{
typeSpec = new DTypeSpec(data);
}
public DTypeSpecAttribute(int data0, int data1, byte[]/*!*/ strings)
{
typeSpec = new DTypeSpec(new int[] { data0, data1 }, strings);
}
public DTypeSpecAttribute(int[]/*!*/ data, byte[]/*!*/ strings)
{
typeSpec = new DTypeSpec(data, strings);
}
internal static DTypeSpecAttribute Reflect(ICustomAttributeProvider/*!*/ parameterInfo)
{
object[] attrs = parameterInfo.GetCustomAttributes(typeof(DTypeSpecAttribute), false);
return (attrs.Length == 1) ? (DTypeSpecAttribute)attrs[0] : null;
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class RoutineAttribute : Attribute
{
private RoutineProperties properties;
public RoutineAttribute(RoutineProperties properties)
{
this.properties = properties;
}
public RoutineProperties Properties { get { return properties; } }
}
/// <summary>
/// Marks namespace-private PHP types and functions.
/// </summary>
/// <remarks>Attribute is used by <see cref="Reflection"/>.</remarks>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class PhpNamespacePrivateAttribute : Attribute
{
}
/// <summary>
/// Marks CLR type representing a PHP trait.
/// </summary>
/// <remarks>Attribute is used by <see cref="Reflection"/>.</remarks>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public sealed class PhpTraitAttribute : Attribute
{
}
/// <summary>
/// CLI does not allow static final methods. If a static method is declared as
/// final, it is marked with this attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class PhpFinalAttribute : Attribute
{
}
/// <summary>
/// CLI does not allow static abstract methods. If a static method is declared as
/// abstract, it is marked with this attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class PhpAbstractAttribute : Attribute
{
}
/// <summary>
/// Class field that have an init value is marked with this attribute.
/// </summary>
/// <remarks>Attribute is used by <see cref="Reflection"/>.</remarks>
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
public sealed class PhpHasInitValueAttribute : Attribute
{
}
/// <summary>
/// Interface method marked by this attribute can be implemented without adhering to its return type.
/// </summary>
/// <remarks>
/// An interface method returning by reference (<B>&</B>) that is decorated by this attribute
/// can be implemented by a method that does not return by reference.
/// Attribute is used by <see cref="Reflection"/>.
/// </remarks>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class AllowReturnValueOverrideAttribute : Attribute
{
}
/// <summary>
/// Interface method marked by this attribute can be implemented without adhering to its parameters.
/// </summary>
/// <remarks>Attribute is used by <see cref="Reflection"/>.</remarks>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class AllowParametersOverrideAttribute : Attribute
{
}
/// <summary>
/// PHP allows increasing visibility of fields that are declared as protected
/// in ancestor class. A class that increases the visibility declares no field
/// but is marked with that attribute.
/// </summary>
/// <remarks>Attribute is used by <see cref="Reflection"/>.</remarks>
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
public sealed class PhpPublicFieldAttribute : Attribute
{
private string fieldName;
private bool isStatic;
private bool hasInitValue;
public PhpPublicFieldAttribute(string fieldName, bool isStatic, bool hasInitValue)
{
this.fieldName = fieldName;
this.isStatic = isStatic;
this.hasInitValue = hasInitValue;
}
public string FieldName { get { return fieldName; } }
public bool IsStatic { get { return isStatic; } }
public bool HasInitValue { get { return hasInitValue; } }
}
public abstract class PseudoCustomAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class |
AttributeTargets.Interface | AttributeTargets.Constructor | AttributeTargets.Method |
AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public sealed class ExportAttribute : PseudoCustomAttribute
{
internal static readonly ExportAttribute/*!*/ Default = new ExportAttribute();
public ExportAttribute()
{
}
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
public sealed class AppStaticAttribute : PseudoCustomAttribute
{
public AppStaticAttribute()
{
}
}
#endregion
#region Class Library and Extensions
/// <summary>
/// Options of the function implementation.
/// </summary>
[Flags]
public enum FunctionImplOptions : ushort
{
/// <summary>
/// No options defined.
/// </summary>
None = 0,
/// <summary>
/// <see cref="IDictionary"/> of declared variables will be passed to the first argument.
/// </summary>
NeedsVariables = 1,
/// <summary>
/// Whether the function accesses currently executed PHP function arguments.
/// </summary>
NeedsFunctionArguments = 2,
/// <summary>
/// Whether the function needs to access instance of the object calling the function ($this reference)
/// </summary>
NeedsThisReference = 4,
///// <summary>
///// Whether the function is special for compiler. Setting this flag implies changes in compiler so
///// only compiler writers should set it.
///// </summary>
//Special = 8,
/// <summary>
/// Function is not supported.
/// </summary>
NotSupported = 16,
/// <summary>
/// Function is internal.
/// </summary>
Internal = 32,
/// <summary>
/// Captures eval to the current <see cref="ScriptContext"/>.
/// The captured values has to be reset immediately before the method returns.
/// </summary>
CaptureEvalInfo = 64,
/// <summary>
/// Whether the function uses the current naming context.
/// </summary>
NeedsNamingContext = 128,
/// <summary>
/// Needs DTypeDesc class context of the caller.
/// </summary>
NeedsClassContext = 256,
/// <summary>
/// Needs DTypeDesc class context of the late static binding.
/// </summary>
NeedsLateStaticBind = 512,
}
/// <summary>
/// Marks static methods of the Class Library which implements PHP functions.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class ImplementsFunctionAttribute : Attribute
{
/// <summary>
/// Creates an instance of the <see cref="ImplementsFunctionAttribute"/> attribute.
/// </summary>
/// <param name="name">The name of the PHP function implemented by marked method.</param>
public ImplementsFunctionAttribute(string name)
: this(name, FunctionImplOptions.None)
{
}
/// <summary>
/// Creates an instance of the <see cref="ImplementsFunctionAttribute"/> attribute.
/// </summary>
/// <param name="name">The name of the PHP function implemented by marked method.</param>
/// <param name="options">Options.</param>
public ImplementsFunctionAttribute(string name, FunctionImplOptions options)
{
this.name = name;
this.options = options;
}
/// <summary>
/// The name of the PHP function.
/// </summary>
public string Name { get { return name; } }
private string name;
/// <summary>
/// Options.
/// </summary>
public FunctionImplOptions Options { get { return options; } }
private FunctionImplOptions options;
internal static ImplementsFunctionAttribute Reflect(MethodBase/*!*/ method)
{
object[] attributes = method.GetCustomAttributes(Emit.Types.ImplementsFunctionAttribute, false);
return (attributes.Length == 1) ? (ImplementsFunctionAttribute)attributes[0] : null;
}
/// <summary>
/// Reflects an assembly, but also supports a case where Phalanger is reflecting
/// Silverlight version of the assembly (and so the type of attribute is different)
/// </summary>
/// <param name="attrType"></param>
/// <param name="method"></param>
/// <returns></returns>
internal static ImplementsFunctionAttribute ReflectDynamic(Type/*!*/ attrType, MethodBase/*!*/ method)
{
object[] attributes = method.GetCustomAttributes(attrType, false);
if (attributes.Length == 1)
{
string name = (string)attrType.GetProperty("Name").GetValue(attributes[0], ArrayUtils.EmptyObjects);
object options = attrType.GetProperty("Options").GetValue(attributes[0], ArrayUtils.EmptyObjects);
int opt = System.Convert.ToInt32(options);
return new ImplementsFunctionAttribute(name, (FunctionImplOptions)opt);
}
else
return null;
}
}
/// <summary>
/// Marks class library function that the specified method is pure. Therefore it can be evaluated at the compilation time.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class PureFunctionAttribute : Attribute
{
/// <summary>
/// True if special method must be called for compile-time evaluation.
/// </summary>
public bool CallSpecialMethod { get { return SpecialMethodType != null && SpecialMethodName != null; } }
/// <summary>
/// MethodInfo of the method to be used during the compile-time evaluation.
/// </summary>
public MethodInfo SpecialMethod
{
get
{
Debug.Assert(CallSpecialMethod);
return SpecialMethodType.GetMethod(SpecialMethodName, BindingFlags.Static | BindingFlags.Public);
}
}
/// <summary>
/// Type containing special method to be called for compile-time evaluation.
/// </summary>
private Type SpecialMethodType { get; set; }
/// <summary>
/// Special method name to be called for compile-time evaluation.
/// </summary>
private string SpecialMethodName { get; set; }
/// <summary>
/// Creates an instance of the <see cref="PureFunctionAttribute"/> attribute. Used if the method can be called during the compile-time evaluation.
/// </summary>
public PureFunctionAttribute()
: this(null, null)
{
}
/// <summary>
/// Creates an instance of the <see cref="PureFunctionAttribute"/> attribute. Used if another method must be called during the compile-time evaluation.
/// </summary>
/// <param name="specialMethodType">Type containing special method to be called for compile-time evaluation.</param>
/// <param name="specialMethodName">Special method name to be called for compile-time evaluation.</param>
public PureFunctionAttribute(Type specialMethodType, string specialMethodName)
{
this.SpecialMethodType = specialMethodType;
this.SpecialMethodName = specialMethodName;
}
/// <summary>
/// Reflect the given MethodBase to fund the PureFunctionAttribute.
/// </summary>
/// <param name="method">The method where to find PureFunctionAttribute.</param>
/// <returns>PureFunctionAttribute of the <c>method</c> or null if the attribute was not found.</returns>
internal static PureFunctionAttribute Reflect(MethodBase/*!*/ method)
{
object[] attributes = method.GetCustomAttributes(typeof(PureFunctionAttribute), false);
return (attributes.Length == 1) ? (PureFunctionAttribute)attributes[0] : null;
}
}
/// <summary>
/// Marks the pseudo-this parameter of a class library method.
/// </summary>
/// <remarks>
/// The method should be static and the parameter marked by this attribute should have the
/// enclosing type. Use this attribute when the method must be callable both using an instance
/// and statically (e.g. <c>DOMDocument::load</c>).
/// </remarks>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
public sealed class ThisAttribute : Attribute
{
public ThisAttribute()
{
}
}
/// <summary>
/// Marks a nullable parameter of a class library method.
/// </summary>
/// <remarks>
/// When a parameter of a reference type is marked by this attribute, <B>null</B> is also a legal
/// argument value.
/// </remarks>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
public sealed class NullableAttribute : Attribute
{
public NullableAttribute()
{
}
}
/// <summary>
/// Marks methods of the Class Library which implement PHP methods.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class ImplementsMethodAttribute : Attribute
{
public ImplementsMethodAttribute()
{
}
}
/// <summary>
/// Marks properties/methods of Class Library types which should be exposed to PHP.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class PhpVisibleAttribute : Attribute
{
public PhpVisibleAttribute()
{
}
internal static PhpVisibleAttribute Reflect(MemberInfo/*!*/ info)
{
object[] attributes = info.GetCustomAttributes(typeof(PhpVisibleAttribute), false);
return (attributes.Length == 1) ? (PhpVisibleAttribute)attributes[0] : null;
}
}
/// <summary>
/// Marks constants and items of enumerations in the Class Library which represent PHP constants.
/// </summary>
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
public sealed class ImplementsConstantAttribute : Attribute
{
/// <summary>
/// Creates an instance of the <see cref="ImplementsConstantAttribute"/> attribute.
/// </summary>
/// <param name="name">The name of the PHP constant implemented by marked constant or enum item.</param>
public ImplementsConstantAttribute(string name)
{
this.name = name;
this.caseInsensitive = false;
}
/// <summary>
/// The name of the PHP constant.
/// </summary>
public string Name { get { return name; } }
private string name;
/// <summary>
/// Whether the constant name is not case sensitive.
/// </summary>
public bool CaseInsensitive { get { return caseInsensitive; } set { caseInsensitive = value; } }
private bool caseInsensitive;
internal static ImplementsConstantAttribute Reflect(FieldInfo/*!*/ field)
{
object[] attributes = field.GetCustomAttributes(typeof(ImplementsConstantAttribute), false);
return (attributes.Length == 1) ? (ImplementsConstantAttribute)attributes[0] : null;
}
}
/// <summary>
/// Marks classes in the Class Library which implements a part or entire PHP extension.
/// </summary>
/// <remarks>
/// Libraries which implements more than one extension should use the attribute
/// to distinguish which types belongs to which extension. If the library implements a single extension
/// it is not required to use the attribute.
/// </remarks>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface, AllowMultiple = false, Inherited = false)]
public sealed class ImplementsExtensionAttribute : Attribute
{
/// <summary>
/// Creates an instance of the <see cref="ImplementsExtensionAttribute"/> attribute.
/// </summary>
/// <param name="name">The name of the PHP extension.</param>
public ImplementsExtensionAttribute(string name)
{
this.name = name;
}
/// <summary>
/// The name of the PHP extension.
/// </summary>
public string Name { get { return name; } }
private string name;
}
/// <summary>
/// Marks return values of methods implementing PHP functions which returns <B>false</B> on error
/// but has other return type than <see cref="bool"/> or <see cref="object"/>.
/// </summary>
/// <remarks>
/// Compiler takes care of converting a return value of a method into <B>false</B> if necessary.
/// An attribute can be applied only on return values of type <see cref="int"/> (-1 is converted to <B>false</B>)
/// or of a reference type (<B>null</B> is converted to <B>false</B>).
/// </remarks>
[AttributeUsage(AttributeTargets.ReturnValue, AllowMultiple = false, Inherited = false)]
public sealed class CastToFalseAttribute : Attribute
{
public CastToFalseAttribute()
{
}
/// <summary>
/// Determine wheter the attribute is defined for given <paramref name="method"/>.
/// </summary>
/// <param name="method"><see cref="MethodInfo"/> to check for the attribute.</param>
/// <returns>True iff given <paramref name="method"/> has <see cref="CastToFalseAttribute"/>.</returns>
internal static bool IsDefined(MethodInfo/*!*/ method)
{
return method.ReturnTypeCustomAttributes.IsDefined(typeof(CastToFalseAttribute), false);
}
}
/// <summary>
/// If a parameter or a return value is marked by this attribute compiler should
/// generate deep-copy code before or after the method's call respectively.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = false, Inherited = false)]
public sealed class PhpDeepCopyAttribute : Attribute
{
}
/// <summary>
/// Marks arguments having by-value argument pass semantics and data of the value can be changed by a callee.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
public sealed class PhpRwAttribute : Attribute
{
internal static bool IsDefined(ParameterInfo/*!*/ param)
{
return param != null && param.IsDefined(typeof(PhpRwAttribute), false);
}
}
/// <summary>
/// Marks argless stubs in (dynamic) wrappers which consumes <see cref="PhpStack.Variables"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class NeedsVariablesAttribute : Attribute
{
}
/// <summary>
/// ExternalCallbackAttribute marks methods which are intended to be called by some PHP extension module.
/// </summary>
/// <remarks>
/// Informative only. Not used so far.
/// </remarks>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class ExternalCallbackAttribute : Attribute
{
/// <summary>
/// Creates an instance of the <see cref="ImplementsConstantAttribute"/> attribute.
/// </summary>
/// <param name="callbackName">The name the callback.</param>
public ExternalCallbackAttribute(string callbackName)
{
name = callbackName;
}
/// <summary>The name of the callback.</summary>
public string Name { get { return name; } }
/// <summary>The name of the callback.</summary>
private string name;
}
#endregion
#region Scripts
/// <summary>
/// An attribute associated with the persistent script type.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public sealed class ScriptAttribute : Attribute
{
/// <summary>
/// A timestamp of the source file when the script builder is created.
/// </summary>
public DateTime SourceTimestamp { get { return new DateTime(sourceTimestamp, DateTimeKind.Utc); } }
private readonly long sourceTimestamp;
/// <summary>
/// Source file relative path.
/// </summary>
public string/*!*/RelativePath { get { return relativePath; } }
private readonly string/*!*/relativePath;
/// <summary>
/// Used in SSA/MSA (target web and dll). Contains info needed for compile-time/runtime reflection.
/// </summary>
/// <param name="sourceTimestamp">A timestamp of the source file when the script builder is created.</param>
/// <param name="relativePath">Source file relative path.</param>
public ScriptAttribute(long sourceTimestamp, string relativePath)
{
this.sourceTimestamp = sourceTimestamp;
this.relativePath = relativePath;
}
/// <summary>
/// Determine the [ScriptInfoAttribute] attribute of given script type.
/// </summary>
/// <param name="type">The script type to reflect from.</param>
/// <returns>Script attribute associated with the given <c>type</c> or null.</returns>
internal static ScriptAttribute Reflect(Type/*!*/ type)
{
object[] attrs = type.GetCustomAttributes(typeof(ScriptAttribute), false);
return (attrs.Length == 1) ? (ScriptAttribute)attrs[0] : null;
}
}
/// <summary>
/// An attribute associated with the persistent script type.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public sealed class ScriptIncludersAttribute : Attribute
{
/// <summary>
/// Array of Scripts that statically include this script within current assembly.
/// Script is represented as type token to the Script type resolved within current module.
/// </summary>
public int[]/*!*/ Includers { get { return includers ?? ArrayUtils.EmptyIntegers; } }
private readonly int[] includers;
/// <summary>
/// Used in SSA/MSA (target web and dll). Contains info needed for compile-time/runtime reflection.
/// </summary>
/// <param name="includers">
/// Array of Scripts that statically include this script within current assembly.
/// Script is represented as type token to the Script type.
/// </param>
public ScriptIncludersAttribute(int[] includers)
{
this.includers = includers;
}
/// <summary>
/// Determine the [ScriptIncludersAttribute] attribute of given script type.
/// </summary>
/// <param name="type">The script type to reflect from.</param>
/// <returns>Script attribute associated with the given <c>type</c> or null.</returns>
internal static ScriptIncludersAttribute Reflect(Type/*!*/ type)
{
object[] attrs = type.GetCustomAttributes(typeof(ScriptIncludersAttribute), false);
return (attrs.Length == 1) ? (ScriptIncludersAttribute)attrs[0] : null;
}
}
/// <summary>
/// An attribute associated with the persistent script type.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public sealed class ScriptIncludeesAttribute : Attribute
{
/// <summary>
/// Array of statically included Scripts.
/// Script is represented as type token to the Script type resolved within current module.
/// </summary>
public int[]/*!*/ Inclusions { get { return inclusions ?? ArrayUtils.EmptyIntegers; } }
private readonly int[] inclusions;
/// <summary>
/// Get bit array with flags determining if static inclusion on specific index is included conditionally.
/// </summary>
public BitArray/*!*/InclusionsConditionalFlags { get { return new BitArray(inclusionsConditionalFlag ?? ArrayUtils.EmptyBytes); } }
/// <summary>
/// Bit array. Bit is set to 1 if inclusion on specified bit index is conditional.
/// </summary>
private readonly byte[] inclusionsConditionalFlag;
/// <summary>
/// Used in SSA/MSA (target web and dll). Contains info needed for compile-time/runtime reflection.
/// </summary>
/// <param name="inclusions">
/// Array of statically included Scripts.
/// Script is represented as type token to the Script type.
/// </param>
/// <param name="inclusionsConditionalFlag">
/// Array with bit flags determining if static inclusion on specific index is included conditionally.
/// </param>
public ScriptIncludeesAttribute(int[] inclusions, byte[] inclusionsConditionalFlag)
{
this.inclusions = inclusions;
this.inclusionsConditionalFlag = inclusionsConditionalFlag;
}
/// <summary>
/// Convert array of bools into array of bytes.
/// Note: BitArray cannot be used, missing method <c>ToBytes</c>.
/// </summary>
/// <param name="array">An array to convert.</param>
/// <returns>Bytes with particular bits set or null of <c>array</c> is null or empty.</returns>
internal static byte[] ConvertBoolsToBits(bool[] array)
{
if (array == null || array.Length == 0)
return null;
// construct the bit array from given array
int bytesCount = array.Length / 8;
if ((array.Length % 8) != 0) bytesCount++;
byte[] bits = new byte[bytesCount];
for (int i = 0; i < array.Length; ++i)
if (array[i])
bits[i / 8] |= (byte)(1 << (i % 8));
return bits;
}
/// <summary>
/// Determine the [ScriptIncludesAttribute] attribute of given script type.
/// </summary>
/// <param name="type">The script type to reflect from.</param>
/// <returns>Script attribute associated with the given <c>type</c> or null.</returns>
internal static ScriptIncludeesAttribute Reflect(Type/*!*/ type)
{
object[] attrs = type.GetCustomAttributes(typeof(ScriptIncludeesAttribute), false);
return (attrs.Length == 1) ? (ScriptIncludeesAttribute)attrs[0] : null;
}
}
/// <summary>
/// An attribute associated with the persistent script type.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public sealed class ScriptDeclaresAttribute : Attribute
{
/// <summary>
/// Array of Types that are statically declared by this Script.
/// Type is represented as type token to the Type resolved within current module.
/// </summary>
public int[]/*!*/ DeclaredTypes { get { return declaredTypes ?? ArrayUtils.EmptyIntegers; } }
private readonly int[] declaredTypes;
/// <summary>
/// Used in SSA/MSA (target web and dll). Contains info needed for compile-time/runtime reflection.
/// </summary>
/// <param name="declaredTypes">
/// Array of Types that are statically declared by this Script.
/// Type is represented as type token to the Type resolved within current module.
/// </param>
public ScriptDeclaresAttribute(int[] declaredTypes)
{
this.declaredTypes = declaredTypes;
}
/// <summary>
/// Determine the [ScriptIncludersAttribute] attribute of given script type.
/// </summary>
/// <param name="type">The script type to reflect from.</param>
/// <returns>Script attribute associated with the given <c>type</c> or null.</returns>
internal static ScriptDeclaresAttribute Reflect(Type/*!*/ type)
{
object[] attrs = type.GetCustomAttributes(typeof(ScriptDeclaresAttribute), false);
return (attrs.Length == 1) ? (ScriptDeclaresAttribute)attrs[0] : null;
}
}
/// <summary>
/// Stores information about scripts directly included by a module which is decorated by this attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public sealed class IncludesAttribute : Attribute
{
/// <summary>
/// Creates a new instance of the attribute with a specified source path and a conditionality flag.
/// </summary>
/// <param name="relativeSourcePath">Relative path remainder.</param>
/// <param name="level">Relative path level.</param>
/// <param name="isConditional">Whether the inclusion is conditional.</param>
/// <param name="once"><B>True</B> if the include is include_once or require_once.</param>
public IncludesAttribute(string relativeSourcePath, sbyte level, bool isConditional, bool once)
{
this.relativeSourceFile = new RelativePath(level, relativeSourcePath);
this.isConditional = isConditional;
this.once = once;
}
/// <summary>
/// An included script's canonical source path relative to the application source root.
/// </summary>
public RelativePath RelativeSourceFile { get { return relativeSourceFile; } }
private RelativePath relativeSourceFile;
/// <summary>
/// Whether the inclusion is conditional.
/// </summary>
public bool IsConditional { get { return isConditional; } }
private bool isConditional;
/// <summary>
/// Whether the inclusion is include_once or require_once.
/// </summary>
public bool Once { get { return once; } }
private bool once;
}
/// <summary>
/// Associates a class with an eval id.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class PhpEvalIdAttribute : Attribute
{
public PhpEvalIdAttribute(int id)
{
this.id = id;
}
internal static PhpEvalIdAttribute Reflect(Type/*!*/ type)
{
object[] attrs = type.GetCustomAttributes(typeof(PhpEvalIdAttribute), false);
return (attrs.Length == 1) ? (PhpEvalIdAttribute)attrs[0] : null;
}
#if DEBUG
public override string ToString()
{
//EvalInfo info = (EvalInfo)EvalCompilerManager.Default.GetEvalInfo(id);
//return String.Format("PhpEvalId(id={4},parent={5},kind={0},line={2},column={3},file={1})",
// info.Kind,
// (info.File != null) ? "@\"" + info.File + "\"" : "null",
// info.Line,
// info.Column,
// id,
// info.ParentId);
return "TODO";
}
#endif
/// <summary>
/// Eval id.
/// </summary>
public int Id { get { return id; } }
private int id;
}
#endregion
#region Miscellaneous
/// <summary>
/// Specifies that a target field, property, or class defined in the configuration record
/// is not displayd by PHP info.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class NoPhpInfoAttribute : Attribute
{
}
/// <summary>
/// Used for marking Core members that are emitted to the user code.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
internal class EmittedAttribute : Attribute
{
}
/// <summary>
/// Attribute specifying that function should be called statically with valid PhpStack. Such a function needs function arguments,
/// e.g. it calls func_num_args() or func_get_arg() inside.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)]
public class NeedsArglessAttribute : Attribute
{
/// <summary>
/// Determines if given <c>method</c> has [NeedsArgless] attribute set.
/// </summary>
/// <param name="method">The method to reflect from.</param>
/// <returns>True if the method is marked.</returns>
internal static bool IsSet(MethodInfo/*!*/method)
{
object[] attrs;
return (attrs = method.GetCustomAttributes(typeof(NeedsArglessAttribute), false)) != null && attrs.Length > 0;
}
}
/// <summary>
/// Attribute specifying that function contains usage of <c>static</c> (late static binding),
/// runtime should pass type used to call a static method into script context, so it can be used by late static binding.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)]
public class UsesLateStaticBindingAttribute : Attribute
{
/// <summary>
/// Determines if given <c>method</c> has [UsesLateStaticBinding] attribute set.
/// </summary>
/// <param name="method">The method to reflect from.</param>
/// <returns>True if the method is marked.</returns>
internal static bool IsSet(MethodInfo/*!*/method)
{
object[] attrs;
return (attrs = method.GetCustomAttributes(typeof(UsesLateStaticBindingAttribute), false)) != null && attrs.Length > 0;
}
}
#endregion
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using NUnit.Framework;
using Newtonsoft.Json;
using GlmSharp;
// ReSharper disable InconsistentNaming
namespace GlmSharpTest.Generated.Vec4
{
[TestFixture]
public class IntVec4Test
{
[Test]
public void Constructors()
{
{
var v = new ivec4(9);
Assert.AreEqual(9, v.x);
Assert.AreEqual(9, v.y);
Assert.AreEqual(9, v.z);
Assert.AreEqual(9, v.w);
}
{
var v = new ivec4(5, 4, 2, 0);
Assert.AreEqual(5, v.x);
Assert.AreEqual(4, v.y);
Assert.AreEqual(2, v.z);
Assert.AreEqual(0, v.w);
}
{
var v = new ivec4(new ivec2(2, -6));
Assert.AreEqual(2, v.x);
Assert.AreEqual(-6, v.y);
Assert.AreEqual(0, v.z);
Assert.AreEqual(0, v.w);
}
{
var v = new ivec4(new ivec3(-5, -9, 6));
Assert.AreEqual(-5, v.x);
Assert.AreEqual(-9, v.y);
Assert.AreEqual(6, v.z);
Assert.AreEqual(0, v.w);
}
{
var v = new ivec4(new ivec4(-1, -9, 3, -7));
Assert.AreEqual(-1, v.x);
Assert.AreEqual(-9, v.y);
Assert.AreEqual(3, v.z);
Assert.AreEqual(-7, v.w);
}
}
[Test]
public void Indexer()
{
var v = new ivec4(9, -7, -3, -9);
Assert.AreEqual(9, v[0]);
Assert.AreEqual(-7, v[1]);
Assert.AreEqual(-3, v[2]);
Assert.AreEqual(-9, v[3]);
Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[-2147483648]; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { v[-2147483648] = 0; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[-1]; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { v[-1] = 0; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[4]; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { v[4] = 0; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[2147483647]; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { v[2147483647] = 0; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[5]; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { v[5] = 0; } );
v[3] = 0;
Assert.AreEqual(0, v[3]);
v[2] = 1;
Assert.AreEqual(1, v[2]);
v[1] = 2;
Assert.AreEqual(2, v[1]);
v[3] = 3;
Assert.AreEqual(3, v[3]);
v[1] = 4;
Assert.AreEqual(4, v[1]);
v[0] = 5;
Assert.AreEqual(5, v[0]);
v[1] = 6;
Assert.AreEqual(6, v[1]);
v[2] = 7;
Assert.AreEqual(7, v[2]);
v[1] = 8;
Assert.AreEqual(8, v[1]);
v[1] = 9;
Assert.AreEqual(9, v[1]);
v[2] = -1;
Assert.AreEqual(-1, v[2]);
v[1] = -2;
Assert.AreEqual(-2, v[1]);
v[0] = -3;
Assert.AreEqual(-3, v[0]);
v[1] = -4;
Assert.AreEqual(-4, v[1]);
v[1] = -5;
Assert.AreEqual(-5, v[1]);
v[0] = -6;
Assert.AreEqual(-6, v[0]);
v[3] = -7;
Assert.AreEqual(-7, v[3]);
v[2] = -8;
Assert.AreEqual(-8, v[2]);
v[1] = -9;
Assert.AreEqual(-9, v[1]);
}
[Test]
public void PropertyValues()
{
var v = new ivec4(-7, -5, -7, -3);
var vals = v.Values;
Assert.AreEqual(-7, vals[0]);
Assert.AreEqual(-5, vals[1]);
Assert.AreEqual(-7, vals[2]);
Assert.AreEqual(-3, vals[3]);
Assert.That(vals.SequenceEqual(v.ToArray()));
}
[Test]
public void StaticProperties()
{
Assert.AreEqual(0, ivec4.Zero.x);
Assert.AreEqual(0, ivec4.Zero.y);
Assert.AreEqual(0, ivec4.Zero.z);
Assert.AreEqual(0, ivec4.Zero.w);
Assert.AreEqual(1, ivec4.Ones.x);
Assert.AreEqual(1, ivec4.Ones.y);
Assert.AreEqual(1, ivec4.Ones.z);
Assert.AreEqual(1, ivec4.Ones.w);
Assert.AreEqual(1, ivec4.UnitX.x);
Assert.AreEqual(0, ivec4.UnitX.y);
Assert.AreEqual(0, ivec4.UnitX.z);
Assert.AreEqual(0, ivec4.UnitX.w);
Assert.AreEqual(0, ivec4.UnitY.x);
Assert.AreEqual(1, ivec4.UnitY.y);
Assert.AreEqual(0, ivec4.UnitY.z);
Assert.AreEqual(0, ivec4.UnitY.w);
Assert.AreEqual(0, ivec4.UnitZ.x);
Assert.AreEqual(0, ivec4.UnitZ.y);
Assert.AreEqual(1, ivec4.UnitZ.z);
Assert.AreEqual(0, ivec4.UnitZ.w);
Assert.AreEqual(0, ivec4.UnitW.x);
Assert.AreEqual(0, ivec4.UnitW.y);
Assert.AreEqual(0, ivec4.UnitW.z);
Assert.AreEqual(1, ivec4.UnitW.w);
Assert.AreEqual(int.MaxValue, ivec4.MaxValue.x);
Assert.AreEqual(int.MaxValue, ivec4.MaxValue.y);
Assert.AreEqual(int.MaxValue, ivec4.MaxValue.z);
Assert.AreEqual(int.MaxValue, ivec4.MaxValue.w);
Assert.AreEqual(int.MinValue, ivec4.MinValue.x);
Assert.AreEqual(int.MinValue, ivec4.MinValue.y);
Assert.AreEqual(int.MinValue, ivec4.MinValue.z);
Assert.AreEqual(int.MinValue, ivec4.MinValue.w);
}
[Test]
public void Operators()
{
var v1 = new ivec4(2, 5, 1, -8);
var v2 = new ivec4(2, 5, 1, -8);
var v3 = new ivec4(-8, 1, 5, 2);
Assert.That(v1 == new ivec4(v1));
Assert.That(v2 == new ivec4(v2));
Assert.That(v3 == new ivec4(v3));
Assert.That(v1 == v2);
Assert.That(v1 != v3);
Assert.That(v2 != v3);
}
[Test]
public void StringInterop()
{
var v = new ivec4(8, 0, 3, -7);
var s0 = v.ToString();
var s1 = v.ToString("#");
var v0 = ivec4.Parse(s0);
var v1 = ivec4.Parse(s1, "#");
Assert.AreEqual(v, v0);
Assert.AreEqual(v, v1);
var b0 = ivec4.TryParse(s0, out v0);
var b1 = ivec4.TryParse(s1, "#", out v1);
Assert.That(b0);
Assert.That(b1);
Assert.AreEqual(v, v0);
Assert.AreEqual(v, v1);
b0 = ivec4.TryParse(null, out v0);
Assert.False(b0);
b0 = ivec4.TryParse("", out v0);
Assert.False(b0);
b0 = ivec4.TryParse(s0 + ", 0", out v0);
Assert.False(b0);
Assert.Throws<NullReferenceException>(() => { ivec4.Parse(null); });
Assert.Throws<FormatException>(() => { ivec4.Parse(""); });
Assert.Throws<FormatException>(() => { ivec4.Parse(s0 + ", 0"); });
var s2 = v.ToString(";", CultureInfo.InvariantCulture);
Assert.That(s2.Length > 0);
var s3 = v.ToString("; ", "G");
var s4 = v.ToString("; ", "G", CultureInfo.InvariantCulture);
var v3 = ivec4.Parse(s3, "; ", NumberStyles.Number);
var v4 = ivec4.Parse(s4, "; ", NumberStyles.Number, CultureInfo.InvariantCulture);
Assert.AreEqual(v, v3);
Assert.AreEqual(v, v4);
var b4 = ivec4.TryParse(s4, "; ", NumberStyles.Number, CultureInfo.InvariantCulture, out v4);
Assert.That(b4);
Assert.AreEqual(v, v4);
}
[Test]
public void SerializationJson()
{
var v0 = new ivec4(-8, -1, 6, -1);
var s0 = JsonConvert.SerializeObject(v0);
var v1 = JsonConvert.DeserializeObject<ivec4>(s0);
var s1 = JsonConvert.SerializeObject(v1);
Assert.AreEqual(v0, v1);
Assert.AreEqual(s0, s1);
}
[Test]
public void InvariantId()
{
{
var v0 = new ivec4(-1, -4, -9, -2);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new ivec4(-7, -5, -7, 4);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new ivec4(6, -2, -3, -2);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new ivec4(9, 4, -3, 5);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new ivec4(-2, 4, -5, -2);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new ivec4(8, -7, -6, -6);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new ivec4(9, -1, 8, -8);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new ivec4(5, 0, 5, -6);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new ivec4(5, 2, -2, -9);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new ivec4(1, 9, -4, -3);
Assert.AreEqual(v0, +v0);
}
}
[Test]
public void InvariantDouble()
{
{
var v0 = new ivec4(-1, 7, 8, 9);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new ivec4(5, 5, 8, 8);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new ivec4(9, 5, 2, -8);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new ivec4(-4, 7, 1, 5);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new ivec4(-8, 9, -2, 8);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new ivec4(-7, 5, 1, -2);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new ivec4(-5, -9, 9, 2);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new ivec4(-4, 0, 4, -1);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new ivec4(4, 1, 4, -8);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new ivec4(-5, 1, -8, -6);
Assert.AreEqual(v0 + v0, 2 * v0);
}
}
[Test]
public void InvariantTriple()
{
{
var v0 = new ivec4(3, 7, -8, 0);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new ivec4(-3, 5, 3, -9);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new ivec4(3, -5, 3, 1);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new ivec4(9, 0, 3, 2);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new ivec4(-7, -1, -1, -6);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new ivec4(6, -6, -9, -5);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new ivec4(-4, -9, 4, -4);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new ivec4(-2, 0, -4, 6);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new ivec4(-2, 2, 6, -8);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new ivec4(3, 4, -1, 6);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
}
[Test]
public void InvariantCommutative()
{
{
var v0 = new ivec4(-2, -3, 4, 2);
var v1 = new ivec4(2, 0, 4, 0);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new ivec4(7, -6, 5, -4);
var v1 = new ivec4(-4, -4, -1, -5);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new ivec4(8, 5, -2, 0);
var v1 = new ivec4(2, 2, -1, -3);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new ivec4(-3, 1, -2, -3);
var v1 = new ivec4(-2, 4, -9, -4);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new ivec4(6, 6, 7, 0);
var v1 = new ivec4(-4, -5, 5, -6);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new ivec4(-8, -4, 8, -1);
var v1 = new ivec4(-7, -5, -4, 6);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new ivec4(-5, -8, -6, 6);
var v1 = new ivec4(0, 2, -9, 9);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new ivec4(1, -2, 9, 1);
var v1 = new ivec4(8, -1, 8, 2);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new ivec4(-7, -2, 6, 6);
var v1 = new ivec4(5, -1, 1, -3);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new ivec4(0, -6, 1, 7);
var v1 = new ivec4(-3, 0, -5, -7);
Assert.AreEqual(v0 * v1, v1 * v0);
}
}
[Test]
public void InvariantAssociative()
{
{
var v0 = new ivec4(6, 1, -2, 5);
var v1 = new ivec4(-9, -7, -9, 3);
var v2 = new ivec4(2, -4, -4, 4);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new ivec4(-3, 6, -9, -6);
var v1 = new ivec4(-5, 9, -3, -7);
var v2 = new ivec4(-7, -2, -7, -6);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new ivec4(8, 4, -2, 8);
var v1 = new ivec4(0, 5, -3, 0);
var v2 = new ivec4(6, -2, 8, 9);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new ivec4(9, 2, 1, 7);
var v1 = new ivec4(7, -1, 9, -8);
var v2 = new ivec4(8, -8, -3, -2);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new ivec4(9, -5, -5, 2);
var v1 = new ivec4(-7, -5, 3, -4);
var v2 = new ivec4(4, -5, -7, -5);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new ivec4(5, 9, 3, -6);
var v1 = new ivec4(0, -3, -7, 0);
var v2 = new ivec4(-8, 8, 6, -2);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new ivec4(8, 5, 8, 6);
var v1 = new ivec4(2, -8, 7, 9);
var v2 = new ivec4(-1, 0, -9, 4);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new ivec4(-1, -1, 3, -2);
var v1 = new ivec4(7, -4, 5, -4);
var v2 = new ivec4(5, 5, 2, -7);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new ivec4(6, -4, -7, -5);
var v1 = new ivec4(0, -3, -3, 1);
var v2 = new ivec4(8, 2, -3, -1);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new ivec4(5, -7, -2, 5);
var v1 = new ivec4(7, 6, 3, 5);
var v2 = new ivec4(-1, -8, 4, 9);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
}
[Test]
public void InvariantIdNeg()
{
{
var v0 = new ivec4(6, 7, -4, 7);
Assert.AreEqual(v0, -(-v0));
}
{
var v0 = new ivec4(-3, 2, -1, 8);
Assert.AreEqual(v0, -(-v0));
}
{
var v0 = new ivec4(-8, -9, -7, -4);
Assert.AreEqual(v0, -(-v0));
}
{
var v0 = new ivec4(-8, -3, -2, 0);
Assert.AreEqual(v0, -(-v0));
}
{
var v0 = new ivec4(-7, -1, 0, 6);
Assert.AreEqual(v0, -(-v0));
}
{
var v0 = new ivec4(-3, 5, -2, -1);
Assert.AreEqual(v0, -(-v0));
}
{
var v0 = new ivec4(-4, 3, 7, 2);
Assert.AreEqual(v0, -(-v0));
}
{
var v0 = new ivec4(-2, -3, 8, 6);
Assert.AreEqual(v0, -(-v0));
}
{
var v0 = new ivec4(2, 2, -4, 8);
Assert.AreEqual(v0, -(-v0));
}
{
var v0 = new ivec4(-6, 4, -8, -6);
Assert.AreEqual(v0, -(-v0));
}
}
[Test]
public void InvariantCommutativeNeg()
{
{
var v0 = new ivec4(3, -6, 6, 4);
var v1 = new ivec4(4, 1, -4, 4);
Assert.AreEqual(v0 - v1, -(v1 - v0));
}
{
var v0 = new ivec4(4, 6, 3, -5);
var v1 = new ivec4(9, -1, 1, -3);
Assert.AreEqual(v0 - v1, -(v1 - v0));
}
{
var v0 = new ivec4(-2, 3, -2, 2);
var v1 = new ivec4(-2, -6, -6, 2);
Assert.AreEqual(v0 - v1, -(v1 - v0));
}
{
var v0 = new ivec4(5, 1, 7, 3);
var v1 = new ivec4(1, -3, -7, 9);
Assert.AreEqual(v0 - v1, -(v1 - v0));
}
{
var v0 = new ivec4(4, -3, -1, -8);
var v1 = new ivec4(-2, -4, -8, -2);
Assert.AreEqual(v0 - v1, -(v1 - v0));
}
{
var v0 = new ivec4(-4, -1, 3, 0);
var v1 = new ivec4(-7, -3, -2, 3);
Assert.AreEqual(v0 - v1, -(v1 - v0));
}
{
var v0 = new ivec4(1, -5, -6, -7);
var v1 = new ivec4(9, 4, -1, 6);
Assert.AreEqual(v0 - v1, -(v1 - v0));
}
{
var v0 = new ivec4(0, 3, -9, 3);
var v1 = new ivec4(-4, -1, 2, -2);
Assert.AreEqual(v0 - v1, -(v1 - v0));
}
{
var v0 = new ivec4(9, -4, -1, -6);
var v1 = new ivec4(-9, 3, 0, -8);
Assert.AreEqual(v0 - v1, -(v1 - v0));
}
{
var v0 = new ivec4(4, 0, 7, 0);
var v1 = new ivec4(-2, -5, 5, -3);
Assert.AreEqual(v0 - v1, -(v1 - v0));
}
}
[Test]
public void InvariantAssociativeNeg()
{
{
var v0 = new ivec4(7, -2, -3, -4);
var v1 = new ivec4(0, 4, 0, 8);
var v2 = new ivec4(2, 6, -5, -8);
Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2);
}
{
var v0 = new ivec4(-2, 2, -4, 2);
var v1 = new ivec4(-5, 0, 8, -2);
var v2 = new ivec4(-8, -6, -4, 1);
Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2);
}
{
var v0 = new ivec4(-8, 0, 1, 4);
var v1 = new ivec4(-8, -6, 4, -6);
var v2 = new ivec4(1, 0, 8, 4);
Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2);
}
{
var v0 = new ivec4(-7, -3, 4, -7);
var v1 = new ivec4(1, 0, -4, 0);
var v2 = new ivec4(-5, -4, -4, 6);
Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2);
}
{
var v0 = new ivec4(5, -4, -3, 8);
var v1 = new ivec4(-1, 5, 8, -1);
var v2 = new ivec4(-8, -2, -5, -9);
Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2);
}
{
var v0 = new ivec4(2, -6, 9, 5);
var v1 = new ivec4(2, -9, -6, -2);
var v2 = new ivec4(-3, 8, 4, 1);
Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2);
}
{
var v0 = new ivec4(-5, -1, -1, -8);
var v1 = new ivec4(1, -3, 5, 3);
var v2 = new ivec4(5, -5, -9, 3);
Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2);
}
{
var v0 = new ivec4(3, -5, 4, -6);
var v1 = new ivec4(-2, -7, 6, 5);
var v2 = new ivec4(-7, 5, -4, 5);
Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2);
}
{
var v0 = new ivec4(9, 7, -8, -6);
var v1 = new ivec4(-8, 2, -3, -6);
var v2 = new ivec4(9, -1, -3, -9);
Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2);
}
{
var v0 = new ivec4(-4, -1, 9, 5);
var v1 = new ivec4(5, -1, -3, 7);
var v2 = new ivec4(-6, 6, 2, 6);
Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2);
}
}
[Test]
public void TriangleInequality()
{
{
var v0 = new ivec4(-4, 7, 2, 7);
var v1 = new ivec4(5, 4, 9, 1);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new ivec4(-2, 0, 1, -2);
var v1 = new ivec4(2, -1, 5, -5);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new ivec4(2, 7, -7, 1);
var v1 = new ivec4(-6, -6, 9, -1);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new ivec4(8, 6, 4, 0);
var v1 = new ivec4(0, 8, -8, -5);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new ivec4(-3, -3, -6, -8);
var v1 = new ivec4(2, -2, 1, -5);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new ivec4(-3, -5, 9, 7);
var v1 = new ivec4(-6, 4, -5, 1);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new ivec4(-3, 0, -3, -1);
var v1 = new ivec4(-4, -5, -2, -8);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new ivec4(-7, -2, -8, -9);
var v1 = new ivec4(-9, 9, 0, 2);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new ivec4(2, 6, -8, 9);
var v1 = new ivec4(-5, 7, -3, 9);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new ivec4(5, 2, 8, 1);
var v1 = new ivec4(6, 2, -4, 4);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
}
[Test]
public void InvariantNorm()
{
{
var v0 = new ivec4(4, -1, -2, -1);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new ivec4(2, 0, -8, -9);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new ivec4(4, 8, -1, -3);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new ivec4(-8, 6, 0, 8);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new ivec4(-1, 7, 9, 2);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new ivec4(4, 2, -3, 6);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new ivec4(9, 4, -2, 8);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new ivec4(-8, 5, -2, -2);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new ivec4(-5, 1, -5, -9);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new ivec4(-1, -4, -7, -7);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
}
[Test]
public void RandomUniform0()
{
var random = new Random(889490485);
var sum = new dvec4(0.0);
var sumSqr = new dvec4(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = ivec4.Random(random, 1, 4);
sum += (dvec4)v;
sumSqr += glm.Pow2((dvec4)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 2, 1.0);
Assert.AreEqual(avg.y, 2, 1.0);
Assert.AreEqual(avg.z, 2, 1.0);
Assert.AreEqual(avg.w, 2, 1.0);
Assert.AreEqual(variance.x, 0.666666666666667, 3.0);
Assert.AreEqual(variance.y, 0.666666666666667, 3.0);
Assert.AreEqual(variance.z, 0.666666666666667, 3.0);
Assert.AreEqual(variance.w, 0.666666666666667, 3.0);
}
[Test]
public void RandomUniform1()
{
var random = new Random(1608058487);
var sum = new dvec4(0.0);
var sumSqr = new dvec4(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = ivec4.RandomUniform(random, -2, 2);
sum += (dvec4)v;
sumSqr += glm.Pow2((dvec4)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, -0.5, 1.0);
Assert.AreEqual(avg.y, -0.5, 1.0);
Assert.AreEqual(avg.z, -0.5, 1.0);
Assert.AreEqual(avg.w, -0.5, 1.0);
Assert.AreEqual(variance.x, 1.25, 3.0);
Assert.AreEqual(variance.y, 1.25, 3.0);
Assert.AreEqual(variance.z, 1.25, 3.0);
Assert.AreEqual(variance.w, 1.25, 3.0);
}
[Test]
public void RandomUniform2()
{
var random = new Random(179142842);
var sum = new dvec4(0.0);
var sumSqr = new dvec4(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = ivec4.Random(random, 3, 7);
sum += (dvec4)v;
sumSqr += glm.Pow2((dvec4)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 4.5, 1.0);
Assert.AreEqual(avg.y, 4.5, 1.0);
Assert.AreEqual(avg.z, 4.5, 1.0);
Assert.AreEqual(avg.w, 4.5, 1.0);
Assert.AreEqual(variance.x, 1.25, 3.0);
Assert.AreEqual(variance.y, 1.25, 3.0);
Assert.AreEqual(variance.z, 1.25, 3.0);
Assert.AreEqual(variance.w, 1.25, 3.0);
}
[Test]
public void RandomUniform3()
{
var random = new Random(897710844);
var sum = new dvec4(0.0);
var sumSqr = new dvec4(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = ivec4.RandomUniform(random, -2, 3);
sum += (dvec4)v;
sumSqr += glm.Pow2((dvec4)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 0, 1.0);
Assert.AreEqual(avg.y, 0, 1.0);
Assert.AreEqual(avg.z, 0, 1.0);
Assert.AreEqual(avg.w, 0, 1.0);
Assert.AreEqual(variance.x, 2, 3.0);
Assert.AreEqual(variance.y, 2, 3.0);
Assert.AreEqual(variance.z, 2, 3.0);
Assert.AreEqual(variance.w, 2, 3.0);
}
[Test]
public void RandomUniform4()
{
var random = new Random(162702124);
var sum = new dvec4(0.0);
var sumSqr = new dvec4(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = ivec4.Random(random, 4, 9);
sum += (dvec4)v;
sumSqr += glm.Pow2((dvec4)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 6, 1.0);
Assert.AreEqual(avg.y, 6, 1.0);
Assert.AreEqual(avg.z, 6, 1.0);
Assert.AreEqual(avg.w, 6, 1.0);
Assert.AreEqual(variance.x, 2, 3.0);
Assert.AreEqual(variance.y, 2, 3.0);
Assert.AreEqual(variance.z, 2, 3.0);
Assert.AreEqual(variance.w, 2, 3.0);
}
[Test]
public void RandomPoisson0()
{
var random = new Random(1631764852);
var sum = new dvec4(0.0);
var sumSqr = new dvec4(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = ivec4.RandomPoisson(random, 1.34020516501749);
sum += (dvec4)v;
sumSqr += glm.Pow2((dvec4)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 1.34020516501749, 1.0);
Assert.AreEqual(avg.y, 1.34020516501749, 1.0);
Assert.AreEqual(avg.z, 1.34020516501749, 1.0);
Assert.AreEqual(avg.w, 1.34020516501749, 1.0);
Assert.AreEqual(variance.x, 1.34020516501749, 3.0);
Assert.AreEqual(variance.y, 1.34020516501749, 3.0);
Assert.AreEqual(variance.z, 1.34020516501749, 3.0);
Assert.AreEqual(variance.w, 1.34020516501749, 3.0);
}
[Test]
public void RandomPoisson1()
{
var random = new Random(202849207);
var sum = new dvec4(0.0);
var sumSqr = new dvec4(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = ivec4.RandomPoisson(random, 3.42047775253676);
sum += (dvec4)v;
sumSqr += glm.Pow2((dvec4)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 3.42047775253676, 1.0);
Assert.AreEqual(avg.y, 3.42047775253676, 1.0);
Assert.AreEqual(avg.z, 3.42047775253676, 1.0);
Assert.AreEqual(avg.w, 3.42047775253676, 1.0);
Assert.AreEqual(variance.x, 3.42047775253676, 3.0);
Assert.AreEqual(variance.y, 3.42047775253676, 3.0);
Assert.AreEqual(variance.z, 3.42047775253676, 3.0);
Assert.AreEqual(variance.w, 3.42047775253676, 3.0);
}
[Test]
public void RandomPoisson2()
{
var random = new Random(194628848);
var sum = new dvec4(0.0);
var sumSqr = new dvec4(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = ivec4.RandomPoisson(random, 1.97291060605688);
sum += (dvec4)v;
sumSqr += glm.Pow2((dvec4)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 1.97291060605688, 1.0);
Assert.AreEqual(avg.y, 1.97291060605688, 1.0);
Assert.AreEqual(avg.z, 1.97291060605688, 1.0);
Assert.AreEqual(avg.w, 1.97291060605688, 1.0);
Assert.AreEqual(variance.x, 1.97291060605688, 3.0);
Assert.AreEqual(variance.y, 1.97291060605688, 3.0);
Assert.AreEqual(variance.z, 1.97291060605688, 3.0);
Assert.AreEqual(variance.w, 1.97291060605688, 3.0);
}
[Test]
public void RandomPoisson3()
{
var random = new Random(913196850);
var sum = new dvec4(0.0);
var sumSqr = new dvec4(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = ivec4.RandomPoisson(random, 3.31561204549652);
sum += (dvec4)v;
sumSqr += glm.Pow2((dvec4)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 3.31561204549652, 1.0);
Assert.AreEqual(avg.y, 3.31561204549652, 1.0);
Assert.AreEqual(avg.z, 3.31561204549652, 1.0);
Assert.AreEqual(avg.w, 3.31561204549652, 1.0);
Assert.AreEqual(variance.x, 3.31561204549652, 3.0);
Assert.AreEqual(variance.y, 3.31561204549652, 3.0);
Assert.AreEqual(variance.z, 3.31561204549652, 3.0);
Assert.AreEqual(variance.w, 3.31561204549652, 3.0);
}
[Test]
public void RandomPoisson4()
{
var random = new Random(904976491);
var sum = new dvec4(0.0);
var sumSqr = new dvec4(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = ivec4.RandomPoisson(random, 1.86804489901664);
sum += (dvec4)v;
sumSqr += glm.Pow2((dvec4)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 1.86804489901664, 1.0);
Assert.AreEqual(avg.y, 1.86804489901664, 1.0);
Assert.AreEqual(avg.z, 1.86804489901664, 1.0);
Assert.AreEqual(avg.w, 1.86804489901664, 1.0);
Assert.AreEqual(variance.x, 1.86804489901664, 3.0);
Assert.AreEqual(variance.y, 1.86804489901664, 3.0);
Assert.AreEqual(variance.z, 1.86804489901664, 3.0);
Assert.AreEqual(variance.w, 1.86804489901664, 3.0);
}
}
}
| |
--- /dev/null 2016-03-09 10:01:51.000000000 -0500
+++ src/System.Runtime.Numerics/src/SR.cs 2016-03-09 10:02:06.455007000 -0500
@@ -0,0 +1,214 @@
+using System;
+using System.Resources;
+
+namespace FxResources.System.Runtime.Numerics
+{
+ internal static class SR
+ {
+
+ }
+}
+
+namespace System
+{
+ internal static class SR
+ {
+ private static ResourceManager s_resourceManager;
+
+ private const String s_resourcesName = "FxResources.System.Runtime.Numerics.SR";
+
+ internal static String Argument_BadFormatSpecifier
+ {
+ get
+ {
+ return SR.GetResourceString("Argument_BadFormatSpecifier", null);
+ }
+ }
+
+ internal static String Argument_InvalidHexStyle
+ {
+ get
+ {
+ return SR.GetResourceString("Argument_InvalidHexStyle", null);
+ }
+ }
+
+ internal static String Argument_InvalidNumberStyles
+ {
+ get
+ {
+ return SR.GetResourceString("Argument_InvalidNumberStyles", null);
+ }
+ }
+
+ internal static String Argument_MustBeBigInt
+ {
+ get
+ {
+ return SR.GetResourceString("Argument_MustBeBigInt", null);
+ }
+ }
+
+ internal static String ArgumentOutOfRange_MustBeNonNeg
+ {
+ get
+ {
+ return SR.GetResourceString("ArgumentOutOfRange_MustBeNonNeg", null);
+ }
+ }
+
+ internal static String Format_TooLarge
+ {
+ get
+ {
+ return SR.GetResourceString("Format_TooLarge", null);
+ }
+ }
+
+ internal static String Overflow_BigIntInfinity
+ {
+ get
+ {
+ return SR.GetResourceString("Overflow_BigIntInfinity", null);
+ }
+ }
+
+ internal static String Overflow_Decimal
+ {
+ get
+ {
+ return SR.GetResourceString("Overflow_Decimal", null);
+ }
+ }
+
+ internal static String Overflow_Int32
+ {
+ get
+ {
+ return SR.GetResourceString("Overflow_Int32", null);
+ }
+ }
+
+ internal static String Overflow_Int64
+ {
+ get
+ {
+ return SR.GetResourceString("Overflow_Int64", null);
+ }
+ }
+
+ internal static String Overflow_NotANumber
+ {
+ get
+ {
+ return SR.GetResourceString("Overflow_NotANumber", null);
+ }
+ }
+
+ internal static String Overflow_ParseBigInteger
+ {
+ get
+ {
+ return SR.GetResourceString("Overflow_ParseBigInteger", null);
+ }
+ }
+
+ internal static String Overflow_UInt32
+ {
+ get
+ {
+ return SR.GetResourceString("Overflow_UInt32", null);
+ }
+ }
+
+ internal static String Overflow_UInt64
+ {
+ get
+ {
+ return SR.GetResourceString("Overflow_UInt64", null);
+ }
+ }
+
+ private static ResourceManager ResourceManager
+ {
+ get
+ {
+ if (SR.s_resourceManager == null)
+ {
+ SR.s_resourceManager = new ResourceManager(SR.ResourceType);
+ }
+ return SR.s_resourceManager;
+ }
+ }
+
+ internal static Type ResourceType
+ {
+ get
+ {
+ return typeof(FxResources.System.Runtime.Numerics.SR);
+ }
+ }
+
+ internal static String Format(String resourceFormat, params Object[] args)
+ {
+ if (args == null)
+ {
+ return resourceFormat;
+ }
+ if (!SR.UsingResourceKeys())
+ {
+ return String.Format(resourceFormat, args);
+ }
+ return String.Concat(resourceFormat, String.Join(", ", args));
+ }
+
+ internal static String Format(String resourceFormat, Object p1)
+ {
+ if (!SR.UsingResourceKeys())
+ {
+ return String.Format(resourceFormat, p1);
+ }
+ return String.Join(", ", new Object[] { resourceFormat, p1 });
+ }
+
+ internal static String Format(String resourceFormat, Object p1, Object p2)
+ {
+ if (!SR.UsingResourceKeys())
+ {
+ return String.Format(resourceFormat, p1, p2);
+ }
+ return String.Join(", ", new Object[] { resourceFormat, p1, p2 });
+ }
+
+ internal static String Format(String resourceFormat, Object p1, Object p2, Object p3)
+ {
+ if (!SR.UsingResourceKeys())
+ {
+ return String.Format(resourceFormat, p1, p2, p3);
+ }
+ return String.Join(", ", new Object[] { resourceFormat, p1, p2, p3 });
+ }
+
+ internal static String GetResourceString(String resourceKey, String defaultString)
+ {
+ String str = null;
+ try
+ {
+ str = SR.ResourceManager.GetString(resourceKey);
+ }
+ catch (MissingManifestResourceException missingManifestResourceException)
+ {
+ }
+ if (defaultString != null && resourceKey.Equals(str))
+ {
+ return defaultString;
+ }
+ return str;
+ }
+
+ private static Boolean UsingResourceKeys()
+ {
+ return false;
+ }
+ }
+}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Forms;
using System.Text;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using Revit.SDK.Samples.NewRoof.RoofForms.CS;
namespace Revit.SDK.Samples.NewRoof.RoofsManager.CS
{
/// <summary>
/// The kinds of roof than can be created.
/// </summary>
public enum CreateRoofKind
{
FootPrintRoof,
ExtrusionRoof
};
/// <summary>
/// The RoofsManager is used to manage the operations between Revit and UI.
/// </summary>
public class RoofsManager
{
// To store a reference to the commandData.
ExternalCommandData m_commandData;
// To store the levels info in the Revit.
List<Level> m_levels;
// To store the roof types info in the Revit.
List<RoofType> m_roofTypes;
// To store a reference to the FootPrintRoofManager to create footprint roof.
FootPrintRoofManager m_footPrintRoofManager;
// To store a reference to the ExtrusionRoofManager to create extrusion roof.
ExtrusionRoofManager m_extrusionRoofManager;
// To store the selected elements in the Revit
Selection m_selection;
// roofs list
ElementSet m_footPrintRoofs;
ElementSet m_extrusionRoofs;
// To store the footprint roof lines.
Autodesk.Revit.DB.CurveArray m_footPrint;
// To store the profile lines.
Autodesk.Revit.DB.CurveArray m_profile;
// Reference Plane for creating extrusion roof
List<ReferencePlane> m_referencePlanes;
// Transaction for manual mode
Transaction m_transaction;
// Current creating roof kind.
public CreateRoofKind RoofKind;
/// <summary>
/// The constructor of RoofsManager class.
/// </summary>
/// <param name="commandData">The ExternalCommandData</param>
public RoofsManager(ExternalCommandData commandData)
{
m_commandData = commandData;
m_levels = new List<Level>();
m_roofTypes = new List<RoofType>();
m_referencePlanes = new List<ReferencePlane>();
m_footPrint = new CurveArray();
m_profile = new CurveArray();
m_footPrintRoofManager = new FootPrintRoofManager(commandData);
m_extrusionRoofManager = new ExtrusionRoofManager(commandData);
m_selection = commandData.Application.ActiveUIDocument.Selection;
m_transaction = new Transaction(commandData.Application.ActiveUIDocument.Document, "Document");
RoofKind = CreateRoofKind.FootPrintRoof;
Initialize();
}
/// <summary>
/// Initialize the data member
/// </summary>
private void Initialize()
{
Document doc = m_commandData.Application.ActiveUIDocument.Document;
FilteredElementIterator iter = (new FilteredElementCollector(doc)).OfClass(typeof(Level)).GetElementIterator();
iter.Reset();
while (iter.MoveNext())
{
m_levels.Add(iter.Current as Level);
}
foreach (RoofType roofType in m_commandData.Application.ActiveUIDocument.Document.RoofTypes)
{
m_roofTypes.Add(roofType);
}
// FootPrint Roofs
m_footPrintRoofs = new ElementSet();
iter = (new FilteredElementCollector(doc)).OfClass(typeof(FootPrintRoof)).GetElementIterator();
iter.Reset();
while (iter.MoveNext())
{
m_footPrintRoofs.Insert(iter.Current as FootPrintRoof);
}
// Extrusion Roofs
m_extrusionRoofs = new ElementSet();
iter = (new FilteredElementCollector(doc)).OfClass(typeof(ExtrusionRoof)).GetElementIterator();
iter.Reset();
while (iter.MoveNext())
{
m_extrusionRoofs.Insert(iter.Current as ExtrusionRoof);
}
// Reference Planes
iter = (new FilteredElementCollector(doc)).OfClass(typeof(ReferencePlane)).GetElementIterator();
iter.Reset();
while (iter.MoveNext())
{
ReferencePlane plane = iter.Current as ReferencePlane;
// just use the vertical plane
if (Math.Abs(plane.Normal.DotProduct(Autodesk.Revit.DB.XYZ.BasisZ)) < 1.0e-09)
{
if (plane.Name == "Reference Plane")
{
plane.Name = "Reference Plane" + "(" + plane.Id.IntegerValue.ToString() + ")";
}
m_referencePlanes.Add(plane);
}
}
}
/// <summary>
/// Get the Level elements.
/// </summary>
public ReadOnlyCollection<Level> Levels
{
get
{
return new ReadOnlyCollection<Level>(m_levels);
}
}
/// <summary>
/// Get the RoofTypes.
/// </summary>
public ReadOnlyCollection<RoofType> RoofTypes
{
get
{
return new ReadOnlyCollection<RoofType>(m_roofTypes);
}
}
/// <summary>
/// Get the RoofTypes.
/// </summary>
public ReadOnlyCollection<ReferencePlane> ReferencePlanes
{
get
{
return new ReadOnlyCollection<ReferencePlane>(m_referencePlanes);
}
}
/// <summary>
/// Get all the footprint roofs in Revit.
/// </summary>
public ElementSet FootPrintRoofs
{
get
{
return m_footPrintRoofs;
}
}
/// <summary>
/// Get all the extrusion roofs in Revit.
/// </summary>
public ElementSet ExtrusionRoofs
{
get
{
return m_extrusionRoofs;
}
}
/// <summary>
/// Get the footprint roof lines.
/// </summary>
public CurveArray FootPrint
{
get
{
return m_footPrint;
}
}
/// <summary>
/// Get the extrusion profile lines.
/// </summary>
public CurveArray Profile
{
get
{
return m_profile;
}
}
/// <summary>
/// Select elements in Revit to obtain the footprint roof lines or extrusion profile lines.
/// </summary>
/// <returns>A curve array to hold the footprint roof lines or extrusion profile lines.</returns>
public CurveArray WindowSelect()
{
if (RoofKind == CreateRoofKind.FootPrintRoof)
{
return SelectFootPrint();
}
else
{
return SelectProfile();
}
}
/// <summary>
/// Select elements in Revit to obtain the footprint roof lines.
/// </summary>
/// <returns>A curve array to hold the footprint roof lines.</returns>
public CurveArray SelectFootPrint()
{
m_footPrint.Clear();
while (true)
{
m_selection.Elements.Clear();
IList<Element> selectResult;
try
{
selectResult = m_selection.PickElementsByRectangle();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
break;
}
if (selectResult.Count != 0)
{
foreach (Autodesk.Revit.DB.Element element in selectResult)
{
Wall wall = element as Wall;
if (wall != null)
{
LocationCurve wallCurve = wall.Location as LocationCurve;
m_footPrint.Append(wallCurve.Curve);
continue;
}
ModelCurve modelCurve = element as ModelCurve;
if (modelCurve != null)
{
m_footPrint.Append(modelCurve.GeometryCurve);
}
}
break;
}
else
{
DialogResult result = MessageBox.Show("You should select a curve loop, or a wall loop, or loops combination \r\nof walls and curves to create a footprint roof.", "Warning",
MessageBoxButtons.OKCancel);
if (result == DialogResult.Cancel)
{
break;
}
}
}
return m_footPrint;
}
/// <summary>
/// Create a footprint roof.
/// </summary>
/// <param name="level">The base level of the roof to be created.</param>
/// <param name="roofType">The type of the newly created roof.</param>
/// <returns>Return a new created footprint roof.</returns>
public FootPrintRoof CreateFootPrintRoof(Level level, RoofType roofType)
{
FootPrintRoof roof = null;
roof = m_footPrintRoofManager.CreateFootPrintRoof(m_footPrint, level, roofType);
if (roof != null)
{
this.m_footPrintRoofs.Insert(roof);
}
return roof;
}
/// <summary>
/// Select elements in Revit to obtain the extrusion profile lines.
/// </summary>
/// <returns>A curve array to hold the extrusion profile lines.</returns>
public CurveArray SelectProfile()
{
m_profile.Clear();
while (true)
{
m_selection.Elements.Clear();
IList<Element> selectResult;
try
{
selectResult = m_selection.PickElementsByRectangle();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
break;
}
if (selectResult.Count != 0)
{
foreach (Autodesk.Revit.DB.Element element in selectResult)
{
ModelCurve modelCurve = element as ModelCurve;
if (modelCurve != null)
{
m_profile.Append(modelCurve.GeometryCurve);
continue;
}
}
break;
}
else
{
DialogResult result = MessageBox.Show("You should select a connected lines or arcs, \r\nnot closed in a loop to create extrusion roof.", "Warning",
MessageBoxButtons.OKCancel);
if (result == DialogResult.Cancel)
{
break;
}
}
}
return m_profile;
}
/// <summary>
/// Create a extrusion roof.
/// </summary>
/// <param name="refPlane">The reference plane for the extrusion roof.</param>
/// <param name="level">The reference level of the roof to be created.</param>
/// <param name="roofType">The type of the newly created roof.</param>
/// <param name="extrusionStart">The extrusion start point.</param>
/// <param name="extrusionEnd">The extrusion end point.</param>
/// <returns>Return a new created extrusion roof.</returns>
public ExtrusionRoof CreateExtrusionRoof(ReferencePlane refPlane,
Level level, RoofType roofType, double extrusionStart, double extrusionEnd)
{
ExtrusionRoof roof = null;
roof = m_extrusionRoofManager.CreateExtrusionRoof(m_profile, refPlane, level, roofType, extrusionStart, extrusionEnd);
if (roof != null)
{
m_extrusionRoofs.Insert(roof);
}
return roof;
}
/// <summary>
/// Begin a transaction.
/// </summary>
/// <returns></returns>
public TransactionStatus BeginTransaction()
{
if (m_transaction.GetStatus() == TransactionStatus.Started)
{
MessageBox.Show("Transaction started already");
}
return m_transaction.Start();
}
/// <summary>
/// Finish a transaction.
/// </summary>
/// <returns></returns>
public TransactionStatus EndTransaction()
{
return m_transaction.Commit();
}
/// <summary>
/// Abort a transaction.
/// </summary>
public TransactionStatus AbortTransaction()
{
return m_transaction.RollBack();
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// Animation.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region File Information
//-----------------------------------------------------------------------------
// Animation.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#endregion
namespace HoneycombRush
{
/// <summary>
/// Supports animation playback.
/// </summary>
public class Animation
{
#region Fields
Texture2D animatedCharacter;
Point sheetSize;
public Point currentFrame;
public Point frameSize;
private TimeSpan lastestChangeTime;
private TimeSpan timeInterval = TimeSpan.Zero;
private int startFrame;
private int endFrame;
private int lastSubFrame = -1;
bool drawWasAlreadyCalledOnce = false;
public int FrameCount
{
get
{
return sheetSize.X * sheetSize.Y;
}
}
public Vector2 Offset { get; set; }
public int FrameIndex
{
get
{
return sheetSize.X * currentFrame.Y + currentFrame.X;
}
set
{
if (value >= sheetSize.X * sheetSize.Y + 1)
{
throw new InvalidOperationException("Specified frame index exceeds available frames");
}
currentFrame.Y = value / sheetSize.X;
currentFrame.X = value % sheetSize.X;
}
}
public bool IsActive { get; private set; }
#endregion
#region Initialization
/// <summary>
/// Creates a new instance of the animation class
/// </summary>
/// <param name="frameSheet">Texture which is a sheet containing
/// the animation frames.</param>
/// <param name="size">The size of a single frame.</param>
/// <param name="frameSheetSize">The size of the entire animation sheet.</param>
public Animation(Texture2D frameSheet, Point size, Point frameSheetSize)
{
animatedCharacter = frameSheet;
frameSize = size;
sheetSize = frameSheetSize;
Offset = Vector2.Zero;
}
#endregion
#region Update and Render
/// <summary>
/// Updates the animation's progress.
/// </summary>
/// <param name="gameTime">Game time information.</param>
/// <param name="isInMotion">Whether or not the animation element itself is
/// currently in motion.</param>
public void Update(GameTime gameTime, bool isInMotion)
{
Update(gameTime, isInMotion, false);
}
/// <summary>
/// Updates the animation's progress.
/// </summary>
/// <param name="gameTime">Game time information.</param>
/// <param name="isInMotion">Whether or not the animation element itself is
/// currently in motion.</param>
/// <param name="runSubAnimation"></param>
public void Update(GameTime gameTime, bool isInMotion, bool runSubAnimation)
{
if (IsActive && gameTime.TotalGameTime != lastestChangeTime)
{
// See if a time interval between frames is defined
if (timeInterval != TimeSpan.Zero)
{
// Do nothing until an interval passes
if (lastestChangeTime + timeInterval > gameTime.TotalGameTime)
{
return;
}
}
lastestChangeTime = gameTime.TotalGameTime;
if (FrameIndex >= FrameCount)
{
FrameIndex = 0; // Reset the animation
}
else
{
// Only advance the animation if the animation element is moving
if (isInMotion)
{
if (runSubAnimation)
{
// Initialize the animation
if (lastSubFrame == -1)
{
lastSubFrame = startFrame;
}
// Calculate the currentFrame, which depends on the current
// frame in the parent animation
currentFrame.Y = lastSubFrame / sheetSize.X;
currentFrame.X = lastSubFrame % sheetSize.X;
// Move to the next Frame
lastSubFrame += 1;
// Loop the animation
if (lastSubFrame > endFrame)
{
lastSubFrame = startFrame;
}
}
else
{
// Do not advance frames before the first draw operation
if (drawWasAlreadyCalledOnce)
{
currentFrame.X++;
if (currentFrame.X >= sheetSize.X)
{
currentFrame.X = 0;
currentFrame.Y++;
}
if (currentFrame.Y >= sheetSize.Y)
currentFrame.Y = 0;
if (lastSubFrame != -1)
{
lastSubFrame = -1;
}
}
}
}
}
}
}
/// <summary>
/// Render the animation.
/// </summary>
/// <param name="spriteBatch">SpriteBatch with which the current
/// frame will be rendered.</param>
/// <param name="position">The position to draw the current frame.</param>
/// <param name="spriteEffect">SpriteEffect to apply to the
/// current frame.</param>
public void Draw(SpriteBatch spriteBatch, Vector2 position, SpriteEffects spriteEffect)
{
Draw(spriteBatch, position, 1.0f, spriteEffect);
}
/// <summary>
/// Render the animation.
/// </summary>
/// <param name="spriteBatch">SpriteBatch with which the current frame
/// will be rendered.</param>
/// <param name="position">The position to draw the current frame.</param>
/// <param name="scale">Scale factor to apply to the current frame.</param>
/// <param name="spriteEffect">SpriteEffect to apply to the
/// current frame.</param>
public void Draw(SpriteBatch spriteBatch, Vector2 position, float scale, SpriteEffects spriteEffect)
{
drawWasAlreadyCalledOnce = true;
spriteBatch.Draw(animatedCharacter, position + Offset,
new Rectangle(frameSize.X * currentFrame.X, frameSize.Y * currentFrame.Y, frameSize.X, frameSize.Y),
Color.White, 0f, Vector2.Zero, scale, spriteEffect, 0);
}
/// <summary>
/// Causes the animation to start playing from a specified frame index.
/// </summary>
/// <param name="frameIndex">Frame index to play the animation from.</param>
public void PlayFromFrameIndex(int frameIndex)
{
FrameIndex = frameIndex;
IsActive = true;
drawWasAlreadyCalledOnce = false;
}
/// <summary>
/// Sets the range of frames which serves as the sub animation.
/// </summary>
/// <param name="startFrame">Start frame for the sub-animation.</param>
/// <param name="endFrame">End frame for the sub-animation.</param>
public void SetSubAnimation(int startFrame, int endFrame)
{
this.startFrame = startFrame;
this.endFrame = endFrame;
}
/// <summary>
/// Used to set the interval between frames.
/// </summary>
/// <param name="interval">The interval between frames.</param>
public void SetFrameInterval(TimeSpan interval)
{
timeInterval = interval;
}
#endregion
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using Adxstudio.Xrm.Cms.Security;
using Adxstudio.Xrm.Web.Providers;
using Adxstudio.Xrm.Resources;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Metadata;
using Microsoft.Xrm.Client.Security;
using Microsoft.Xrm.Portal;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Metadata;
using Newtonsoft.Json.Linq;
namespace Adxstudio.Xrm.Web.Handlers
{
/// <summary>
/// </summary>
public class CmsEntityRelationshipHandler : CmsEntityHandler
{
private static readonly Regex _relationshipSchemaNameRegex = new Regex(@"^(?<schemaName>[^\.]+)(\.(?<entityRole>.+))?$");
public CmsEntityRelationshipHandler() : this(null, null, null, null, null) { }
public CmsEntityRelationshipHandler(string portalName, Guid? portalScopeId, string entityLogicalName, Guid? id, string relationshipSchemaName) : base(portalName, portalScopeId, entityLogicalName, id)
{
RelationshipSchemaName = relationshipSchemaName;
}
/// <summary>
/// The CRM schema name of the relationship being requested.
/// </summary>
protected virtual string RelationshipSchemaName { get; private set; }
protected override void AssertRequestEntitySecurity(IPortalContext portal, OrganizationServiceContext serviceContext, Entity entity, ICrmEntitySecurityProvider security)
{
// If the current request entity is the current website, leave security handling for later, once we have info about
// the relationship being requested.
if (entity.ToEntityReference().Equals(portal.Website.ToEntityReference()))
{
return;
}
base.AssertRequestEntitySecurity(portal, serviceContext, entity, security);
}
protected virtual void AssertRequestEntitySecurity(IPortalContext portal, OrganizationServiceContext serviceContext, Entity entity, ICrmEntitySecurityProvider security, IWebsiteAccessPermissionProvider websiteAccess, CmsEntityRelationshipInfo relationshipInfo)
{
if (!entity.ToEntityReference().Equals(portal.Website.ToEntityReference()))
{
return;
}
var otherEntity = relationshipInfo.IsCollection
? relationshipInfo.ReferencingEntity
: relationshipInfo.ReferencedEntity;
if (string.Equals(otherEntity, "adx_contentsnippet", StringComparison.OrdinalIgnoreCase))
{
if (!websiteAccess.TryAssert(serviceContext, WebsiteRight.ManageContentSnippets))
{
throw new CmsEntityServiceException(HttpStatusCode.Forbidden, "Manage Content Snippets permission denied.");
}
return;
}
if (string.Equals(otherEntity, "adx_sitemarker", StringComparison.OrdinalIgnoreCase))
{
if (!websiteAccess.TryAssert(serviceContext, WebsiteRight.ManageSiteMarkers))
{
throw new CmsEntityServiceException(HttpStatusCode.Forbidden, "Manage Site Markers permission denied.");
}
return;
}
if (string.Equals(otherEntity, "adx_weblinkset", StringComparison.OrdinalIgnoreCase)
|| string.Equals(otherEntity, "adx_weblink", StringComparison.OrdinalIgnoreCase))
{
if (!websiteAccess.TryAssert(serviceContext, WebsiteRight.ManageWebLinkSets))
{
throw new CmsEntityServiceException(HttpStatusCode.Forbidden, "Manage Web Link Sets permission denied.");
}
return;
}
base.AssertRequestEntitySecurity(portal, serviceContext, entity, security);
}
protected override void ProcessRequest(HttpContext context, ICmsEntityServiceProvider serviceProvider, Guid portalScopeId, IPortalContext portal, OrganizationServiceContext serviceContext, Entity entity, CmsEntityMetadata entityMetadata, ICrmEntitySecurityProvider security)
{
var relationshipSchemaName = string.IsNullOrWhiteSpace(RelationshipSchemaName) ? context.Request.Params["relationshipSchemaName"] : RelationshipSchemaName;
if (string.IsNullOrWhiteSpace(relationshipSchemaName))
{
throw new CmsEntityServiceException(HttpStatusCode.BadRequest, "Unable to determine entity relationship schema name from request.");
}
var match = _relationshipSchemaNameRegex.Match(relationshipSchemaName);
if (!match.Success)
{
throw new CmsEntityServiceException(HttpStatusCode.BadRequest, "Unable to determine entity relationship schema name from request.");
}
var schemaName = match.Groups["schemaName"].Value;
if (string.IsNullOrWhiteSpace(schemaName))
{
throw new CmsEntityServiceException(HttpStatusCode.BadRequest, "Unable to determine entity relationship schema name from request.");
}
var entityRole = match.Groups["entityRole"].Value;
EntityRole parsedRole;
var relationship = new Relationship(schemaName)
{
PrimaryEntityRole = Enum.TryParse(entityRole, true, out parsedRole) ? new EntityRole?(parsedRole) : null
};
CmsEntityRelationshipInfo relationshipInfo;
if (!entityMetadata.TryGetRelationshipInfo(relationship, out relationshipInfo))
{
throw new CmsEntityServiceException(HttpStatusCode.NotFound, "Entity relationship not found.");
}
// If the current request entity is the current website, do security handling here, since we skipped it earlier.
if (entity.ToEntityReference().Equals(portal.Website.ToEntityReference()))
{
AssertRequestEntitySecurity(portal, serviceContext, entity, security, CreateWebsiteAccessPermissionProvider(portal), relationshipInfo);
}
if (IsRequestMethod(context.Request, "GET"))
{
if (relationshipInfo.IsCollection)
{
var readableRelatedEntities = entity.GetRelatedEntities(serviceContext, relationship)
.Where(e => security.TryAssert(serviceContext, e, CrmEntityRight.Read));
var entityMetadataLookup = new Dictionary<string, CmsEntityMetadata>();
var entityJsonObjects = readableRelatedEntities.Select(e =>
{
CmsEntityMetadata relatedEntityMetadata;
if (!entityMetadataLookup.TryGetValue(e.LogicalName, out relatedEntityMetadata))
{
relatedEntityMetadata = new CmsEntityMetadata(serviceContext, e.LogicalName);
entityMetadataLookup[e.LogicalName] = relatedEntityMetadata;
}
return GetEntityJson(context, serviceProvider, portalScopeId, portal, serviceContext, e, relatedEntityMetadata);
});
WriteResponse(context.Response, new JObject
{
{ "d", new JArray(entityJsonObjects) }
});
}
else
{
var relatedEntity = entity.GetRelatedEntity(serviceContext, relationship);
if (relatedEntity == null)
{
throw new CmsEntityServiceException(HttpStatusCode.NotFound, "Related entity not found.");
}
if (!security.TryAssert(serviceContext, relatedEntity, CrmEntityRight.Read))
{
throw new CmsEntityServiceException(HttpStatusCode.Forbidden, "Related entity access denied.");
}
WriteResponse(context.Response, new JObject
{
{ "d", GetEntityJson(context, serviceProvider, portalScopeId, portal, serviceContext, relatedEntity, new CmsEntityMetadata(serviceContext, relatedEntity.LogicalName)) }
});
}
return;
}
if (IsRequestMethod(context.Request, "POST"))
{
if (relationshipInfo.IsCollection)
{
OneToManyRelationshipMetadata relationshipMetadata;
if (!entityMetadata.TryGetOneToManyRelationshipMetadata(relationship, out relationshipMetadata))
{
throw new CmsEntityServiceException(HttpStatusCode.BadRequest, "Unable to retrieve the one-to-many relationship metadata for relationship {0} on entity type".FormatWith(relationship.ToSchemaName("."), entity.LogicalName));
}
var relatedEntity = CreateEntityOfType(serviceContext, relationshipMetadata.ReferencingEntity);
var relatedEntityMetadata = new CmsEntityMetadata(serviceContext, relatedEntity.LogicalName);
var extensions = UpdateEntityFromJsonRequestBody(context.Request, serviceContext, relatedEntity, relatedEntityMetadata);
var preImage = relatedEntity.Clone(false);
// Ensure the reference to the target entity is set.
relatedEntity.SetAttributeValue(relationshipMetadata.ReferencingAttribute, new EntityReference(entity.LogicalName, entity.GetAttributeValue<Guid>(relationshipMetadata.ReferencedAttribute)));
serviceProvider.InterceptChange(context, portal, serviceContext, relatedEntity, relatedEntityMetadata, CmsEntityOperation.Create, preImage);
serviceContext.AddObject(relatedEntity);
serviceProvider.InterceptExtensionChange(context, portal, serviceContext, relatedEntity, relatedEntityMetadata, extensions, CmsEntityOperation.Create);
serviceContext.SaveChanges();
var refetchedEntity = serviceContext.CreateQuery(relatedEntity.LogicalName)
.FirstOrDefault(e => e.GetAttributeValue<Guid>(relatedEntityMetadata.PrimaryIdAttribute) == relatedEntity.Id);
if (refetchedEntity == null)
{
throw new CmsEntityServiceException(HttpStatusCode.InternalServerError, "Unable to retrieve the created entity.");
}
WriteResponse(context.Response, new JObject
{
{ "d", GetEntityJson(context, serviceProvider, portalScopeId, portal, serviceContext, refetchedEntity, relatedEntityMetadata) }
}, HttpStatusCode.Created);
}
else
{
OneToManyRelationshipMetadata relationshipMetadata;
if (!entityMetadata.TryGetManyToOneRelationshipMetadata(relationship, out relationshipMetadata))
{
throw new CmsEntityServiceException(HttpStatusCode.BadRequest, "Unable to retrieve the many-to-one relationship metadata for relationship {0} on entity type".FormatWith(relationship.ToSchemaName("."), entity.LogicalName));
}
var relatedEntity = CreateEntityOfType(serviceContext, relationshipMetadata.ReferencedEntity);
var relatedEntityMetadata = new CmsEntityMetadata(serviceContext, relatedEntity.LogicalName);
var extensions = UpdateEntityFromJsonRequestBody(context.Request, serviceContext, relatedEntity, relatedEntityMetadata);
serviceProvider.InterceptChange(context, portal, serviceContext, relatedEntity, relatedEntityMetadata, CmsEntityOperation.Create);
serviceContext.AddObject(relatedEntity);
serviceContext.AddLink(relatedEntity, relationship, entity);
serviceProvider.InterceptExtensionChange(context, portal, serviceContext, relatedEntity, relatedEntityMetadata, extensions, CmsEntityOperation.Create);
serviceContext.SaveChanges();
var refetchedEntity = serviceContext.CreateQuery(relatedEntity.LogicalName)
.FirstOrDefault(e => e.GetAttributeValue<Guid>(relatedEntityMetadata.PrimaryIdAttribute) == relatedEntity.Id);
if (refetchedEntity == null)
{
throw new CmsEntityServiceException(HttpStatusCode.InternalServerError, "Unable to retrieve the created entity.");
}
WriteResponse(context.Response, new JObject
{
{ "d", GetEntityJson(context, serviceProvider, portalScopeId, portal, serviceContext, refetchedEntity, relatedEntityMetadata) }
}, HttpStatusCode.Created);
}
return;
}
throw new CmsEntityServiceException(HttpStatusCode.MethodNotAllowed, "Request method {0} not allowed for this resource.".FormatWith(context.Request.HttpMethod));
}
private static Entity CreateEntityOfType(OrganizationServiceContext serviceContext, string entityLogicalName)
{
EntitySetInfo entitySetInfo;
if (OrganizationServiceContextInfo.TryGet(serviceContext.GetType(), entityLogicalName, out entitySetInfo))
{
try
{
return (Entity)Activator.CreateInstance(entitySetInfo.Entity.EntityType);
}
catch
{
return new Entity(entityLogicalName);
}
}
return new Entity(entityLogicalName);
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Management.Automation.Internal;
namespace System.Management.Automation
{
/// <summary>
/// Implements the help provider for alias help.
/// </summary>
/// <remarks>
/// Unlike other help providers, AliasHelpProvider directly inherits from HelpProvider
/// instead of HelpProviderWithCache. This is because alias can be created/removed/updated
/// in a Microsoft Command Shell session. And thus caching may result in old alias being cached.
///
/// The real information for alias is stored in command help. To retrieve the real
/// help information, help forwarding is needed.
/// </remarks>
internal class AliasHelpProvider : HelpProvider
{
/// <summary>
/// Initializes a new instance of AliasHelpProvider class.
/// </summary>
internal AliasHelpProvider(HelpSystem helpSystem) : base(helpSystem)
{
_sessionState = helpSystem.ExecutionContext.SessionState;
_commandDiscovery = helpSystem.ExecutionContext.CommandDiscovery;
_context = helpSystem.ExecutionContext;
}
private readonly ExecutionContext _context;
/// <summary>
/// Session state for current Microsoft Command Shell session.
/// </summary>
/// <remarks>
/// _sessionState is mainly used for alias help search in the case
/// of wildcard search patterns. This is currently not achievable
/// through _commandDiscovery.
/// </remarks>
private readonly SessionState _sessionState;
/// <summary>
/// Command Discovery object for current session.
/// </summary>
/// <remarks>
/// _commandDiscovery is mainly used for exact match help for alias.
/// The AliasInfo object returned from _commandDiscovery is essential
/// in creating AliasHelpInfo.
/// </remarks>
private readonly CommandDiscovery _commandDiscovery;
#region Common Properties
/// <summary>
/// Name of alias help provider.
/// </summary>
/// <value>Name of alias help provider</value>
internal override string Name
{
get
{
return "Alias Help Provider";
}
}
/// <summary>
/// Help category of alias help provider, which is a constant: HelpCategory.Alias.
/// </summary>
/// <value>Help category of alias help provider.</value>
internal override HelpCategory HelpCategory
{
get
{
return HelpCategory.Alias;
}
}
#endregion
#region Help Provider Interface
/// <summary>
/// Exact match an alias help target.
/// </summary>
/// <remarks>
/// This will
/// a. use _commandDiscovery object to retrieve AliasInfo object.
/// b. Create AliasHelpInfo object based on AliasInfo object
/// </remarks>
/// <param name="helpRequest">Help request object.</param>
/// <returns>Help info found.</returns>
internal override IEnumerable<HelpInfo> ExactMatchHelp(HelpRequest helpRequest)
{
CommandInfo commandInfo = null;
try
{
commandInfo = _commandDiscovery.LookupCommandInfo(helpRequest.Target);
}
catch (CommandNotFoundException)
{
// CommandNotFoundException is expected here if target doesn't match any
// commandlet. Just ignore this exception and bail out.
}
if ((commandInfo != null) && (commandInfo.CommandType == CommandTypes.Alias))
{
AliasInfo aliasInfo = (AliasInfo)commandInfo;
HelpInfo helpInfo = AliasHelpInfo.GetHelpInfo(aliasInfo);
if (helpInfo != null)
{
yield return helpInfo;
}
}
}
/// <summary>
/// Search an alias help target.
/// </summary>
/// <remarks>
/// This will,
/// a. use _sessionState object to get a list of alias that match the target.
/// b. for each alias, retrieve help info as in ExactMatchHelp.
/// </remarks>
/// <param name="helpRequest">Help request object.</param>
/// <param name="searchOnlyContent">
/// If true, searches for pattern in the help content. Individual
/// provider can decide which content to search in.
///
/// If false, searches for pattern in the command names.
/// </param>
/// <returns>A IEnumerable of helpinfo object.</returns>
internal override IEnumerable<HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent)
{
// aliases do not have help content...so doing nothing in that case
if (!searchOnlyContent)
{
string target = helpRequest.Target;
string pattern = target;
var allAliases = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (!WildcardPattern.ContainsWildcardCharacters(target))
{
pattern += "*";
}
WildcardPattern matcher = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
IDictionary<string, AliasInfo> aliasTable = _sessionState.Internal.GetAliasTable();
foreach (string name in aliasTable.Keys)
{
if (matcher.IsMatch(name))
{
HelpRequest exactMatchHelpRequest = helpRequest.Clone();
exactMatchHelpRequest.Target = name;
// Duplicates??
foreach (HelpInfo helpInfo in ExactMatchHelp(exactMatchHelpRequest))
{
// Component/Role/Functionality match is done only for SearchHelp
// as "get-help * -category alias" should not forwad help to
// CommandHelpProvider..(ExactMatchHelp does forward help to
// CommandHelpProvider)
if (!Match(helpInfo, helpRequest))
{
continue;
}
if (allAliases.Contains(name))
{
continue;
}
allAliases.Add(name);
yield return helpInfo;
}
}
}
CommandSearcher searcher =
new CommandSearcher(
pattern,
SearchResolutionOptions.ResolveAliasPatterns, CommandTypes.Alias,
_context);
while (searcher.MoveNext())
{
CommandInfo current = ((IEnumerator<CommandInfo>)searcher).Current;
if (_context.CurrentPipelineStopping)
{
yield break;
}
AliasInfo alias = current as AliasInfo;
if (alias != null)
{
string name = alias.Name;
HelpRequest exactMatchHelpRequest = helpRequest.Clone();
exactMatchHelpRequest.Target = name;
// Duplicates??
foreach (HelpInfo helpInfo in ExactMatchHelp(exactMatchHelpRequest))
{
// Component/Role/Functionality match is done only for SearchHelp
// as "get-help * -category alias" should not forwad help to
// CommandHelpProvider..(ExactMatchHelp does forward help to
// CommandHelpProvider)
if (!Match(helpInfo, helpRequest))
{
continue;
}
if (allAliases.Contains(name))
{
continue;
}
allAliases.Add(name);
yield return helpInfo;
}
}
}
foreach (CommandInfo current in ModuleUtils.GetMatchingCommands(pattern, _context, helpRequest.CommandOrigin))
{
if (_context.CurrentPipelineStopping)
{
yield break;
}
AliasInfo alias = current as AliasInfo;
if (alias != null)
{
string name = alias.Name;
HelpInfo helpInfo = AliasHelpInfo.GetHelpInfo(alias);
if (allAliases.Contains(name))
{
continue;
}
allAliases.Add(name);
yield return helpInfo;
}
}
}
}
private static bool Match(HelpInfo helpInfo, HelpRequest helpRequest)
{
if (helpRequest == null)
return true;
if ((helpRequest.HelpCategory & helpInfo.HelpCategory) == 0)
{
return false;
}
if (!Match(helpInfo.Component, helpRequest.Component))
{
return false;
}
if (!Match(helpInfo.Role, helpRequest.Role))
{
return false;
}
if (!Match(helpInfo.Functionality, helpRequest.Functionality))
{
return false;
}
return true;
}
private static bool Match(string target, string[] patterns)
{
// patterns should never be null as shell never accepts
// empty inputs. Keeping this check as a safe measure.
if (patterns == null || patterns.Length == 0)
return true;
foreach (string pattern in patterns)
{
if (Match(target, pattern))
{
// we have a match so return true
return true;
}
}
// We dont have a match so far..so return false
return false;
}
private static bool Match(string target, string pattern)
{
if (string.IsNullOrEmpty(pattern))
return true;
if (string.IsNullOrEmpty(target))
target = string.Empty;
WildcardPattern matcher = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
return matcher.IsMatch(target);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Linq;
using System.Text;
using Microsoft.AspNetCore.Html;
namespace Orchard.ResourceManagement
{
public class ResourceManager : IResourceManager
{
private readonly Dictionary<ResourceTypeName, RequireSettings> _required = new Dictionary<ResourceTypeName, RequireSettings>();
private readonly Dictionary<string, IList<ResourceRequiredContext>> _builtResources;
private readonly IEnumerable<IResourceManifestProvider> _providers;
private ResourceManifest _dynamicManifest;
private List<LinkEntry> _links;
private Dictionary<string, MetaEntry> _metas;
private List<IHtmlContent> _headScripts;
private List<IHtmlContent> _footScripts;
private readonly IResourceManifestState _resourceManifestState;
public ResourceManager(
IEnumerable<IResourceManifestProvider> resourceProviders,
IResourceManifestState resourceManifestState)
{
_resourceManifestState = resourceManifestState;
_providers = resourceProviders;
_builtResources = new Dictionary<string, IList<ResourceRequiredContext>>(StringComparer.OrdinalIgnoreCase);
}
public IEnumerable<ResourceManifest> ResourceManifests
{
get
{
if (_resourceManifestState.ResourceManifests == null)
{
var builder = new ResourceManifestBuilder();
foreach (var provider in _providers)
{
provider.BuildManifests(builder);
}
_resourceManifestState.ResourceManifests = builder.ResourceManifests;
}
return _resourceManifestState.ResourceManifests;
}
}
public ResourceManifest InlineManifest
{
get
{
if(_dynamicManifest == null)
{
_dynamicManifest = new ResourceManifest();
}
return _dynamicManifest;
}
}
public RequireSettings RegisterResource(string resourceType, string resourceName)
{
if (resourceType == null)
{
throw new ArgumentNullException(nameof(resourceType));
}
if (resourceName == null)
{
throw new ArgumentNullException(nameof(resourceName));
}
RequireSettings settings;
var key = new ResourceTypeName(resourceType, resourceName);
if (!_required.TryGetValue(key, out settings))
{
settings = new RequireSettings { Type = resourceType, Name = resourceName };
_required[key] = settings;
}
_builtResources[resourceType] = null;
return settings;
}
public RequireSettings Include(string resourceType, string resourcePath, string resourceDebugPath)
{
return RegisterUrl(resourceType, resourcePath, resourceDebugPath, null);
}
public RequireSettings RegisterUrl(string resourceType, string resourcePath, string resourceDebugPath, string relativeFromPath)
{
if (resourceType == null)
{
throw new ArgumentNullException(nameof(resourceType));
}
if (resourcePath == null)
{
throw new ArgumentNullException(nameof(resourcePath));
}
// ~/ ==> convert to absolute path (e.g. /orchard/..)
if (resourcePath.StartsWith("~/", StringComparison.Ordinal))
{
// For tilde slash paths, drop the leading ~ to make it work with the underlying IFileProvider.
resourcePath = resourcePath.Substring(1);
}
if (resourceDebugPath != null && resourceDebugPath.StartsWith("~/", StringComparison.Ordinal))
{
// For tilde slash paths, drop the leading ~ to make it work with the underlying IFileProvider.
resourceDebugPath = resourceDebugPath.Substring(1);
}
return RegisterResource(resourceType, resourcePath).Define(d => d.SetUrl(resourcePath, resourceDebugPath));
}
public void RegisterHeadScript(IHtmlContent script)
{
if (_headScripts == null)
{
_headScripts = new List<IHtmlContent>();
}
_headScripts.Add(script);
}
public void RegisterFootScript(IHtmlContent script)
{
if (_footScripts == null)
{
_footScripts = new List<IHtmlContent>();
}
_footScripts.Add(script);
}
public void NotRequired(string resourceType, string resourceName)
{
if (resourceType == null)
{
throw new ArgumentNullException(nameof(resourceType));
}
if (resourceName == null)
{
throw new ArgumentNullException(nameof(resourceName));
}
var key = new ResourceTypeName(resourceType, resourceName);
_builtResources[resourceType] = null;
_required.Remove(key);
}
public ResourceDefinition FindResource(RequireSettings settings)
{
return FindResource(settings, true);
}
private ResourceDefinition FindResource(RequireSettings settings, bool resolveInlineDefinitions)
{
// find the resource with the given type and name
// that has at least the given version number. If multiple,
// return the resource with the greatest version number.
// If not found and an inlineDefinition is given, define the resource on the fly
// using the action.
var name = settings.Name ?? "";
var type = settings.Type;
ResourceDefinition resource;
var resources = (from p in ResourceManifests
from r in p.GetResources(type)
where name.Equals(r.Key, StringComparison.OrdinalIgnoreCase)
select r.Value).SelectMany(x => x);
if(!String.IsNullOrEmpty(settings.Version))
{
// Specific version, filter
var upper = GetUpperBoundVersion(new Version(settings.Version));
resources = from r in resources
let version = r.Version != null ? new Version(r.Version) : null
where version < upper
select r;
}
resource = (from r in resources
let version = r.Version != null ? new Version(r.Version) : null
orderby version descending
select r).FirstOrDefault();
if (resource == null && _dynamicManifest != null)
{
resources = (from r in _dynamicManifest.GetResources(type)
where name.Equals(r.Key, StringComparison.OrdinalIgnoreCase)
select r.Value).SelectMany(x => x);
if (!String.IsNullOrEmpty(settings.Version))
{
// Specific version, filter
var upper = GetUpperBoundVersion(new Version(settings.Version));
resources = from r in resources
let version = r.Version != null ? new Version(r.Version) : null
where version < upper
select r;
}
resource = (from r in resources
let version = r.Version != null ? new Version(r.Version) : null
orderby version descending
select r).FirstOrDefault();
}
if (resolveInlineDefinitions && resource == null)
{
// Does not seem to exist, but it's possible it is being
// defined by a Define() from a RequireSettings somewhere.
if (ResolveInlineDefinitions(settings.Type))
{
// if any were defined, now try to find it
resource = FindResource(settings, false);
}
}
return resource;
}
private Version GetUpperBoundVersion(Version version)
{
if (version.Build != 0)
{
return new Version(version.Major, version.Minor, version.Build + 1);
}
if (version.Minor != 0)
{
return new Version(version.Major, version.Minor + 1, 0);
}
if (version.Major != 0)
{
return new Version(version.Major + 1, 0, 0);
}
return version;
}
private bool ResolveInlineDefinitions(string resourceType)
{
bool anyWereDefined = false;
foreach (var settings in ResolveRequiredResources(resourceType).Where(settings => settings.InlineDefinition != null))
{
// defining it on the fly
var resource = FindResource(settings, false);
if (resource == null)
{
// does not already exist, so define it
resource = InlineManifest.DefineResource(resourceType, settings.Name).SetBasePath(settings.BasePath);
anyWereDefined = true;
}
settings.InlineDefinition(resource);
settings.InlineDefinition = null;
}
return anyWereDefined;
}
private IEnumerable<RequireSettings> ResolveRequiredResources(string resourceType)
{
return _required.Where(r => r.Key.Type == resourceType).Select(r => r.Value);
}
public IEnumerable<LinkEntry> GetRegisteredLinks()
{
if (_links == null)
{
return Enumerable.Empty<LinkEntry>();
}
return _links.AsReadOnly();
}
public IEnumerable<MetaEntry> GetRegisteredMetas()
{
if(_metas == null)
{
return Enumerable.Empty<MetaEntry>();
}
return _metas.Values;
}
public IEnumerable<IHtmlContent> GetRegisteredHeadScripts()
{
return _headScripts == null ? Enumerable.Empty<IHtmlContent>() : _headScripts;
}
public IEnumerable<IHtmlContent> GetRegisteredFootScripts()
{
return _footScripts == null ? Enumerable.Empty<IHtmlContent>() : _footScripts;
}
public IEnumerable<ResourceRequiredContext> GetRequiredResources(string resourceType)
{
IList<ResourceRequiredContext> requiredResources;
if (_builtResources.TryGetValue(resourceType, out requiredResources) && requiredResources != null)
{
return requiredResources;
}
var allResources = new OrderedDictionary();
foreach (var settings in ResolveRequiredResources(resourceType))
{
var resource = FindResource(settings);
if (resource == null)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, "A '{1}' named '{0}' could not be found.", settings.Name, settings.Type));
}
ExpandDependencies(resource, settings, allResources);
}
requiredResources = (from DictionaryEntry entry in allResources
select new ResourceRequiredContext { Resource = (ResourceDefinition)entry.Key, Settings = (RequireSettings)entry.Value }).ToList();
_builtResources[resourceType] = requiredResources;
return requiredResources;
}
protected virtual void ExpandDependencies(ResourceDefinition resource, RequireSettings settings, OrderedDictionary allResources)
{
if (resource == null)
{
return;
}
// Settings is given so they can cascade down into dependencies. For example, if Foo depends on Bar, and Foo's required
// location is Head, so too should Bar's location.
// forge the effective require settings for this resource
// (1) If a require exists for the resource, combine with it. Last settings in gets preference for its specified values.
// (2) If no require already exists, form a new settings object based on the given one but with its own type/name.
settings = allResources.Contains(resource)
? ((RequireSettings)allResources[resource]).Combine(settings)
: new RequireSettings { Type = resource.Type, Name = resource.Name }.Combine(settings);
if (resource.Dependencies != null)
{
var dependencies = from d in resource.Dependencies
let segments = d.Split('-')
let name = segments[0]
let version = segments.Length > 1 ? segments[1] : null
select FindResource(new RequireSettings { Type = resource.Type, Name = name, Version = version });
foreach (var dependency in dependencies)
{
if (dependency == null)
{
continue;
}
ExpandDependencies(dependency, settings, allResources);
}
}
allResources[resource] = settings;
}
public void RegisterLink(LinkEntry link)
{
if(_links == null)
{
_links = new List<LinkEntry>();
}
_links.Add(link);
}
public void RegisterMeta(MetaEntry meta)
{
if (meta == null)
{
return;
}
if(_metas == null)
{
_metas = new Dictionary<string, MetaEntry>();
}
var index = meta.Name ?? meta.HttpEquiv ?? "charset";
_metas[index] = meta;
}
public void AppendMeta(MetaEntry meta, string contentSeparator)
{
if (meta == null)
{
return;
}
var index = meta.Name ?? meta.HttpEquiv;
if (String.IsNullOrEmpty(index))
{
return;
}
if (_metas == null)
{
_metas = new Dictionary<string, MetaEntry>();
}
MetaEntry existingMeta;
if (_metas.TryGetValue(index, out existingMeta))
{
meta = MetaEntry.Combine(existingMeta, meta, contentSeparator);
}
_metas[index] = meta;
}
public IHtmlContent RenderMeta()
{
var htmlBuilder = new HtmlContentBuilder();
var first = true;
foreach (var meta in this.GetRegisteredMetas())
{
if (!first)
{
htmlBuilder.AppendHtml(Environment.NewLine);
}
first = false;
htmlBuilder.AppendHtml(meta.GetTag());
}
return htmlBuilder;
}
public IHtmlContent RenderHeadLink()
{
var htmlBuilder = new HtmlContentBuilder();
var first = true;
foreach (var link in this.GetRegisteredLinks())
{
if (!first)
{
htmlBuilder.AppendHtml(Environment.NewLine);
}
first = false;
htmlBuilder.AppendHtml(link.GetTag());
}
return htmlBuilder;
}
public IHtmlContent RenderStylesheet(RequireSettings settings)
{
var htmlBuilder = new HtmlContentBuilder();
var first = true;
var styleSheets = this.GetRequiredResources("stylesheet");
foreach (var context in styleSheets)
{
if (!first)
{
htmlBuilder.AppendHtml(Environment.NewLine);
}
first = false;
htmlBuilder.AppendHtml(context.GetHtmlContent(settings, "/"));
}
return htmlBuilder;
}
public IHtmlContent RenderHeadScript(RequireSettings settings)
{
var htmlBuilder = new HtmlContentBuilder();
var headScripts = this.GetRequiredResources("script");
var first = true;
foreach (var context in headScripts.Where(r => r.Settings.Location == ResourceLocation.Head))
{
if (!first)
{
htmlBuilder.AppendHtml(Environment.NewLine);
}
first = false;
htmlBuilder.AppendHtml(context.GetHtmlContent(settings, "/"));
}
foreach (var context in GetRegisteredHeadScripts())
{
if (!first)
{
htmlBuilder.AppendHtml(Environment.NewLine);
}
first = false;
htmlBuilder.AppendHtml(context);
}
return htmlBuilder;
}
public IHtmlContent RenderFootScript(RequireSettings settings)
{
var htmlBuilder = new HtmlContentBuilder();
var footScripts = this.GetRequiredResources("script");
var first = true;
foreach (var context in footScripts.Where(r => r.Settings.Location == ResourceLocation.Foot))
{
if (!first)
{
htmlBuilder.AppendHtml(Environment.NewLine);
}
first = false;
htmlBuilder.AppendHtml(context.GetHtmlContent(settings, "/"));
}
foreach (var context in GetRegisteredFootScripts())
{
if (!first)
{
htmlBuilder.AppendHtml(Environment.NewLine);
}
first = false;
htmlBuilder.AppendHtml(context);
}
return htmlBuilder;
}
private class ResourceTypeName : IEquatable<ResourceTypeName>
{
private readonly string _type;
private readonly string _name;
public string Type { get { return _type; } }
public string Name { get { return _name; } }
public ResourceTypeName(string resourceType, string resourceName)
{
_type = resourceType;
_name = resourceName;
}
public bool Equals(ResourceTypeName other)
{
if (other == null)
{
return false;
}
return _type.Equals(other._type) && _name.Equals(other._name);
}
public override int GetHashCode()
{
return _type.GetHashCode() << 17 + _name.GetHashCode();
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("(");
sb.Append(_type);
sb.Append(", ");
sb.Append(_name);
sb.Append(")");
return sb.ToString();
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;
/// <summary>
/// User Profile Class
/// </summary>
public class UserProfile
{
public Profile profile;
public string profileName;
public UserProfile()
{
profile = new Profile();
profileName = "";
}
}
public class EmoProfileManagement : MonoBehaviour
{
//----------------------------------------
EmoEngine engine = EmoEngine.Instance;
public static int currentIndex = 0;
static ArrayList userProfiles = new ArrayList();
//----------------------------------------
//-------Added by Daniela Florescu 15 Nov 2014: implement persistent singleton(http://unitypatterns.com/singletons/)------------------
private static EmoProfileManagement _instance;
public static EmoProfileManagement Instance
{
get
{
if (_instance == null)
{
_instance = GameObject.FindObjectOfType<EmoProfileManagement>();
DontDestroyOnLoad(_instance.gameObject);
}
return _instance;
}
}
void Awake()
{
if (_instance == null)
{
_instance = this;
DontDestroyOnLoad(this);
}
else
{
if (this != _instance)
Destroy (this.gameObject);
}
}
//--end addition------------------------------------
/// <summary>
/// Function to save byte array to a file
/// </summary>
/// <param name="_FileName">File name to save byte array</param>
/// <param name="_ByteArray">Byte array to save to external file</param>
/// <returns>Return true if byte array save successfully, if not return false</returns>
public bool ByteArrayToFile(string _FileName, byte[] _ByteArray)
{
try
{
System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
_FileStream.Write(_ByteArray, 0, _ByteArray.Length);
_FileStream.Close();
return true;
}catch (Exception _Exception){
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());}return false;
}
/// <summary>
/// Save all profiles in arraylist to file
/// </summary>
public void SaveProfilesToFile()
{
Debug.Log("Save file");
//---------------------
string mStr = System.IO.Directory.GetCurrentDirectory();
if (!System.IO.Directory.Exists(mStr + @"/EmotivUserProfile"))
{
System.IO.Directory.CreateDirectory(mStr + @"/EmotivUserProfile");
}
System.IO.Directory.SetCurrentDirectory(mStr + @"/EmotivUserProfile");
for (int i = 0; i < userProfiles.Count; i++)
{
UserProfile tmp = (UserProfile)userProfiles[i];
ByteArrayToFile(tmp.profileName + ".up", tmp.profile.GetBytes());
}
System.IO.Directory.SetCurrentDirectory(mStr);
}
/// <summary>
/// Get Profile List
/// </summary>
/// <returns></returns>
public static string[] GetProfileList()
{
string mStr = System.IO.Directory.GetCurrentDirectory();
if (!System.IO.Directory.Exists(mStr + @"/EmotivUserProfile"))
{
System.IO.Directory.CreateDirectory(mStr + @"/EmotivUserProfile");
}
mStr += @"/EmotivUserProfile";
string[] strArrFiles = System.IO.Directory.GetFiles(mStr, "*.up");
for (int i = 0; i < strArrFiles.Length; i++)
{
strArrFiles[i] = strArrFiles[i].Substring(0, strArrFiles[i].Length - 3);
strArrFiles[i] = Path.GetFileName(strArrFiles[i]);
}
return strArrFiles;
}
/// <summary>
/// Load all profile file in EmotivUserProfile folder into arraylist
/// </summary>
public void LoadProfilesFromFile()
{
Debug.Log("Load file");
//---------------------
string mStr = System.IO.Directory.GetCurrentDirectory();
if (!System.IO.Directory.Exists(mStr + @"/EmotivUserProfile"))
{
System.IO.Directory.CreateDirectory(mStr + @"/EmotivUserProfile");
}
mStr += @"/EmotivUserProfile";
string[] strArrFiles = System.IO.Directory.GetFiles(mStr, "*.up");
for (int i = 0; i < strArrFiles.Length; i++)
{
System.IO.FileStream _FileStream = new System.IO.FileStream(strArrFiles[i], System.IO.FileMode.Open, System.IO.FileAccess.Read);
Byte[] buffer = new Byte[_FileStream.Length];
_FileStream.Read(buffer, 0,(int)_FileStream.Length);
_FileStream.Close();
engine.SetUserProfile((uint)EmoUserManagement.currentUser, buffer);
UserProfile tmp = new UserProfile();
tmp.profileName = strArrFiles[i].Substring(0, strArrFiles[i].Length -3);
tmp.profileName = Path.GetFileName(tmp.profileName);
tmp.profile = engine.GetUserProfile((uint)EmoUserManagement.currentUser);
userProfiles.Add(tmp);
}
}
/// <summary>
/// Set user profile , remember to save current profile before or lose it
/// </summary>
/// <param name="prName">Profile Name</param>
/// <returns>Return false if no profile with this name</returns>
public Boolean SetUserProfile(string prName)
{
int i = FindProfileName(prName);
if (i != userProfiles.Count)
{
UserProfile tmp = (UserProfile)userProfiles[i];
engine.SetUserProfile((uint)EmoUserManagement.currentUser, tmp.profile);
currentIndex = i;
Debug.Log(prName);
EmoCognitiv.cognitivActionsEnabled = CheckCurrentProfile();
return true;
}
else
{
Debug.Log("Set user profile failed");
return false;
}// have no profile with this name
}
/// <summary>
/// Find index of profile in arraylist
/// </summary>
/// <param name="prName">Profile Name</param>
/// <returns></returns>
int FindProfileName(string prName)
{
int i = 0;
Boolean IsFound = false;
while ((!IsFound)&&(i<userProfiles.Count))
{
UserProfile tmp = (UserProfile) userProfiles[i];
if (prName == tmp.profileName)
{
IsFound = true;
}else i++;
}
return i;
}
/// <summary>
/// Add new profile into arraylist , set this profile to current user
/// </summary>
/// <param name="prName"></param>
/// <returns></returns>
public Boolean AddNewProfile(string prName)
{
Debug.Log("add new profile");
if (FindProfileName(prName) == userProfiles.Count )
{
if(userProfiles.Count > 0 ) SaveCurrentProfile();
UserProfile tmp = new UserProfile();
tmp.profileName = prName;
currentIndex = 0;
userProfiles.Insert(currentIndex, tmp);
engine.SetUserProfile((uint)EmoUserManagement.currentUser, tmp.profile);
SaveCurrentProfile();
//check current profile
EmoCognitiv.cognitivActionsEnabled = CheckCurrentProfile();
return true;
}
else
{
Debug.Log("Already have this profile name");
return false;//Already have this profile name
}
}
/// <summary>
/// Back up current profile of current user into arraylist
/// </summary>
public void SaveCurrentProfile()
{
UserProfile tmp = (UserProfile)userProfiles[currentIndex];
tmp.profile = engine.GetUserProfile((uint)EmoUserManagement.currentUser);
userProfiles.RemoveAt(currentIndex);
userProfiles.Insert(currentIndex, tmp);
}
/// <summary>
/// Delete a profile in arraylist
/// </summary>
/// <param name="prName"></param>
/// <returns></returns>
public Boolean DeleteProfile(string prName)
{
int i = FindProfileName(prName);
if (i != userProfiles.Count + 1)
{
userProfiles.RemoveAt(i);
if ( i== currentIndex)
{
if (currentIndex > 0)
{
currentIndex--;
}
}
return true;
}
else return false;// have no profile with this name
}
/// <summary>
/// Get a profile name in arraylist
/// </summary>
/// <param name="profileIndex">Index of a profile</param>
/// <returns></returns>
public static string GetProfileName(int profileIndex)
{
if (profileIndex < userProfiles.Count)
{
UserProfile tmp = (UserProfile)userProfiles[profileIndex];
return tmp.profileName;
}
else return null;
}
/// <summary>
/// Get number of profile in arraylist
/// </summary>
/// <returns>Arraylist size</returns>
public static int GetProfilesArraySize()
{
return userProfiles.Count;
}
public static void ClearProfileList()
{
userProfiles.Clear();
currentIndex = 0;
}
void Start()
{
}
//test
//public int numOfProfile;
//public string currentDir;
//void Update()
//{
// numOfProfile = GetProfilesArraySize();
// currentDir = System.IO.Directory.GetCurrentDirectory();
//}
public static bool[] CheckCurrentProfile()
{
uint temp;
EdkDll.EE_CognitivGetActiveActions((uint)EmoUserManagement.currentUser,out temp);
string test = Convert.ToString(temp, 2);
// Debug.Log("CheckCurrentProfile test: " + temp);
bool[] actionLever = new bool[EmoCognitiv.cognitivActionList.Length];
for (int i = 0; i < EmoCognitiv.cognitivActionList.Length; i++ )
{
actionLever[i] = false;
}
for (int i = test.Length -1; i >= 0 ;i-- )
{
//if (test[i] == '0')
//{
// actionLever[test.Length - i -1] = false;
//}
if (test[i] == '1')
{
actionLever[test.Length - i -1] = true;
}
}
return actionLever;
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace Mono.Cecil.Pdb {
// WARNING: most methods should be reworked into PreserveSig methods
[ComImport, InterfaceType (ComInterfaceType.InterfaceIsIUnknown), Guid ("BA3FEE4C-ECB9-4e41-83B7-183FA41CD859")]
unsafe interface IMetaDataEmit {
void SetModuleProps (string szName);
void Save (string szFile, uint dwSaveFlags);
void SaveToStream (IntPtr pIStream, uint dwSaveFlags);
uint GetSaveSize (uint fSave);
uint DefineTypeDef (IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements);
uint DefineNestedType (IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements, uint tdEncloser);
void SetHandler ([MarshalAs (UnmanagedType.IUnknown), In]object pUnk);
uint DefineMethod (uint td, IntPtr zName, uint dwMethodFlags, IntPtr pvSigBlob, uint cbSigBlob, uint ulCodeRVA, uint dwImplFlags);
void DefineMethodImpl (uint td, uint tkBody, uint tkDecl);
uint DefineTypeRefByName (uint tkResolutionScope, IntPtr szName);
uint DefineImportType (IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport,
uint tdImport, IntPtr pAssemEmit);
uint DefineMemberRef (uint tkImport, string szName, IntPtr pvSigBlob, uint cbSigBlob);
uint DefineImportMember (IntPtr pAssemImport, IntPtr /* void* */ pbHashValue, uint cbHashValue,
IMetaDataImport pImport, uint mbMember, IntPtr pAssemEmit, uint tkParent);
uint DefineEvent (uint td, string szEvent, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr /* uint* */ rmdOtherMethods);
void SetClassLayout (uint td, uint dwPackSize, IntPtr /*COR_FIELD_OFFSET**/ rFieldOffsets, uint ulClassSize);
void DeleteClassLayout (uint td);
void SetFieldMarshal (uint tk, IntPtr /* byte* */ pvNativeType, uint cbNativeType);
void DeleteFieldMarshal (uint tk);
uint DefinePermissionSet (uint tk, uint dwAction, IntPtr /* void* */ pvPermission, uint cbPermission);
void SetRVA (uint md, uint ulRVA);
uint GetTokenFromSig (IntPtr /* byte* */ pvSig, uint cbSig);
uint DefineModuleRef (string szName);
void SetParent (uint mr, uint tk);
uint GetTokenFromTypeSpec (IntPtr /* byte* */ pvSig, uint cbSig);
void SaveToMemory (IntPtr /* void* */ pbData, uint cbData);
uint DefineUserString (string szString, uint cchString);
void DeleteToken (uint tkObj);
void SetMethodProps (uint md, uint dwMethodFlags, uint ulCodeRVA, uint dwImplFlags);
void SetTypeDefProps (uint td, uint dwTypeDefFlags, uint tkExtends, IntPtr /* uint* */ rtkImplements);
void SetEventProps (uint ev, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr /* uint* */ rmdOtherMethods);
uint SetPermissionSetProps (uint tk, uint dwAction, IntPtr /* void* */ pvPermission, uint cbPermission);
void DefinePinvokeMap (uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL);
void SetPinvokeMap (uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL);
void DeletePinvokeMap (uint tk);
uint DefineCustomAttribute (uint tkObj, uint tkType, IntPtr /* void* */ pCustomAttribute, uint cbCustomAttribute);
void SetCustomAttributeValue (uint pcv, IntPtr /* void* */ pCustomAttribute, uint cbCustomAttribute);
uint DefineField (uint td, string szName, uint dwFieldFlags, IntPtr /* byte* */ pvSigBlob, uint cbSigBlob, uint dwCPlusTypeFlag, IntPtr /* void* */ pValue, uint cchValue);
uint DefineProperty (uint td, string szProperty, uint dwPropFlags, IntPtr /* byte* */ pvSig, uint cbSig, uint dwCPlusTypeFlag,
IntPtr /* void* */ pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr /* uint* */ rmdOtherMethods);
uint DefineParam (uint md, uint ulParamSeq, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr /* void* */ pValue, uint cchValue);
void SetFieldProps (uint fd, uint dwFieldFlags, uint dwCPlusTypeFlag, IntPtr /* void* */ pValue, uint cchValue);
void SetPropertyProps (uint pr, uint dwPropFlags, uint dwCPlusTypeFlag, IntPtr /* void* */ pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr /* uint* */ rmdOtherMethods);
void SetParamProps (uint pd, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr /* void* */ pValue, uint cchValue);
uint DefineSecurityAttributeSet (uint tkObj, IntPtr rSecAttrs, uint cSecAttrs);
void ApplyEditAndContinue ([MarshalAs (UnmanagedType.IUnknown)]object pImport);
uint TranslateSigWithScope (IntPtr pAssemImport, IntPtr /* void* */ pbHashValue, uint cbHashValue,
IMetaDataImport import, IntPtr /* byte* */ pbSigBlob, uint cbSigBlob, IntPtr pAssemEmit, IMetaDataEmit emit, IntPtr /* byte* */ pvTranslatedSig, uint cbTranslatedSigMax);
void SetMethodImplFlags (uint md, uint dwImplFlags);
void SetFieldRVA (uint fd, uint ulRVA);
void Merge (IMetaDataImport pImport, IntPtr pHostMapToken, [MarshalAs (UnmanagedType.IUnknown)]object pHandler);
void MergeEnd ();
}
[ComImport, InterfaceType (ComInterfaceType.InterfaceIsIUnknown), Guid ("7DAC8207-D3AE-4c75-9B67-92801A497D44")]
unsafe interface IMetaDataImport {
[PreserveSig]
void CloseEnum (uint hEnum);
uint CountEnum (uint hEnum);
void ResetEnum (uint hEnum, uint ulPos);
uint EnumTypeDefs (ref uint phEnum, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 2)] uint [] rTypeDefs, uint cMax);
uint EnumInterfaceImpls (ref uint phEnum, uint td, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] uint [] rImpls, uint cMax);
uint EnumTypeRefs (ref uint phEnum, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 2)] uint [] rTypeRefs, uint cMax);
uint FindTypeDefByName (string szTypeDef, uint tkEnclosingClass);
Guid GetScopeProps (StringBuilder szName, uint cchName, out uint pchName);
uint GetModuleFromScope ();
[PreserveSig]
uint GetTypeDefProps (uint td, char* szTypeDef, uint cchTypeDef, uint* pchTypeDef, uint* pdwTypeDefFlags, uint* ptkExtends);
uint GetInterfaceImplProps (uint iiImpl, out uint pClass);
uint GetTypeRefProps (uint tr, out uint ptkResolutionScope, StringBuilder szName, uint cchName);
uint ResolveTypeRef (uint tr, [In] ref Guid riid, [MarshalAs (UnmanagedType.Interface)] out object ppIScope);
uint EnumMembers (ref uint phEnum, uint cl, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] uint [] rMembers, uint cMax);
uint EnumMembersWithName (ref uint phEnum, uint cl, string szName, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 4)] uint [] rMembers, uint cMax);
uint EnumMethods (ref uint phEnum, uint cl, IntPtr /* uint* */ rMethods, uint cMax);
uint EnumMethodsWithName (ref uint phEnum, uint cl, string szName, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 4)] uint [] rMethods, uint cMax);
uint EnumFields (ref uint phEnum, uint cl, IntPtr /* uint* */ rFields, uint cMax);
uint EnumFieldsWithName (ref uint phEnum, uint cl, string szName, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 4)] uint [] rFields, uint cMax);
uint EnumParams (ref uint phEnum, uint mb, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] uint [] rParams, uint cMax);
uint EnumMemberRefs (ref uint phEnum, uint tkParent, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] uint [] rMemberRefs, uint cMax);
uint EnumMethodImpls (ref uint phEnum, uint td, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 4)] uint [] rMethodBody,
[MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 4)] uint [] rMethodDecl, uint cMax);
uint EnumPermissionSets (ref uint phEnum, uint tk, uint dwActions, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 4)] uint [] rPermission,
uint cMax);
uint FindMember (uint td, string szName, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] byte [] pvSigBlob, uint cbSigBlob);
uint FindMethod (uint td, string szName, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] byte [] pvSigBlob, uint cbSigBlob);
uint FindField (uint td, string szName, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] byte [] pvSigBlob, uint cbSigBlob);
uint FindMemberRef (uint td, string szName, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] byte [] pvSigBlob, uint cbSigBlob);
[PreserveSig]
uint GetMethodProps (uint mb, uint* pClass, char* szMethod, uint cchMethod, uint* pchMethod, uint* pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, uint* pulCodeRVA, uint* pdwImplFlags);
uint GetMemberRefProps (uint mr, ref uint ptk, StringBuilder szMember, uint cchMember, out uint pchMember, out IntPtr /* byte* */ ppvSigBlob);
uint EnumProperties (ref uint phEnum, uint td, IntPtr /* uint* */ rProperties, uint cMax);
uint EnumEvents (ref uint phEnum, uint td, IntPtr /* uint* */ rEvents, uint cMax);
uint GetEventProps (uint ev, out uint pClass, StringBuilder szEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags,
out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire,
[MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 11)] uint [] rmdOtherMethod, uint cMax);
uint EnumMethodSemantics (ref uint phEnum, uint mb, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] uint [] rEventProp, uint cMax);
uint GetMethodSemantics (uint mb, uint tkEventProp);
uint GetClassLayout (uint td, out uint pdwPackSize, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 3)] IntPtr /*COR_FIELD_OFFSET **/ rFieldOffset, uint cMax, out uint pcFieldOffset);
uint GetFieldMarshal (uint tk, out IntPtr /* byte* */ ppvNativeType);
uint GetRVA (uint tk, out uint pulCodeRVA);
uint GetPermissionSetProps (uint pm, out uint pdwAction, out IntPtr /* void* */ ppvPermission);
uint GetSigFromToken (uint mdSig, out IntPtr /* byte* */ ppvSig);
uint GetModuleRefProps (uint mur, StringBuilder szName, uint cchName);
uint EnumModuleRefs (ref uint phEnum, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 2)] uint [] rModuleRefs, uint cmax);
uint GetTypeSpecFromToken (uint typespec, out IntPtr /* byte* */ ppvSig);
uint GetNameFromToken (uint tk);
uint EnumUnresolvedMethods (ref uint phEnum, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 2)] uint [] rMethods, uint cMax);
uint GetUserString (uint stk, StringBuilder szString, uint cchString);
uint GetPinvokeMap (uint tk, out uint pdwMappingFlags, StringBuilder szImportName, uint cchImportName, out uint pchImportName);
uint EnumSignatures (ref uint phEnum, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 2)] uint [] rSignatures, uint cmax);
uint EnumTypeSpecs (ref uint phEnum, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 2)] uint [] rTypeSpecs, uint cmax);
uint EnumUserStrings (ref uint phEnum, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 2)] uint [] rStrings, uint cmax);
[PreserveSig]
int GetParamForMethodIndex (uint md, uint ulParamSeq, out uint pParam);
uint EnumCustomAttributes (ref uint phEnum, uint tk, uint tkType, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 4)] uint [] rCustomAttributes, uint cMax);
uint GetCustomAttributeProps (uint cv, out uint ptkObj, out uint ptkType, out IntPtr /* void* */ ppBlob);
uint FindTypeRef (uint tkResolutionScope, string szName);
uint GetMemberProps (uint mb, out uint pClass, StringBuilder szMember, uint cchMember, out uint pchMember, out uint pdwAttr,
out IntPtr /* byte* */ ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out IntPtr /* void* */ ppValue);
uint GetFieldProps (uint mb, out uint pClass, StringBuilder szField, uint cchField, out uint pchField, out uint pdwAttr,
out IntPtr /* byte* */ ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out IntPtr /* void* */ ppValue);
uint GetPropertyProps (uint prop, out uint pClass, StringBuilder szProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags,
out IntPtr /* byte* */ ppvSig, out uint pbSig, out uint pdwCPlusTypeFlag, out IntPtr /* void* */ ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter,
out uint pmdGetter, [MarshalAs (UnmanagedType.LPArray, SizeParamIndex = 14)] uint [] rmdOtherMethod, uint cMax);
uint GetParamProps (uint tk, out uint pmd, out uint pulSequence, StringBuilder szName, uint cchName, out uint pchName,
out uint pdwAttr, out uint pdwCPlusTypeFlag, out IntPtr /* void* */ ppValue);
uint GetCustomAttributeByName (uint tkObj, string szName, out IntPtr /* void* */ ppData);
[PreserveSig]
[return: MarshalAs (UnmanagedType.Bool)]
bool IsValidToken (uint tk);
[PreserveSig]
uint GetNestedClassProps (uint tdNestedClass, uint* ptdEnclosingClass);
uint GetNativeCallConvFromSig (IntPtr /* void* */ pvSig, uint cbSig);
int IsGlobal (uint pd);
}
unsafe class ModuleMetadata : IMetaDataEmit, IMetaDataImport {
readonly ModuleDefinition module;
Dictionary<uint, TypeDefinition> types;
Dictionary<uint, MethodDefinition> methods;
const uint S_OK = 0x00000000;
const uint E_FAIL = 0x80004005;
public ModuleMetadata (ModuleDefinition module)
{
this.module = module;
}
bool TryGetType (uint token, out TypeDefinition type)
{
if (types == null)
InitializeMetadata (module);
return types.TryGetValue (token, out type);
}
bool TryGetMethod (uint token, out MethodDefinition method)
{
if (methods == null)
InitializeMetadata (module);
return methods.TryGetValue (token, out method);
}
void InitializeMetadata (ModuleDefinition module)
{
types = new Dictionary<uint, TypeDefinition> ();
methods = new Dictionary<uint, MethodDefinition> ();
foreach (var type in module.GetTypes ()) {
types.Add (type.MetadataToken.ToUInt32 (), type);
InitializeMethods (type);
}
}
void InitializeMethods (TypeDefinition type)
{
foreach (var method in type.Methods)
methods.Add (method.MetadataToken.ToUInt32 (), method);
}
public void SetModuleProps (string szName)
{
throw new NotImplementedException ();
}
public void Save (string szFile, uint dwSaveFlags)
{
throw new NotImplementedException ();
}
public void SaveToStream (IntPtr pIStream, uint dwSaveFlags)
{
throw new NotImplementedException ();
}
public uint GetSaveSize (uint fSave)
{
throw new NotImplementedException ();
}
public uint DefineTypeDef (IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements)
{
throw new NotImplementedException ();
}
public uint DefineNestedType (IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements, uint tdEncloser)
{
throw new NotImplementedException ();
}
public void SetHandler (object pUnk)
{
throw new NotImplementedException ();
}
public uint DefineMethod (uint td, IntPtr zName, uint dwMethodFlags, IntPtr pvSigBlob, uint cbSigBlob, uint ulCodeRVA, uint dwImplFlags)
{
throw new NotImplementedException ();
}
public void DefineMethodImpl (uint td, uint tkBody, uint tkDecl)
{
throw new NotImplementedException ();
}
public uint DefineTypeRefByName (uint tkResolutionScope, IntPtr szName)
{
throw new NotImplementedException ();
}
public uint DefineImportType (IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint tdImport, IntPtr pAssemEmit)
{
throw new NotImplementedException ();
}
public uint DefineMemberRef (uint tkImport, string szName, IntPtr pvSigBlob, uint cbSigBlob)
{
throw new NotImplementedException ();
}
public uint DefineImportMember (IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint mbMember, IntPtr pAssemEmit, uint tkParent)
{
throw new NotImplementedException ();
}
public uint DefineEvent (uint td, string szEvent, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods)
{
throw new NotImplementedException ();
}
public void SetClassLayout (uint td, uint dwPackSize, IntPtr rFieldOffsets, uint ulClassSize)
{
throw new NotImplementedException ();
}
public void DeleteClassLayout (uint td)
{
throw new NotImplementedException ();
}
public void SetFieldMarshal (uint tk, IntPtr pvNativeType, uint cbNativeType)
{
throw new NotImplementedException ();
}
public void DeleteFieldMarshal (uint tk)
{
throw new NotImplementedException ();
}
public uint DefinePermissionSet (uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission)
{
throw new NotImplementedException ();
}
public void SetRVA (uint md, uint ulRVA)
{
throw new NotImplementedException ();
}
public uint GetTokenFromSig (IntPtr pvSig, uint cbSig)
{
throw new NotImplementedException ();
}
public uint DefineModuleRef (string szName)
{
throw new NotImplementedException ();
}
public void SetParent (uint mr, uint tk)
{
throw new NotImplementedException ();
}
public uint GetTokenFromTypeSpec (IntPtr pvSig, uint cbSig)
{
throw new NotImplementedException ();
}
public void SaveToMemory (IntPtr pbData, uint cbData)
{
throw new NotImplementedException ();
}
public uint DefineUserString (string szString, uint cchString)
{
throw new NotImplementedException ();
}
public void DeleteToken (uint tkObj)
{
throw new NotImplementedException ();
}
public void SetMethodProps (uint md, uint dwMethodFlags, uint ulCodeRVA, uint dwImplFlags)
{
throw new NotImplementedException ();
}
public void SetTypeDefProps (uint td, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements)
{
throw new NotImplementedException ();
}
public void SetEventProps (uint ev, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods)
{
throw new NotImplementedException ();
}
public uint SetPermissionSetProps (uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission)
{
throw new NotImplementedException ();
}
public void DefinePinvokeMap (uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL)
{
throw new NotImplementedException ();
}
public void SetPinvokeMap (uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL)
{
throw new NotImplementedException ();
}
public void DeletePinvokeMap (uint tk)
{
throw new NotImplementedException ();
}
public uint DefineCustomAttribute (uint tkObj, uint tkType, IntPtr pCustomAttribute, uint cbCustomAttribute)
{
throw new NotImplementedException ();
}
public void SetCustomAttributeValue (uint pcv, IntPtr pCustomAttribute, uint cbCustomAttribute)
{
throw new NotImplementedException ();
}
public uint DefineField (uint td, string szName, uint dwFieldFlags, IntPtr pvSigBlob, uint cbSigBlob, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue)
{
throw new NotImplementedException ();
}
public uint DefineProperty (uint td, string szProperty, uint dwPropFlags, IntPtr pvSig, uint cbSig, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods)
{
throw new NotImplementedException ();
}
public uint DefineParam (uint md, uint ulParamSeq, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue)
{
throw new NotImplementedException ();
}
public void SetFieldProps (uint fd, uint dwFieldFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue)
{
throw new NotImplementedException ();
}
public void SetPropertyProps (uint pr, uint dwPropFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods)
{
throw new NotImplementedException ();
}
public void SetParamProps (uint pd, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue)
{
throw new NotImplementedException ();
}
public uint DefineSecurityAttributeSet (uint tkObj, IntPtr rSecAttrs, uint cSecAttrs)
{
throw new NotImplementedException ();
}
public void ApplyEditAndContinue (object pImport)
{
throw new NotImplementedException ();
}
public uint TranslateSigWithScope (IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport import, IntPtr pbSigBlob, uint cbSigBlob, IntPtr pAssemEmit, IMetaDataEmit emit, IntPtr pvTranslatedSig, uint cbTranslatedSigMax)
{
throw new NotImplementedException ();
}
public void SetMethodImplFlags (uint md, uint dwImplFlags)
{
throw new NotImplementedException ();
}
public void SetFieldRVA (uint fd, uint ulRVA)
{
throw new NotImplementedException ();
}
public void Merge (IMetaDataImport pImport, IntPtr pHostMapToken, object pHandler)
{
throw new NotImplementedException ();
}
public void MergeEnd ()
{
throw new NotImplementedException ();
}
public void CloseEnum (uint hEnum)
{
throw new NotImplementedException ();
}
public uint CountEnum (uint hEnum)
{
throw new NotImplementedException ();
}
public void ResetEnum (uint hEnum, uint ulPos)
{
throw new NotImplementedException ();
}
public uint EnumTypeDefs (ref uint phEnum, uint[] rTypeDefs, uint cMax)
{
throw new NotImplementedException ();
}
public uint EnumInterfaceImpls (ref uint phEnum, uint td, uint[] rImpls, uint cMax)
{
throw new NotImplementedException ();
}
public uint EnumTypeRefs (ref uint phEnum, uint[] rTypeRefs, uint cMax)
{
throw new NotImplementedException ();
}
public uint FindTypeDefByName (string szTypeDef, uint tkEnclosingClass)
{
throw new NotImplementedException ();
}
public Guid GetScopeProps (StringBuilder szName, uint cchName, out uint pchName)
{
throw new NotImplementedException ();
}
public uint GetModuleFromScope ()
{
throw new NotImplementedException ();
}
public uint GetTypeDefProps (uint td, char* szTypeDef, uint cchTypeDef, uint* pchTypeDef, uint* pdwTypeDefFlags, uint* ptkExtends)
{
TypeDefinition type;
if (!TryGetType (td, out type))
return E_FAIL;
var name = type.IsNested ? type.Name : type.FullName;
WriteNameBuffer (name, szTypeDef, cchTypeDef, pchTypeDef);
if (pdwTypeDefFlags != null)
*pdwTypeDefFlags = (uint) type.Attributes;
if (ptkExtends != null)
*ptkExtends = type.BaseType != null ? type.BaseType.MetadataToken.ToUInt32 () : 0;
return S_OK;
}
public uint GetInterfaceImplProps (uint iiImpl, out uint pClass)
{
throw new NotImplementedException ();
}
public uint GetTypeRefProps (uint tr, out uint ptkResolutionScope, StringBuilder szName, uint cchName)
{
throw new NotImplementedException ();
}
public uint ResolveTypeRef (uint tr, ref Guid riid, out object ppIScope)
{
throw new NotImplementedException ();
}
public uint EnumMembers (ref uint phEnum, uint cl, uint[] rMembers, uint cMax)
{
throw new NotImplementedException ();
}
public uint EnumMembersWithName (ref uint phEnum, uint cl, string szName, uint[] rMembers, uint cMax)
{
throw new NotImplementedException ();
}
public uint EnumMethods (ref uint phEnum, uint cl, IntPtr rMethods, uint cMax)
{
throw new NotImplementedException ();
}
public uint EnumMethodsWithName (ref uint phEnum, uint cl, string szName, uint[] rMethods, uint cMax)
{
throw new NotImplementedException ();
}
public uint EnumFields (ref uint phEnum, uint cl, IntPtr rFields, uint cMax)
{
throw new NotImplementedException ();
}
public uint EnumFieldsWithName (ref uint phEnum, uint cl, string szName, uint[] rFields, uint cMax)
{
throw new NotImplementedException ();
}
public uint EnumParams (ref uint phEnum, uint mb, uint[] rParams, uint cMax)
{
throw new NotImplementedException ();
}
public uint EnumMemberRefs (ref uint phEnum, uint tkParent, uint[] rMemberRefs, uint cMax)
{
throw new NotImplementedException ();
}
public uint EnumMethodImpls (ref uint phEnum, uint td, uint[] rMethodBody, uint[] rMethodDecl, uint cMax)
{
throw new NotImplementedException ();
}
public uint EnumPermissionSets (ref uint phEnum, uint tk, uint dwActions, uint[] rPermission, uint cMax)
{
throw new NotImplementedException ();
}
public uint FindMember (uint td, string szName, byte[] pvSigBlob, uint cbSigBlob)
{
throw new NotImplementedException ();
}
public uint FindMethod (uint td, string szName, byte[] pvSigBlob, uint cbSigBlob)
{
throw new NotImplementedException ();
}
public uint FindField (uint td, string szName, byte[] pvSigBlob, uint cbSigBlob)
{
throw new NotImplementedException ();
}
public uint FindMemberRef (uint td, string szName, byte[] pvSigBlob, uint cbSigBlob)
{
throw new NotImplementedException ();
}
public uint GetMethodProps (uint mb, uint* pClass, char* szMethod, uint cchMethod, uint* pchMethod, uint* pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, uint* pulCodeRVA, uint* pdwImplFlags)
{
MethodDefinition method;
if (!TryGetMethod (mb, out method))
return E_FAIL;
if (pClass != null)
*pClass = method.DeclaringType.MetadataToken.ToUInt32 ();
WriteNameBuffer (method.Name, szMethod, cchMethod, pchMethod);
if (pdwAttr != null)
*pdwAttr = (uint) method.Attributes;
if (pulCodeRVA != null)
*pulCodeRVA = (uint) method.RVA;
if (pdwImplFlags != null)
*pdwImplFlags = (uint) method.ImplAttributes;
return S_OK;
}
static void WriteNameBuffer(string name, char* buffer, uint bufferLength, uint* actualLength)
{
var length = Math.Min (name.Length, bufferLength - 1);
if (actualLength != null)
*actualLength = (uint) length;
if (buffer != null && bufferLength > 0) {
for (int i = 0; i < length; i++)
buffer [i] = name [i];
buffer [length + 1] = '\0';
}
}
public uint GetMemberRefProps (uint mr, ref uint ptk, StringBuilder szMember, uint cchMember, out uint pchMember, out IntPtr ppvSigBlob)
{
throw new NotImplementedException ();
}
public uint EnumProperties (ref uint phEnum, uint td, IntPtr rProperties, uint cMax)
{
throw new NotImplementedException ();
}
public uint EnumEvents (ref uint phEnum, uint td, IntPtr rEvents, uint cMax)
{
throw new NotImplementedException ();
}
public uint GetEventProps (uint ev, out uint pClass, StringBuilder szEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags, out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire, uint[] rmdOtherMethod, uint cMax)
{
throw new NotImplementedException ();
}
public uint EnumMethodSemantics (ref uint phEnum, uint mb, uint[] rEventProp, uint cMax)
{
throw new NotImplementedException ();
}
public uint GetMethodSemantics (uint mb, uint tkEventProp)
{
throw new NotImplementedException ();
}
public uint GetClassLayout (uint td, out uint pdwPackSize, IntPtr rFieldOffset, uint cMax, out uint pcFieldOffset)
{
throw new NotImplementedException ();
}
public uint GetFieldMarshal (uint tk, out IntPtr ppvNativeType)
{
throw new NotImplementedException ();
}
public uint GetRVA (uint tk, out uint pulCodeRVA)
{
throw new NotImplementedException ();
}
public uint GetPermissionSetProps (uint pm, out uint pdwAction, out IntPtr ppvPermission)
{
throw new NotImplementedException ();
}
public uint GetSigFromToken (uint mdSig, out IntPtr ppvSig)
{
throw new NotImplementedException ();
}
public uint GetModuleRefProps (uint mur, StringBuilder szName, uint cchName)
{
throw new NotImplementedException ();
}
public uint EnumModuleRefs (ref uint phEnum, uint[] rModuleRefs, uint cmax)
{
throw new NotImplementedException ();
}
public uint GetTypeSpecFromToken (uint typespec, out IntPtr ppvSig)
{
throw new NotImplementedException ();
}
public uint GetNameFromToken (uint tk)
{
throw new NotImplementedException ();
}
public uint EnumUnresolvedMethods (ref uint phEnum, uint[] rMethods, uint cMax)
{
throw new NotImplementedException ();
}
public uint GetUserString (uint stk, StringBuilder szString, uint cchString)
{
throw new NotImplementedException ();
}
public uint GetPinvokeMap (uint tk, out uint pdwMappingFlags, StringBuilder szImportName, uint cchImportName, out uint pchImportName)
{
throw new NotImplementedException ();
}
public uint EnumSignatures (ref uint phEnum, uint[] rSignatures, uint cmax)
{
throw new NotImplementedException ();
}
public uint EnumTypeSpecs (ref uint phEnum, uint[] rTypeSpecs, uint cmax)
{
throw new NotImplementedException ();
}
public uint EnumUserStrings (ref uint phEnum, uint[] rStrings, uint cmax)
{
throw new NotImplementedException ();
}
public int GetParamForMethodIndex (uint md, uint ulParamSeq, out uint pParam)
{
throw new NotImplementedException ();
}
public uint EnumCustomAttributes (ref uint phEnum, uint tk, uint tkType, uint[] rCustomAttributes, uint cMax)
{
throw new NotImplementedException ();
}
public uint GetCustomAttributeProps (uint cv, out uint ptkObj, out uint ptkType, out IntPtr ppBlob)
{
throw new NotImplementedException ();
}
public uint FindTypeRef (uint tkResolutionScope, string szName)
{
throw new NotImplementedException ();
}
public uint GetMemberProps (uint mb, out uint pClass, StringBuilder szMember, uint cchMember, out uint pchMember, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out IntPtr ppValue)
{
throw new NotImplementedException ();
}
public uint GetFieldProps (uint mb, out uint pClass, StringBuilder szField, uint cchField, out uint pchField, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out IntPtr ppValue)
{
throw new NotImplementedException ();
}
public uint GetPropertyProps (uint prop, out uint pClass, StringBuilder szProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags, out IntPtr ppvSig, out uint pbSig, out uint pdwCPlusTypeFlag, out IntPtr ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter, out uint pmdGetter, uint[] rmdOtherMethod, uint cMax)
{
throw new NotImplementedException ();
}
public uint GetParamProps (uint tk, out uint pmd, out uint pulSequence, StringBuilder szName, uint cchName, out uint pchName, out uint pdwAttr, out uint pdwCPlusTypeFlag, out IntPtr ppValue)
{
throw new NotImplementedException ();
}
public uint GetCustomAttributeByName (uint tkObj, string szName, out IntPtr ppData)
{
throw new NotImplementedException ();
}
public bool IsValidToken (uint tk)
{
throw new NotImplementedException ();
}
public uint GetNestedClassProps (uint tdNestedClass, uint* ptdEnclosingClass)
{
TypeDefinition type;
if (!TryGetType (tdNestedClass, out type))
return E_FAIL;
if (ptdEnclosingClass != null)
*ptdEnclosingClass = type.IsNested ? type.DeclaringType.MetadataToken.ToUInt32 () : 0;
return S_OK;
}
public uint GetNativeCallConvFromSig (IntPtr pvSig, uint cbSig)
{
throw new NotImplementedException ();
}
public int IsGlobal (uint pd)
{
throw new NotImplementedException ();
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Dataflow.V1Beta3
{
/// <summary>Settings for <see cref="SnapshotsV1Beta3Client"/> instances.</summary>
public sealed partial class SnapshotsV1Beta3Settings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="SnapshotsV1Beta3Settings"/>.</summary>
/// <returns>A new instance of the default <see cref="SnapshotsV1Beta3Settings"/>.</returns>
public static SnapshotsV1Beta3Settings GetDefault() => new SnapshotsV1Beta3Settings();
/// <summary>Constructs a new <see cref="SnapshotsV1Beta3Settings"/> object with default settings.</summary>
public SnapshotsV1Beta3Settings()
{
}
private SnapshotsV1Beta3Settings(SnapshotsV1Beta3Settings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetSnapshotSettings = existing.GetSnapshotSettings;
DeleteSnapshotSettings = existing.DeleteSnapshotSettings;
ListSnapshotsSettings = existing.ListSnapshotsSettings;
OnCopy(existing);
}
partial void OnCopy(SnapshotsV1Beta3Settings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>SnapshotsV1Beta3Client.GetSnapshot</c> and <c>SnapshotsV1Beta3Client.GetSnapshotAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetSnapshotSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>SnapshotsV1Beta3Client.DeleteSnapshot</c> and <c>SnapshotsV1Beta3Client.DeleteSnapshotAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings DeleteSnapshotSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>SnapshotsV1Beta3Client.ListSnapshots</c> and <c>SnapshotsV1Beta3Client.ListSnapshotsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListSnapshotsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="SnapshotsV1Beta3Settings"/> object.</returns>
public SnapshotsV1Beta3Settings Clone() => new SnapshotsV1Beta3Settings(this);
}
/// <summary>
/// Builder class for <see cref="SnapshotsV1Beta3Client"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
public sealed partial class SnapshotsV1Beta3ClientBuilder : gaxgrpc::ClientBuilderBase<SnapshotsV1Beta3Client>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public SnapshotsV1Beta3Settings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public SnapshotsV1Beta3ClientBuilder()
{
UseJwtAccessWithScopes = SnapshotsV1Beta3Client.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref SnapshotsV1Beta3Client client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<SnapshotsV1Beta3Client> task);
/// <summary>Builds the resulting client.</summary>
public override SnapshotsV1Beta3Client Build()
{
SnapshotsV1Beta3Client client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<SnapshotsV1Beta3Client> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<SnapshotsV1Beta3Client> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private SnapshotsV1Beta3Client BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return SnapshotsV1Beta3Client.Create(callInvoker, Settings);
}
private async stt::Task<SnapshotsV1Beta3Client> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return SnapshotsV1Beta3Client.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => SnapshotsV1Beta3Client.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => SnapshotsV1Beta3Client.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => SnapshotsV1Beta3Client.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>SnapshotsV1Beta3 client wrapper, for convenient use.</summary>
/// <remarks>
/// Provides methods to manage snapshots of Google Cloud Dataflow jobs.
/// </remarks>
public abstract partial class SnapshotsV1Beta3Client
{
/// <summary>
/// The default endpoint for the SnapshotsV1Beta3 service, which is a host of "dataflow.googleapis.com" and a
/// port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "dataflow.googleapis.com:443";
/// <summary>The default SnapshotsV1Beta3 scopes.</summary>
/// <remarks>
/// The default SnapshotsV1Beta3 scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// <item><description>https://www.googleapis.com/auth/compute</description></item>
/// <item><description>https://www.googleapis.com/auth/compute.readonly</description></item>
/// <item><description>https://www.googleapis.com/auth/userinfo.email</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly",
"https://www.googleapis.com/auth/userinfo.email",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="SnapshotsV1Beta3Client"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="SnapshotsV1Beta3ClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="SnapshotsV1Beta3Client"/>.</returns>
public static stt::Task<SnapshotsV1Beta3Client> CreateAsync(st::CancellationToken cancellationToken = default) =>
new SnapshotsV1Beta3ClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="SnapshotsV1Beta3Client"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="SnapshotsV1Beta3ClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="SnapshotsV1Beta3Client"/>.</returns>
public static SnapshotsV1Beta3Client Create() => new SnapshotsV1Beta3ClientBuilder().Build();
/// <summary>
/// Creates a <see cref="SnapshotsV1Beta3Client"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="SnapshotsV1Beta3Settings"/>.</param>
/// <returns>The created <see cref="SnapshotsV1Beta3Client"/>.</returns>
internal static SnapshotsV1Beta3Client Create(grpccore::CallInvoker callInvoker, SnapshotsV1Beta3Settings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
SnapshotsV1Beta3.SnapshotsV1Beta3Client grpcClient = new SnapshotsV1Beta3.SnapshotsV1Beta3Client(callInvoker);
return new SnapshotsV1Beta3ClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC SnapshotsV1Beta3 client</summary>
public virtual SnapshotsV1Beta3.SnapshotsV1Beta3Client GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Gets information about a snapshot.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Snapshot GetSnapshot(GetSnapshotRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets information about a snapshot.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Snapshot> GetSnapshotAsync(GetSnapshotRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets information about a snapshot.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Snapshot> GetSnapshotAsync(GetSnapshotRequest request, st::CancellationToken cancellationToken) =>
GetSnapshotAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Deletes a snapshot.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual DeleteSnapshotResponse DeleteSnapshot(DeleteSnapshotRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes a snapshot.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<DeleteSnapshotResponse> DeleteSnapshotAsync(DeleteSnapshotRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes a snapshot.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<DeleteSnapshotResponse> DeleteSnapshotAsync(DeleteSnapshotRequest request, st::CancellationToken cancellationToken) =>
DeleteSnapshotAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Lists snapshots.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual ListSnapshotsResponse ListSnapshots(ListSnapshotsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists snapshots.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ListSnapshotsResponse> ListSnapshotsAsync(ListSnapshotsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists snapshots.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<ListSnapshotsResponse> ListSnapshotsAsync(ListSnapshotsRequest request, st::CancellationToken cancellationToken) =>
ListSnapshotsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>SnapshotsV1Beta3 client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Provides methods to manage snapshots of Google Cloud Dataflow jobs.
/// </remarks>
public sealed partial class SnapshotsV1Beta3ClientImpl : SnapshotsV1Beta3Client
{
private readonly gaxgrpc::ApiCall<GetSnapshotRequest, Snapshot> _callGetSnapshot;
private readonly gaxgrpc::ApiCall<DeleteSnapshotRequest, DeleteSnapshotResponse> _callDeleteSnapshot;
private readonly gaxgrpc::ApiCall<ListSnapshotsRequest, ListSnapshotsResponse> _callListSnapshots;
/// <summary>
/// Constructs a client wrapper for the SnapshotsV1Beta3 service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="SnapshotsV1Beta3Settings"/> used within this client.</param>
public SnapshotsV1Beta3ClientImpl(SnapshotsV1Beta3.SnapshotsV1Beta3Client grpcClient, SnapshotsV1Beta3Settings settings)
{
GrpcClient = grpcClient;
SnapshotsV1Beta3Settings effectiveSettings = settings ?? SnapshotsV1Beta3Settings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetSnapshot = clientHelper.BuildApiCall<GetSnapshotRequest, Snapshot>(grpcClient.GetSnapshotAsync, grpcClient.GetSnapshot, effectiveSettings.GetSnapshotSettings).WithGoogleRequestParam("project_id", request => request.ProjectId).WithGoogleRequestParam("location", request => request.Location).WithGoogleRequestParam("snapshot_id", request => request.SnapshotId);
Modify_ApiCall(ref _callGetSnapshot);
Modify_GetSnapshotApiCall(ref _callGetSnapshot);
_callDeleteSnapshot = clientHelper.BuildApiCall<DeleteSnapshotRequest, DeleteSnapshotResponse>(grpcClient.DeleteSnapshotAsync, grpcClient.DeleteSnapshot, effectiveSettings.DeleteSnapshotSettings).WithGoogleRequestParam("project_id", request => request.ProjectId).WithGoogleRequestParam("location", request => request.Location).WithGoogleRequestParam("snapshot_id", request => request.SnapshotId);
Modify_ApiCall(ref _callDeleteSnapshot);
Modify_DeleteSnapshotApiCall(ref _callDeleteSnapshot);
_callListSnapshots = clientHelper.BuildApiCall<ListSnapshotsRequest, ListSnapshotsResponse>(grpcClient.ListSnapshotsAsync, grpcClient.ListSnapshots, effectiveSettings.ListSnapshotsSettings).WithGoogleRequestParam("project_id", request => request.ProjectId).WithGoogleRequestParam("location", request => request.Location).WithGoogleRequestParam("job_id", request => request.JobId);
Modify_ApiCall(ref _callListSnapshots);
Modify_ListSnapshotsApiCall(ref _callListSnapshots);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetSnapshotApiCall(ref gaxgrpc::ApiCall<GetSnapshotRequest, Snapshot> call);
partial void Modify_DeleteSnapshotApiCall(ref gaxgrpc::ApiCall<DeleteSnapshotRequest, DeleteSnapshotResponse> call);
partial void Modify_ListSnapshotsApiCall(ref gaxgrpc::ApiCall<ListSnapshotsRequest, ListSnapshotsResponse> call);
partial void OnConstruction(SnapshotsV1Beta3.SnapshotsV1Beta3Client grpcClient, SnapshotsV1Beta3Settings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC SnapshotsV1Beta3 client</summary>
public override SnapshotsV1Beta3.SnapshotsV1Beta3Client GrpcClient { get; }
partial void Modify_GetSnapshotRequest(ref GetSnapshotRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_DeleteSnapshotRequest(ref DeleteSnapshotRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_ListSnapshotsRequest(ref ListSnapshotsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Gets information about a snapshot.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Snapshot GetSnapshot(GetSnapshotRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetSnapshotRequest(ref request, ref callSettings);
return _callGetSnapshot.Sync(request, callSettings);
}
/// <summary>
/// Gets information about a snapshot.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Snapshot> GetSnapshotAsync(GetSnapshotRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetSnapshotRequest(ref request, ref callSettings);
return _callGetSnapshot.Async(request, callSettings);
}
/// <summary>
/// Deletes a snapshot.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override DeleteSnapshotResponse DeleteSnapshot(DeleteSnapshotRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteSnapshotRequest(ref request, ref callSettings);
return _callDeleteSnapshot.Sync(request, callSettings);
}
/// <summary>
/// Deletes a snapshot.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<DeleteSnapshotResponse> DeleteSnapshotAsync(DeleteSnapshotRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteSnapshotRequest(ref request, ref callSettings);
return _callDeleteSnapshot.Async(request, callSettings);
}
/// <summary>
/// Lists snapshots.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override ListSnapshotsResponse ListSnapshots(ListSnapshotsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListSnapshotsRequest(ref request, ref callSettings);
return _callListSnapshots.Sync(request, callSettings);
}
/// <summary>
/// Lists snapshots.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<ListSnapshotsResponse> ListSnapshotsAsync(ListSnapshotsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListSnapshotsRequest(ref request, ref callSettings);
return _callListSnapshots.Async(request, callSettings);
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.IO;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Internal;
using Dbg = System.Management.Automation.Diagnostics;
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
namespace Microsoft.PowerShell.Commands
{
#region ConsoleCmdletsBase
/// <summary>
/// Base class for all the Console related cmdlets.
/// </summary>
public abstract class ConsoleCmdletsBase : PSCmdlet
{
/// <summary>
/// Runspace configuration for the current engine
/// </summary>
/// <remarks>
/// Console cmdlets need <see cref="RunspaceConfigForSingleShell"/> object to work with.
/// </remarks>
internal RunspaceConfigForSingleShell Runspace
{
get
{
RunspaceConfigForSingleShell runSpace = Context.RunspaceConfiguration as RunspaceConfigForSingleShell;
return runSpace;
}
}
/// <summary>
/// InitialSessionState for the current engine
/// </summary>
internal InitialSessionState InitialSessionState
{
get
{
return Context.InitialSessionState;
}
}
/// <summary>
/// Throws a terminating error.
/// </summary>
/// <param name="targetObject">Object which caused this exception.</param>
/// <param name="errorId">ErrorId for this error.</param>
/// <param name="innerException">Complete exception object.</param>
/// <param name="category">ErrorCategory for this exception.</param>
internal void ThrowError(
Object targetObject,
string errorId,
Exception innerException,
ErrorCategory category)
{
ThrowTerminatingError(new ErrorRecord(innerException, errorId, category, targetObject));
}
}
#endregion
#region export-console
/// <summary>
/// Class that implements export-console cmdlet.
/// </summary>
[Cmdlet(VerbsData.Export, "Console", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113298")]
public sealed class ExportConsoleCommand : ConsoleCmdletsBase
{
#region Parameters
/// <summary>
/// Property that gets/sets console file name.
/// </summary>
/// <remarks>
/// If a parameter is not supplied then the file represented by $console
/// will be used for saving.
/// </remarks>
[Parameter(Position = 0, Mandatory = false, ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
[Alias("PSPath")]
public string Path
{
get
{
return _fileName;
}
set
{
_fileName = value;
}
}
private string _fileName;
/// <summary>
/// Property that sets force parameter. This will reset the read-only
/// attribute on an existing file before deleting it.
/// </summary>
[Parameter()]
public SwitchParameter Force
{
get
{
return _force;
}
set
{
_force = value;
}
}
private bool _force;
/// <summary>
/// Property that prevents file overwrite.
/// </summary>
[Parameter()]
[Alias("NoOverwrite")]
public SwitchParameter NoClobber
{
get
{
return _noclobber;
}
set
{
_noclobber = value;
}
}
private bool _noclobber;
#endregion
#region Overrides
/// <summary>
/// Saves the current console info into a file.
/// </summary>
protected override void ProcessRecord()
{
// Get filename..
string file = GetFileName();
// if file is null or empty..prompt the user for filename
if (string.IsNullOrEmpty(file))
{
file = PromptUserForFile();
}
// if file is still empty..write error and back out..
if (string.IsNullOrEmpty(file))
{
PSArgumentException ae = PSTraceSource.NewArgumentException("file", ConsoleInfoErrorStrings.FileNameNotResolved);
ThrowError(file, "FileNameNotResolved", ae, ErrorCategory.InvalidArgument);
}
if (WildcardPattern.ContainsWildcardCharacters(file))
{
ThrowError(file, "WildCardNotSupported",
PSTraceSource.NewInvalidOperationException(ConsoleInfoErrorStrings.ConsoleFileWildCardsNotSupported,
file), ErrorCategory.InvalidOperation);
}
// Ofcourse, you cant write to a file from HKLM: etc..
string resolvedPath = ResolveProviderAndPath(file);
// If resolvedPath is empty just return..
if (string.IsNullOrEmpty(resolvedPath))
{
return;
}
// Check whether the file ends with valid extension
if (!resolvedPath.EndsWith(StringLiterals.PowerShellConsoleFileExtension,
StringComparison.OrdinalIgnoreCase))
{
// file does not end with proper extension..create one..
resolvedPath = resolvedPath + StringLiterals.PowerShellConsoleFileExtension;
}
if (!ShouldProcess(this.Path)) // should this be resolvedPath?
return;
//check if destination file exists.
if (File.Exists(resolvedPath))
{
if (NoClobber)
{
string message = StringUtil.Format(
ConsoleInfoErrorStrings.FileExistsNoClobber,
resolvedPath,
"NoClobber"); // prevents localization
Exception uae = new UnauthorizedAccessException(message);
ErrorRecord errorRecord = new ErrorRecord(
uae, "NoClobber", ErrorCategory.ResourceExists, resolvedPath);
// NOTE: this call will throw
ThrowTerminatingError(errorRecord);
}
// Check if the file is read-only
System.IO.FileAttributes attrib = System.IO.File.GetAttributes(resolvedPath);
if ((attrib & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly)
{
if (Force)
{
RemoveFileThrowIfError(resolvedPath);
// Note, we do not attempt to set read-only on the new file
}
else
{
ThrowError(file, "ConsoleFileReadOnly",
PSTraceSource.NewArgumentException(file, ConsoleInfoErrorStrings.ConsoleFileReadOnly, resolvedPath),
ErrorCategory.InvalidArgument);
}
}
}
try
{
if (this.Runspace != null)
{
this.Runspace.SaveAsConsoleFile(resolvedPath);
}
else if (InitialSessionState != null)
{
this.InitialSessionState.SaveAsConsoleFile(resolvedPath);
}
else
{
Dbg.Assert(false, "Both RunspaceConfiguration and InitialSessionState should not be null");
throw PSTraceSource.NewInvalidOperationException(ConsoleInfoErrorStrings.CmdletNotAvailable);
}
}
catch (PSArgumentException mae)
{
ThrowError(resolvedPath,
"PathNotAbsolute", mae, ErrorCategory.InvalidArgument);
}
catch (PSArgumentNullException mane)
{
ThrowError(resolvedPath,
"PathNull", mane, ErrorCategory.InvalidArgument);
}
catch (ArgumentException ae)
{
ThrowError(resolvedPath,
"InvalidCharacetersInPath", ae, ErrorCategory.InvalidArgument);
}
// looks like saving succeeded.
// Now try changing $console
Exception e = null;
try
{
//Update $Console variable
Context.EngineSessionState.SetConsoleVariable();
}
catch (ArgumentNullException ane)
{
e = ane;
}
catch (ArgumentOutOfRangeException aor)
{
e = aor;
}
catch (ArgumentException ae)
{
e = ae;
}
catch (SessionStateUnauthorizedAccessException sue)
{
e = sue;
}
catch (SessionStateOverflowException sof)
{
e = sof;
}
catch (ProviderNotFoundException pnf)
{
e = pnf;
}
catch (System.Management.Automation.DriveNotFoundException dnfe)
{
e = dnfe;
}
catch (NotSupportedException ne)
{
e = ne;
}
catch (ProviderInvocationException pin)
{
e = pin;
}
if (e != null)
{
throw PSTraceSource.NewInvalidOperationException(e,
ConsoleInfoErrorStrings.ConsoleVariableCannotBeSet, resolvedPath);
}
}
#endregion
#region Private Methods
/// <summary>
/// Removes file specified by destination
/// </summary>
/// <param name="destination">Absolute path of the file to be removed.</param>
private void RemoveFileThrowIfError(string destination)
{
Diagnostics.Assert(System.IO.Path.IsPathRooted(destination),
"RemoveFile expects an absolute path");
System.IO.FileInfo destfile = new System.IO.FileInfo(destination);
if (destfile != null)
{
Exception e = null;
try
{
//Make sure the file is not read only
destfile.Attributes = destfile.Attributes & ~(FileAttributes.ReadOnly | FileAttributes.Hidden);
destfile.Delete();
}
catch (FileNotFoundException fnf)
{
e = fnf;
}
catch (DirectoryNotFoundException dnf)
{
e = dnf;
}
catch (UnauthorizedAccessException uac)
{
e = uac;
}
catch (System.Security.SecurityException se)
{
e = se;
}
catch (ArgumentNullException ane)
{
e = ane;
}
catch (ArgumentException ae)
{
e = ae;
}
catch (PathTooLongException pe)
{
e = pe;
}
catch (NotSupportedException ns)
{
e = ns;
}
catch (IOException ioe)
{
e = ioe;
}
if (e != null)
{
throw PSTraceSource.NewInvalidOperationException(e,
ConsoleInfoErrorStrings.ExportConsoleCannotDeleteFile,
destfile);
}
}
}
/// <summary>
/// Resolves the specified path and verifies the path belongs to
/// FileSystemProvider.
/// </summary>
/// <param name="path">Path to resolve</param>
/// <returns>A fully qualified string representing filename.</returns>
private string ResolveProviderAndPath(string path)
{
// Construct cmdletprovidercontext
CmdletProviderContext cmdContext = new CmdletProviderContext(this);
// First resolve path
PathInfo resolvedPath = ResolvePath(path, true, cmdContext);
// Check whether this is FileSystemProvider..
if (resolvedPath != null)
{
if (resolvedPath.Provider.ImplementingType == typeof(FileSystemProvider))
{
return resolvedPath.Path;
}
throw PSTraceSource.NewInvalidOperationException(ConsoleInfoErrorStrings.ProviderNotSupported, resolvedPath.Provider.Name);
}
return null;
}
/// <summary>
/// Resolves the specified path to PathInfo objects
/// </summary>
///
/// <param name="pathToResolve">
/// The path to be resolved. Each path may contain glob characters.
/// </param>
///
/// <param name="allowNonexistingPaths">
/// If true, resolves the path even if it doesn't exist.
/// </param>
///
/// <param name="currentCommandContext">
/// The context under which the command is running.
/// </param>
///
/// <returns>
/// A string representing the resolved path.
/// </returns>
///
private PathInfo ResolvePath(
string pathToResolve,
bool allowNonexistingPaths,
CmdletProviderContext currentCommandContext)
{
Collection<PathInfo> results = new Collection<PathInfo>();
try
{
// First resolve path
Collection<PathInfo> pathInfos =
SessionState.Path.GetResolvedPSPathFromPSPath(
pathToResolve,
currentCommandContext);
foreach (PathInfo pathInfo in pathInfos)
{
results.Add(pathInfo);
}
}
catch (PSNotSupportedException notSupported)
{
WriteError(
new ErrorRecord(
notSupported.ErrorRecord,
notSupported));
}
catch (System.Management.Automation.DriveNotFoundException driveNotFound)
{
WriteError(
new ErrorRecord(
driveNotFound.ErrorRecord,
driveNotFound));
}
catch (ProviderNotFoundException providerNotFound)
{
WriteError(
new ErrorRecord(
providerNotFound.ErrorRecord,
providerNotFound));
}
catch (ItemNotFoundException pathNotFound)
{
if (allowNonexistingPaths)
{
ProviderInfo provider = null;
System.Management.Automation.PSDriveInfo drive = null;
string unresolvedPath =
SessionState.Path.GetUnresolvedProviderPathFromPSPath(
pathToResolve,
currentCommandContext,
out provider,
out drive);
PathInfo pathInfo =
new PathInfo(
drive,
provider,
unresolvedPath,
SessionState);
results.Add(pathInfo);
}
else
{
WriteError(
new ErrorRecord(
pathNotFound.ErrorRecord,
pathNotFound));
}
}
if (results.Count == 1)
{
return results[0];
}
else if (results.Count > 1)
{
Exception e = PSTraceSource.NewNotSupportedException();
WriteError(
new ErrorRecord(e,
"NotSupported",
ErrorCategory.NotImplemented,
results));
return null;
}
else
{
return null;
}
} // ResolvePath
/// <summary>
/// Gets the filename for the current operation. If Name parameter is empty
/// checks $console. If $console is not present, prompts user?
/// </summary>
/// <returns>
/// A string representing filename.
/// If filename cannot be deduced returns null.
/// </returns>
/// <exception cref="PSArgumentException">
/// 1. $console points to an PSObject that cannot be converted to string.
/// </exception>
private string GetFileName()
{
if (!string.IsNullOrEmpty(_fileName))
{
// if user specified input..just return
return _fileName;
}
// no input is specified..
// check whether $console is set
PSVariable consoleVariable = Context.SessionState.PSVariable.Get(SpecialVariables.ConsoleFileName);
if (consoleVariable == null)
{
return string.Empty;
}
string consoleValue = consoleVariable.Value as string;
if (consoleValue == null)
{
// $console is not in string format
// Check whether it is in PSObject format
PSObject consolePSObject = consoleVariable.Value as PSObject;
if ((consolePSObject != null) && ((consolePSObject.BaseObject as string) != null))
{
consoleValue = consolePSObject.BaseObject as string;
}
}
if (consoleValue != null)
{
// ConsoleFileName variable is found..
return consoleValue;
}
throw PSTraceSource.NewArgumentException("fileName", ConsoleInfoErrorStrings.ConsoleCannotbeConvertedToString);
}
/// <summary>
/// Prompt user for filename.
/// </summary>
/// <returns>
/// User input in string format.
/// If user chooses not to export, an empty string is returned.
/// </returns>
/// <remarks>No exception is thrown</remarks>
private string PromptUserForFile()
{
// ask user what to do..
if (ShouldContinue(
ConsoleInfoErrorStrings.PromptForExportConsole,
null))
{
string caption = StringUtil.Format(ConsoleInfoErrorStrings.FileNameCaptionForExportConsole, "export-console");
string message = ConsoleInfoErrorStrings.FileNamePromptMessage;
// Construct a field description object of required parameters
Collection<System.Management.Automation.Host.FieldDescription> desc = new Collection<System.Management.Automation.Host.FieldDescription>();
desc.Add(new System.Management.Automation.Host.FieldDescription("Name"));
// get user input from the host
System.Collections.Generic.Dictionary<string, PSObject> returnValue =
this.PSHostInternal.UI.Prompt(caption, message, desc);
if ((returnValue != null) && (returnValue["Name"] != null))
{
return (returnValue["Name"].BaseObject as string);
}
// We dont have any input..
return string.Empty;
}
// If user chooses not to export, return empty string.
return string.Empty;
}
#endregion
}
#endregion
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using ServiceStack.Common;
namespace ServiceStack.ServiceInterface.Auth
{
/// <summary>
/// Thread-safe In memory UserAuth data store so it can be used without a dependency on Redis.
/// </summary>
public class InMemoryAuthRepository : RedisAuthRepository
{
public static readonly InMemoryAuthRepository Instance = new InMemoryAuthRepository();
protected Dictionary<string, HashSet<string>> Sets { get; set; }
protected Dictionary<string, Dictionary<string, string>> Hashes { get; set; }
internal List<IClearable> TrackedTypes = new List<IClearable>();
class TypedData<T> : IClearable
{
internal static TypedData<T> Instance = new TypedData<T>();
private TypedData()
{
lock (InMemoryAuthRepository.Instance.TrackedTypes)
InMemoryAuthRepository.Instance.TrackedTypes.Add(this);
}
internal readonly List<T> Items = new List<T>();
internal int Sequence = 0;
public void Clear()
{
lock (Items) Items.Clear();
Interlocked.CompareExchange(ref Sequence, 0, Sequence);
}
}
public InMemoryAuthRepository() : base(new InMemoryManagerFacade(Instance))
{
this.Sets = new Dictionary<string, HashSet<string>>();
this.Hashes = new Dictionary<string, Dictionary<string, string>>();
}
class InMemoryManagerFacade : IRedisClientManagerFacade
{
private readonly InMemoryAuthRepository root;
public InMemoryManagerFacade(InMemoryAuthRepository root)
{
this.root = root;
}
public IRedisClientFacade GetClient()
{
return new InMemoryClientFacade(root);
}
public void Clear()
{
lock (Instance.Sets) Instance.Sets.Clear();
lock (Instance.Hashes) Instance.Hashes.Clear();
lock (Instance.TrackedTypes) Instance.TrackedTypes.ForEach(x => x.Clear());
}
}
class InMemoryClientFacade : IRedisClientFacade
{
private readonly InMemoryAuthRepository root;
public InMemoryClientFacade(InMemoryAuthRepository root)
{
this.root = root;
}
class InMemoryTypedClientFacade<T> : ITypedRedisClientFacade<T>
{
private readonly InMemoryAuthRepository root;
public InMemoryTypedClientFacade(InMemoryAuthRepository root)
{
this.root = root;
}
public int GetNextSequence()
{
return Interlocked.Increment(ref TypedData<T>.Instance.Sequence);
}
public T GetById(object id)
{
if (id == null) return default(T);
lock (TypedData<T>.Instance.Items)
{
return TypedData<T>.Instance.Items.FirstOrDefault(x => id.ToString() == x.ToId().ToString());
}
}
public List<T> GetByIds(IEnumerable ids)
{
var idsSet = new HashSet<object>();
foreach (var id in ids) idsSet.Add(id.ToString());
lock (TypedData<T>.Instance.Items)
{
return TypedData<T>.Instance.Items.Where(x => idsSet.Contains(x.ToId().ToString())).ToList();
}
}
}
public HashSet<string> GetAllItemsFromSet(string setId)
{
lock (root.Sets)
{
HashSet<string> set;
return root.Sets.TryGetValue(setId, out set) ? set : new HashSet<string>();
}
}
public void Store<T>(T item) where T : class , new()
{
if (item == null) return;
lock (TypedData<T>.Instance.Items)
{
for (var i = 0; i < TypedData<T>.Instance.Items.Count; i++)
{
var o = TypedData<T>.Instance.Items[i];
if (o.ToId().ToString() != item.ToId().ToString()) continue;
TypedData<T>.Instance.Items[i] = item;
return;
}
TypedData<T>.Instance.Items.Add(item);
}
}
public string GetValueFromHash(string hashId, string key)
{
hashId.ThrowIfNull("hashId");
key.ThrowIfNull("key");
lock (root.Hashes)
{
Dictionary<string, string> hash;
if (!root.Hashes.TryGetValue(hashId, out hash)) return null;
string value;
hash.TryGetValue(key, out value);
return value;
}
}
public void SetEntryInHash(string hashId, string key, string value)
{
hashId.ThrowIfNull("hashId");
key.ThrowIfNull("key");
lock (root.Hashes)
{
Dictionary<string, string> hash;
if (!root.Hashes.TryGetValue(hashId, out hash))
root.Hashes[hashId] = hash = new Dictionary<string, string>();
hash[key] = value;
}
}
public void RemoveEntryFromHash(string hashId, string key)
{
hashId.ThrowIfNull("hashId");
key.ThrowIfNull("key");
lock (root.Hashes)
{
Dictionary<string, string> hash;
if (!root.Hashes.TryGetValue(hashId, out hash))
root.Hashes[hashId] = hash = new Dictionary<string, string>();
hash.Remove(key);
}
}
public void AddItemToSet(string setId, string item)
{
lock (root.Sets)
{
HashSet<string> set;
if (!root.Sets.TryGetValue(setId, out set))
root.Sets[setId] = set = new HashSet<string>();
set.Add(item);
}
}
public ITypedRedisClientFacade<T> As<T>()
{
return new InMemoryTypedClientFacade<T>(root);
}
public void Dispose()
{
}
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using NUnit.Framework;
using UnityEditor.Graphing;
using UnityEngine;
using UnityEditor.Graphing.Util;
using UnityEditor.Rendering;
namespace UnityEditor.ShaderGraph.UnitTests
{
class TestMessageManager : MessageManager
{
public Dictionary<object, Dictionary<Identifier, List<ShaderMessage>>> Messages
{
get { return m_Messages; }
}
}
class MessageManagerTests
{
TestMessageManager m_EmptyMgr;
TestMessageManager m_ComplexMgr;
string p0 = "Provider 0";
string p1 = "Provider 1";
Identifier node0 = new Identifier(0);
Identifier node1 = new Identifier(1);
Identifier node2 = new Identifier(2);
ShaderMessage e0 = new ShaderMessage("e0");
ShaderMessage e1 = new ShaderMessage("e1");
ShaderMessage e2 = new ShaderMessage("e2");
ShaderMessage e3 = new ShaderMessage("e3");
ShaderMessage w0 = new ShaderMessage("w0", ShaderCompilerMessageSeverity.Warning);
ShaderMessage w1 = new ShaderMessage("w1", ShaderCompilerMessageSeverity.Warning);
[SetUp]
public void Setup()
{
m_EmptyMgr = new TestMessageManager();
m_ComplexMgr = new TestMessageManager();
m_ComplexMgr.AddOrAppendError(p0, node0, e0);
m_ComplexMgr.AddOrAppendError(p0, node0, e1);
m_ComplexMgr.AddOrAppendError(p0, node1, e2);
m_ComplexMgr.AddOrAppendError(p1, node0, e1);
m_ComplexMgr.AddOrAppendError(p1, node1, e0);
m_ComplexMgr.AddOrAppendError(p1, node1, e1);
m_ComplexMgr.AddOrAppendError(p1, node2, e3);
}
// Simple helper to avoid typing that ungodly generic type
static List<KeyValuePair<Identifier, List<ShaderMessage>>> GetListFrom(MessageManager mgr)
{
return new List<KeyValuePair<Identifier, List<ShaderMessage>>>(mgr.GetNodeMessages());
}
[Test]
public void NewManager_IsEmpty()
{
var ret = GetListFrom(m_EmptyMgr);
Assert.IsEmpty(ret);
}
[Test]
public void AddMessage_CreatesMessage()
{
m_EmptyMgr.AddOrAppendError(p0, node0, e0);
var ret = GetListFrom(m_EmptyMgr);
Assert.IsNotEmpty(ret);
Assert.AreEqual(node0, ret[0].Key);
Assert.IsNotEmpty(ret[0].Value);
Assert.AreEqual(e0, ret[0].Value[0]);
}
[Test]
public void AddMessage_DirtiesManager()
{
m_EmptyMgr.AddOrAppendError(p0, node0, e0);
Assert.IsTrue(m_EmptyMgr.nodeMessagesChanged);
}
[Test]
public void GettingMessages_ClearsDirtyFlag()
{
m_EmptyMgr.AddOrAppendError(p0, node0, e0);
GetListFrom(m_EmptyMgr);
Assert.IsFalse(m_EmptyMgr.nodeMessagesChanged);
}
[Test]
public void GettingMessages_DoesNotChangeLists()
{
m_EmptyMgr.AddOrAppendError(p0, node0, e0);
m_EmptyMgr.AddOrAppendError(p0, node0, e1);
m_EmptyMgr.AddOrAppendError(p1, node0, e2);
GetListFrom(m_EmptyMgr);
Assert.AreEqual(2, m_EmptyMgr.Messages[p0][node0].Count);
Assert.AreEqual(e0, m_EmptyMgr.Messages[p0][node0][0]);
Assert.AreEqual(e1, m_EmptyMgr.Messages[p0][node0][1]);
Assert.AreEqual(1, m_EmptyMgr.Messages[p1][node0].Count);
Assert.AreEqual(e2, m_EmptyMgr.Messages[p1][node0][0]);
}
[Test]
public void RemoveNode_DoesNotDirty_IfNodeDoesNotExist()
{
m_EmptyMgr.AddOrAppendError(p0, node0, e0);
GetListFrom(m_EmptyMgr);
m_EmptyMgr.RemoveNode(node1);
Assert.IsFalse(m_EmptyMgr.nodeMessagesChanged);
}
[Test]
public void RemoveNode_DirtiesList_IfNodeExists()
{
m_EmptyMgr.AddOrAppendError(p0, node0, e0);
GetListFrom(m_EmptyMgr);
m_EmptyMgr.RemoveNode(node0);
Assert.IsTrue(m_EmptyMgr.nodeMessagesChanged);
}
[Test]
public void RemoveNode_RemovesNode()
{
m_EmptyMgr.AddOrAppendError(p0, node0, e0);
m_EmptyMgr.RemoveNode(node0);
var ret = GetListFrom(m_EmptyMgr);
Assert.IsEmpty(ret);
}
[Test]
public void RemoveNode_RemovesNode_FromAllProvides()
{
m_EmptyMgr.AddOrAppendError(p0, node0, e0);
m_EmptyMgr.AddOrAppendError(p1, node0, e1);
m_EmptyMgr.RemoveNode(node0);
var ret = GetListFrom(m_EmptyMgr);
Assert.IsEmpty(ret);
}
[Test]
public void AppendMessage_AppendsMessage()
{
m_EmptyMgr.AddOrAppendError(p0, node0, e0);
m_EmptyMgr.AddOrAppendError(p0, node0, e1);
var ret = GetListFrom(m_EmptyMgr);
Assert.IsNotEmpty(ret);
Assert.AreEqual(node0, ret[0].Key);
Assert.AreEqual(2, ret[0].Value.Count);
Assert.AreEqual(e0, ret[0].Value[0]);
Assert.AreEqual(e1, ret[0].Value[1]);
}
[Test]
public void Warnings_SortedAfterErrors()
{
var mixedMgr = new MessageManager();
mixedMgr.AddOrAppendError(p0, node0, e0);
mixedMgr.AddOrAppendError(p0, node0, w0);
mixedMgr.AddOrAppendError(p0, node0, e1);
mixedMgr.AddOrAppendError(p0, node0, w1);
var ret = GetListFrom(mixedMgr)[0].Value;
Assert.AreEqual(e0, ret[0]);
Assert.AreEqual(e1, ret[1]);
Assert.AreEqual(w0, ret[2]);
Assert.AreEqual(w1, ret[3]);
}
[Test]
public void Warnings_FromDifferentProviders_SortedAfterErrors()
{
var mixedMgr = new MessageManager();
mixedMgr.AddOrAppendError(p0, node0, e0);
mixedMgr.AddOrAppendError(p0, node0, w0);
mixedMgr.AddOrAppendError(p1, node0, e1);
mixedMgr.AddOrAppendError(p1, node0, w1);
var ret = GetListFrom(mixedMgr)[0].Value;
Assert.AreEqual(e0, ret[0]);
Assert.AreEqual(e1, ret[1]);
Assert.AreEqual(w0, ret[2]);
Assert.AreEqual(w1, ret[3]);
}
[Test]
public void MultipleNodes_RemainSeparate()
{
m_EmptyMgr.AddOrAppendError(p0, node0, e0);
m_EmptyMgr.AddOrAppendError(p0, node1, e1);
var ret = GetListFrom(m_EmptyMgr);
Assert.AreEqual(2, ret.Count);
Assert.AreEqual(node0, ret[0].Key);
Assert.AreEqual(e0, ret[0].Value[0]);
Assert.AreEqual(node1, ret[1].Key);
Assert.AreEqual(e1, ret[1].Value[0]);
}
[Test]
public void MultipleCreators_AggregatePerNode()
{
m_EmptyMgr.AddOrAppendError(p0, node0, e0);
m_EmptyMgr.AddOrAppendError(p1, node0, e1);
var ret = GetListFrom(m_EmptyMgr);
Assert.IsNotEmpty(ret);
Assert.AreEqual(node0, ret[0].Key);
Assert.AreEqual(2, ret[0].Value.Count);
Assert.AreEqual(e0, ret[0].Value[0]);
Assert.AreEqual(e1, ret[0].Value[1]);
}
[Test]
public void DuplicateEntries_AreNotIgnored()
{
m_EmptyMgr.AddOrAppendError(p0, node0, e0);
m_EmptyMgr.AddOrAppendError(p0, node0, e0);
var ret = GetListFrom(m_EmptyMgr);
Assert.IsNotEmpty(ret);
Assert.AreEqual(node0, ret[0].Key);
Assert.AreEqual(2, ret[0].Value.Count);
Assert.AreEqual(e0, ret[0].Value[0]);
Assert.AreEqual(e0, ret[0].Value[1]);
}
[Test]
public void ClearAllFromProvider_ZerosMessageLists()
{
m_ComplexMgr.ClearAllFromProvider(p1);
var ret = GetListFrom(m_ComplexMgr);
Assert.IsNotEmpty(ret);
Assert.AreEqual(3, ret.Count);
Assert.AreEqual(node0, ret[0].Key);
Assert.AreEqual(2, ret[0].Value.Count);
Assert.AreEqual(node1, ret[1].Key);
Assert.AreEqual(1, ret[1].Value.Count);
Assert.AreEqual(node2, ret[2].Key);
Assert.IsEmpty(ret[2].Value);
}
[Test]
public void GetList_RemovesZeroLengthLists()
{
m_ComplexMgr.ClearAllFromProvider(p1);
var ret = GetListFrom(m_ComplexMgr);
Assert.IsNotEmpty(ret.Where(kvp => kvp.Key.Equals(node2)));
Assert.IsEmpty(ret.First(kvp => kvp.Key.Equals(node2)).Value);
ret = GetListFrom(m_ComplexMgr);
Assert.IsEmpty(ret.Where(kvp => kvp.Key.Equals(node2)));
}
[Test]
public void ClearNodesFromProvider_ClearsNodes()
{
var n0 = new AndNode {tempId = node0};
var n2 = new AndNode {tempId = node2};
var nodesToClear = new List<AbstractMaterialNode>() { n0, n2 };
m_ComplexMgr.ClearNodesFromProvider(p1, nodesToClear);
var ret = GetListFrom(m_ComplexMgr);
Assert.AreEqual(2, ret.Find(kpv => kpv.Key.Equals(node0)).Value.Count);
Assert.IsEmpty(ret.Find(kvp => kvp.Key.Equals(node2)).Value);
}
[Test]
public void ClearNodesFromProvider_LeavesOtherNodes()
{
var n0 = new AndNode {tempId = node0};
var n2 = new AndNode {tempId = node2};
var nodesToClear = new List<AbstractMaterialNode>() { n0, n2 };
m_ComplexMgr.ClearNodesFromProvider(p1, nodesToClear);
var ret = GetListFrom(m_ComplexMgr);
Assert.AreEqual(3, ret.Find(kpv => kpv.Key.Equals(node1)).Value.Count);
}
}
}
// m_ComplesMgr definition:
// m_ComplexMgr.AddOrAppendError(p0, node0, e0);
// m_ComplexMgr.AddOrAppendError(p0, node0, e1);
// m_ComplexMgr.AddOrAppendError(p0, node1, e2);
// m_ComplexMgr.AddOrAppendError(p1, node0, e1);
// m_ComplexMgr.AddOrAppendError(p1, node1, e0);
// m_ComplexMgr.AddOrAppendError(p1, node1, e1);
// m_ComplexMgr.AddOrAppendError(p1, node2, e3);
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
namespace BracketPipe
{
/// <summary>
/// An XML reader wrapper of a list of HTML nodes.
/// </summary>
/// <seealso cref="System.Xml.XmlReader" />
public class HtmlXmlReader : XmlReader
{
private readonly IEnumerator<HtmlNode> _enumerator;
private int _attrIndex;
private int _depth;
private ReadState _state = ReadState.Initial;
/// <summary>
/// Gets the number of attributes on the current node.
/// </summary>
public override int AttributeCount
{
get
{
var tag = Current as HtmlStartTag;
if (tag == null)
return 0;
return tag.Attributes.Count;
}
}
/// <summary>
/// Gets the base URI of the current node.
/// </summary>
public override string BaseURI
{
get
{
return string.Empty;
}
}
/// <summary>
/// Gets the depth of the current node in the XML document.
/// </summary>
public override int Depth
{
get
{
return 0;
}
}
/// <summary>
/// Gets a value indicating whether the reader is positioned at the end of the stream.
/// </summary>
public override bool EOF { get { return _state == ReadState.EndOfFile; } }
/// <summary>
/// Gets a value indicating whether the current node is an empty element (for example, <MyElement/>).
/// </summary>
public override bool IsEmptyElement
{
get
{
var tag = Current as HtmlStartTag;
if (tag == null)
return false;
return tag.IsEmpty;
}
}
/// <summary>
/// Gets the local name of the current node.
/// </summary>
public override string LocalName { get { return GetName().Last(); } }
private readonly static string[] _emptyStringArray = new string[] { "" };
private string[] GetName()
{
if (_attrIndex >= 0)
return ((HtmlStartTag)Current).Attributes[_attrIndex].Key.Split(':');
if (_attrIndex < -1)
return _emptyStringArray;
if (Current == null)
return _emptyStringArray;
if (Current.Type == HtmlTokenType.EndTag
|| Current.Type == HtmlTokenType.StartTag
|| Current.Type == HtmlTokenType.Doctype)
return Current.Value.Split(':');
return _emptyStringArray;
}
/// <summary>
/// Gets the namespace URI (as defined in the W3C Namespace specification) of the node on which the reader is positioned.
/// </summary>
public override string NamespaceURI
{
get
{
return string.Empty;
}
}
private readonly XmlNameTable _table = new NameTable();
/// <summary>
/// Gets the <see cref="T:System.Xml.XmlNameTable" /> associated with this implementation.
/// </summary>
public override XmlNameTable NameTable
{
get { return _table; }
}
/// <summary>
/// Gets the type of the current node.
/// </summary>
public override XmlNodeType NodeType
{
get
{
if (Current == null)
return XmlNodeType.None;
if (_attrIndex >= 0)
return XmlNodeType.Attribute;
if (_attrIndex < -1)
return XmlNodeType.Text;
switch (Current.Type)
{
case HtmlTokenType.Comment:
return XmlNodeType.Comment;
case HtmlTokenType.Doctype:
return XmlNodeType.DocumentType;
case HtmlTokenType.EndTag:
return XmlNodeType.EndElement;
case HtmlTokenType.StartTag:
return XmlNodeType.Element;
case HtmlTokenType.Text:
var val = Current.Value ?? "";
for (var i = 0; i < val.Length; i++)
{
switch (val[i])
{
case '\t':
case '\r':
case '\n':
case ' ':
// The core whitespace characters
break;
default:
return XmlNodeType.Text;
}
}
return XmlNodeType.Whitespace;
}
return XmlNodeType.None;
}
}
/// <summary>
/// Gets the namespace prefix associated with the current node.
/// </summary>
public override string Prefix
{
get
{
//var name = GetName();
//if (name.Length > 1)
// return name[0];
return string.Empty;
}
}
/// <summary>
/// Gets the state of the reader.
/// </summary>
public override ReadState ReadState { get { return _state; } }
private HtmlNode Current { get { return _enumerator.Current; } }
/// <summary>
/// Initializes a new instance of the <see cref="HtmlXmlReader"/> class.
/// </summary>
protected HtmlXmlReader()
{
_enumerator = this as IEnumerator<HtmlNode>;
}
/// <summary>
/// Initializes a new instance of the <see cref="HtmlXmlReader"/> class.
/// </summary>
/// <param name="enumerator">The enumerator.</param>
public HtmlXmlReader(IEnumerator<HtmlNode> enumerator)
{
_enumerator = enumerator;
}
/// <summary>
/// Initializes a new instance of the <see cref="HtmlXmlReader"/> class.
/// </summary>
/// <param name="enumerable">The enumerable.</param>
public HtmlXmlReader(IEnumerable<HtmlNode> enumerable)
{
_enumerator = enumerable.GetEnumerator();
}
/// <summary>
/// Gets the text value of the current node.
/// </summary>
public override string Value
{
get
{
if (_attrIndex >= 0)
return ((HtmlStartTag)Current).Attributes[_attrIndex].Value;
if (_attrIndex < -1)
return ((HtmlStartTag)Current).Attributes[_attrIndex * -1 - 2].Value;
if (Current == null)
return string.Empty;
switch (Current.Type)
{
case HtmlTokenType.Comment:
case HtmlTokenType.Text:
return Current.Value;
}
return string.Empty;
}
}
/// <summary>
/// Gets the value of the attribute with the specified index.
/// </summary>
/// <param name="i">The index of the attribute. The index is zero-based. (The first attribute has index 0.)</param>
/// <returns>
/// The value of the specified attribute. This method does not move the reader.
/// </returns>
public override string GetAttribute(int i)
{
var tag = Current as HtmlStartTag;
if (tag == null)
return string.Empty;
return tag.Attributes[i].Value;
}
/// <summary>
/// Gets the value of the attribute with the specified <see cref="P:System.Xml.XmlReader.Name" />.
/// </summary>
/// <param name="name">The qualified name of the attribute.</param>
/// <returns>
/// The value of the specified attribute. If the attribute is not found or the value is String.Empty, null is returned.
/// </returns>
public override string GetAttribute(string name)
{
return GetAttribute(name, null);
}
/// <summary>
/// Gets the value of the attribute with the specified <see cref="P:System.Xml.XmlReader.LocalName" /> and <see cref="P:System.Xml.XmlReader.NamespaceURI" />.
/// </summary>
/// <param name="name">The local name of the attribute.</param>
/// <param name="namespaceURI">The namespace URI of the attribute.</param>
/// <returns>
/// The value of the specified attribute. If the attribute is not found or the value is String.Empty, null is returned. This method does not move the reader.
/// </returns>
public override string GetAttribute(string name, string namespaceURI)
{
var tag = Current as HtmlStartTag;
if (tag == null)
return string.Empty;
return tag[name];
}
/// <summary>
/// Resolves a namespace prefix in the current element's scope.
/// </summary>
/// <param name="prefix">The prefix whose namespace URI you want to resolve. To match the default namespace, pass an empty string.</param>
/// <returns>
/// The namespace URI to which the prefix maps or null if no matching prefix is found.
/// </returns>
public override string LookupNamespace(string prefix)
{
return string.Empty;
}
/// <summary>
/// Moves to the attribute with the specified <see cref="P:System.Xml.XmlReader.Name" />.
/// </summary>
/// <param name="name">The qualified name of the attribute.</param>
/// <returns>
/// <c>true</c> if the attribute is found; otherwise, <c>false</c>. If <c>false</c>, the reader's position does not change.
/// </returns>
public override bool MoveToAttribute(string name)
{
return MoveToAttribute(name, null);
}
/// <summary>
/// When overridden in a derived class, moves to the attribute with the specified <see cref="P:System.Xml.XmlReader.LocalName" /> and <see cref="P:System.Xml.XmlReader.NamespaceURI" />.
/// </summary>
/// <param name="name">The local name of the attribute.</param>
/// <param name="ns">The namespace URI of the attribute.</param>
/// <returns>
/// <c>true</c> if the attribute is found; otherwise, <c>false</c>. If <c>false</c>, the reader's position does not change.
/// </returns>
public override bool MoveToAttribute(string name, string ns)
{
var tag = Current as HtmlStartTag;
if (tag != null)
{
for (var i = 0; i < tag.Attributes.Count; i++)
{
if (string.Equals(tag.Attributes[i].Key, name, StringComparison.OrdinalIgnoreCase))
{
_attrIndex = i;
return true;
}
}
}
_attrIndex = -1;
return false;
}
/// <summary>
/// Moves to the element that contains the current attribute node.
/// </summary>
/// <returns>
/// <c>true</c> if the reader is positioned on an attribute (the reader moves to the element that owns the attribute); <c>false</c> if the reader is not positioned on an attribute (the position of the reader does not change).
/// </returns>
public override bool MoveToElement()
{
_attrIndex = -1;
return Current != null && Current.Type == HtmlTokenType.StartTag;
}
/// <summary>
/// Moves to the first attribute.
/// </summary>
/// <returns>
/// <c>true</c> if an attribute exists (the reader moves to the first attribute); otherwise, <c>false</c> (the position of the reader does not change).
/// </returns>
public override bool MoveToFirstAttribute()
{
var tag = Current as HtmlStartTag;
if (tag == null || tag.Attributes.Count < 1)
{
_attrIndex = -1;
return false;
}
_attrIndex = 0;
return true;
}
/// <summary>
/// Moves to the next attribute.
/// </summary>
/// <returns>
/// <c>true</c> if there is a next attribute; <c>false</c> if there are no more attributes.
/// </returns>
public override bool MoveToNextAttribute()
{
var tag = Current as HtmlStartTag;
if (tag == null || _attrIndex + 1 >= tag.Attributes.Count)
{
_attrIndex = -1;
return false;
}
_attrIndex++;
return true;
}
/// <summary>
/// Parses the attribute value into one or more <see cref="XmlNodeType.Text"/>, <see cref="XmlNodeType.EntityReference"/>, or <see cref="XmlNodeType.EndEntity"/> nodes.
/// </summary>
/// <returns>
/// <c>true</c> if there are nodes to return. <c>false</c> if the reader is not positioned on an attribute node when the initial call is made or if all the attribute values have been read. An empty attribute, such as, <c>misc=""</c>, returns <c>true</c> with a single node with a value of <see cref="String.Empty"/>.
/// </returns>
public override bool ReadAttributeValue()
{
if (_attrIndex < -1)
{
_attrIndex = _attrIndex * -1 - 2;
return false;
}
else
{
_attrIndex = _attrIndex * -1 - 2;
return true;
}
}
/// <summary>
/// Resolves the entity reference for <see cref="XmlNodeType.EntityReference"/> nodes.
/// </summary>
public override void ResolveEntity()
{
// Do nothing
}
/// <summary>
/// Reads the next node from the stream.
/// </summary>
/// <returns>
/// <c>true</c> if the next node was read successfully; otherwise, <c>false</c>.
/// </returns>
public override bool Read()
{
var result = _enumerator.MoveNext();
OnAfterRead(result);
return result;
}
/// <summary>
/// Tracking code called after each read operation.
/// </summary>
protected virtual void OnAfterRead(bool success)
{
_attrIndex = -1;
_state = success ? ReadState.Interactive : ReadState.EndOfFile;
if (success)
{
if (Current.Type == HtmlTokenType.StartTag && !IsEmptyElement)
_depth++;
else if (Current.Type == HtmlTokenType.EndTag)
_depth--;
}
}
#if NET35
public override bool HasValue
{
get { return true; }
}
#endif
#if !PORTABLE
public override void Close()
{
}
#endif
}
}
| |
// <copyright>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
namespace Microsoft.Activities.Presentation.Xaml
{
using System;
using System.Activities.Presentation.Toolbox;
using System.Xaml;
// ActivityTemplateFactoryBuilderWriter is a XamlWriter that support <ActivityTemplateFactory x:Class ...
//
// Think of this class (and any other XamlWriter) as a XAML node stream editor
// XAML node are *not* objects, they are represented as method calls. For example, when WriteStartObject is called, a StartObject node is send to this writer.
// The writer will then edit the stream and send the nodes to the underlying stream (by calling the methods on the underlying writer)
//
// The editing algorithm goes as follow:
//
// The system starts as the InitialState. There are five states in total: (InitialState, BufferingState, BufferingNameState, BufferingTargetTypeState, BypassState)
// If the very first StartObject node is ActivityTemplateFactory, then start buffering by going to the buffering state, otherwise simply go to the ByPassState.
//
// In the buffering state, the nodes are buffered in a XamlNodeQueue, until we see the Implementation Node.
// When we reach the Implementation node, we will flush all the nodes transformed to the underlyingWriter, we will also switch to the ByPass state.
//
// During the buffering, it is possible that we encounter the Name/TargetType node - the name node cannot enter the buffer because editing is required, we will use a separate state to track that.
internal sealed class ActivityTemplateFactoryBuilderWriter : XamlWriter
{
private XamlSchemaContext schemaContext;
private XamlWriter underlyingWriter;
private XamlType activityTemplateFactoryType;
private XamlMember activityTemplateFactoryImplementationMember;
private XamlMember activityTemplateFactoryBuilderImplementationMember;
private XamlMember activityTemplateFactoryBuilderNameMember;
private XamlMember activityTemplateFactoryBuilderTargetTypeMember;
// Buffering of nodes before starting the Implementation node
private ActivityTemplateFactoryBuilderWriterStates currentState = ActivityTemplateFactoryBuilderWriterStates.InitialState;
private XamlNodeQueue queuedNodes;
private string className;
private string targetType;
private bool xamlLanguageNamespaceWritten = false;
public ActivityTemplateFactoryBuilderWriter(XamlWriter underlyingWriter, XamlSchemaContext schemaContext)
{
this.schemaContext = schemaContext;
this.underlyingWriter = underlyingWriter;
}
private enum ActivityTemplateFactoryBuilderWriterStates
{
InitialState,
BufferingState,
BufferingNameState,
BufferingTargetTypeState,
BypassState,
}
public override XamlSchemaContext SchemaContext
{
get { return this.schemaContext; }
}
private XamlType ActivityTemplateFactoryType
{
get
{
if (this.activityTemplateFactoryType == null)
{
this.activityTemplateFactoryType = new XamlType(typeof(ActivityTemplateFactory), this.schemaContext);
}
return this.activityTemplateFactoryType;
}
}
private XamlMember ActivityTemplateFactoryImplementationMember
{
get
{
if (this.activityTemplateFactoryImplementationMember == null)
{
this.activityTemplateFactoryImplementationMember = ActivityTemplateFactoryBuilderXamlMembers.ActivityTemplateFactoryImplementationMemberForWriter(this.schemaContext);
}
return this.activityTemplateFactoryImplementationMember;
}
}
private XamlMember ActivityTemplateFactoryBuilderImplementationMember
{
get
{
if (this.activityTemplateFactoryBuilderImplementationMember == null)
{
this.activityTemplateFactoryBuilderImplementationMember = ActivityTemplateFactoryBuilderXamlMembers.ActivityTemplateFactoryBuilderImplementationMember(this.schemaContext);
}
return this.activityTemplateFactoryBuilderImplementationMember;
}
}
private XamlMember ActivityTemplateFactoryBuilderNameMember
{
get
{
if (this.activityTemplateFactoryBuilderNameMember == null)
{
this.activityTemplateFactoryBuilderNameMember = ActivityTemplateFactoryBuilderXamlMembers.ActivityTemplateFactoryBuilderNameMember(this.schemaContext);
}
return this.activityTemplateFactoryBuilderNameMember;
}
}
private XamlMember ActivityTemplateFactoryBuilderTargetTypeMember
{
get
{
if (this.activityTemplateFactoryBuilderTargetTypeMember == null)
{
this.activityTemplateFactoryBuilderTargetTypeMember = ActivityTemplateFactoryBuilderXamlMembers.ActivityTemplateFactoryBuilderTargetTypeMember(this.schemaContext);
}
return this.activityTemplateFactoryBuilderTargetTypeMember;
}
}
public override void WriteNamespace(NamespaceDeclaration namespaceDeclaration)
{
if (namespaceDeclaration.Prefix == "x")
{
this.xamlLanguageNamespaceWritten = true;
}
this.underlyingWriter.WriteNamespace(namespaceDeclaration);
}
public override void WriteStartObject(XamlType type)
{
switch (this.currentState)
{
case ActivityTemplateFactoryBuilderWriterStates.InitialState:
if (type.Equals(new XamlType(typeof(ActivityTemplateFactoryBuilder), this.schemaContext)))
{
this.queuedNodes = new XamlNodeQueue(this.schemaContext);
this.currentState = ActivityTemplateFactoryBuilderWriterStates.BufferingState;
}
else
{
this.currentState = ActivityTemplateFactoryBuilderWriterStates.BypassState;
this.underlyingWriter.WriteStartObject(type);
}
break;
case ActivityTemplateFactoryBuilderWriterStates.BypassState:
this.underlyingWriter.WriteStartObject(type);
break;
default:
SharedFx.Assert(
this.currentState == ActivityTemplateFactoryBuilderWriterStates.BufferingState
|| this.currentState == ActivityTemplateFactoryBuilderWriterStates.BufferingNameState
|| this.currentState == ActivityTemplateFactoryBuilderWriterStates.BufferingTargetTypeState,
"These are the only possible ActivityTemplateFactoryBuilderWriterStates.");
SharedFx.Assert("It is impossible to start any object during the buffering state.");
break;
}
}
public override void WriteEndObject()
{
switch (this.currentState)
{
case ActivityTemplateFactoryBuilderWriterStates.InitialState:
SharedFx.Assert("It is impossible to end an object during InitialState");
break;
case ActivityTemplateFactoryBuilderWriterStates.BufferingState:
this.queuedNodes.Writer.WriteEndObject();
break;
case ActivityTemplateFactoryBuilderWriterStates.BypassState:
this.underlyingWriter.WriteEndObject();
break;
default:
SharedFx.Assert(
this.currentState == ActivityTemplateFactoryBuilderWriterStates.BufferingNameState
|| this.currentState == ActivityTemplateFactoryBuilderWriterStates.BufferingTargetTypeState,
"These are the only possible ActivityTemplateFactoryBuilderWriterStates.");
SharedFx.Assert("It is impossible to end an object when we are buffering the name / targetType.");
break;
}
}
public override void WriteGetObject()
{
switch (this.currentState)
{
case ActivityTemplateFactoryBuilderWriterStates.InitialState:
SharedFx.Assert("It is impossible to end an object during InitialState");
break;
case ActivityTemplateFactoryBuilderWriterStates.BufferingState:
this.queuedNodes.Writer.WriteGetObject();
break;
case ActivityTemplateFactoryBuilderWriterStates.BypassState:
this.underlyingWriter.WriteGetObject();
break;
default:
SharedFx.Assert(
this.currentState == ActivityTemplateFactoryBuilderWriterStates.BufferingNameState
|| this.currentState == ActivityTemplateFactoryBuilderWriterStates.BufferingTargetTypeState,
"These are the only possible ActivityTemplateFactoryBuilderWriterStates.");
SharedFx.Assert("It is impossible to get an object when we are buffering the name / targetType.");
break;
}
}
public override void WriteStartMember(XamlMember xamlMember)
{
switch (this.currentState)
{
case ActivityTemplateFactoryBuilderWriterStates.InitialState:
SharedFx.Assert("It is impossible to start a member during InitialState");
break;
case ActivityTemplateFactoryBuilderWriterStates.BufferingState:
if (xamlMember == this.ActivityTemplateFactoryBuilderImplementationMember)
{
xamlMember = this.ActivityTemplateFactoryImplementationMember;
if (!this.xamlLanguageNamespaceWritten)
{
// Required namespace for XAML x:Class
this.underlyingWriter.WriteNamespace(new NamespaceDeclaration("http://schemas.microsoft.com/winfx/2006/xaml", "x"));
}
this.underlyingWriter.WriteStartObject(this.ActivityTemplateFactoryType);
this.underlyingWriter.WriteStartMember(XamlLanguage.Class);
this.underlyingWriter.WriteValue(this.className);
this.underlyingWriter.WriteEndMember();
this.underlyingWriter.WriteStartMember(XamlLanguage.TypeArguments);
this.underlyingWriter.WriteValue(this.targetType);
this.underlyingWriter.WriteEndMember();
this.Transform(this.queuedNodes.Reader, this.underlyingWriter);
this.underlyingWriter.WriteStartMember(xamlMember);
this.currentState = ActivityTemplateFactoryBuilderWriterStates.BypassState;
}
if (xamlMember == this.ActivityTemplateFactoryBuilderNameMember)
{
this.currentState = ActivityTemplateFactoryBuilderWriterStates.BufferingNameState;
}
else if (xamlMember == this.ActivityTemplateFactoryBuilderTargetTypeMember)
{
this.currentState = ActivityTemplateFactoryBuilderWriterStates.BufferingTargetTypeState;
}
else
{
this.queuedNodes.Writer.WriteStartMember(xamlMember);
}
break;
case ActivityTemplateFactoryBuilderWriterStates.BypassState:
this.underlyingWriter.WriteStartMember(xamlMember);
break;
default:
SharedFx.Assert(
this.currentState == ActivityTemplateFactoryBuilderWriterStates.BufferingNameState
|| this.currentState == ActivityTemplateFactoryBuilderWriterStates.BufferingTargetTypeState,
"These are the only possible ActivityTemplateFactoryBuilderWriterStates.");
SharedFx.Assert("It is impossible to get an object when we are buffering the name / targetType.");
break;
}
}
public override void WriteEndMember()
{
switch (this.currentState)
{
case ActivityTemplateFactoryBuilderWriterStates.InitialState:
SharedFx.Assert("It is impossible to end a member during InitialState");
break;
case ActivityTemplateFactoryBuilderWriterStates.BufferingState:
this.queuedNodes.Writer.WriteEndMember();
break;
case ActivityTemplateFactoryBuilderWriterStates.BypassState:
this.underlyingWriter.WriteEndMember();
break;
default:
SharedFx.Assert(
this.currentState == ActivityTemplateFactoryBuilderWriterStates.BufferingNameState
|| this.currentState == ActivityTemplateFactoryBuilderWriterStates.BufferingTargetTypeState,
"These are the only possible ActivityTemplateFactoryBuilderWriterStates.");
// Intentionally skipped the end member of Name / TargetType node
this.currentState = ActivityTemplateFactoryBuilderWriterStates.BufferingState;
break;
}
}
public override void WriteValue(object value)
{
switch (this.currentState)
{
case ActivityTemplateFactoryBuilderWriterStates.InitialState:
SharedFx.Assert("It is impossible to write a value during InitialState");
break;
case ActivityTemplateFactoryBuilderWriterStates.BufferingState:
this.queuedNodes.Writer.WriteValue(value);
break;
case ActivityTemplateFactoryBuilderWriterStates.BufferingNameState:
this.className = (string)value;
break;
case ActivityTemplateFactoryBuilderWriterStates.BufferingTargetTypeState:
this.targetType = (string)value;
break;
default:
SharedFx.Assert(
this.currentState == ActivityTemplateFactoryBuilderWriterStates.BypassState,
"This is the only possible ActivityTemplateFactoryBuilderWriterStates");
this.underlyingWriter.WriteValue(value);
break;
}
}
private void Transform(XamlReader reader, XamlWriter myWriter)
{
while (!reader.IsEof)
{
reader.Read();
myWriter.WriteNode(reader);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public static class CtorTests
{
[Fact]
public static void TestDefaultConstructor()
{
using (X509Certificate2 c = new X509Certificate2())
{
VerifyDefaultConstructor(c);
}
}
private static void VerifyDefaultConstructor(X509Certificate2 c)
{
IntPtr h = c.Handle;
object ignored;
Assert.Equal(IntPtr.Zero, h);
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash());
#if HAVE_THUMBPRINT_OVERLOADS
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash(HashAlgorithmName.SHA256));
#endif
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithm());
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParameters());
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParametersString());
Assert.ThrowsAny<CryptographicException>(() => c.GetPublicKey());
Assert.ThrowsAny<CryptographicException>(() => c.GetSerialNumber());
Assert.ThrowsAny<CryptographicException>(() => ignored = c.Issuer);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.Subject);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.RawData);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.Thumbprint);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.SignatureAlgorithm);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.HasPrivateKey);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.Version);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.Archived);
Assert.ThrowsAny<CryptographicException>(() => c.Archived = false);
Assert.ThrowsAny<CryptographicException>(() => c.FriendlyName = "Hi");
Assert.ThrowsAny<CryptographicException>(() => ignored = c.SubjectName);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.IssuerName);
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHashString());
#if HAVE_THUMBPRINT_OVERLOADS
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHashString(HashAlgorithmName.SHA256));
#endif
Assert.ThrowsAny<CryptographicException>(() => c.GetEffectiveDateString());
Assert.ThrowsAny<CryptographicException>(() => c.GetExpirationDateString());
Assert.ThrowsAny<CryptographicException>(() => c.GetPublicKeyString());
Assert.ThrowsAny<CryptographicException>(() => c.GetRawCertData());
Assert.ThrowsAny<CryptographicException>(() => c.GetRawCertDataString());
Assert.ThrowsAny<CryptographicException>(() => c.GetSerialNumberString());
#pragma warning disable 0618
Assert.ThrowsAny<CryptographicException>(() => c.GetIssuerName());
Assert.ThrowsAny<CryptographicException>(() => c.GetName());
#pragma warning restore 0618
#if HAVE_THUMBPRINT_OVERLOADS
Assert.ThrowsAny<CryptographicException>(
() => c.TryGetCertHash(HashAlgorithmName.SHA256, Array.Empty<byte>(), out _));
#endif
}
[Fact]
public static void TestConstructor_DER()
{
byte[] expectedThumbPrintSha1 =
{
0x10, 0x8e, 0x2b, 0xa2, 0x36, 0x32, 0x62, 0x0c,
0x42, 0x7c, 0x57, 0x0b, 0x6d, 0x9d, 0xb5, 0x1a,
0xc3, 0x13, 0x87, 0xfe,
};
Action<X509Certificate2> assert = (c) =>
{
IntPtr h = c.Handle;
Assert.NotEqual(IntPtr.Zero, h);
byte[] actualThumbprint = c.GetCertHash();
Assert.Equal(expectedThumbPrintSha1, actualThumbprint);
#if HAVE_THUMBPRINT_OVERLOADS
byte[] specifiedAlgThumbprint = c.GetCertHash(HashAlgorithmName.SHA1);
Assert.Equal(expectedThumbPrintSha1, specifiedAlgThumbprint);
#endif
};
using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate))
{
assert(c);
using (X509Certificate2 c2 = new X509Certificate2(c))
{
assert(c2);
}
}
}
[Fact]
public static void TestConstructor_PEM()
{
byte[] expectedThumbPrintSha1 =
{
0x10, 0x8e, 0x2b, 0xa2, 0x36, 0x32, 0x62, 0x0c,
0x42, 0x7c, 0x57, 0x0b, 0x6d, 0x9d, 0xb5, 0x1a,
0xc3, 0x13, 0x87, 0xfe,
};
Action<X509Certificate2> assert = (cert) =>
{
IntPtr h = cert.Handle;
Assert.NotEqual(IntPtr.Zero, h);
byte[] actualThumbprint = cert.GetCertHash();
Assert.Equal(expectedThumbPrintSha1, actualThumbprint);
#if HAVE_THUMBPRINT_OVERLOADS
byte[] specifiedAlgThumbprint = cert.GetCertHash(HashAlgorithmName.SHA1);
Assert.Equal(expectedThumbPrintSha1, specifiedAlgThumbprint);
#endif
};
using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificatePemBytes))
{
assert(c);
using (X509Certificate2 c2 = new X509Certificate2(c))
{
assert(c2);
}
}
}
[Fact]
public static void TestCopyConstructor_NoPal()
{
using (var c1 = new X509Certificate2())
using (var c2 = new X509Certificate2(c1))
{
VerifyDefaultConstructor(c1);
VerifyDefaultConstructor(c2);
}
}
[Fact]
public static void TestCopyConstructor_Pal()
{
using (var c1 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
using (var c2 = new X509Certificate2(c1))
{
Assert.Equal(c1.GetCertHash(), c2.GetCertHash());
#if HAVE_THUMBPRINT_OVERLOADS
Assert.Equal(c1.GetCertHash(HashAlgorithmName.SHA256), c2.GetCertHash(HashAlgorithmName.SHA256));
#endif
Assert.Equal(c1.GetKeyAlgorithm(), c2.GetKeyAlgorithm());
Assert.Equal(c1.GetKeyAlgorithmParameters(), c2.GetKeyAlgorithmParameters());
Assert.Equal(c1.GetKeyAlgorithmParametersString(), c2.GetKeyAlgorithmParametersString());
Assert.Equal(c1.GetPublicKey(), c2.GetPublicKey());
Assert.Equal(c1.GetSerialNumber(), c2.GetSerialNumber());
Assert.Equal(c1.Issuer, c2.Issuer);
Assert.Equal(c1.Subject, c2.Subject);
Assert.Equal(c1.RawData, c2.RawData);
Assert.Equal(c1.Thumbprint, c2.Thumbprint);
Assert.Equal(c1.SignatureAlgorithm.Value, c2.SignatureAlgorithm.Value);
Assert.Equal(c1.HasPrivateKey, c2.HasPrivateKey);
Assert.Equal(c1.Version, c2.Version);
Assert.Equal(c1.Archived, c2.Archived);
Assert.Equal(c1.SubjectName.Name, c2.SubjectName.Name);
Assert.Equal(c1.IssuerName.Name, c2.IssuerName.Name);
Assert.Equal(c1.GetCertHashString(), c2.GetCertHashString());
#if HAVE_THUMBPRINT_OVERLOADS
Assert.Equal(c1.GetCertHashString(HashAlgorithmName.SHA256), c2.GetCertHashString(HashAlgorithmName.SHA256));
#endif
Assert.Equal(c1.GetEffectiveDateString(), c2.GetEffectiveDateString());
Assert.Equal(c1.GetExpirationDateString(), c2.GetExpirationDateString());
Assert.Equal(c1.GetPublicKeyString(), c2.GetPublicKeyString());
Assert.Equal(c1.GetRawCertData(), c2.GetRawCertData());
Assert.Equal(c1.GetRawCertDataString(), c2.GetRawCertDataString());
Assert.Equal(c1.GetSerialNumberString(), c2.GetSerialNumberString());
#pragma warning disable 0618
Assert.Equal(c1.GetIssuerName(), c2.GetIssuerName());
Assert.Equal(c1.GetName(), c2.GetName());
#pragma warning restore 0618
}
}
[Fact]
public static void TestCopyConstructor_Lifetime_Independent()
{
var c1 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword);
using (var c2 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
{
RSA rsa = c2.GetRSAPrivateKey();
byte[] hash = new byte[20];
byte[] sig = rsa.SignHash(hash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.Equal(TestData.PfxSha1Empty_ExpectedSig, sig);
c1.Dispose();
rsa.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
// Verify other cert and previous key do not affect cert
using (rsa = c2.GetRSAPrivateKey())
{
hash = new byte[20];
sig = rsa.SignHash(hash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.Equal(TestData.PfxSha1Empty_ExpectedSig, sig);
}
}
}
[Fact]
public static void TestCopyConstructor_Lifetime_Cloned()
{
var c1 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword);
var c2 = new X509Certificate2(c1);
TestPrivateKey(c1, true);
TestPrivateKey(c2, true);
c1.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
TestPrivateKey(c1, false);
TestPrivateKey(c2, true);
c2.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
TestPrivateKey(c2, false);
}
[Fact]
public static void TestCopyConstructor_Lifetime_Cloned_Reversed()
{
var c1 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword);
var c2 = new X509Certificate2(c1);
TestPrivateKey(c1, true);
TestPrivateKey(c2, true);
c2.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
TestPrivateKey(c1, true);
TestPrivateKey(c2, false);
c1.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
TestPrivateKey(c1, false);
}
private static void TestPrivateKey(X509Certificate2 c, bool expectSuccess)
{
if (expectSuccess)
{
using (RSA rsa = c.GetRSAPrivateKey())
{
byte[] hash = new byte[20];
byte[] sig = rsa.SignHash(hash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.Equal(TestData.PfxSha1Empty_ExpectedSig, sig);
}
}
else
{
Assert.ThrowsAny<CryptographicException>(() => c.GetRSAPrivateKey());
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // StoreSavedAsSerializedCerData not supported on Unix
public static void TestConstructor_SerializedCert_Windows()
{
const string ExpectedThumbPrint = "71CB4E2B02738AD44F8B382C93BD17BA665F9914";
Action<X509Certificate2> assert = (cert) =>
{
IntPtr h = cert.Handle;
Assert.NotEqual(IntPtr.Zero, h);
Assert.Equal(ExpectedThumbPrint, cert.Thumbprint);
};
using (X509Certificate2 c = new X509Certificate2(TestData.StoreSavedAsSerializedCerData))
{
assert(c);
using (X509Certificate2 c2 = new X509Certificate2(c))
{
assert(c2);
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // StoreSavedAsSerializedCerData not supported on Unix
public static void TestByteArrayConstructor_SerializedCert_Unix()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.StoreSavedAsSerializedCerData));
}
[Fact]
public static void TestNullConstructorArguments()
{
Assert.Throws<ArgumentNullException>(() => new X509Certificate2((string)null));
AssertExtensions.Throws<ArgumentException>("handle", () => new X509Certificate2(IntPtr.Zero));
AssertExtensions.Throws<ArgumentException>("rawData", () => new X509Certificate2((byte[])null, (string)null));
AssertExtensions.Throws<ArgumentException>("rawData", () => new X509Certificate2(Array.Empty<byte>(), (string)null));
AssertExtensions.Throws<ArgumentException>("rawData", () => new X509Certificate2((byte[])null, (string)null, X509KeyStorageFlags.DefaultKeySet));
AssertExtensions.Throws<ArgumentException>("rawData", () => new X509Certificate2(Array.Empty<byte>(), (string)null, X509KeyStorageFlags.DefaultKeySet));
// A null string password does not throw
using (new X509Certificate2(TestData.MsCertificate, (string)null)) { }
using (new X509Certificate2(TestData.MsCertificate, (string)null, X509KeyStorageFlags.DefaultKeySet)) { }
Assert.Throws<ArgumentNullException>(() => X509Certificate.CreateFromCertFile(null));
Assert.Throws<ArgumentNullException>(() => X509Certificate.CreateFromSignedFile(null));
AssertExtensions.Throws<ArgumentNullException>("cert", () => new X509Certificate2((X509Certificate2)null));
AssertExtensions.Throws<ArgumentException>("handle", () => new X509Certificate2(IntPtr.Zero));
// A null SecureString password does not throw
using (new X509Certificate2(TestData.MsCertificate, (SecureString)null)) { }
using (new X509Certificate2(TestData.MsCertificate, (SecureString)null, X509KeyStorageFlags.DefaultKeySet)) { }
// For compat reasons, the (byte[]) constructor (and only that constructor) treats a null or 0-length array as the same
// as calling the default constructor.
{
using (X509Certificate2 c = new X509Certificate2((byte[])null))
{
IntPtr h = c.Handle;
Assert.Equal(IntPtr.Zero, h);
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash());
}
}
{
using (X509Certificate2 c = new X509Certificate2(Array.Empty<byte>()))
{
IntPtr h = c.Handle;
Assert.Equal(IntPtr.Zero, h);
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash());
}
}
}
[Fact]
public static void InvalidCertificateBlob()
{
CryptographicException ex = Assert.ThrowsAny<CryptographicException>(
() => new X509Certificate2(new byte[] { 0x01, 0x02, 0x03 }));
CryptographicException defaultException = new CryptographicException();
Assert.NotEqual(defaultException.Message, ex.Message);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.Equal(unchecked((int)0x80092009), ex.HResult);
// TODO (3233): Test that Message is also set correctly
//Assert.Equal("Cannot find the requested object.", ex.Message);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Assert.Equal(-25257, ex.HResult);
}
else // Any Unix
{
// OpenSSL encodes the function name into the error code. However, the function name differs
// between versions (OpenSSL 1.0, OpenSSL 1.1 and BoringSSL) and it's subject to change in
// the future, so don't test for the exact match and mask out the function code away. The
// component number (high 8 bits) and error code (low 12 bits) should remain the same.
Assert.Equal(0x0D00003A, ex.HResult & 0xFF000FFF);
}
}
#if !NO_EPHEMERALKEYSET_AVAILABLE
[Fact]
public static void InvalidStorageFlags()
{
byte[] nonEmptyBytes = new byte[1];
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate(nonEmptyBytes, string.Empty, (X509KeyStorageFlags)0xFF));
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate(string.Empty, string.Empty, (X509KeyStorageFlags)0xFF));
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate2(nonEmptyBytes, string.Empty, (X509KeyStorageFlags)0xFF));
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate2(string.Empty, string.Empty, (X509KeyStorageFlags)0xFF));
// No test is performed here for the ephemeral flag failing downlevel, because the live
// binary is always used by default, meaning it doesn't know EphemeralKeySet doesn't exist.
}
[Fact]
public static void InvalidStorageFlags_PersistedEphemeral()
{
const X509KeyStorageFlags PersistedEphemeral =
X509KeyStorageFlags.EphemeralKeySet | X509KeyStorageFlags.PersistKeySet;
byte[] nonEmptyBytes = new byte[1];
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate(nonEmptyBytes, string.Empty, PersistedEphemeral));
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate(string.Empty, string.Empty, PersistedEphemeral));
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate2(nonEmptyBytes, string.Empty, PersistedEphemeral));
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate2(string.Empty, string.Empty, PersistedEphemeral));
}
#endif
}
}
| |
// 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.Data.Common;
using System.Diagnostics;
using System.Threading;
namespace System.Data.SqlClient
{
internal sealed partial class SqlConnectionString : DbConnectionOptions
{
// instances of this class are intended to be immutable, i.e readonly
// used by pooling classes so it is much easier to verify correctness
// when not worried about the class being modified during execution
internal static partial class DEFAULT
{
internal const ApplicationIntent ApplicationIntent = DbConnectionStringDefaults.ApplicationIntent;
internal const string Application_Name = TdsEnums.SQL_PROVIDER_NAME;
internal const string AttachDBFilename = "";
internal const int Connect_Timeout = ADP.DefaultConnectionTimeout;
internal const string Current_Language = "";
internal const string Data_Source = "";
internal const bool Encrypt = false;
internal const bool Enlist = true;
internal const string FailoverPartner = "";
internal const string Initial_Catalog = "";
internal const bool Integrated_Security = false;
internal const int Load_Balance_Timeout = 0; // default of 0 means don't use
internal const bool MARS = false;
internal const int Max_Pool_Size = 100;
internal const int Min_Pool_Size = 0;
internal const bool MultiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover;
internal const int Packet_Size = 8000;
internal const string Password = "";
internal const bool Persist_Security_Info = false;
internal const bool Pooling = true;
internal const bool TrustServerCertificate = false;
internal const string Type_System_Version = "";
internal const string User_ID = "";
internal const bool User_Instance = false;
internal const bool Replication = false;
internal const int Connect_Retry_Count = 1;
internal const int Connect_Retry_Interval = 10;
}
// SqlConnection ConnectionString Options
// keys must be lowercase!
internal static class KEY
{
internal const string ApplicationIntent = "applicationintent";
internal const string Application_Name = "application name";
internal const string AsynchronousProcessing = "asynchronous processing";
internal const string AttachDBFilename = "attachdbfilename";
#if NETCOREAPP
internal const string PoolBlockingPeriod = "poolblockingperiod";
#endif
internal const string Connect_Timeout = "connect timeout";
internal const string Connection_Reset = "connection reset";
internal const string Context_Connection = "context connection";
internal const string Current_Language = "current language";
internal const string Data_Source = "data source";
internal const string Encrypt = "encrypt";
internal const string Enlist = "enlist";
internal const string FailoverPartner = "failover partner";
internal const string Initial_Catalog = "initial catalog";
internal const string Integrated_Security = "integrated security";
internal const string Load_Balance_Timeout = "load balance timeout";
internal const string MARS = "multipleactiveresultsets";
internal const string Max_Pool_Size = "max pool size";
internal const string Min_Pool_Size = "min pool size";
internal const string MultiSubnetFailover = "multisubnetfailover";
internal const string Network_Library = "network library";
internal const string Packet_Size = "packet size";
internal const string Password = "password";
internal const string Persist_Security_Info = "persist security info";
internal const string Pooling = "pooling";
internal const string TransactionBinding = "transaction binding";
internal const string TrustServerCertificate = "trustservercertificate";
internal const string Type_System_Version = "type system version";
internal const string User_ID = "user id";
internal const string User_Instance = "user instance";
internal const string Workstation_Id = "workstation id";
internal const string Replication = "replication";
internal const string Connect_Retry_Count = "connectretrycount";
internal const string Connect_Retry_Interval = "connectretryinterval";
}
// Constant for the number of duplicate options in the connection string
private static class SYNONYM
{
// application name
internal const string APP = "app";
internal const string Async = "async";
// attachDBFilename
internal const string EXTENDED_PROPERTIES = "extended properties";
internal const string INITIAL_FILE_NAME = "initial file name";
// connect timeout
internal const string CONNECTION_TIMEOUT = "connection timeout";
internal const string TIMEOUT = "timeout";
// current language
internal const string LANGUAGE = "language";
// data source
internal const string ADDR = "addr";
internal const string ADDRESS = "address";
internal const string SERVER = "server";
internal const string NETWORK_ADDRESS = "network address";
// initial catalog
internal const string DATABASE = "database";
// integrated security
internal const string TRUSTED_CONNECTION = "trusted_connection";
// load balance timeout
internal const string Connection_Lifetime = "connection lifetime";
// network library
internal const string NET = "net";
internal const string NETWORK = "network";
// password
internal const string Pwd = "pwd";
// persist security info
internal const string PERSISTSECURITYINFO = "persistsecurityinfo";
// user id
internal const string UID = "uid";
internal const string User = "user";
// workstation id
internal const string WSID = "wsid";
// make sure to update SynonymCount value below when adding or removing synonyms
}
internal const int SynonymCount = 18;
internal const int DeprecatedSynonymCount = 3;
internal enum TypeSystem
{
Latest = 2008,
SQLServer2000 = 2000,
SQLServer2005 = 2005,
SQLServer2008 = 2008,
SQLServer2012 = 2012,
}
internal static class TYPESYSTEMVERSION
{
internal const string Latest = "Latest";
internal const string SQL_Server_2000 = "SQL Server 2000";
internal const string SQL_Server_2005 = "SQL Server 2005";
internal const string SQL_Server_2008 = "SQL Server 2008";
internal const string SQL_Server_2012 = "SQL Server 2012";
}
internal enum TransactionBindingEnum
{
ImplicitUnbind,
ExplicitUnbind
}
internal static class TRANSACTIONBINDING
{
internal const string ImplicitUnbind = "Implicit Unbind";
internal const string ExplicitUnbind = "Explicit Unbind";
}
private static Dictionary<string, string> s_sqlClientSynonyms;
private readonly bool _integratedSecurity;
private readonly bool _encrypt;
private readonly bool _trustServerCertificate;
private readonly bool _enlist;
private readonly bool _mars;
private readonly bool _persistSecurityInfo;
private readonly bool _pooling;
private readonly bool _replication;
private readonly bool _userInstance;
private readonly bool _multiSubnetFailover;
private readonly int _connectTimeout;
private readonly int _loadBalanceTimeout;
private readonly int _maxPoolSize;
private readonly int _minPoolSize;
private readonly int _packetSize;
private readonly int _connectRetryCount;
private readonly int _connectRetryInterval;
private readonly ApplicationIntent _applicationIntent;
private readonly string _applicationName;
private readonly string _attachDBFileName;
private readonly string _currentLanguage;
private readonly string _dataSource;
private readonly string _localDBInstance; // created based on datasource, set to NULL if datasource is not LocalDB
private readonly string _failoverPartner;
private readonly string _initialCatalog;
private readonly string _password;
private readonly string _userID;
private readonly string _workstationId;
private readonly TransactionBindingEnum _transactionBinding;
private readonly TypeSystem _typeSystemVersion;
private readonly Version _typeSystemAssemblyVersion;
private static readonly Version constTypeSystemAsmVersion10 = new Version("10.0.0.0");
private static readonly Version constTypeSystemAsmVersion11 = new Version("11.0.0.0");
internal SqlConnectionString(string connectionString) : base(connectionString, GetParseSynonyms())
{
ThrowUnsupportedIfKeywordSet(KEY.AsynchronousProcessing);
ThrowUnsupportedIfKeywordSet(KEY.Connection_Reset);
ThrowUnsupportedIfKeywordSet(KEY.Context_Connection);
// Network Library has its own special error message
if (ContainsKey(KEY.Network_Library))
{
throw SQL.NetworkLibraryKeywordNotSupported();
}
_integratedSecurity = ConvertValueToIntegratedSecurity();
#if NETCOREAPP
_poolBlockingPeriod = ConvertValueToPoolBlockingPeriod();
#endif
_encrypt = ConvertValueToBoolean(KEY.Encrypt, DEFAULT.Encrypt);
_enlist = ConvertValueToBoolean(KEY.Enlist, DEFAULT.Enlist);
_mars = ConvertValueToBoolean(KEY.MARS, DEFAULT.MARS);
_persistSecurityInfo = ConvertValueToBoolean(KEY.Persist_Security_Info, DEFAULT.Persist_Security_Info);
_pooling = ConvertValueToBoolean(KEY.Pooling, DEFAULT.Pooling);
_replication = ConvertValueToBoolean(KEY.Replication, DEFAULT.Replication);
_userInstance = ConvertValueToBoolean(KEY.User_Instance, DEFAULT.User_Instance);
_multiSubnetFailover = ConvertValueToBoolean(KEY.MultiSubnetFailover, DEFAULT.MultiSubnetFailover);
_connectTimeout = ConvertValueToInt32(KEY.Connect_Timeout, DEFAULT.Connect_Timeout);
_loadBalanceTimeout = ConvertValueToInt32(KEY.Load_Balance_Timeout, DEFAULT.Load_Balance_Timeout);
_maxPoolSize = ConvertValueToInt32(KEY.Max_Pool_Size, DEFAULT.Max_Pool_Size);
_minPoolSize = ConvertValueToInt32(KEY.Min_Pool_Size, DEFAULT.Min_Pool_Size);
_packetSize = ConvertValueToInt32(KEY.Packet_Size, DEFAULT.Packet_Size);
_connectRetryCount = ConvertValueToInt32(KEY.Connect_Retry_Count, DEFAULT.Connect_Retry_Count);
_connectRetryInterval = ConvertValueToInt32(KEY.Connect_Retry_Interval, DEFAULT.Connect_Retry_Interval);
_applicationIntent = ConvertValueToApplicationIntent();
_applicationName = ConvertValueToString(KEY.Application_Name, DEFAULT.Application_Name);
_attachDBFileName = ConvertValueToString(KEY.AttachDBFilename, DEFAULT.AttachDBFilename);
_currentLanguage = ConvertValueToString(KEY.Current_Language, DEFAULT.Current_Language);
_dataSource = ConvertValueToString(KEY.Data_Source, DEFAULT.Data_Source);
_localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource);
_failoverPartner = ConvertValueToString(KEY.FailoverPartner, DEFAULT.FailoverPartner);
_initialCatalog = ConvertValueToString(KEY.Initial_Catalog, DEFAULT.Initial_Catalog);
_password = ConvertValueToString(KEY.Password, DEFAULT.Password);
_trustServerCertificate = ConvertValueToBoolean(KEY.TrustServerCertificate, DEFAULT.TrustServerCertificate);
// Temporary string - this value is stored internally as an enum.
string typeSystemVersionString = ConvertValueToString(KEY.Type_System_Version, null);
string transactionBindingString = ConvertValueToString(KEY.TransactionBinding, null);
_userID = ConvertValueToString(KEY.User_ID, DEFAULT.User_ID);
_workstationId = ConvertValueToString(KEY.Workstation_Id, null);
if (_loadBalanceTimeout < 0)
{
throw ADP.InvalidConnectionOptionValue(KEY.Load_Balance_Timeout);
}
if (_connectTimeout < 0)
{
throw ADP.InvalidConnectionOptionValue(KEY.Connect_Timeout);
}
if (_maxPoolSize < 1)
{
throw ADP.InvalidConnectionOptionValue(KEY.Max_Pool_Size);
}
if (_minPoolSize < 0)
{
throw ADP.InvalidConnectionOptionValue(KEY.Min_Pool_Size);
}
if (_maxPoolSize < _minPoolSize)
{
throw ADP.InvalidMinMaxPoolSizeValues();
}
if ((_packetSize < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < _packetSize))
{
throw SQL.InvalidPacketSizeValue();
}
ValidateValueLength(_applicationName, TdsEnums.MAXLEN_APPNAME, KEY.Application_Name);
ValidateValueLength(_currentLanguage, TdsEnums.MAXLEN_LANGUAGE, KEY.Current_Language);
ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source);
ValidateValueLength(_failoverPartner, TdsEnums.MAXLEN_SERVERNAME, KEY.FailoverPartner);
ValidateValueLength(_initialCatalog, TdsEnums.MAXLEN_DATABASE, KEY.Initial_Catalog);
ValidateValueLength(_password, TdsEnums.MAXLEN_PASSWORD, KEY.Password);
ValidateValueLength(_userID, TdsEnums.MAXLEN_USERNAME, KEY.User_ID);
if (null != _workstationId)
{
ValidateValueLength(_workstationId, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id);
}
if (!string.Equals(DEFAULT.FailoverPartner, _failoverPartner, StringComparison.OrdinalIgnoreCase))
{
// fail-over partner is set
if (_multiSubnetFailover)
{
throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: false, internalConnection: null);
}
if (string.Equals(DEFAULT.Initial_Catalog, _initialCatalog, StringComparison.OrdinalIgnoreCase))
{
throw ADP.MissingConnectionOptionValue(KEY.FailoverPartner, KEY.Initial_Catalog);
}
}
// string.Contains(char) is .NetCore2.1+ specific
if (0 <= _attachDBFileName.IndexOf('|'))
{
throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename);
}
else
{
ValidateValueLength(_attachDBFileName, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename);
}
_typeSystemAssemblyVersion = constTypeSystemAsmVersion10;
if (true == _userInstance && !string.IsNullOrEmpty(_failoverPartner))
{
throw SQL.UserInstanceFailoverNotCompatible();
}
if (string.IsNullOrEmpty(typeSystemVersionString))
{
typeSystemVersionString = DbConnectionStringDefaults.TypeSystemVersion;
}
if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.Latest, StringComparison.OrdinalIgnoreCase))
{
_typeSystemVersion = TypeSystem.Latest;
}
else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2000, StringComparison.OrdinalIgnoreCase))
{
_typeSystemVersion = TypeSystem.SQLServer2000;
}
else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2005, StringComparison.OrdinalIgnoreCase))
{
_typeSystemVersion = TypeSystem.SQLServer2005;
}
else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2008, StringComparison.OrdinalIgnoreCase))
{
_typeSystemVersion = TypeSystem.SQLServer2008;
}
else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2012, StringComparison.OrdinalIgnoreCase))
{
_typeSystemVersion = TypeSystem.SQLServer2012;
_typeSystemAssemblyVersion = constTypeSystemAsmVersion11;
}
else
{
throw ADP.InvalidConnectionOptionValue(KEY.Type_System_Version);
}
if (string.IsNullOrEmpty(transactionBindingString))
{
transactionBindingString = DbConnectionStringDefaults.TransactionBinding;
}
if (transactionBindingString.Equals(TRANSACTIONBINDING.ImplicitUnbind, StringComparison.OrdinalIgnoreCase))
{
_transactionBinding = TransactionBindingEnum.ImplicitUnbind;
}
else if (transactionBindingString.Equals(TRANSACTIONBINDING.ExplicitUnbind, StringComparison.OrdinalIgnoreCase))
{
_transactionBinding = TransactionBindingEnum.ExplicitUnbind;
}
else
{
throw ADP.InvalidConnectionOptionValue(KEY.TransactionBinding);
}
if (_applicationIntent == ApplicationIntent.ReadOnly && !string.IsNullOrEmpty(_failoverPartner))
throw SQL.ROR_FailoverNotSupportedConnString();
if ((_connectRetryCount < 0) || (_connectRetryCount > 255))
{
throw ADP.InvalidConnectRetryCountValue();
}
if ((_connectRetryInterval < 1) || (_connectRetryInterval > 60))
{
throw ADP.InvalidConnectRetryIntervalValue();
}
}
// This c-tor is used to create SSE and user instance connection strings when user instance is set to true
// BUG (VSTFDevDiv) 479687: Using TransactionScope with Linq2SQL against user instances fails with "connection has been broken" message
internal SqlConnectionString(SqlConnectionString connectionOptions, string dataSource, bool userInstance, bool? setEnlistValue) : base(connectionOptions)
{
_integratedSecurity = connectionOptions._integratedSecurity;
_encrypt = connectionOptions._encrypt;
if (setEnlistValue.HasValue)
{
_enlist = setEnlistValue.Value;
}
else
{
_enlist = connectionOptions._enlist;
}
_mars = connectionOptions._mars;
_persistSecurityInfo = connectionOptions._persistSecurityInfo;
_pooling = connectionOptions._pooling;
_replication = connectionOptions._replication;
_userInstance = userInstance;
_connectTimeout = connectionOptions._connectTimeout;
_loadBalanceTimeout = connectionOptions._loadBalanceTimeout;
#if NETCOREAPP
_poolBlockingPeriod = connectionOptions._poolBlockingPeriod;
#endif
_maxPoolSize = connectionOptions._maxPoolSize;
_minPoolSize = connectionOptions._minPoolSize;
_multiSubnetFailover = connectionOptions._multiSubnetFailover;
_packetSize = connectionOptions._packetSize;
_applicationName = connectionOptions._applicationName;
_attachDBFileName = connectionOptions._attachDBFileName;
_currentLanguage = connectionOptions._currentLanguage;
_dataSource = dataSource;
_localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource);
_failoverPartner = connectionOptions._failoverPartner;
_initialCatalog = connectionOptions._initialCatalog;
_password = connectionOptions._password;
_userID = connectionOptions._userID;
_workstationId = connectionOptions._workstationId;
_typeSystemVersion = connectionOptions._typeSystemVersion;
_transactionBinding = connectionOptions._transactionBinding;
_applicationIntent = connectionOptions._applicationIntent;
_connectRetryCount = connectionOptions._connectRetryCount;
_connectRetryInterval = connectionOptions._connectRetryInterval;
ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source);
}
internal bool IntegratedSecurity { get { return _integratedSecurity; } }
// We always initialize in Async mode so that both synchronous and asynchronous methods
// will work. In the future we can deprecate the keyword entirely.
internal bool Asynchronous { get { return true; } }
// SQLPT 41700: Ignore ResetConnection=False, always reset the connection for security
internal bool ConnectionReset { get { return true; } }
// internal bool EnableUdtDownload { get { return _enableUdtDownload;} }
internal bool Encrypt { get { return _encrypt; } }
internal bool TrustServerCertificate { get { return _trustServerCertificate; } }
internal bool Enlist { get { return _enlist; } }
internal bool MARS { get { return _mars; } }
internal bool MultiSubnetFailover { get { return _multiSubnetFailover; } }
internal bool PersistSecurityInfo { get { return _persistSecurityInfo; } }
internal bool Pooling { get { return _pooling; } }
internal bool Replication { get { return _replication; } }
internal bool UserInstance { get { return _userInstance; } }
internal int ConnectTimeout { get { return _connectTimeout; } }
internal int LoadBalanceTimeout { get { return _loadBalanceTimeout; } }
internal int MaxPoolSize { get { return _maxPoolSize; } }
internal int MinPoolSize { get { return _minPoolSize; } }
internal int PacketSize { get { return _packetSize; } }
internal int ConnectRetryCount { get { return _connectRetryCount; } }
internal int ConnectRetryInterval { get { return _connectRetryInterval; } }
internal ApplicationIntent ApplicationIntent { get { return _applicationIntent; } }
internal string ApplicationName { get { return _applicationName; } }
internal string AttachDBFilename { get { return _attachDBFileName; } }
internal string CurrentLanguage { get { return _currentLanguage; } }
internal string DataSource { get { return _dataSource; } }
internal string LocalDBInstance { get { return _localDBInstance; } }
internal string FailoverPartner { get { return _failoverPartner; } }
internal string InitialCatalog { get { return _initialCatalog; } }
internal string Password { get { return _password; } }
internal string UserID { get { return _userID; } }
internal string WorkstationId { get { return _workstationId; } }
internal TypeSystem TypeSystemVersion { get { return _typeSystemVersion; } }
internal Version TypeSystemAssemblyVersion { get { return _typeSystemAssemblyVersion; } }
internal TransactionBindingEnum TransactionBinding { get { return _transactionBinding; } }
// This dictionary is meant to be read-only translation of parsed string
// keywords/synonyms to a known keyword string.
internal static Dictionary<string, string> GetParseSynonyms()
{
Dictionary<string, string> synonyms = s_sqlClientSynonyms;
if (null == synonyms)
{
int count = SqlConnectionStringBuilder.KeywordsCount + SqlConnectionStringBuilder.DeprecatedKeywordsCount + SynonymCount + DeprecatedSynonymCount;
synonyms = new Dictionary<string, string>(count)
{
{ KEY.ApplicationIntent, KEY.ApplicationIntent },
{ KEY.Application_Name, KEY.Application_Name },
{ KEY.AsynchronousProcessing, KEY.AsynchronousProcessing },
{ KEY.AttachDBFilename, KEY.AttachDBFilename },
#if NETCOREAPP
{ KEY.PoolBlockingPeriod, KEY.PoolBlockingPeriod},
#endif
{ KEY.Connect_Timeout, KEY.Connect_Timeout },
{ KEY.Connection_Reset, KEY.Connection_Reset },
{ KEY.Context_Connection, KEY.Context_Connection },
{ KEY.Current_Language, KEY.Current_Language },
{ KEY.Data_Source, KEY.Data_Source },
{ KEY.Encrypt, KEY.Encrypt },
{ KEY.Enlist, KEY.Enlist },
{ KEY.FailoverPartner, KEY.FailoverPartner },
{ KEY.Initial_Catalog, KEY.Initial_Catalog },
{ KEY.Integrated_Security, KEY.Integrated_Security },
{ KEY.Load_Balance_Timeout, KEY.Load_Balance_Timeout },
{ KEY.MARS, KEY.MARS },
{ KEY.Max_Pool_Size, KEY.Max_Pool_Size },
{ KEY.Min_Pool_Size, KEY.Min_Pool_Size },
{ KEY.MultiSubnetFailover, KEY.MultiSubnetFailover },
{ KEY.Network_Library, KEY.Network_Library },
{ KEY.Packet_Size, KEY.Packet_Size },
{ KEY.Password, KEY.Password },
{ KEY.Persist_Security_Info, KEY.Persist_Security_Info },
{ KEY.Pooling, KEY.Pooling },
{ KEY.Replication, KEY.Replication },
{ KEY.TrustServerCertificate, KEY.TrustServerCertificate },
{ KEY.TransactionBinding, KEY.TransactionBinding },
{ KEY.Type_System_Version, KEY.Type_System_Version },
{ KEY.User_ID, KEY.User_ID },
{ KEY.User_Instance, KEY.User_Instance },
{ KEY.Workstation_Id, KEY.Workstation_Id },
{ KEY.Connect_Retry_Count, KEY.Connect_Retry_Count },
{ KEY.Connect_Retry_Interval, KEY.Connect_Retry_Interval },
{ SYNONYM.APP, KEY.Application_Name },
{ SYNONYM.Async, KEY.AsynchronousProcessing },
{ SYNONYM.EXTENDED_PROPERTIES, KEY.AttachDBFilename },
{ SYNONYM.INITIAL_FILE_NAME, KEY.AttachDBFilename },
{ SYNONYM.CONNECTION_TIMEOUT, KEY.Connect_Timeout },
{ SYNONYM.TIMEOUT, KEY.Connect_Timeout },
{ SYNONYM.LANGUAGE, KEY.Current_Language },
{ SYNONYM.ADDR, KEY.Data_Source },
{ SYNONYM.ADDRESS, KEY.Data_Source },
{ SYNONYM.NETWORK_ADDRESS, KEY.Data_Source },
{ SYNONYM.SERVER, KEY.Data_Source },
{ SYNONYM.DATABASE, KEY.Initial_Catalog },
{ SYNONYM.TRUSTED_CONNECTION, KEY.Integrated_Security },
{ SYNONYM.Connection_Lifetime, KEY.Load_Balance_Timeout },
{ SYNONYM.NET, KEY.Network_Library },
{ SYNONYM.NETWORK, KEY.Network_Library },
{ SYNONYM.Pwd, KEY.Password },
{ SYNONYM.PERSISTSECURITYINFO, KEY.Persist_Security_Info },
{ SYNONYM.UID, KEY.User_ID },
{ SYNONYM.User, KEY.User_ID },
{ SYNONYM.WSID, KEY.Workstation_Id }
};
Debug.Assert(synonyms.Count == count, "incorrect initial ParseSynonyms size");
Interlocked.CompareExchange(ref s_sqlClientSynonyms, synonyms, null);
}
return synonyms;
}
internal string ObtainWorkstationId()
{
// If not supplied by the user, the default value is the MachineName
// Note: In Longhorn you'll be able to rename a machine without
// rebooting. Therefore, don't cache this machine name.
string result = WorkstationId;
if (null == result)
{
// permission to obtain Environment.MachineName is Asserted
// since permission to open the connection has been granted
// the information is shared with the server, but not directly with the user
result = ADP.MachineName();
ValidateValueLength(result, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id);
}
return result;
}
private void ValidateValueLength(string value, int limit, string key)
{
if (limit < value.Length)
{
throw ADP.InvalidConnectionOptionValueLength(key, limit);
}
}
internal System.Data.SqlClient.ApplicationIntent ConvertValueToApplicationIntent()
{
string value;
if (!TryGetParsetableValue(KEY.ApplicationIntent, out value))
{
return DEFAULT.ApplicationIntent;
}
// when wrong value is used in the connection string provided to SqlConnection.ConnectionString or c-tor,
// wrap Format and Overflow exceptions with Argument one, to be consistent with rest of the keyword types (like int and bool)
try
{
return DbConnectionStringBuilderUtil.ConvertToApplicationIntent(KEY.ApplicationIntent, value);
}
catch (FormatException e)
{
throw ADP.InvalidConnectionOptionValue(KEY.ApplicationIntent, e);
}
catch (OverflowException e)
{
throw ADP.InvalidConnectionOptionValue(KEY.ApplicationIntent, e);
}
// ArgumentException and other types are raised as is (no wrapping)
}
internal void ThrowUnsupportedIfKeywordSet(string keyword)
{
if (ContainsKey(keyword))
{
throw SQL.UnsupportedKeyword(keyword);
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Xml;
using Palaso.IO;
using Palaso.Xml;
namespace Palaso.TestUtilities
{
public class TempLiftFile : TempFile
{
public TempLiftFile(string xmlOfEntries)
: this(xmlOfEntries, /*LiftIO.Validation.Validator.LiftVersion*/ "0.12")
{
}
public TempLiftFile(string xmlOfEntries, string claimedLiftVersion)
: this(null, xmlOfEntries, claimedLiftVersion)
{
}
public TempLiftFile(TemporaryFolder parentFolder, string xmlOfEntries, string claimedLiftVersion)
: base(true) // True means "I'll set the the pathname, thank you very much." Otherwise, the temp one 'false' creates will stay forever, and fill the hard drive up.
{
if (parentFolder != null)
{
_path = parentFolder.GetPathForNewTempFile(false) + ".lift";
}
else
{
var temp = System.IO.Path.GetTempFileName();
_path = temp + ".lift";
File.Move(temp, _path);
}
string liftContents = string.Format("<?xml version='1.0' encoding='utf-8'?><lift version='{0}'>{1}</lift>", claimedLiftVersion, xmlOfEntries);
File.WriteAllText(_path, liftContents);
}
public TempLiftFile(string fileName, TemporaryFolder parentFolder, string xmlOfEntries, string claimedLiftVersion)
: base(true) // True means "I'll set the the pathname, thank you very much." Otherwise, the temp one 'false' creates will stay forever, and fill the hard drive up.
{
_path = parentFolder.Combine(fileName);
string liftContents = string.Format("<?xml version='1.0' encoding='utf-8'?><lift version='{0}'>{1}</lift>", claimedLiftVersion, xmlOfEntries);
File.WriteAllText(_path, liftContents);
}
private TempLiftFile()
: base(true) // True means "I'll set the the pathname, thank you very much." Otherwise, the temp one 'false' creates will stay forever, and fill the hard drive up.
{
}
/// <summary>
/// Create a TempLiftFile based on a pre-existing file, which will be deleted when this is disposed.
/// </summary>
public static TempLiftFile TrackExisting(string path)
{
Debug.Assert(File.Exists(path));
TempLiftFile t = new TempLiftFile();
t._path = path;
return t;
}
}
/// <summary>
/// This is useful for unit tests. When it is disposed, it will delete the file.
/// </summary>
/// <example>using(f = new TemporaryFile(){}</example>
public class TempFileFromFolder : TempFile
{
/// <summary>
/// Create a tempfile within the given parent folder
/// </summary>
public TempFileFromFolder(TemporaryFolder parentFolder)
: base(true) // True means "I'll set the the pathname, thank you very much." Otherwise, the temp one 'false' creates will stay forever, and fill the hard drive up.
{
_path = parentFolder != null ? parentFolder.GetPathForNewTempFile(true) : System.IO.Path.GetTempFileName();
}
public TempFileFromFolder(TemporaryFolder parentFolder, string name, string contents)
: base(true) // True means "I'll set the the pathname, thank you very much." Otherwise, the temp one 'false' creates will stay forever, and fill the hard drive up.
{
_path = parentFolder.Combine(name);
File.WriteAllText(_path, contents);
}
public static TempFile CreateXmlFileWithContents(string fileName, TemporaryFolder folder, string xmlBody)
{
string path = folder.Combine(fileName);
using (var reader = XmlReader.Create(new StringReader(xmlBody)))
{
using (var writer = XmlWriter.Create(path, CanonicalXmlSettings.CreateXmlWriterSettings()))
{
writer.WriteStartDocument();
writer.WriteNode(reader, false);
}
}
return new TempFile(path, true);
}
public static TempFile CreateAt(string path, string contents)
{
File.WriteAllText(path, contents);
return TrackExisting(path);
}
}
/// <summary>
/// This is useful for unit tests. When it is disposed, it works hard to empty and remove the folder.
/// </summary>
/// <example>using(f = new TemporaryFolder("My Export Tests"){}</example>
public class TemporaryFolder : IDisposable
{
private string _path;
/// <summary>
/// Create a TemporaryFolder based on a pre-existing directory, which will be deleted when this is disposed.
/// </summary>
static public TemporaryFolder TrackExisting(string path)
{
Debug.Assert(Directory.Exists(path), @"TrackExisting given non existant folder to track.");
var f = new TemporaryFolder(false);
f._path = path;
return f;
}
[Obsolete("Go ahead and give it a name related to the test. Makes it easier to track down problems.")]
public TemporaryFolder()
: this(System.IO.Path.GetRandomFileName())
{
}
/// <summary>
/// Private constructor that doesn't create a file. Used when tracking a pre-existing
/// directory.
/// </summary>
private TemporaryFolder(bool ignored)
{
}
public TemporaryFolder(string name)
{
_path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), name);
if (Directory.Exists(_path))
{
TestUtilities.DeleteFolderThatMayBeInUse(_path);
}
Directory.CreateDirectory(_path);
}
public TemporaryFolder(TemporaryFolder parent, string name)
{
_path = parent.Combine(name);
if (Directory.Exists(_path))
{
TestUtilities.DeleteFolderThatMayBeInUse(_path);
}
Directory.CreateDirectory(_path);
}
[Obsolete("Path is preferred")]
public string FolderPath
{
get { return _path; }
}
/// <summary>
/// Same as FolderPath, but I repent of that poor name
/// </summary>
public string Path
{
get { return _path; }
}
public void Dispose()
{
TestUtilities.DeleteFolderThatMayBeInUse(_path);
}
[Obsolete("It's better to wrap the use of this in a using() so that it is automatically cleaned up, even if a test fails.")]
public void Delete()
{
TestUtilities.DeleteFolderThatMayBeInUse(_path);
}
public string GetPathForNewTempFile(bool doCreateTheFile)
{
string s = System.IO.Path.GetRandomFileName();
s = System.IO.Path.Combine(_path, s);
if (doCreateTheFile)
{
File.Create(s).Close();
}
return s;
}
public TempFile GetNewTempFile(bool doCreateTheFile)
{
string s = System.IO.Path.GetRandomFileName();
s = System.IO.Path.Combine(_path, s);
if (doCreateTheFile)
{
File.Create(s).Close();
}
return TempFile.TrackExisting(s);
}
[Obsolete("It's better to use the explict GetNewTempFile, which makes you say if you want the file to be created or not, and give you back a whole TempFile class, which is itself IDisposable.")]
public string GetTemporaryFile()
{
return GetTemporaryFile(System.IO.Path.GetRandomFileName());
}
[Obsolete("It's better to use the explict GetNewTempFile, which makes you say if you want the file to be created or not, and give you back a whole TempFile class, which is itself IDisposable.")]
public string GetTemporaryFile(string name)
{
string s = System.IO.Path.Combine(_path, name);
File.Create(s).Close();
return s;
}
/// <summary>
/// Similar to Path.Combine, but you don't have to specify the location of the temporaryfolder itself, and you can add multiple parts to combine.
/// </summary>
/// <example> string path = t.Combine("stuff", "toys", "ball.txt")</example>
public string Combine(params string[] partsOfThePath)
{
string result = _path;
foreach (var s in partsOfThePath)
{
result = System.IO.Path.Combine(result, s);
}
return result;
}
}
}
| |
using System;
using System.Collections;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
namespace Assets.Common.StandardAssets.Utility
{
[AddComponentMenu("Scripts/Standard Assets/Utility/Waypoint Circuit")]
public class WaypointCircuit : MonoBehaviour
{
public WaypointList waypointList = new WaypointList();
[SerializeField] private bool smoothRoute = true;
private int numPoints;
private Vector3[] points;
private float[] distances;
public float editorVisualisationSubsteps = 100;
public float Length { get; private set; }
public Transform[] Waypoints
{
get { return waypointList.items; }
}
// this being here will save GC allocs
private int p0n;
private int p1n;
private int p2n;
private int p3n;
private float i;
private Vector3 P0;
private Vector3 P1;
private Vector3 P2;
private Vector3 P3;
// Use this for initialization
private void Awake()
{
if (Waypoints.Length > 1)
{
CachePositionsAndDistances();
}
numPoints = Waypoints.Length;
}
public RoutePoint GetRoutePoint(float dist)
{
// position and direction
Vector3 p1 = GetRoutePosition(dist);
Vector3 p2 = GetRoutePosition(dist + 0.1f);
Vector3 delta = p2 - p1;
return new RoutePoint(p1, delta.normalized);
}
public Vector3 GetRoutePosition(float dist)
{
int point = 0;
if (Length == 0)
{
Length = distances[distances.Length - 1];
}
dist = Mathf.Repeat(dist, Length);
while (distances[point] < dist)
{
++point;
}
// get nearest two points, ensuring points wrap-around start & end of circuit
p1n = ((point - 1) + numPoints)%numPoints;
p2n = point;
// found point numbers, now find interpolation value between the two middle points
i = Mathf.InverseLerp(distances[p1n], distances[p2n], dist);
if (smoothRoute)
{
// smooth catmull-rom calculation between the two relevant points
// get indices for the surrounding 2 points, because
// four points are required by the catmull-rom function
p0n = ((point - 2) + numPoints)%numPoints;
p3n = (point + 1)%numPoints;
// 2nd point may have been the 'last' point - a dupe of the first,
// (to give a value of max track distance instead of zero)
// but now it must be wrapped back to zero if that was the case.
p2n = p2n%numPoints;
P0 = points[p0n];
P1 = points[p1n];
P2 = points[p2n];
P3 = points[p3n];
return CatmullRom(P0, P1, P2, P3, i);
}
else
{
// simple linear lerp between the two points:
p1n = ((point - 1) + numPoints)%numPoints;
p2n = point;
return Vector3.Lerp(points[p1n], points[p2n], i);
}
}
private Vector3 CatmullRom(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float i)
{
// comments are no use here... it's the catmull-rom equation.
// Un-magic this, lord vector!
return 0.5f*
((2*p1) + (-p0 + p2)*i + (2*p0 - 5*p1 + 4*p2 - p3)*i*i +
(-p0 + 3*p1 - 3*p2 + p3)*i*i*i);
}
private void CachePositionsAndDistances()
{
// transfer the position of each point and distances between points to arrays for
// speed of lookup at runtime
points = new Vector3[Waypoints.Length + 1];
distances = new float[Waypoints.Length + 1];
float accumulateDistance = 0;
for (int i = 0; i < points.Length; ++i)
{
Transform t1 = Waypoints[i%Waypoints.Length];
Transform t2 = Waypoints[(i + 1)%Waypoints.Length];
if (t1 != null && t2 != null)
{
Vector3 p1 = t1.position;
Vector3 p2 = t2.position;
points[i] = Waypoints[i%Waypoints.Length].position;
distances[i] = accumulateDistance;
accumulateDistance += (p1 - p2).magnitude;
}
}
}
private void OnDrawGizmos()
{
DrawGizmos(false);
}
private void OnDrawGizmosSelected()
{
DrawGizmos(true);
}
private void DrawGizmos(bool selected)
{
waypointList.circuit = this;
if (Waypoints.Length > 1)
{
numPoints = Waypoints.Length;
CachePositionsAndDistances();
Length = distances[distances.Length - 1];
Gizmos.color = selected ? Color.yellow : new Color(1, 1, 0, 0.5f);
Vector3 prev = Waypoints[0].position;
if (smoothRoute)
{
for (float dist = 0; dist < Length; dist += Length/editorVisualisationSubsteps)
{
Vector3 next = GetRoutePosition(dist + 1);
Gizmos.DrawLine(prev, next);
prev = next;
}
Gizmos.DrawLine(prev, Waypoints[0].position);
}
else
{
for (int n = 0; n < Waypoints.Length; ++n)
{
Vector3 next = Waypoints[(n + 1)%Waypoints.Length].position;
Gizmos.DrawLine(prev, next);
prev = next;
}
}
}
}
[Serializable]
public class WaypointList
{
public WaypointCircuit circuit;
public Transform[] items = new Transform[0];
}
public struct RoutePoint
{
public Vector3 position;
public Vector3 direction;
public RoutePoint(Vector3 position, Vector3 direction)
{
this.position = position;
this.direction = direction;
}
}
}
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(WaypointCircuit.WaypointList))]
public class WaypointListDrawer : PropertyDrawer
{
private float lineHeight = 18;
private float spacing = 4;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
float x = position.x;
float y = position.y;
float inspectorWidth = position.width;
// Draw label
// Don't make child fields be indented
int indent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
SerializedProperty items = property.FindPropertyRelative("items");
string[] titles = new[] {"Transform", string.Empty, string.Empty, string.Empty};
string[] props = new[] {"transform", "^", "v", "-"};
float[] widths = new[] {.7f, .1f, .1f, .1f};
float lineHeight = 18;
bool changedLength = false;
if (items.arraySize > 0)
{
for (int i = -1; i < items.arraySize; ++i)
{
SerializedProperty item = items.GetArrayElementAtIndex(i);
float rowX = x;
for (int n = 0; n < props.Length; ++n)
{
float w = widths[n]*inspectorWidth;
// Calculate rects
Rect rect = new Rect(rowX, y, w, lineHeight);
rowX += w;
if (i == -1)
{
EditorGUI.LabelField(rect, titles[n]);
}
else
{
if (n == 0)
{
EditorGUI.ObjectField(rect, item.objectReferenceValue, typeof(Transform), true);
}
else
{
if (GUI.Button(rect, props[n]))
{
switch(props[n])
{
case "-":
items.DeleteArrayElementAtIndex(i);
items.DeleteArrayElementAtIndex(i);
changedLength = true;
break;
case "v":
if (i > 0)
{
items.MoveArrayElement(i, i + 1);
}
break;
case "^":
if (i < items.arraySize - 1)
{
items.MoveArrayElement(i, i - 1);
}
break;
}
}
}
}
}
y += lineHeight + spacing;
if (changedLength)
{
break;
}
}
}
else
{
// add button
Rect addButtonRect = new Rect((x + position.width) - widths[widths.Length - 1]*inspectorWidth, y,
widths[widths.Length - 1]*inspectorWidth, lineHeight);
if (GUI.Button(addButtonRect, "+"))
{
items.InsertArrayElementAtIndex(items.arraySize);
}
y += lineHeight + spacing;
}
// add all button
Rect addAllButtonRect = new Rect(x, y, inspectorWidth, lineHeight);
if (GUI.Button(addAllButtonRect, "Assign using all child objects"))
{
WaypointCircuit circuit = property.FindPropertyRelative("circuit").objectReferenceValue as WaypointCircuit;
Transform[] children = new Transform[circuit.transform.childCount];
int n = 0;
foreach (Transform child in circuit.transform)
{
children[n++] = child;
}
Array.Sort(children, new TransformNameComparer());
circuit.waypointList.items = new Transform[children.Length];
for (n = 0; n < children.Length; ++n)
{
circuit.waypointList.items[n] = children[n];
}
}
y += lineHeight + spacing;
// rename all button
Rect renameButtonRect = new Rect(x, y, inspectorWidth, lineHeight);
if (GUI.Button(renameButtonRect, "Auto Rename numerically from this order"))
{
WaypointCircuit circuit = property.FindPropertyRelative("circuit").objectReferenceValue as WaypointCircuit;
int n = 0;
foreach (Transform child in circuit.waypointList.items)
{
child.name = "Waypoint " + (n++).ToString("000");
}
}
y += lineHeight + spacing;
// Set indent back to what it was
EditorGUI.indentLevel = indent;
EditorGUI.EndProperty();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
SerializedProperty items = property.FindPropertyRelative("items");
float lineAndSpace = lineHeight + spacing;
return 40 + (items.arraySize*lineAndSpace) + lineAndSpace;
}
// comparer for check distances in ray cast hits
public class TransformNameComparer : IComparer
{
public int Compare(object x, object y)
{
return ((Transform) x).name.CompareTo(((Transform) y).name);
}
}
}
#endif
}
| |
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
//using LitJson;
#if UNITY_EDITOR
using UnityEditor;
#endif
[RequireComponent(typeof(GA_HeatMapRenderer))]
[ExecuteInEditMode]
public class GA_HeatMapDataFilter : GA_HeatMapDataFilterBase
{
public enum CombineHeatmapType { None, Add, Subtract, SubtractZero };
[HideInInspector]
public List<string> AvailableTypes;
[HideInInspector]
public int CurrentTypeIndex;
[HideInInspector]
public List<string> AvailableBuilds;
[HideInInspector]
public int CurrentBuildIndex;
public bool RedownloadDataOnPlay;
public bool IgnoreDates = true;
public bool IgnoreBuilds = true;
public bool DownloadingData = false;
public bool BuildingHeatmap = false;
public float BuildHeatmapPercentage = 0;
#if UNITY_EDITOR || !UNITY_FLASH
//Pretty silly hack to force Unity to serialize DateTime.
//(It makes sense that it doesn't serialize structs, but there might be a better workaround.
[SerializeField]
private string _startDateTime;
public DateTime? StartDateTime
{
get {
DateTime res = DateTime.Now;
DateTime.TryParse(_startDateTime,out res);
return res;
}
set {_startDateTime = value.HasValue?value.Value.ToString():"";}
}
[SerializeField]
private string _endDateTime;
public DateTime? EndDateTime
{
get {
DateTime res = DateTime.Now;
DateTime.TryParse(_endDateTime,out res);
return res;
}
set {_endDateTime = value.HasValue?value.Value.ToString():"";}
}
#endif
[HideInInspector]
public List<string> AvailableAreas;
[HideInInspector]
public int CurrentAreaIndex;
[HideInInspector]
public List<string> AvailableEvents;
[HideInInspector]
public List<bool> CurrentEventFlag;
[HideInInspector]
public GA_HeatmapData DataContainer;
[SerializeField]
private bool didInit = false;
#if UNITY_EDITOR || !UNITY_FLASH
private CombineHeatmapType _combineType = CombineHeatmapType.None;
#endif
public void OnEnable ()
{
#if UNITY_EDITOR
EditorApplication.hierarchyWindowItemOnGUI += GA.HierarchyWindowCallback;
#endif
if(didInit)
return;
Debug.Break();
AvailableBuilds = new List<string>();
AvailableAreas = new List<string>();
AvailableTypes = new List<string>();
AvailableEvents = new List<string>();
AvailableTypes.Add("Design");
AvailableTypes.Add("Quality");
AvailableTypes.Add("Business");
#if UNITY_EDITOR || !UNITY_FLASH
StartDateTime = DateTime.Now;
EndDateTime = DateTime.Now;
#endif
didInit = true;
}
#if UNITY_EDITOR
void OnDisable ()
{
EditorApplication.hierarchyWindowItemOnGUI -= GA.HierarchyWindowCallback;
}
#endif
void Awake()
{
if(Application.isPlaying && !Application.isEditor && RedownloadDataOnPlay)
{
DownloadData();
}
}
public override List<GA_DataPoint> GetData()
{
return DataContainer!=null?DataContainer.Data:null;
}
public float LoadProgress;
public bool Loading;
private IEnumerator FollowProgress(WWW progress)
{
Loading = true;
while(!progress.isDone)
{
LoadProgress = progress.progress;
yield return null;
}
Loading = false;
LoadProgress = 0;
}
void NormalizeDataPoints (List<GA_DataPoint> Data)
{
float dataMax = 0,dataMin = 0;
foreach(GA_DataPoint p in Data)
{
if(dataMax < p.count)
{
dataMax = p.count;
}
if(dataMin > p.count)
{
dataMin = p.count;
}
}
foreach(GA_DataPoint p in Data)
{
p.density = (p.count - dataMin) / (dataMax - dataMin);
}
}
#if UNITY_EDITOR || !UNITY_FLASH
public void OnSuccessDownload(GA_Request.RequestType requestType, Hashtable jsonList, GA_Request.SubmitErrorHandler errorEvent)
{
DownloadingData = false;
BuildingHeatmap = true;
if(DataContainer == null)
{
var dataContainerObject = new GameObject("GA_Data");
dataContainerObject.transform.parent = transform;
DataContainer = dataContainerObject.AddComponent<GA_HeatmapData>();
DataContainer.Data = new List<GA_DataPoint>();
GA.Log(DataContainer);
}
else if (_combineType == CombineHeatmapType.None)
DataContainer.Data.Clear();
List<GA_DataPoint> DPsToDelete = new List<GA_DataPoint>();
ArrayList jsonArrayX = (ArrayList)jsonList["x"];
ArrayList jsonArrayY = (ArrayList)jsonList["y"];
ArrayList jsonArrayZ = (ArrayList)jsonList["z"];
ArrayList jsonArrayValue = (ArrayList)jsonList["value"];
for (int i = 0; i < jsonArrayX.Count; i++)
{
try
{
bool done = false;
if (_combineType == CombineHeatmapType.Add)
{
Vector3 position = new Vector3(float.Parse(jsonArrayX[i].ToString()) / GA.SettingsGA.HeatmapGridSize.x, float.Parse(jsonArrayY[i].ToString()) / GA.SettingsGA.HeatmapGridSize.y, float.Parse(jsonArrayZ[i].ToString()) / GA.SettingsGA.HeatmapGridSize.z);
int count = int.Parse(jsonArrayValue[i].ToString());
for (int u = 0; u < DataContainer.Data.Count; u++)
{
if (DataContainer.Data[u].position == position)
{
DataContainer.Data[u].count += count;
done = true;
u = DataContainer.Data.Count;
}
}
}
else if (_combineType == CombineHeatmapType.Subtract)
{
Vector3 position = new Vector3(float.Parse(jsonArrayX[i].ToString()) / GA.SettingsGA.HeatmapGridSize.x, float.Parse(jsonArrayY[i].ToString()) / GA.SettingsGA.HeatmapGridSize.y, float.Parse(jsonArrayZ[i].ToString()) / GA.SettingsGA.HeatmapGridSize.z);
int count = int.Parse(jsonArrayValue[i].ToString());
for (int u = 0; u < DataContainer.Data.Count; u++)
{
if (DataContainer.Data[u].position == position)
{
DataContainer.Data[u].count = DataContainer.Data[u].count - count;
u = DataContainer.Data.Count;
done = true;
}
}
}
else if (_combineType == CombineHeatmapType.SubtractZero)
{
done = true;
Vector3 position = new Vector3(float.Parse(jsonArrayX[i].ToString()) / GA.SettingsGA.HeatmapGridSize.x, float.Parse(jsonArrayY[i].ToString()) / GA.SettingsGA.HeatmapGridSize.y, float.Parse(jsonArrayZ[i].ToString()) / GA.SettingsGA.HeatmapGridSize.z);
int count = int.Parse(jsonArrayValue[i].ToString());
for (int u = 0; u < DataContainer.Data.Count; u++)
{
if (DataContainer.Data[u].position == position)
{
DataContainer.Data[u].count = Mathf.Max(DataContainer.Data[u].count - count, 0);
if (DataContainer.Data[u].count == 0)
DPsToDelete.Add(DataContainer.Data[u]);
u = DataContainer.Data.Count;
}
}
}
if (_combineType == CombineHeatmapType.Subtract && !done)
{
GA_DataPoint p = new GA_DataPoint();
p.position = new Vector3(float.Parse(jsonArrayX[i].ToString()) / GA.SettingsGA.HeatmapGridSize.x, float.Parse(jsonArrayY[i].ToString()) / GA.SettingsGA.HeatmapGridSize.y, float.Parse(jsonArrayZ[i].ToString()) / GA.SettingsGA.HeatmapGridSize.z);
p.count = -(int.Parse(jsonArrayValue[i].ToString()));
DataContainer.Data.Add(p);
}
else if (_combineType != CombineHeatmapType.Subtract && (_combineType == CombineHeatmapType.None || !done))
{
GA_DataPoint p = new GA_DataPoint();
p.position = new Vector3(float.Parse(jsonArrayX[i].ToString()) / GA.SettingsGA.HeatmapGridSize.x, float.Parse(jsonArrayY[i].ToString()) / GA.SettingsGA.HeatmapGridSize.y, float.Parse(jsonArrayZ[i].ToString()) / GA.SettingsGA.HeatmapGridSize.z);
p.count = int.Parse(jsonArrayValue[i].ToString());
DataContainer.Data.Add(p);
}
}
catch (Exception e)
{
// JSON format error
GA.LogError("GameAnalytics: Error in parsing JSON data from server - " + e.Message);
}
BuildHeatmapPercentage = (i * 100) / jsonArrayX.Count;
}
foreach (GA_DataPoint dp in DPsToDelete)
{
DataContainer.Data.Remove(dp);
}
BuildingHeatmap = false;
BuildHeatmapPercentage = 0;
NormalizeDataPoints (DataContainer.Data);
GetComponent<GA_HeatMapRenderer>().OnDataUpdate();
Loading = false;
}
#endif
public void OnErrorDownload(string msg)
{
GA.Log("GameAnalytics: Download failed: "+msg);
DownloadingData = false;
Loading = false;
}
#if UNITY_EDITOR || !UNITY_FLASH
public void SetCombineHeatmapType(CombineHeatmapType combineType)
{
_combineType = combineType;
}
#endif
public void DownloadData()
{
DownloadingData = true;
List<string> events = new List<string>();
for(int i = 0; i<AvailableEvents.Count;i++)
{
if(CurrentEventFlag[i])
events.Add(AvailableEvents[i]);
}
bool cancel = false;
if(CurrentAreaIndex>=AvailableAreas.Count)
{
GA.LogWarning("GameAnalytics: Warning: Area selected is out of bounds. Not downloading data.");
cancel = true;
}
string build = "";
if (!IgnoreBuilds)
{
if(CurrentBuildIndex>=AvailableBuilds.Count)
{
GA.LogWarning("GameAnalytics: Warning: Build selected is out of bounds. Not downloading data.");
cancel = true;
}
else
{
build = AvailableBuilds[CurrentBuildIndex];
}
}
if (cancel)
{
DownloadingData = false;
return;
}
#if UNITY_EDITOR || !UNITY_FLASH
GA.API.Request.RequestHeatmapData(events, AvailableAreas[CurrentAreaIndex], build,IgnoreDates?null:StartDateTime,IgnoreDates?null:EndDateTime, OnSuccessDownload, OnErrorDownload);
#endif
}
// Update is called once per frame
public void DownloadUpdate ()
{
DownloadData();
}
#if UNITY_EDITOR || !UNITY_FLASH
public void OnSuccessDownloadInfo(GA_Request.RequestType requestType, Hashtable jsonList, GA_Request.SubmitErrorHandler errorEvent)
{
GA.Log("Succesful index downloaded");
CurrentAreaIndex = 0;
CurrentTypeIndex = 0;
CurrentBuildIndex = 0;
StartDateTime = DateTime.Now.AddDays(-14);
EndDateTime = DateTime.Now;
AvailableEvents = new List<string>();
CurrentEventFlag = new List<bool>();
AvailableAreas = new List<string>();
AvailableBuilds = new List<string>();
IgnoreDates = true;
ArrayList jsonArrayEventID = (ArrayList)jsonList["event_id"];
for (int i = 0; i < jsonArrayEventID.Count; i++)
{
try
{
string name;
name = jsonArrayEventID[i].ToString();
AvailableEvents.Add(name);
CurrentEventFlag.Add(false);
}
catch
{
// JSON format error
GA.LogError("GameAnalytics: Error in parsing JSON data from server");
}
}
ArrayList jsonArrayArea = (ArrayList)jsonList["area"];
for (int j = 0; j < jsonArrayArea.Count; j++)
{
try
{
string name;
name = jsonArrayArea[j].ToString();
AvailableAreas.Add(name);
}
catch
{
// JSON format error
GA.LogError("GameAnalytics: Error in parsing JSON data from server");
}
}
ArrayList jsonArrayBuild = (ArrayList)jsonList["build"];
for (int k = 0; k < jsonArrayBuild.Count; k++)
{
try
{
string name;
name = jsonArrayBuild[k].ToString();
AvailableBuilds.Add(name);
}
catch
{
// JSON format error
GA.LogError("GameAnalytics: Error in parsing JSON data from server");
}
}
}
public void OnErrorDownloadInfo(string msg)
{
GA.Log("GameAnalytics: Download failed: "+msg);
}
public void UpdateIndexData ()
{
GA.Log("Downloading index from server");
GA.API.Request.RequestGameInfo(OnSuccessDownloadInfo, OnErrorDownloadInfo);
}
#endif
}
| |
namespace PeregrineDb.Tests.Databases
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using PeregrineDb.Dialects;
using PeregrineDb.Schema;
using PeregrineDb.Tests.ExampleEntities;
using PeregrineDb.Tests.Utils;
using Xunit;
[SuppressMessage("ReSharper", "StringLiteralAsInterpolationArgument")]
[SuppressMessage("ReSharper", "AccessToDisposedClosure")]
public abstract partial class DefaultDatabaseConnectionCrudAsyncTests
{
public class GetRangeAsync
: DefaultDatabaseConnectionCrudAsyncTests
{
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Filters_result_by_conditions(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
database.Insert(new Dog { Name = "Some Name 1", Age = 10 });
database.Insert(new Dog { Name = "Some Name 2", Age = 10 });
database.Insert(new Dog { Name = "Some Name 3", Age = 10 });
database.Insert(new Dog { Name = "Some Name 4", Age = 11 });
// Act
var dogs = await database.GetRangeAsync<Dog>("WHERE Name LIKE CONCAT(@Name, '%') and Age = @Age", new { Name = "Some Name", Age = 10 });
// Assert
dogs.Should().HaveCount(3);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Returns_everything_when_conditions_is_null(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
database.Insert(new Dog { Name = "Some Name 1", Age = 10 });
database.Insert(new Dog { Name = "Some Name 2", Age = 10 });
database.Insert(new Dog { Name = "Some Name 3", Age = 10 });
database.Insert(new Dog { Name = "Some Name 4", Age = 11 });
// Act
var entities = await database.GetRangeAsync<Dog>(null);
// Assert
entities.Count().Should().Be(4);
}
}
}
public class GetRangeAsyncWhereObject
: DefaultDatabaseConnectionCrudAsyncTests
{
[Theory]
[MemberData(nameof(TestDialects))]
public void Throws_exception_when_conditions_is_null(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Act
Func<Task> act = async () => await database.GetRangeAsync<Dog>((object)null);
// Assert
act.Should().Throw<ArgumentNullException>();
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Returns_all_when_conditions_is_empty(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
database.Insert(new Dog { Name = "Some Name 1", Age = 10 });
database.Insert(new Dog { Name = "Some Name 2", Age = 10 });
database.Insert(new Dog { Name = "Some Name 3", Age = 10 });
database.Insert(new Dog { Name = "Some Name 4", Age = 11 });
// Act
var entities = await database.GetRangeAsync<Dog>(new { });
// Assert
entities.Count().Should().Be(4);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Filters_result_by_conditions(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
database.Insert(new Dog { Name = "Some Name 1", Age = 10 });
database.Insert(new Dog { Name = "Some Name 2", Age = 10 });
database.Insert(new Dog { Name = "Some Name 3", Age = 10 });
database.Insert(new Dog { Name = "Some Name 4", Age = 11 });
// Act
var entities = await database.GetRangeAsync<Dog>(new { Age = 10 });
// Assert
entities.Count().Should().Be(3);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Matches_column_name_case_insensitively(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
database.Insert(new Dog { Name = "Some Name 1", Age = 10 });
database.Insert(new Dog { Name = "Some Name 2", Age = 10 });
database.Insert(new Dog { Name = "Some Name 3", Age = 10 });
database.Insert(new Dog { Name = "Some Name 4", Age = 11 });
// Act
var entities = await database.GetRangeAsync<Dog>(new { age = 10 });
// Assert
entities.Count().Should().Be(3);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
[SuppressMessage("ReSharper", "AccessToDisposedClosure")]
public void Throws_exception_when_column_not_found(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Act
Func<Task> act = async () => await database.GetRangeAsync<Dog>(new { Ages = 10 });
// Assert
act.Should().Throw<InvalidConditionSchemaException>();
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task When_value_is_not_null_does_not_find_nulls(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
database.Insert(new PropertyNullable { Name = null });
database.Insert(new PropertyNullable { Name = "Some Name 3" });
database.Insert(new PropertyNullable { Name = null });
// Act
var entities = await database.GetRangeAsync<PropertyNullable>(new { Name = "Some Name 3" });
// Assert
entities.Count().Should().Be(1);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task When_value_is_null_finds_nulls(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
database.Insert(new PropertyNullable { Name = null });
database.Insert(new PropertyNullable { Name = "Some Name 3" });
database.Insert(new PropertyNullable { Name = null });
// Act
var entities = await database.GetRangeAsync<PropertyNullable>(new { Name = (string)null });
// Assert
entities.Count().Should().Be(2);
}
}
[Theory]
[MemberData(nameof(TestDialects))]
public async Task Filters_on_multiple_properties(IDialect dialect)
{
using (var database = BlankDatabaseFactory.MakeDatabase(dialect))
{
// Arrange
database.Insert(new Dog { Name = "Some Name 1", Age = 10 });
database.Insert(new Dog { Name = "Some Name 2", Age = 10 });
database.Insert(new Dog { Name = "Some Name 2", Age = 12 });
// Act
var entities = await database.GetRangeAsync<Dog>(new { Name = "Some Name 2", Age = 10 });
// Assert
entities.Count().Should().Be(1);
}
}
}
}
}
| |
// KnockoutApi.cs
// Script#/Libraries/Knockout
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Html;
using System.Text.RegularExpressions;
namespace KnockoutApi {
[Imported]
[ScriptNamespace("ko")]
[ScriptName("utils")]
public static class KnockoutUtils {
/// <summary>
/// Returns the First Matching Item (predicate function) from the given array
/// </summary>
public static T ArrayFirst<T>(IEnumerable<T> array, Func<T, bool> predicate, object owner) {
return default(T);
}
/// <summary>
/// Applies the predicate filter to the given array
/// Returns the matching items as a new array
/// </summary>
public static T[] ArrayFilter<T>(IEnumerable<T> array, Func<T, bool> predicate) {
return null;
}
/// <summary>
/// Applies the Action to each item in the given array
/// </summary>
public static void ArrayForEach<T>(IEnumerable<T> array, Action<T> action) {
}
/// <summary>
/// Returns a new array containing distinct values only
/// </summary>
public static T[] ArrayGetDistinctValues<T>(IEnumerable<T> array) {
return null;
}
/// <summary>
/// Finds and Returns the Index of the item in the given array
/// </summary>
/// <returns>Returns the Index number of -1 if not found</returns>
public static int ArrayIndexOf<T>(IEnumerable<T> array, T item) {
return -1;
}
/// <summary>
/// Processes each item in the given array and applies the mapping function
/// Returns the Mapping Results
/// </summary>
public static TOut[] ArrayMap<T, TOut>(IEnumerable<T> array, Func<T, TOut> mapping) {
return null;
}
/// <summary>
/// Pushes each item into the given array
/// </summary>
public static void ArrayPushAll<T>(IEnumerable<T> array, params T[] items) {
}
/// <summary>
/// Removes the Specified item from the given array
/// </summary>
public static void ArrayRemoveItem<T>(IEnumerable<T> array, T item) {
}
/// <summary>
/// Compares the changes between two arrays
/// </summary>
public static CompareResult<T>[] CompareArrays<T>(IEnumerable<T> oldArray, IEnumerable<T> newArray) {
return null;
}
/// <summary>
/// Compares the changes between two arrays
/// </summary>
public static CompareResult<T>[] CompareArrays<T>(IEnumerable<T> oldArray, IEnumerable<T> newArray, int maxEditsToConsider) {
return null;
}
public static T Extend<T>(T target, object source) {
return default(T);
}
/// <summary>
/// Finds the Matching Field Elements (input) in the given Form Element and the given fieldName
/// </summary>
public static Element[] GetFormFields(Element form, string fieldName) {
return null;
}
/// <summary>
/// Finds the Matching Field Elements (input) in the given Form Element and the given regular expression
/// </summary>
public static Element[] GetFormFields(Element form, Regex match) {
return null;
}
/// <summary>
/// If the provided value is an observable, returns the current value without creating a dependency, otherwise just pass it through.
/// </summary>
/// <param name="value">The value to peek.</param>
public static T PeekObservable<T>(T value) {
return default(T);
}
/// <summary>
/// If the provided value is an observable, returns the current value without creating a dependency, otherwise just pass it through.
/// </summary>
/// <param name="value">The value to peek.</param>
public static T PeekObservable<T>(Observable<T> value) {
return default(T);
}
/// <summary>
/// If the provided value is an observable, returns the current value without creating a dependency, otherwise just pass it through.
/// </summary>
/// <param name="value">The value to peek.</param>
public static T[] PeekObservable<T>(ObservableArray<T> value) {
return null;
}
/// <summary>
/// Parses the Json String into a native javascript object
/// </summary>
/// <param name="jsonString"></param>
public static T ParseJson<T>(string jsonString) {
return default(T);
}
/// <summary>
/// Makes a Post Request to the specified url or using the specified Form element
/// </summary>
/// <param name="urlOrForm"></param>
/// <param name="data"></param>
/// <param name="options">{ "params": [], "includeFields": [], "submitter": [] }</param>
public static void PostJson(object urlOrForm, object data, JsDictionary options) {
}
/// <summary>
/// Returns an Array of numbers starting from the specified minimum to the maximum
/// </summary>
public static int[] Range(int min, int max) {
return null;
}
/// <summary>
/// Returns an Array of numbers starting from the specified minimum to the maximum
/// </summary>
public static int[] Range(Observable<int> min, Observable<int> max) {
return null;
}
/// <summary>
/// Registers an Event Handler for the given element
/// </summary>
public static void RegisterEventHandler(Element element, string eventType, EventHandler handler) {
}
/// <summary>
/// Returns a json string from the specified object
/// Requires Native JSON support or json2.js
/// </summary>
public static string StringifyJson(object obj) {
return null;
}
/// <summary>
/// Triggers the specified event on the given element
/// i.e. produce a 'click' event on a input element
/// </summary>
public static void TriggerEvent(Element element, string eventType) {
}
/// <summary>
/// If the provided value is an observable, return its value, otherwise just pass it through.
/// </summary>
/// <param name="value">The value to unwrap.</param>
public static T UnwrapObservable<T>(T value) {
return default(T);
}
/// <summary>
/// If the provided value is an observable, return its value, otherwise just pass it through.
/// </summary>
/// <param name="value">The value to unwrap.</param>
public static T UnwrapObservable<T>(Observable<T> value) {
return default(T);
}
/// <summary>
/// If the provided value is an observable, return its value, otherwise just pass it through.
/// </summary>
/// <param name="value">The value to unwrap.</param>
public static T[] UnwrapObservable<T>(ObservableArray<T> value) {
return null;
}
}
}
| |
namespace EffectEditor
{
partial class EditorForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.tabControl = new System.Windows.Forms.TabControl();
this.viewTab = new System.Windows.Forms.TabPage();
this.blueCustomColorBar = new System.Windows.Forms.TrackBar();
this.greenCustomColorBar = new System.Windows.Forms.TrackBar();
this.BLabel = new System.Windows.Forms.Label();
this.bgColorLabel = new System.Windows.Forms.Label();
this.redCustomColorBar = new System.Windows.Forms.TrackBar();
this.GLabel = new System.Windows.Forms.Label();
this.RLabel = new System.Windows.Forms.Label();
this.bgColorComboBox = new System.Windows.Forms.ComboBox();
this.modelPage = new System.Windows.Forms.TabPage();
this.modelSelectionBox = new System.Windows.Forms.ComboBox();
this.modelPropertyGrid = new System.Windows.Forms.PropertyGrid();
this.currentModelLabel = new System.Windows.Forms.Label();
this.effectTab = new System.Windows.Forms.TabPage();
this.effectPropertyGrid = new System.Windows.Forms.PropertyGrid();
this.modelViewPanel = new EffectEditor.Controls.ModelViewControl();
this.statusLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.mainTabControl = new System.Windows.Forms.TabControl();
this.modelViewTab = new System.Windows.Forms.TabPage();
this.effectEditTab = new System.Windows.Forms.TabPage();
this.effectEditorContainer = new System.Windows.Forms.SplitContainer();
this.effectEditorTabPages = new System.Windows.Forms.TabControl();
this.componentsTab = new System.Windows.Forms.TabPage();
this.removeEffectComponentButton = new System.Windows.Forms.Button();
this.addEffectComponentButton = new System.Windows.Forms.Button();
this.effectComponentsList = new System.Windows.Forms.ListBox();
this.compileEffectButton = new System.Windows.Forms.Button();
this.parametersTab = new System.Windows.Forms.TabPage();
this.addStandardParameterButton = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.standardParametersList = new System.Windows.Forms.ListBox();
this.effectParametersList = new EffectEditor.Controls.ComponentParameterList();
this.vertexShadersTab = new System.Windows.Forms.TabPage();
this.splitContainer2 = new System.Windows.Forms.SplitContainer();
this.removeVertexShaderButton = new System.Windows.Forms.Button();
this.addVertexShaderButton = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.vertexShadersList = new System.Windows.Forms.ListBox();
this.effectEditBox = new System.Windows.Forms.RichTextBox();
this.vertexShaderEditor = new EffectEditor.Controls.ComponentEditor();
this.pixelShadersTab = new System.Windows.Forms.TabPage();
this.splitContainer3 = new System.Windows.Forms.SplitContainer();
this.removePixelShaderButton = new System.Windows.Forms.Button();
this.addPixelShaderButton = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.pixelShadersList = new System.Windows.Forms.ListBox();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.pixelShaderEditor = new EffectEditor.Controls.ComponentEditor();
this.techniquesTab = new System.Windows.Forms.TabPage();
this.splitContainer4 = new System.Windows.Forms.SplitContainer();
this.removeTechniqueButton = new System.Windows.Forms.Button();
this.addTechniqueButton = new System.Windows.Forms.Button();
this.label4 = new System.Windows.Forms.Label();
this.effectTechniquesList = new System.Windows.Forms.ListBox();
this.effectTechniqueEditor = new System.Windows.Forms.Panel();
this.techniqueNameBox = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.effectTechniquePassesEditor = new System.Windows.Forms.SplitContainer();
this.removePassButton = new System.Windows.Forms.Button();
this.effectTechniquePassesList = new System.Windows.Forms.ListBox();
this.addPassButton = new System.Windows.Forms.Button();
this.label5 = new System.Windows.Forms.Label();
this.passPixelShaderProfileBox = new System.Windows.Forms.ComboBox();
this.label11 = new System.Windows.Forms.Label();
this.passPixelShaderBox = new System.Windows.Forms.ComboBox();
this.passVertexShaderProfileBox = new System.Windows.Forms.ComboBox();
this.label10 = new System.Windows.Forms.Label();
this.label9 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.passVertexShaderBox = new System.Windows.Forms.ComboBox();
this.passNameBox = new System.Windows.Forms.TextBox();
this.label7 = new System.Windows.Forms.Label();
this.effectCompileOutput = new System.Windows.Forms.RichTextBox();
this.componentTab = new System.Windows.Forms.TabPage();
this.componentEditor = new EffectEditor.Controls.ComponentEditor();
this.hlslInfoBox = new System.Windows.Forms.RichTextBox();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.effectToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loadEffectToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveEffectToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.componentToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newComponentToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.loadComponentToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveComponentToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openModelFileDialog = new System.Windows.Forms.OpenFileDialog();
this.statusStrip = new System.Windows.Forms.StatusStrip();
this.panel1 = new System.Windows.Forms.Panel();
this.saveComponentDialog = new System.Windows.Forms.SaveFileDialog();
this.openComponentDialog = new System.Windows.Forms.OpenFileDialog();
this.saveEffectDialog = new System.Windows.Forms.SaveFileDialog();
this.openEffectDialog = new System.Windows.Forms.OpenFileDialog();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.tabControl.SuspendLayout();
this.viewTab.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.blueCustomColorBar)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.greenCustomColorBar)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.redCustomColorBar)).BeginInit();
this.modelPage.SuspendLayout();
this.effectTab.SuspendLayout();
this.mainTabControl.SuspendLayout();
this.modelViewTab.SuspendLayout();
this.effectEditTab.SuspendLayout();
this.effectEditorContainer.Panel1.SuspendLayout();
this.effectEditorContainer.Panel2.SuspendLayout();
this.effectEditorContainer.SuspendLayout();
this.effectEditorTabPages.SuspendLayout();
this.componentsTab.SuspendLayout();
this.parametersTab.SuspendLayout();
this.vertexShadersTab.SuspendLayout();
this.splitContainer2.Panel1.SuspendLayout();
this.splitContainer2.Panel2.SuspendLayout();
this.splitContainer2.SuspendLayout();
this.pixelShadersTab.SuspendLayout();
this.splitContainer3.Panel1.SuspendLayout();
this.splitContainer3.Panel2.SuspendLayout();
this.splitContainer3.SuspendLayout();
this.techniquesTab.SuspendLayout();
this.splitContainer4.Panel1.SuspendLayout();
this.splitContainer4.Panel2.SuspendLayout();
this.splitContainer4.SuspendLayout();
this.effectTechniqueEditor.SuspendLayout();
this.effectTechniquePassesEditor.Panel1.SuspendLayout();
this.effectTechniquePassesEditor.Panel2.SuspendLayout();
this.effectTechniquePassesEditor.SuspendLayout();
this.componentTab.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.statusStrip.SuspendLayout();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.Location = new System.Drawing.Point(3, 3);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.tabControl);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.modelViewPanel);
this.splitContainer1.Size = new System.Drawing.Size(778, 488);
this.splitContainer1.SplitterDistance = 221;
this.splitContainer1.TabIndex = 1;
//
// tabControl
//
this.tabControl.Controls.Add(this.viewTab);
this.tabControl.Controls.Add(this.modelPage);
this.tabControl.Controls.Add(this.effectTab);
this.tabControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabControl.Location = new System.Drawing.Point(0, 0);
this.tabControl.Name = "tabControl";
this.tabControl.SelectedIndex = 0;
this.tabControl.Size = new System.Drawing.Size(221, 488);
this.tabControl.TabIndex = 4;
//
// viewTab
//
this.viewTab.Controls.Add(this.blueCustomColorBar);
this.viewTab.Controls.Add(this.greenCustomColorBar);
this.viewTab.Controls.Add(this.BLabel);
this.viewTab.Controls.Add(this.bgColorLabel);
this.viewTab.Controls.Add(this.redCustomColorBar);
this.viewTab.Controls.Add(this.GLabel);
this.viewTab.Controls.Add(this.RLabel);
this.viewTab.Controls.Add(this.bgColorComboBox);
this.viewTab.Location = new System.Drawing.Point(4, 22);
this.viewTab.Name = "viewTab";
this.viewTab.Padding = new System.Windows.Forms.Padding(3);
this.viewTab.Size = new System.Drawing.Size(213, 462);
this.viewTab.TabIndex = 0;
this.viewTab.Text = "View";
this.viewTab.UseVisualStyleBackColor = true;
//
// blueCustomColorBar
//
this.blueCustomColorBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.blueCustomColorBar.BackColor = System.Drawing.SystemColors.Window;
this.blueCustomColorBar.Enabled = false;
this.blueCustomColorBar.Location = new System.Drawing.Point(22, 98);
this.blueCustomColorBar.Maximum = 255;
this.blueCustomColorBar.Name = "blueCustomColorBar";
this.blueCustomColorBar.Size = new System.Drawing.Size(185, 45);
this.blueCustomColorBar.TabIndex = 6;
this.blueCustomColorBar.TickStyle = System.Windows.Forms.TickStyle.None;
this.blueCustomColorBar.Scroll += new System.EventHandler(this.CustomColorBar_Scroll);
//
// greenCustomColorBar
//
this.greenCustomColorBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.greenCustomColorBar.BackColor = System.Drawing.SystemColors.Window;
this.greenCustomColorBar.Enabled = false;
this.greenCustomColorBar.Location = new System.Drawing.Point(22, 72);
this.greenCustomColorBar.Maximum = 255;
this.greenCustomColorBar.Name = "greenCustomColorBar";
this.greenCustomColorBar.Size = new System.Drawing.Size(185, 45);
this.greenCustomColorBar.TabIndex = 5;
this.greenCustomColorBar.TickStyle = System.Windows.Forms.TickStyle.None;
this.greenCustomColorBar.Scroll += new System.EventHandler(this.CustomColorBar_Scroll);
//
// BLabel
//
this.BLabel.AutoSize = true;
this.BLabel.Enabled = false;
this.BLabel.Location = new System.Drawing.Point(4, 102);
this.BLabel.Name = "BLabel";
this.BLabel.Size = new System.Drawing.Size(14, 13);
this.BLabel.TabIndex = 9;
this.BLabel.Text = "B";
//
// bgColorLabel
//
this.bgColorLabel.AutoSize = true;
this.bgColorLabel.Location = new System.Drawing.Point(4, 3);
this.bgColorLabel.Name = "bgColorLabel";
this.bgColorLabel.Size = new System.Drawing.Size(92, 13);
this.bgColorLabel.TabIndex = 2;
this.bgColorLabel.Text = "Background Color";
//
// redCustomColorBar
//
this.redCustomColorBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.redCustomColorBar.BackColor = System.Drawing.SystemColors.Window;
this.redCustomColorBar.Enabled = false;
this.redCustomColorBar.Location = new System.Drawing.Point(22, 46);
this.redCustomColorBar.Maximum = 255;
this.redCustomColorBar.Name = "redCustomColorBar";
this.redCustomColorBar.Size = new System.Drawing.Size(185, 45);
this.redCustomColorBar.TabIndex = 4;
this.redCustomColorBar.TickStyle = System.Windows.Forms.TickStyle.None;
this.redCustomColorBar.Scroll += new System.EventHandler(this.CustomColorBar_Scroll);
//
// GLabel
//
this.GLabel.AutoSize = true;
this.GLabel.Enabled = false;
this.GLabel.Location = new System.Drawing.Point(4, 76);
this.GLabel.Name = "GLabel";
this.GLabel.Size = new System.Drawing.Size(15, 13);
this.GLabel.TabIndex = 8;
this.GLabel.Text = "G";
//
// RLabel
//
this.RLabel.AutoSize = true;
this.RLabel.Enabled = false;
this.RLabel.Location = new System.Drawing.Point(4, 50);
this.RLabel.Name = "RLabel";
this.RLabel.Size = new System.Drawing.Size(15, 13);
this.RLabel.TabIndex = 7;
this.RLabel.Text = "R";
//
// bgColorComboBox
//
this.bgColorComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.bgColorComboBox.FormattingEnabled = true;
this.bgColorComboBox.Items.AddRange(new object[] {
"Black",
"White",
"Red",
"Orange",
"Yellow",
"Green",
"Blue",
"Purple",
"Custom..."});
this.bgColorComboBox.Location = new System.Drawing.Point(4, 19);
this.bgColorComboBox.Name = "bgColorComboBox";
this.bgColorComboBox.Size = new System.Drawing.Size(203, 21);
this.bgColorComboBox.TabIndex = 3;
this.bgColorComboBox.Text = "Black";
this.bgColorComboBox.SelectedIndexChanged += new System.EventHandler(this.bgColorComboBox_SelectedIndexChanged);
//
// modelPage
//
this.modelPage.Controls.Add(this.modelSelectionBox);
this.modelPage.Controls.Add(this.modelPropertyGrid);
this.modelPage.Controls.Add(this.currentModelLabel);
this.modelPage.Location = new System.Drawing.Point(4, 22);
this.modelPage.Name = "modelPage";
this.modelPage.Padding = new System.Windows.Forms.Padding(3);
this.modelPage.Size = new System.Drawing.Size(213, 462);
this.modelPage.TabIndex = 1;
this.modelPage.Text = "Model";
this.modelPage.UseVisualStyleBackColor = true;
//
// modelSelectionBox
//
this.modelSelectionBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.modelSelectionBox.FormattingEnabled = true;
this.modelSelectionBox.Location = new System.Drawing.Point(6, 19);
this.modelSelectionBox.Name = "modelSelectionBox";
this.modelSelectionBox.Size = new System.Drawing.Size(201, 21);
this.modelSelectionBox.TabIndex = 0;
this.modelSelectionBox.SelectedIndexChanged += new System.EventHandler(this.modelSelectionBox_SelectedIndexChanged);
//
// modelPropertyGrid
//
this.modelPropertyGrid.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.modelPropertyGrid.BackColor = System.Drawing.SystemColors.Window;
this.modelPropertyGrid.CommandsBackColor = System.Drawing.SystemColors.ControlLightLight;
this.modelPropertyGrid.Location = new System.Drawing.Point(6, 46);
this.modelPropertyGrid.Name = "modelPropertyGrid";
this.modelPropertyGrid.Size = new System.Drawing.Size(201, 209);
this.modelPropertyGrid.TabIndex = 3;
//
// currentModelLabel
//
this.currentModelLabel.AutoSize = true;
this.currentModelLabel.Location = new System.Drawing.Point(3, 3);
this.currentModelLabel.Name = "currentModelLabel";
this.currentModelLabel.Size = new System.Drawing.Size(73, 13);
this.currentModelLabel.TabIndex = 1;
this.currentModelLabel.Text = "Current Model";
//
// effectTab
//
this.effectTab.Controls.Add(this.effectPropertyGrid);
this.effectTab.Location = new System.Drawing.Point(4, 22);
this.effectTab.Name = "effectTab";
this.effectTab.Padding = new System.Windows.Forms.Padding(3);
this.effectTab.Size = new System.Drawing.Size(213, 462);
this.effectTab.TabIndex = 2;
this.effectTab.Text = "Effect";
this.effectTab.UseVisualStyleBackColor = true;
//
// effectPropertyGrid
//
this.effectPropertyGrid.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.effectPropertyGrid.Location = new System.Drawing.Point(9, 48);
this.effectPropertyGrid.Name = "effectPropertyGrid";
this.effectPropertyGrid.Size = new System.Drawing.Size(198, 408);
this.effectPropertyGrid.TabIndex = 1;
//
// modelViewPanel
//
this.modelViewPanel.BackgroundColor = new Microsoft.Xna.Framework.Graphics.Color(((byte)(0)), ((byte)(0)), ((byte)(0)), ((byte)(255)));
this.modelViewPanel.CurrentModel = null;
this.modelViewPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.modelViewPanel.Location = new System.Drawing.Point(0, 0);
this.modelViewPanel.Name = "modelViewPanel";
this.modelViewPanel.Size = new System.Drawing.Size(553, 488);
this.modelViewPanel.StatusStrip = this.statusLabel;
this.modelViewPanel.TabIndex = 0;
this.modelViewPanel.Text = "modelViewControl";
this.modelViewPanel.MouseDown += new System.Windows.Forms.MouseEventHandler(this.modelViewPanel_MouseDown);
//
// statusLabel
//
this.statusLabel.Name = "statusLabel";
this.statusLabel.Size = new System.Drawing.Size(38, 17);
this.statusLabel.Text = "Ready";
//
// mainTabControl
//
this.mainTabControl.Controls.Add(this.modelViewTab);
this.mainTabControl.Controls.Add(this.effectEditTab);
this.mainTabControl.Controls.Add(this.componentTab);
this.mainTabControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.mainTabControl.Location = new System.Drawing.Point(0, 0);
this.mainTabControl.Name = "mainTabControl";
this.mainTabControl.SelectedIndex = 0;
this.mainTabControl.Size = new System.Drawing.Size(792, 520);
this.mainTabControl.TabIndex = 1;
this.mainTabControl.SelectedIndexChanged += new System.EventHandler(this.mainTabControl_SelectedIndexChanged);
//
// modelViewTab
//
this.modelViewTab.Controls.Add(this.splitContainer1);
this.modelViewTab.Location = new System.Drawing.Point(4, 22);
this.modelViewTab.Name = "modelViewTab";
this.modelViewTab.Padding = new System.Windows.Forms.Padding(3);
this.modelViewTab.Size = new System.Drawing.Size(784, 494);
this.modelViewTab.TabIndex = 0;
this.modelViewTab.Text = "Viewport";
this.modelViewTab.UseVisualStyleBackColor = true;
//
// effectEditTab
//
this.effectEditTab.Controls.Add(this.effectEditorContainer);
this.effectEditTab.Location = new System.Drawing.Point(4, 22);
this.effectEditTab.Name = "effectEditTab";
this.effectEditTab.Padding = new System.Windows.Forms.Padding(3);
this.effectEditTab.Size = new System.Drawing.Size(784, 494);
this.effectEditTab.TabIndex = 1;
this.effectEditTab.Text = "Effect Editor";
this.effectEditTab.UseVisualStyleBackColor = true;
//
// effectEditorContainer
//
this.effectEditorContainer.Dock = System.Windows.Forms.DockStyle.Fill;
this.effectEditorContainer.Location = new System.Drawing.Point(3, 3);
this.effectEditorContainer.Name = "effectEditorContainer";
this.effectEditorContainer.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// effectEditorContainer.Panel1
//
this.effectEditorContainer.Panel1.Controls.Add(this.effectEditorTabPages);
//
// effectEditorContainer.Panel2
//
this.effectEditorContainer.Panel2.Controls.Add(this.effectCompileOutput);
this.effectEditorContainer.Size = new System.Drawing.Size(778, 488);
this.effectEditorContainer.SplitterDistance = 388;
this.effectEditorContainer.TabIndex = 1;
//
// effectEditorTabPages
//
this.effectEditorTabPages.Controls.Add(this.componentsTab);
this.effectEditorTabPages.Controls.Add(this.parametersTab);
this.effectEditorTabPages.Controls.Add(this.vertexShadersTab);
this.effectEditorTabPages.Controls.Add(this.pixelShadersTab);
this.effectEditorTabPages.Controls.Add(this.techniquesTab);
this.effectEditorTabPages.Dock = System.Windows.Forms.DockStyle.Fill;
this.effectEditorTabPages.Location = new System.Drawing.Point(0, 0);
this.effectEditorTabPages.Name = "effectEditorTabPages";
this.effectEditorTabPages.SelectedIndex = 0;
this.effectEditorTabPages.Size = new System.Drawing.Size(778, 388);
this.effectEditorTabPages.TabIndex = 5;
//
// componentsTab
//
this.componentsTab.Controls.Add(this.removeEffectComponentButton);
this.componentsTab.Controls.Add(this.addEffectComponentButton);
this.componentsTab.Controls.Add(this.effectComponentsList);
this.componentsTab.Controls.Add(this.compileEffectButton);
this.componentsTab.Location = new System.Drawing.Point(4, 22);
this.componentsTab.Name = "componentsTab";
this.componentsTab.Padding = new System.Windows.Forms.Padding(3);
this.componentsTab.Size = new System.Drawing.Size(770, 362);
this.componentsTab.TabIndex = 0;
this.componentsTab.Text = "Components";
this.componentsTab.UseVisualStyleBackColor = true;
//
// removeEffectComponentButton
//
this.removeEffectComponentButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.removeEffectComponentButton.Enabled = false;
this.removeEffectComponentButton.Location = new System.Drawing.Point(379, 289);
this.removeEffectComponentButton.Name = "removeEffectComponentButton";
this.removeEffectComponentButton.Size = new System.Drawing.Size(75, 23);
this.removeEffectComponentButton.TabIndex = 7;
this.removeEffectComponentButton.Text = "Remove";
this.removeEffectComponentButton.UseVisualStyleBackColor = true;
this.removeEffectComponentButton.Click += new System.EventHandler(this.removeEffectComponentButton_Click);
//
// addEffectComponentButton
//
this.addEffectComponentButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.addEffectComponentButton.Location = new System.Drawing.Point(298, 289);
this.addEffectComponentButton.Name = "addEffectComponentButton";
this.addEffectComponentButton.Size = new System.Drawing.Size(75, 23);
this.addEffectComponentButton.TabIndex = 6;
this.addEffectComponentButton.Text = "Add";
this.addEffectComponentButton.UseVisualStyleBackColor = true;
this.addEffectComponentButton.Click += new System.EventHandler(this.addEffectComponentButton_Click);
//
// effectComponentsList
//
this.effectComponentsList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.effectComponentsList.FormattingEnabled = true;
this.effectComponentsList.HorizontalScrollbar = true;
this.effectComponentsList.Location = new System.Drawing.Point(6, 6);
this.effectComponentsList.Name = "effectComponentsList";
this.effectComponentsList.Size = new System.Drawing.Size(758, 277);
this.effectComponentsList.TabIndex = 5;
this.effectComponentsList.SelectedIndexChanged += new System.EventHandler(this.effectComponentsList_SelectedIndexChanged);
//
// compileEffectButton
//
this.compileEffectButton.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.compileEffectButton.Location = new System.Drawing.Point(84, 334);
this.compileEffectButton.Name = "compileEffectButton";
this.compileEffectButton.Size = new System.Drawing.Size(592, 22);
this.compileEffectButton.TabIndex = 4;
this.compileEffectButton.Text = "Compile and Apply";
this.compileEffectButton.UseVisualStyleBackColor = true;
this.compileEffectButton.Click += new System.EventHandler(this.compileEffectButton_Click_1);
//
// parametersTab
//
this.parametersTab.Controls.Add(this.addStandardParameterButton);
this.parametersTab.Controls.Add(this.label3);
this.parametersTab.Controls.Add(this.standardParametersList);
this.parametersTab.Controls.Add(this.effectParametersList);
this.parametersTab.Location = new System.Drawing.Point(4, 22);
this.parametersTab.Name = "parametersTab";
this.parametersTab.Padding = new System.Windows.Forms.Padding(3);
this.parametersTab.Size = new System.Drawing.Size(770, 362);
this.parametersTab.TabIndex = 3;
this.parametersTab.Text = "Parameters";
this.parametersTab.UseVisualStyleBackColor = true;
//
// addStandardParameterButton
//
this.addStandardParameterButton.Location = new System.Drawing.Point(260, 167);
this.addStandardParameterButton.Name = "addStandardParameterButton";
this.addStandardParameterButton.Size = new System.Drawing.Size(75, 23);
this.addStandardParameterButton.TabIndex = 3;
this.addStandardParameterButton.Text = "<<<";
this.addStandardParameterButton.UseVisualStyleBackColor = true;
this.addStandardParameterButton.Click += new System.EventHandler(this.addStandardParameterButton_Click);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(338, 6);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(109, 13);
this.label3.TabIndex = 2;
this.label3.Text = "Standard Parameters:";
//
// standardParametersList
//
this.standardParametersList.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.standardParametersList.FormattingEnabled = true;
this.standardParametersList.Location = new System.Drawing.Point(341, 22);
this.standardParametersList.Name = "standardParametersList";
this.standardParametersList.Size = new System.Drawing.Size(236, 329);
this.standardParametersList.TabIndex = 1;
this.standardParametersList.SelectedIndexChanged += new System.EventHandler(this.standardParametersList_SelectedIndexChanged);
//
// effectParametersList
//
this.effectParametersList.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.effectParametersList.Location = new System.Drawing.Point(3, 6);
this.effectParametersList.Name = "effectParametersList";
this.effectParametersList.Parameters = null;
this.effectParametersList.SemanticEnabled = false;
this.effectParametersList.Semantics = null;
this.effectParametersList.Size = new System.Drawing.Size(248, 350);
this.effectParametersList.TabIndex = 0;
//
// vertexShadersTab
//
this.vertexShadersTab.Controls.Add(this.splitContainer2);
this.vertexShadersTab.Location = new System.Drawing.Point(4, 22);
this.vertexShadersTab.Name = "vertexShadersTab";
this.vertexShadersTab.Padding = new System.Windows.Forms.Padding(3);
this.vertexShadersTab.Size = new System.Drawing.Size(770, 362);
this.vertexShadersTab.TabIndex = 1;
this.vertexShadersTab.Text = "Vertex Shaders";
this.vertexShadersTab.UseVisualStyleBackColor = true;
//
// splitContainer2
//
this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer2.Location = new System.Drawing.Point(3, 3);
this.splitContainer2.Name = "splitContainer2";
//
// splitContainer2.Panel1
//
this.splitContainer2.Panel1.Controls.Add(this.removeVertexShaderButton);
this.splitContainer2.Panel1.Controls.Add(this.addVertexShaderButton);
this.splitContainer2.Panel1.Controls.Add(this.label1);
this.splitContainer2.Panel1.Controls.Add(this.vertexShadersList);
this.splitContainer2.Panel1.Controls.Add(this.effectEditBox);
//
// splitContainer2.Panel2
//
this.splitContainer2.Panel2.Controls.Add(this.vertexShaderEditor);
this.splitContainer2.Size = new System.Drawing.Size(764, 356);
this.splitContainer2.SplitterDistance = 168;
this.splitContainer2.TabIndex = 4;
//
// removeVertexShaderButton
//
this.removeVertexShaderButton.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.removeVertexShaderButton.Location = new System.Drawing.Point(94, 327);
this.removeVertexShaderButton.Name = "removeVertexShaderButton";
this.removeVertexShaderButton.Size = new System.Drawing.Size(71, 23);
this.removeVertexShaderButton.TabIndex = 11;
this.removeVertexShaderButton.Text = "Remove";
this.removeVertexShaderButton.UseVisualStyleBackColor = true;
this.removeVertexShaderButton.Click += new System.EventHandler(this.removeVertexShaderButton_Click);
//
// addVertexShaderButton
//
this.addVertexShaderButton.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.addVertexShaderButton.Location = new System.Drawing.Point(5, 327);
this.addVertexShaderButton.Name = "addVertexShaderButton";
this.addVertexShaderButton.Size = new System.Drawing.Size(83, 23);
this.addVertexShaderButton.TabIndex = 10;
this.addVertexShaderButton.Text = "Add";
this.addVertexShaderButton.UseVisualStyleBackColor = true;
this.addVertexShaderButton.Click += new System.EventHandler(this.addVertexShaderButton_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(3, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(79, 13);
this.label1.TabIndex = 6;
this.label1.Text = "Vertex Shaders";
//
// vertexShadersList
//
this.vertexShadersList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.vertexShadersList.FormattingEnabled = true;
this.vertexShadersList.Location = new System.Drawing.Point(5, 18);
this.vertexShadersList.Name = "vertexShadersList";
this.vertexShadersList.Size = new System.Drawing.Size(161, 342);
this.vertexShadersList.TabIndex = 4;
this.vertexShadersList.SelectedIndexChanged += new System.EventHandler(this.vertexShadersList_SelectedIndexChanged);
//
// effectEditBox
//
this.effectEditBox.AcceptsTab = true;
this.effectEditBox.DetectUrls = false;
this.effectEditBox.Font = new System.Drawing.Font("Courier New", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.effectEditBox.Location = new System.Drawing.Point(5, 362);
this.effectEditBox.Name = "effectEditBox";
this.effectEditBox.Size = new System.Drawing.Size(189, 23);
this.effectEditBox.TabIndex = 2;
this.effectEditBox.Text = "";
this.effectEditBox.WordWrap = false;
//
// vertexShaderEditor
//
this.vertexShaderEditor.AllowComponentUsage = false;
this.vertexShaderEditor.AllowShaderSelection = false;
this.vertexShaderEditor.Dock = System.Windows.Forms.DockStyle.Fill;
this.vertexShaderEditor.Enabled = false;
this.vertexShaderEditor.IsPixelShader = false;
this.vertexShaderEditor.IsVertexShader = true;
this.vertexShaderEditor.Location = new System.Drawing.Point(0, 0);
this.vertexShaderEditor.Name = "vertexShaderEditor";
this.vertexShaderEditor.SemanticEnabled = true;
this.vertexShaderEditor.Size = new System.Drawing.Size(592, 356);
this.vertexShaderEditor.TabIndex = 0;
this.vertexShaderEditor.ComponentChanged += new System.EventHandler(this.vertexShaderEditor_ComponentChanged);
//
// pixelShadersTab
//
this.pixelShadersTab.Controls.Add(this.splitContainer3);
this.pixelShadersTab.Location = new System.Drawing.Point(4, 22);
this.pixelShadersTab.Name = "pixelShadersTab";
this.pixelShadersTab.Padding = new System.Windows.Forms.Padding(3);
this.pixelShadersTab.Size = new System.Drawing.Size(770, 362);
this.pixelShadersTab.TabIndex = 2;
this.pixelShadersTab.Text = "Pixel Shaders";
this.pixelShadersTab.UseVisualStyleBackColor = true;
//
// splitContainer3
//
this.splitContainer3.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer3.Location = new System.Drawing.Point(3, 3);
this.splitContainer3.Name = "splitContainer3";
//
// splitContainer3.Panel1
//
this.splitContainer3.Panel1.Controls.Add(this.removePixelShaderButton);
this.splitContainer3.Panel1.Controls.Add(this.addPixelShaderButton);
this.splitContainer3.Panel1.Controls.Add(this.label2);
this.splitContainer3.Panel1.Controls.Add(this.pixelShadersList);
this.splitContainer3.Panel1.Controls.Add(this.richTextBox1);
//
// splitContainer3.Panel2
//
this.splitContainer3.Panel2.Controls.Add(this.pixelShaderEditor);
this.splitContainer3.Size = new System.Drawing.Size(764, 356);
this.splitContainer3.SplitterDistance = 168;
this.splitContainer3.TabIndex = 5;
//
// removePixelShaderButton
//
this.removePixelShaderButton.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.removePixelShaderButton.Location = new System.Drawing.Point(93, 327);
this.removePixelShaderButton.Name = "removePixelShaderButton";
this.removePixelShaderButton.Size = new System.Drawing.Size(72, 23);
this.removePixelShaderButton.TabIndex = 11;
this.removePixelShaderButton.Text = "Remove";
this.removePixelShaderButton.UseVisualStyleBackColor = true;
this.removePixelShaderButton.Click += new System.EventHandler(this.removePixelShaderButton_Click);
//
// addPixelShaderButton
//
this.addPixelShaderButton.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.addPixelShaderButton.Location = new System.Drawing.Point(5, 327);
this.addPixelShaderButton.Name = "addPixelShaderButton";
this.addPixelShaderButton.Size = new System.Drawing.Size(82, 23);
this.addPixelShaderButton.TabIndex = 10;
this.addPixelShaderButton.Text = "Add";
this.addPixelShaderButton.UseVisualStyleBackColor = true;
this.addPixelShaderButton.Click += new System.EventHandler(this.addPixelShaderButton_Click);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(3, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(71, 13);
this.label2.TabIndex = 6;
this.label2.Text = "Pixel Shaders";
//
// pixelShadersList
//
this.pixelShadersList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pixelShadersList.FormattingEnabled = true;
this.pixelShadersList.Location = new System.Drawing.Point(5, 18);
this.pixelShadersList.Name = "pixelShadersList";
this.pixelShadersList.Size = new System.Drawing.Size(161, 342);
this.pixelShadersList.TabIndex = 4;
this.pixelShadersList.SelectedIndexChanged += new System.EventHandler(this.pixelShadersList_SelectedIndexChanged);
//
// richTextBox1
//
this.richTextBox1.AcceptsTab = true;
this.richTextBox1.DetectUrls = false;
this.richTextBox1.Font = new System.Drawing.Font("Courier New", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.richTextBox1.Location = new System.Drawing.Point(5, 362);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(189, 23);
this.richTextBox1.TabIndex = 2;
this.richTextBox1.Text = "";
this.richTextBox1.WordWrap = false;
//
// pixelShaderEditor
//
this.pixelShaderEditor.AllowComponentUsage = false;
this.pixelShaderEditor.AllowShaderSelection = false;
this.pixelShaderEditor.Dock = System.Windows.Forms.DockStyle.Fill;
this.pixelShaderEditor.Enabled = false;
this.pixelShaderEditor.IsPixelShader = false;
this.pixelShaderEditor.IsVertexShader = false;
this.pixelShaderEditor.Location = new System.Drawing.Point(0, 0);
this.pixelShaderEditor.Name = "pixelShaderEditor";
this.pixelShaderEditor.SemanticEnabled = true;
this.pixelShaderEditor.Size = new System.Drawing.Size(592, 356);
this.pixelShaderEditor.TabIndex = 0;
this.pixelShaderEditor.ComponentChanged += new System.EventHandler(this.pixelShaderEditor_ComponentChanged);
//
// techniquesTab
//
this.techniquesTab.Controls.Add(this.splitContainer4);
this.techniquesTab.Location = new System.Drawing.Point(4, 22);
this.techniquesTab.Name = "techniquesTab";
this.techniquesTab.Padding = new System.Windows.Forms.Padding(3);
this.techniquesTab.Size = new System.Drawing.Size(770, 362);
this.techniquesTab.TabIndex = 4;
this.techniquesTab.Text = "Techniques";
this.techniquesTab.UseVisualStyleBackColor = true;
//
// splitContainer4
//
this.splitContainer4.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer4.Location = new System.Drawing.Point(3, 3);
this.splitContainer4.Name = "splitContainer4";
//
// splitContainer4.Panel1
//
this.splitContainer4.Panel1.Controls.Add(this.removeTechniqueButton);
this.splitContainer4.Panel1.Controls.Add(this.addTechniqueButton);
this.splitContainer4.Panel1.Controls.Add(this.label4);
this.splitContainer4.Panel1.Controls.Add(this.effectTechniquesList);
//
// splitContainer4.Panel2
//
this.splitContainer4.Panel2.Controls.Add(this.effectTechniqueEditor);
this.splitContainer4.Size = new System.Drawing.Size(764, 356);
this.splitContainer4.SplitterDistance = 248;
this.splitContainer4.TabIndex = 0;
//
// removeTechniqueButton
//
this.removeTechniqueButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.removeTechniqueButton.Location = new System.Drawing.Point(170, 330);
this.removeTechniqueButton.Name = "removeTechniqueButton";
this.removeTechniqueButton.Size = new System.Drawing.Size(75, 23);
this.removeTechniqueButton.TabIndex = 3;
this.removeTechniqueButton.Text = "Remove";
this.removeTechniqueButton.UseVisualStyleBackColor = true;
this.removeTechniqueButton.Click += new System.EventHandler(this.removeTechniqueButton_Click);
//
// addTechniqueButton
//
this.addTechniqueButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.addTechniqueButton.Location = new System.Drawing.Point(3, 330);
this.addTechniqueButton.Name = "addTechniqueButton";
this.addTechniqueButton.Size = new System.Drawing.Size(75, 23);
this.addTechniqueButton.TabIndex = 2;
this.addTechniqueButton.Text = "Add";
this.addTechniqueButton.UseVisualStyleBackColor = true;
this.addTechniqueButton.Click += new System.EventHandler(this.addTechniqueButton_Click);
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(0, 0);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(66, 13);
this.label4.TabIndex = 1;
this.label4.Text = "Techniques:";
//
// effectTechniquesList
//
this.effectTechniquesList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.effectTechniquesList.FormattingEnabled = true;
this.effectTechniquesList.Location = new System.Drawing.Point(3, 16);
this.effectTechniquesList.Name = "effectTechniquesList";
this.effectTechniquesList.Size = new System.Drawing.Size(242, 303);
this.effectTechniquesList.TabIndex = 0;
this.effectTechniquesList.SelectedIndexChanged += new System.EventHandler(this.effectTechniquesList_SelectedIndexChanged);
//
// effectTechniqueEditor
//
this.effectTechniqueEditor.Controls.Add(this.techniqueNameBox);
this.effectTechniqueEditor.Controls.Add(this.label6);
this.effectTechniqueEditor.Controls.Add(this.effectTechniquePassesEditor);
this.effectTechniqueEditor.Dock = System.Windows.Forms.DockStyle.Fill;
this.effectTechniqueEditor.Location = new System.Drawing.Point(0, 0);
this.effectTechniqueEditor.Name = "effectTechniqueEditor";
this.effectTechniqueEditor.Size = new System.Drawing.Size(512, 356);
this.effectTechniqueEditor.TabIndex = 1;
//
// techniqueNameBox
//
this.techniqueNameBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.techniqueNameBox.Location = new System.Drawing.Point(101, 3);
this.techniqueNameBox.Name = "techniqueNameBox";
this.techniqueNameBox.Size = new System.Drawing.Size(408, 20);
this.techniqueNameBox.TabIndex = 5;
this.techniqueNameBox.TextChanged += new System.EventHandler(this.techniqueNameBox_TextChanged);
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(3, 6);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(92, 13);
this.label6.TabIndex = 4;
this.label6.Text = "Technique Name:";
//
// effectTechniquePassesEditor
//
this.effectTechniquePassesEditor.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.effectTechniquePassesEditor.Location = new System.Drawing.Point(2, 29);
this.effectTechniquePassesEditor.Name = "effectTechniquePassesEditor";
//
// effectTechniquePassesEditor.Panel1
//
this.effectTechniquePassesEditor.Panel1.Controls.Add(this.removePassButton);
this.effectTechniquePassesEditor.Panel1.Controls.Add(this.effectTechniquePassesList);
this.effectTechniquePassesEditor.Panel1.Controls.Add(this.addPassButton);
this.effectTechniquePassesEditor.Panel1.Controls.Add(this.label5);
//
// effectTechniquePassesEditor.Panel2
//
this.effectTechniquePassesEditor.Panel2.Controls.Add(this.passPixelShaderProfileBox);
this.effectTechniquePassesEditor.Panel2.Controls.Add(this.label11);
this.effectTechniquePassesEditor.Panel2.Controls.Add(this.passPixelShaderBox);
this.effectTechniquePassesEditor.Panel2.Controls.Add(this.passVertexShaderProfileBox);
this.effectTechniquePassesEditor.Panel2.Controls.Add(this.label10);
this.effectTechniquePassesEditor.Panel2.Controls.Add(this.label9);
this.effectTechniquePassesEditor.Panel2.Controls.Add(this.label8);
this.effectTechniquePassesEditor.Panel2.Controls.Add(this.passVertexShaderBox);
this.effectTechniquePassesEditor.Panel2.Controls.Add(this.passNameBox);
this.effectTechniquePassesEditor.Panel2.Controls.Add(this.label7);
this.effectTechniquePassesEditor.Panel2.Enabled = false;
this.effectTechniquePassesEditor.Size = new System.Drawing.Size(507, 330);
this.effectTechniquePassesEditor.SplitterDistance = 217;
this.effectTechniquePassesEditor.TabIndex = 0;
//
// removePassButton
//
this.removePassButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.removePassButton.Location = new System.Drawing.Point(139, 304);
this.removePassButton.Name = "removePassButton";
this.removePassButton.Size = new System.Drawing.Size(75, 23);
this.removePassButton.TabIndex = 7;
this.removePassButton.Text = "Remove";
this.removePassButton.UseVisualStyleBackColor = true;
this.removePassButton.Click += new System.EventHandler(this.removePassButton_Click);
//
// effectTechniquePassesList
//
this.effectTechniquePassesList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.effectTechniquePassesList.FormattingEnabled = true;
this.effectTechniquePassesList.Location = new System.Drawing.Point(3, 16);
this.effectTechniquePassesList.Name = "effectTechniquePassesList";
this.effectTechniquePassesList.Size = new System.Drawing.Size(211, 277);
this.effectTechniquePassesList.TabIndex = 4;
this.effectTechniquePassesList.SelectedIndexChanged += new System.EventHandler(this.effectTechniquePassesList_SelectedIndexChanged);
//
// addPassButton
//
this.addPassButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.addPassButton.Location = new System.Drawing.Point(3, 304);
this.addPassButton.Name = "addPassButton";
this.addPassButton.Size = new System.Drawing.Size(75, 23);
this.addPassButton.TabIndex = 6;
this.addPassButton.Text = "Add";
this.addPassButton.UseVisualStyleBackColor = true;
this.addPassButton.Click += new System.EventHandler(this.addPassButton_Click);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(0, 0);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(44, 13);
this.label5.TabIndex = 5;
this.label5.Text = "Passes:";
//
// passPixelShaderProfileBox
//
this.passPixelShaderProfileBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.passPixelShaderProfileBox.FormattingEnabled = true;
this.passPixelShaderProfileBox.Location = new System.Drawing.Point(230, 119);
this.passPixelShaderProfileBox.Name = "passPixelShaderProfileBox";
this.passPixelShaderProfileBox.Size = new System.Drawing.Size(53, 21);
this.passPixelShaderProfileBox.TabIndex = 15;
this.passPixelShaderProfileBox.SelectedIndexChanged += new System.EventHandler(this.pass_Changed);
//
// label11
//
this.label11.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(185, 126);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(39, 13);
this.label11.TabIndex = 14;
this.label11.Text = "Profile:";
//
// passPixelShaderBox
//
this.passPixelShaderBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.passPixelShaderBox.FormattingEnabled = true;
this.passPixelShaderBox.Location = new System.Drawing.Point(6, 119);
this.passPixelShaderBox.Name = "passPixelShaderBox";
this.passPixelShaderBox.Size = new System.Drawing.Size(173, 21);
this.passPixelShaderBox.TabIndex = 13;
this.passPixelShaderBox.SelectedIndexChanged += new System.EventHandler(this.pass_Changed);
//
// passVertexShaderProfileBox
//
this.passVertexShaderProfileBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.passVertexShaderProfileBox.FormattingEnabled = true;
this.passVertexShaderProfileBox.Location = new System.Drawing.Point(230, 59);
this.passVertexShaderProfileBox.Name = "passVertexShaderProfileBox";
this.passVertexShaderProfileBox.Size = new System.Drawing.Size(53, 21);
this.passVertexShaderProfileBox.TabIndex = 12;
this.passVertexShaderProfileBox.SelectedIndexChanged += new System.EventHandler(this.pass_Changed);
//
// label10
//
this.label10.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(185, 66);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(39, 13);
this.label10.TabIndex = 11;
this.label10.Text = "Profile:";
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(3, 103);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(69, 13);
this.label9.TabIndex = 10;
this.label9.Text = "Pixel Shader:";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(3, 43);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(77, 13);
this.label8.TabIndex = 9;
this.label8.Text = "Vertex Shader:";
//
// passVertexShaderBox
//
this.passVertexShaderBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.passVertexShaderBox.FormattingEnabled = true;
this.passVertexShaderBox.Location = new System.Drawing.Point(6, 59);
this.passVertexShaderBox.Name = "passVertexShaderBox";
this.passVertexShaderBox.Size = new System.Drawing.Size(173, 21);
this.passVertexShaderBox.TabIndex = 8;
this.passVertexShaderBox.SelectedIndexChanged += new System.EventHandler(this.pass_Changed);
//
// passNameBox
//
this.passNameBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.passNameBox.Location = new System.Drawing.Point(73, 3);
this.passNameBox.Name = "passNameBox";
this.passNameBox.Size = new System.Drawing.Size(210, 20);
this.passNameBox.TabIndex = 7;
this.passNameBox.TextChanged += new System.EventHandler(this.pass_Changed);
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(3, 6);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(64, 13);
this.label7.TabIndex = 6;
this.label7.Text = "Pass Name:";
//
// effectCompileOutput
//
this.effectCompileOutput.Dock = System.Windows.Forms.DockStyle.Fill;
this.effectCompileOutput.Location = new System.Drawing.Point(0, 0);
this.effectCompileOutput.Name = "effectCompileOutput";
this.effectCompileOutput.ReadOnly = true;
this.effectCompileOutput.Size = new System.Drawing.Size(778, 96);
this.effectCompileOutput.TabIndex = 0;
this.effectCompileOutput.Text = "";
//
// componentTab
//
this.componentTab.Controls.Add(this.componentEditor);
this.componentTab.Controls.Add(this.hlslInfoBox);
this.componentTab.Location = new System.Drawing.Point(4, 22);
this.componentTab.Name = "componentTab";
this.componentTab.Padding = new System.Windows.Forms.Padding(3);
this.componentTab.Size = new System.Drawing.Size(784, 494);
this.componentTab.TabIndex = 2;
this.componentTab.Text = "Component Editor";
this.componentTab.UseVisualStyleBackColor = true;
//
// componentEditor
//
this.componentEditor.AllowComponentUsage = false;
this.componentEditor.AllowShaderSelection = false;
this.componentEditor.Dock = System.Windows.Forms.DockStyle.Fill;
this.componentEditor.IsPixelShader = false;
this.componentEditor.IsVertexShader = false;
this.componentEditor.Location = new System.Drawing.Point(3, 3);
this.componentEditor.Name = "componentEditor";
this.componentEditor.SemanticEnabled = false;
this.componentEditor.Size = new System.Drawing.Size(778, 488);
this.componentEditor.TabIndex = 5;
//
// hlslInfoBox
//
this.hlslInfoBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.hlslInfoBox.Font = new System.Drawing.Font("Courier New", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.hlslInfoBox.Location = new System.Drawing.Point(510, -12268);
this.hlslInfoBox.Name = "hlslInfoBox";
this.hlslInfoBox.Size = new System.Drawing.Size(0, 75);
this.hlslInfoBox.TabIndex = 0;
this.hlslInfoBox.Text = "";
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.effectToolStripMenuItem,
this.componentToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(792, 24);
this.menuStrip1.TabIndex = 2;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20);
this.fileToolStripMenuItem.Text = "&File";
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(103, 22);
this.exitToolStripMenuItem.Text = "E&xit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// effectToolStripMenuItem
//
this.effectToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.loadEffectToolStripMenuItem,
this.saveEffectToolStripMenuItem});
this.effectToolStripMenuItem.Name = "effectToolStripMenuItem";
this.effectToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.effectToolStripMenuItem.Text = "&Effect";
//
// loadEffectToolStripMenuItem
//
this.loadEffectToolStripMenuItem.Name = "loadEffectToolStripMenuItem";
this.loadEffectToolStripMenuItem.Size = new System.Drawing.Size(109, 22);
this.loadEffectToolStripMenuItem.Text = "&Load";
this.loadEffectToolStripMenuItem.Click += new System.EventHandler(this.loadEffectToolStripMenuItem_Click);
//
// saveEffectToolStripMenuItem
//
this.saveEffectToolStripMenuItem.Name = "saveEffectToolStripMenuItem";
this.saveEffectToolStripMenuItem.Size = new System.Drawing.Size(109, 22);
this.saveEffectToolStripMenuItem.Text = "&Save";
this.saveEffectToolStripMenuItem.Click += new System.EventHandler(this.saveEffectToolStripMenuItem_Click);
//
// componentToolStripMenuItem
//
this.componentToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newComponentToolStripMenuItem,
this.toolStripSeparator1,
this.loadComponentToolStripMenuItem,
this.saveComponentToolStripMenuItem});
this.componentToolStripMenuItem.Name = "componentToolStripMenuItem";
this.componentToolStripMenuItem.Size = new System.Drawing.Size(74, 20);
this.componentToolStripMenuItem.Text = "&Component";
this.componentToolStripMenuItem.Visible = false;
//
// newComponentToolStripMenuItem
//
this.newComponentToolStripMenuItem.Name = "newComponentToolStripMenuItem";
this.newComponentToolStripMenuItem.Size = new System.Drawing.Size(109, 22);
this.newComponentToolStripMenuItem.Text = "&New";
this.newComponentToolStripMenuItem.Click += new System.EventHandler(this.newComponentToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(106, 6);
//
// loadComponentToolStripMenuItem
//
this.loadComponentToolStripMenuItem.Name = "loadComponentToolStripMenuItem";
this.loadComponentToolStripMenuItem.Size = new System.Drawing.Size(109, 22);
this.loadComponentToolStripMenuItem.Text = "&Load";
this.loadComponentToolStripMenuItem.Click += new System.EventHandler(this.loadComponentToolStripMenuItem_Click);
//
// saveComponentToolStripMenuItem
//
this.saveComponentToolStripMenuItem.Name = "saveComponentToolStripMenuItem";
this.saveComponentToolStripMenuItem.Size = new System.Drawing.Size(109, 22);
this.saveComponentToolStripMenuItem.Text = "&Save";
this.saveComponentToolStripMenuItem.Click += new System.EventHandler(this.saveComponentToolStripMenuItem_Click);
//
// openModelFileDialog
//
this.openModelFileDialog.DefaultExt = "x";
this.openModelFileDialog.FileName = "openFileDialog1";
this.openModelFileDialog.Filter = "X model|*.x|Compiled Model|*.xnb";
//
// statusStrip
//
this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.statusLabel});
this.statusStrip.Location = new System.Drawing.Point(0, 544);
this.statusStrip.Name = "statusStrip";
this.statusStrip.Size = new System.Drawing.Size(792, 22);
this.statusStrip.TabIndex = 3;
this.statusStrip.Text = "statusStrip1";
//
// panel1
//
this.panel1.Controls.Add(this.mainTabControl);
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(0, 24);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(792, 520);
this.panel1.TabIndex = 4;
//
// saveComponentDialog
//
this.saveComponentDialog.DefaultExt = "cmpx";
this.saveComponentDialog.Filter = "FRB Effect Component (cmpx)|*.cmpx";
//
// openComponentDialog
//
this.openComponentDialog.DefaultExt = "cmpx";
this.openComponentDialog.Filter = "FRB Effect Component (cmpx)|*.cmpx";
//
// saveEffectDialog
//
this.saveEffectDialog.DefaultExt = "efx";
this.saveEffectDialog.Filter = "FRB Effect (efx)|*.efx";
//
// openEffectDialog
//
this.openEffectDialog.DefaultExt = "efx";
this.openEffectDialog.FileName = "openFileDialog1";
this.openEffectDialog.Filter = "FRB Effect (efx)|*.efx";
//
// EditorForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(792, 566);
this.Controls.Add(this.panel1);
this.Controls.Add(this.statusStrip);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "EditorForm";
this.Text = "Effect Editor";
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.ResumeLayout(false);
this.tabControl.ResumeLayout(false);
this.viewTab.ResumeLayout(false);
this.viewTab.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.blueCustomColorBar)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.greenCustomColorBar)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.redCustomColorBar)).EndInit();
this.modelPage.ResumeLayout(false);
this.modelPage.PerformLayout();
this.effectTab.ResumeLayout(false);
this.mainTabControl.ResumeLayout(false);
this.modelViewTab.ResumeLayout(false);
this.effectEditTab.ResumeLayout(false);
this.effectEditorContainer.Panel1.ResumeLayout(false);
this.effectEditorContainer.Panel2.ResumeLayout(false);
this.effectEditorContainer.ResumeLayout(false);
this.effectEditorTabPages.ResumeLayout(false);
this.componentsTab.ResumeLayout(false);
this.parametersTab.ResumeLayout(false);
this.parametersTab.PerformLayout();
this.vertexShadersTab.ResumeLayout(false);
this.splitContainer2.Panel1.ResumeLayout(false);
this.splitContainer2.Panel1.PerformLayout();
this.splitContainer2.Panel2.ResumeLayout(false);
this.splitContainer2.ResumeLayout(false);
this.pixelShadersTab.ResumeLayout(false);
this.splitContainer3.Panel1.ResumeLayout(false);
this.splitContainer3.Panel1.PerformLayout();
this.splitContainer3.Panel2.ResumeLayout(false);
this.splitContainer3.ResumeLayout(false);
this.techniquesTab.ResumeLayout(false);
this.splitContainer4.Panel1.ResumeLayout(false);
this.splitContainer4.Panel1.PerformLayout();
this.splitContainer4.Panel2.ResumeLayout(false);
this.splitContainer4.ResumeLayout(false);
this.effectTechniqueEditor.ResumeLayout(false);
this.effectTechniqueEditor.PerformLayout();
this.effectTechniquePassesEditor.Panel1.ResumeLayout(false);
this.effectTechniquePassesEditor.Panel1.PerformLayout();
this.effectTechniquePassesEditor.Panel2.ResumeLayout(false);
this.effectTechniquePassesEditor.Panel2.PerformLayout();
this.effectTechniquePassesEditor.ResumeLayout(false);
this.componentTab.ResumeLayout(false);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.statusStrip.ResumeLayout(false);
this.statusStrip.PerformLayout();
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.Label currentModelLabel;
private System.Windows.Forms.ComboBox modelSelectionBox;
private EffectEditor.Controls.ModelViewControl modelViewPanel;
private System.Windows.Forms.Label bgColorLabel;
private System.Windows.Forms.ComboBox bgColorComboBox;
private System.Windows.Forms.TrackBar blueCustomColorBar;
private System.Windows.Forms.TrackBar greenCustomColorBar;
private System.Windows.Forms.TrackBar redCustomColorBar;
private System.Windows.Forms.Label BLabel;
private System.Windows.Forms.Label GLabel;
private System.Windows.Forms.Label RLabel;
private System.Windows.Forms.OpenFileDialog openModelFileDialog;
private System.Windows.Forms.StatusStrip statusStrip;
private System.Windows.Forms.ToolStripStatusLabel statusLabel;
private System.Windows.Forms.PropertyGrid modelPropertyGrid;
private System.Windows.Forms.TabControl tabControl;
private System.Windows.Forms.TabPage viewTab;
private System.Windows.Forms.TabPage modelPage;
private System.Windows.Forms.TabControl mainTabControl;
private System.Windows.Forms.TabPage modelViewTab;
private System.Windows.Forms.TabPage effectEditTab;
private System.Windows.Forms.TabPage effectTab;
private System.Windows.Forms.SplitContainer effectEditorContainer;
private System.Windows.Forms.RichTextBox effectEditBox;
private System.Windows.Forms.RichTextBox effectCompileOutput;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.PropertyGrid effectPropertyGrid;
private System.Windows.Forms.TabPage componentTab;
private System.Windows.Forms.RichTextBox hlslInfoBox;
private System.Windows.Forms.SaveFileDialog saveComponentDialog;
private System.Windows.Forms.ToolStripMenuItem componentToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveComponentToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem loadComponentToolStripMenuItem;
private System.Windows.Forms.OpenFileDialog openComponentDialog;
private System.Windows.Forms.SplitContainer splitContainer2;
private EffectEditor.Controls.ComponentEditor componentEditor;
private System.Windows.Forms.ToolStripMenuItem newComponentToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ListBox vertexShadersList;
private System.Windows.Forms.Button addVertexShaderButton;
private System.Windows.Forms.TabControl effectEditorTabPages;
private System.Windows.Forms.TabPage componentsTab;
private System.Windows.Forms.Button compileEffectButton;
private System.Windows.Forms.TabPage vertexShadersTab;
private System.Windows.Forms.Button removeVertexShaderButton;
private EffectEditor.Controls.ComponentEditor vertexShaderEditor;
private System.Windows.Forms.TabPage pixelShadersTab;
private System.Windows.Forms.SplitContainer splitContainer3;
private System.Windows.Forms.Button removePixelShaderButton;
private System.Windows.Forms.Button addPixelShaderButton;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ListBox pixelShadersList;
private System.Windows.Forms.RichTextBox richTextBox1;
private EffectEditor.Controls.ComponentEditor pixelShaderEditor;
private System.Windows.Forms.TabPage parametersTab;
private System.Windows.Forms.TabPage techniquesTab;
private EffectEditor.Controls.ComponentParameterList effectParametersList;
private System.Windows.Forms.Button addStandardParameterButton;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ListBox standardParametersList;
private System.Windows.Forms.Button removeEffectComponentButton;
private System.Windows.Forms.Button addEffectComponentButton;
private System.Windows.Forms.ListBox effectComponentsList;
private System.Windows.Forms.SplitContainer splitContainer4;
private System.Windows.Forms.Button removeTechniqueButton;
private System.Windows.Forms.Button addTechniqueButton;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.ListBox effectTechniquesList;
private System.Windows.Forms.SplitContainer effectTechniquePassesEditor;
private System.Windows.Forms.Button removePassButton;
private System.Windows.Forms.ListBox effectTechniquePassesList;
private System.Windows.Forms.Button addPassButton;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Panel effectTechniqueEditor;
private System.Windows.Forms.TextBox techniqueNameBox;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.TextBox passNameBox;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.ComboBox passPixelShaderProfileBox;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.ComboBox passPixelShaderBox;
private System.Windows.Forms.ComboBox passVertexShaderProfileBox;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.ComboBox passVertexShaderBox;
private System.Windows.Forms.ToolStripMenuItem effectToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem loadEffectToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveEffectToolStripMenuItem;
private System.Windows.Forms.SaveFileDialog saveEffectDialog;
private System.Windows.Forms.OpenFileDialog openEffectDialog;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Globalization;
using System.Net.Security;
using System.Runtime.InteropServices;
namespace System.Net
{
internal static class SSPIWrapper
{
internal static SecurityPackageInfoClass[] EnumerateSecurityPackages(SSPIInterface secModule)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null);
if (secModule.SecurityPackages == null)
{
lock (secModule)
{
if (secModule.SecurityPackages == null)
{
int moduleCount = 0;
SafeFreeContextBuffer arrayBaseHandle = null;
try
{
int errorCode = secModule.EnumerateSecurityPackages(out moduleCount, out arrayBaseHandle);
if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"arrayBase: {arrayBaseHandle}");
if (errorCode != 0)
{
throw new Win32Exception(errorCode);
}
var securityPackages = new SecurityPackageInfoClass[moduleCount];
int i;
for (i = 0; i < moduleCount; i++)
{
securityPackages[i] = new SecurityPackageInfoClass(arrayBaseHandle, i);
if (NetEventSource.IsEnabled) NetEventSource.Log.EnumerateSecurityPackages(securityPackages[i].Name);
}
secModule.SecurityPackages = securityPackages;
}
finally
{
if (arrayBaseHandle != null)
{
arrayBaseHandle.Dispose();
}
}
}
}
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null);
return secModule.SecurityPackages;
}
internal static SecurityPackageInfoClass GetVerifyPackageInfo(SSPIInterface secModule, string packageName, bool throwIfMissing)
{
SecurityPackageInfoClass[] supportedSecurityPackages = EnumerateSecurityPackages(secModule);
if (supportedSecurityPackages != null)
{
for (int i = 0; i < supportedSecurityPackages.Length; i++)
{
if (string.Equals(supportedSecurityPackages[i].Name, packageName, StringComparison.OrdinalIgnoreCase))
{
return supportedSecurityPackages[i];
}
}
}
if (NetEventSource.IsEnabled) NetEventSource.Log.SspiPackageNotFound(packageName);
if (throwIfMissing)
{
throw new NotSupportedException(SR.net_securitypackagesupport);
}
return null;
}
public static SafeFreeCredentials AcquireDefaultCredential(SSPIInterface secModule, string package, Interop.SspiCli.CredentialUse intent)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(null, package);
NetEventSource.Log.AcquireDefaultCredential(package, intent);
}
SafeFreeCredentials outCredential = null;
int errorCode = secModule.AcquireDefaultCredential(package, intent, out outCredential);
if (errorCode != 0)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_log_operation_failed_with_error, nameof(AcquireDefaultCredential), $"0x{errorCode:X}"));
throw new Win32Exception(errorCode);
}
return outCredential;
}
public static SafeFreeCredentials AcquireCredentialsHandle(SSPIInterface secModule, string package, Interop.SspiCli.CredentialUse intent, ref SafeSspiAuthDataHandle authdata)
{
if (NetEventSource.IsEnabled) NetEventSource.Log.AcquireCredentialsHandle(package, intent, authdata);
SafeFreeCredentials credentialsHandle = null;
int errorCode = secModule.AcquireCredentialsHandle(package, intent, ref authdata, out credentialsHandle);
if (errorCode != 0)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_log_operation_failed_with_error, nameof(AcquireCredentialsHandle), $"0x{errorCode:X}"));
throw new Win32Exception(errorCode);
}
return credentialsHandle;
}
public static SafeFreeCredentials AcquireCredentialsHandle(SSPIInterface secModule, string package, Interop.SspiCli.CredentialUse intent, Interop.SspiCli.SCHANNEL_CRED scc)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(null, package);
NetEventSource.Log.AcquireCredentialsHandle(package, intent, scc);
}
SafeFreeCredentials outCredential = null;
int errorCode = secModule.AcquireCredentialsHandle(
package,
intent,
ref scc,
out outCredential);
if (errorCode != 0)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_log_operation_failed_with_error, nameof(AcquireCredentialsHandle), $"0x{errorCode:X}"));
throw new Win32Exception(errorCode);
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, outCredential);
return outCredential;
}
internal static int InitializeSecurityContext(SSPIInterface secModule, ref SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness datarep, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags)
{
if (NetEventSource.IsEnabled) NetEventSource.Log.InitializeSecurityContext(credential, context, targetName, inFlags);
int errorCode = secModule.InitializeSecurityContext(ref credential, ref context, targetName, inFlags, datarep, inputBuffer, outputBuffer, ref outFlags);
if (NetEventSource.IsEnabled) NetEventSource.Log.SecurityContextInputBuffer(nameof(InitializeSecurityContext), inputBuffer?.size ?? 0, outputBuffer.size, (Interop.SECURITY_STATUS)errorCode);
return errorCode;
}
internal static int InitializeSecurityContext(SSPIInterface secModule, SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness datarep, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags)
{
if (NetEventSource.IsEnabled) NetEventSource.Log.InitializeSecurityContext(credential, context, targetName, inFlags);
int errorCode = secModule.InitializeSecurityContext(credential, ref context, targetName, inFlags, datarep, inputBuffers, outputBuffer, ref outFlags);
if (NetEventSource.IsEnabled) NetEventSource.Log.SecurityContextInputBuffers(nameof(InitializeSecurityContext), inputBuffers?.Length ?? 0, outputBuffer.size, (Interop.SECURITY_STATUS)errorCode);
return errorCode;
}
internal static int AcceptSecurityContext(SSPIInterface secModule, SafeFreeCredentials credential, ref SafeDeleteContext context, Interop.SspiCli.ContextFlags inFlags, Interop.SspiCli.Endianness datarep, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref Interop.SspiCli.ContextFlags outFlags)
{
if (NetEventSource.IsEnabled) NetEventSource.Log.AcceptSecurityContext(credential, context, inFlags);
int errorCode = secModule.AcceptSecurityContext(credential, ref context, inputBuffers, inFlags, datarep, outputBuffer, ref outFlags);
if (NetEventSource.IsEnabled) NetEventSource.Log.SecurityContextInputBuffers(nameof(AcceptSecurityContext), inputBuffers?.Length ?? 0, outputBuffer.size, (Interop.SECURITY_STATUS)errorCode);
return errorCode;
}
internal static int CompleteAuthToken(SSPIInterface secModule, ref SafeDeleteContext context, SecurityBuffer[] inputBuffers)
{
int errorCode = secModule.CompleteAuthToken(ref context, inputBuffers);
if (NetEventSource.IsEnabled) NetEventSource.Log.OperationReturnedSomething(nameof(CompleteAuthToken), (Interop.SECURITY_STATUS)errorCode);
return errorCode;
}
internal static int ApplyControlToken(SSPIInterface secModule, ref SafeDeleteContext context, SecurityBuffer[] inputBuffers)
{
int errorCode = secModule.ApplyControlToken(ref context, inputBuffers);
if (NetEventSource.IsEnabled) NetEventSource.Log.OperationReturnedSomething(nameof(ApplyControlToken), (Interop.SECURITY_STATUS)errorCode);
return errorCode;
}
public static int QuerySecurityContextToken(SSPIInterface secModule, SafeDeleteContext context, out SecurityContextTokenHandle token)
{
return secModule.QuerySecurityContextToken(context, out token);
}
public static int EncryptMessage(SSPIInterface secModule, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber)
{
return EncryptDecryptHelper(OP.Encrypt, secModule, context, input, sequenceNumber);
}
public static int DecryptMessage(SSPIInterface secModule, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber)
{
return EncryptDecryptHelper(OP.Decrypt, secModule, context, input, sequenceNumber);
}
internal static int MakeSignature(SSPIInterface secModule, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber)
{
return EncryptDecryptHelper(OP.MakeSignature, secModule, context, input, sequenceNumber);
}
public static int VerifySignature(SSPIInterface secModule, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber)
{
return EncryptDecryptHelper(OP.VerifySignature, secModule, context, input, sequenceNumber);
}
private enum OP
{
Encrypt = 1,
Decrypt,
MakeSignature,
VerifySignature
}
private static unsafe int EncryptDecryptHelper(OP op, SSPIInterface secModule, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber)
{
Interop.SspiCli.SecBufferDesc sdcInOut = new Interop.SspiCli.SecBufferDesc(input.Length);
var unmanagedBuffer = new Interop.SspiCli.SecBuffer[input.Length];
fixed (Interop.SspiCli.SecBuffer* unmanagedBufferPtr = unmanagedBuffer)
{
sdcInOut.pBuffers = unmanagedBufferPtr;
GCHandle[] pinnedBuffers = new GCHandle[input.Length];
byte[][] buffers = new byte[input.Length][];
try
{
for (int i = 0; i < input.Length; i++)
{
SecurityBuffer iBuffer = input[i];
unmanagedBuffer[i].cbBuffer = iBuffer.size;
unmanagedBuffer[i].BufferType = iBuffer.type;
if (iBuffer.token == null || iBuffer.token.Length == 0)
{
unmanagedBuffer[i].pvBuffer = IntPtr.Zero;
}
else
{
pinnedBuffers[i] = GCHandle.Alloc(iBuffer.token, GCHandleType.Pinned);
unmanagedBuffer[i].pvBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(iBuffer.token, iBuffer.offset);
buffers[i] = iBuffer.token;
}
}
// The result is written in the input Buffer passed as type=BufferType.Data.
int errorCode;
switch (op)
{
case OP.Encrypt:
errorCode = secModule.EncryptMessage(context, ref sdcInOut, sequenceNumber);
break;
case OP.Decrypt:
errorCode = secModule.DecryptMessage(context, ref sdcInOut, sequenceNumber);
break;
case OP.MakeSignature:
errorCode = secModule.MakeSignature(context, ref sdcInOut, sequenceNumber);
break;
case OP.VerifySignature:
errorCode = secModule.VerifySignature(context, ref sdcInOut, sequenceNumber);
break;
default:
NetEventSource.Fail(null, $"Unknown OP: {op}");
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
// Marshalling back returned sizes / data.
for (int i = 0; i < input.Length; i++)
{
SecurityBuffer iBuffer = input[i];
iBuffer.size = unmanagedBuffer[i].cbBuffer;
iBuffer.type = unmanagedBuffer[i].BufferType;
if (iBuffer.size == 0)
{
iBuffer.offset = 0;
iBuffer.token = null;
}
else
{
checked
{
// Find the buffer this is inside of. Usually they all point inside buffer 0.
int j;
for (j = 0; j < input.Length; j++)
{
if (buffers[j] == null)
{
continue;
}
byte* bufferAddress = (byte*)Marshal.UnsafeAddrOfPinnedArrayElement(buffers[j], 0);
if ((byte*)unmanagedBuffer[i].pvBuffer >= bufferAddress &&
(byte*)unmanagedBuffer[i].pvBuffer + iBuffer.size <= bufferAddress + buffers[j].Length)
{
iBuffer.offset = (int)((byte*)unmanagedBuffer[i].pvBuffer - bufferAddress);
iBuffer.token = buffers[j];
break;
}
}
if (j >= input.Length)
{
NetEventSource.Fail(null, "Output buffer out of range.");
iBuffer.size = 0;
iBuffer.offset = 0;
iBuffer.token = null;
}
}
}
// Backup validate the new sizes.
if (iBuffer.offset < 0 || iBuffer.offset > (iBuffer.token == null ? 0 : iBuffer.token.Length))
{
NetEventSource.Fail(null, $"'offset' out of range. [{iBuffer.offset}]");
}
if (iBuffer.size < 0 || iBuffer.size > (iBuffer.token == null ? 0 : iBuffer.token.Length - iBuffer.offset))
{
NetEventSource.Fail(null, $"'size' out of range. [{iBuffer.size}]");
}
}
if (NetEventSource.IsEnabled && errorCode != 0)
{
if (errorCode == Interop.SspiCli.SEC_I_RENEGOTIATE)
{
NetEventSource.Error(null, SR.Format(SR.event_OperationReturnedSomething, op, "SEC_I_RENEGOTIATE"));
}
else
{
NetEventSource.Error(null, SR.Format(SR.net_log_operation_failed_with_error, op, $"0x{0:X}"));
}
}
return errorCode;
}
finally
{
for (int i = 0; i < pinnedBuffers.Length; ++i)
{
if (pinnedBuffers[i].IsAllocated)
{
pinnedBuffers[i].Free();
}
}
}
}
}
public static SafeFreeContextBufferChannelBinding QueryContextChannelBinding(SSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, contextAttribute);
SafeFreeContextBufferChannelBinding result;
int errorCode = secModule.QueryContextChannelBinding(securityContext, contextAttribute, out result);
if (errorCode != 0)
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"ERROR = {ErrorDescription(errorCode)}");
return null;
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, result);
return result;
}
public static object QueryContextAttributes(SSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute)
{
int errorCode;
return QueryContextAttributes(secModule, securityContext, contextAttribute, out errorCode);
}
public static object QueryContextAttributes(SSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute, out int errorCode)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, contextAttribute);
int nativeBlockSize = IntPtr.Size;
Type handleType = null;
switch (contextAttribute)
{
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_SIZES:
nativeBlockSize = SecPkgContext_Sizes.SizeOf;
break;
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_STREAM_SIZES:
nativeBlockSize = SecPkgContext_StreamSizes.SizeOf;
break;
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_NAMES:
handleType = typeof(SafeFreeContextBuffer);
break;
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_PACKAGE_INFO:
handleType = typeof(SafeFreeContextBuffer);
break;
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_NEGOTIATION_INFO:
handleType = typeof(SafeFreeContextBuffer);
unsafe
{
nativeBlockSize = sizeof(SecPkgContext_NegotiationInfoW);
}
break;
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_CLIENT_SPECIFIED_TARGET:
handleType = typeof(SafeFreeContextBuffer);
break;
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_REMOTE_CERT_CONTEXT:
handleType = typeof(SafeFreeCertContext);
break;
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_LOCAL_CERT_CONTEXT:
handleType = typeof(SafeFreeCertContext);
break;
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_ISSUER_LIST_EX:
nativeBlockSize = Marshal.SizeOf<Interop.SspiCli.SecPkgContext_IssuerListInfoEx>();
handleType = typeof(SafeFreeContextBuffer);
break;
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_CONNECTION_INFO:
nativeBlockSize = Marshal.SizeOf<SecPkgContext_ConnectionInfo>();
break;
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_APPLICATION_PROTOCOL:
nativeBlockSize = Marshal.SizeOf<Interop.SecPkgContext_ApplicationProtocol>();
break;
default:
throw new ArgumentException(SR.Format(SR.net_invalid_enum, nameof(contextAttribute)), nameof(contextAttribute));
}
SafeHandle sspiHandle = null;
object attribute = null;
try
{
var nativeBuffer = new byte[nativeBlockSize];
errorCode = secModule.QueryContextAttributes(securityContext, contextAttribute, nativeBuffer, handleType, out sspiHandle);
if (errorCode != 0)
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, $"ERROR = {ErrorDescription(errorCode)}");
return null;
}
switch (contextAttribute)
{
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_SIZES:
attribute = new SecPkgContext_Sizes(nativeBuffer);
break;
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_STREAM_SIZES:
attribute = new SecPkgContext_StreamSizes(nativeBuffer);
break;
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_NAMES:
attribute = Marshal.PtrToStringUni(sspiHandle.DangerousGetHandle());
break;
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_PACKAGE_INFO:
attribute = new SecurityPackageInfoClass(sspiHandle, 0);
break;
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_NEGOTIATION_INFO:
unsafe
{
fixed (void* ptr = &nativeBuffer[0])
{
attribute = new NegotiationInfoClass(sspiHandle, (int)((SecPkgContext_NegotiationInfoW*)ptr)->NegotiationState);
}
}
break;
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_CLIENT_SPECIFIED_TARGET:
attribute = Marshal.PtrToStringUni(sspiHandle.DangerousGetHandle());
break;
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_LOCAL_CERT_CONTEXT:
// Fall-through to RemoteCertificate is intentional.
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_REMOTE_CERT_CONTEXT:
attribute = sspiHandle;
sspiHandle = null;
break;
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_ISSUER_LIST_EX:
attribute = new Interop.SspiCli.SecPkgContext_IssuerListInfoEx(sspiHandle, nativeBuffer);
sspiHandle = null;
break;
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_CONNECTION_INFO:
attribute = new SecPkgContext_ConnectionInfo(nativeBuffer);
break;
case Interop.SspiCli.ContextAttribute.SECPKG_ATTR_APPLICATION_PROTOCOL:
unsafe
{
fixed (void *ptr = nativeBuffer)
{
attribute = Marshal.PtrToStructure<Interop.SecPkgContext_ApplicationProtocol>(new IntPtr(ptr));
}
}
break;
default:
// Will return null.
break;
}
}
finally
{
if (sspiHandle != null)
{
sspiHandle.Dispose();
}
}
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, attribute);
return attribute;
}
public static string ErrorDescription(int errorCode)
{
if (errorCode == -1)
{
return "An exception when invoking Win32 API";
}
switch ((Interop.SECURITY_STATUS)errorCode)
{
case Interop.SECURITY_STATUS.InvalidHandle:
return "Invalid handle";
case Interop.SECURITY_STATUS.InvalidToken:
return "Invalid token";
case Interop.SECURITY_STATUS.ContinueNeeded:
return "Continue needed";
case Interop.SECURITY_STATUS.IncompleteMessage:
return "Message incomplete";
case Interop.SECURITY_STATUS.WrongPrincipal:
return "Wrong principal";
case Interop.SECURITY_STATUS.TargetUnknown:
return "Target unknown";
case Interop.SECURITY_STATUS.PackageNotFound:
return "Package not found";
case Interop.SECURITY_STATUS.BufferNotEnough:
return "Buffer not enough";
case Interop.SECURITY_STATUS.MessageAltered:
return "Message altered";
case Interop.SECURITY_STATUS.UntrustedRoot:
return "Untrusted root";
default:
return "0x" + errorCode.ToString("x", NumberFormatInfo.InvariantInfo);
}
}
} // class SSPIWrapper
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Xml;
namespace TesterApp
{
public class Form1 : System.Windows.Forms.Form
{
TcpClient socket = new TcpClient();
NetworkStream ns = null;
string crlf = "\r\n";
private System.Windows.Forms.TextBox CommandBox;
private System.Windows.Forms.ListBox CommandList;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button PreMadeCommandBtn;
private System.Windows.Forms.TextBox ResponseBox;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.TextBox Server;
private System.Windows.Forms.TextBox Port;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button Connect;
private System.Windows.Forms.Button ClearResponses;
private TextBox Zone;
private Label label5;
private Label label4;
private TextBox Password;
private Label label3;
private TextBox Username;
private System.ComponentModel.Container components = null;
#region Windows Form Designer generated code
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.CommandBox = new System.Windows.Forms.TextBox();
this.CommandList = new System.Windows.Forms.ListBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.PreMadeCommandBtn = new System.Windows.Forms.Button();
this.ResponseBox = new System.Windows.Forms.TextBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.button1 = new System.Windows.Forms.Button();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.ClearResponses = new System.Windows.Forms.Button();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.Zone = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.Password = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.Username = new System.Windows.Forms.TextBox();
this.Connect = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.Port = new System.Windows.Forms.TextBox();
this.Server = new System.Windows.Forms.TextBox();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox3.SuspendLayout();
this.groupBox4.SuspendLayout();
this.SuspendLayout();
//
// CommandBox
//
this.CommandBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.CommandBox.Location = new System.Drawing.Point(8, 16);
this.CommandBox.Multiline = true;
this.CommandBox.Name = "CommandBox";
this.CommandBox.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.CommandBox.Size = new System.Drawing.Size(440, 217);
this.CommandBox.TabIndex = 0;
this.CommandBox.WordWrap = false;
this.CommandBox.TextChanged += new System.EventHandler(this.CommandBox_TextChanged);
//
// CommandList
//
this.CommandList.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.CommandList.Location = new System.Drawing.Point(8, 16);
this.CommandList.Name = "CommandList";
this.CommandList.Size = new System.Drawing.Size(352, 69);
this.CommandList.TabIndex = 0;
//
// groupBox1
//
this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox1.Controls.Add(this.PreMadeCommandBtn);
this.groupBox1.Controls.Add(this.CommandList);
this.groupBox1.Location = new System.Drawing.Point(472, 8);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(368, 120);
this.groupBox1.TabIndex = 1;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Sample Commands";
//
// PreMadeCommandBtn
//
this.PreMadeCommandBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.PreMadeCommandBtn.Location = new System.Drawing.Point(8, 88);
this.PreMadeCommandBtn.Name = "PreMadeCommandBtn";
this.PreMadeCommandBtn.Size = new System.Drawing.Size(352, 23);
this.PreMadeCommandBtn.TabIndex = 1;
this.PreMadeCommandBtn.Text = "<-- Send to command window";
this.PreMadeCommandBtn.Click += new System.EventHandler(this.PreMadeCommandBtn_Click);
//
// ResponseBox
//
this.ResponseBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ResponseBox.Location = new System.Drawing.Point(8, 16);
this.ResponseBox.Multiline = true;
this.ResponseBox.Name = "ResponseBox";
this.ResponseBox.ReadOnly = true;
this.ResponseBox.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.ResponseBox.Size = new System.Drawing.Size(352, 192);
this.ResponseBox.TabIndex = 0;
this.ResponseBox.WordWrap = false;
this.ResponseBox.TextChanged += new System.EventHandler(this.ResponseBox_TextChanged);
//
// groupBox2
//
this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.groupBox2.Controls.Add(this.button1);
this.groupBox2.Controls.Add(this.CommandBox);
this.groupBox2.Location = new System.Drawing.Point(8, 111);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(456, 273);
this.groupBox2.TabIndex = 2;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Send Commands";
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.button1.Enabled = false;
this.button1.Location = new System.Drawing.Point(336, 241);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(112, 23);
this.button1.TabIndex = 1;
this.button1.Text = "Send Command";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// groupBox3
//
this.groupBox3.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox3.Controls.Add(this.ClearResponses);
this.groupBox3.Controls.Add(this.ResponseBox);
this.groupBox3.Location = new System.Drawing.Point(472, 136);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(368, 248);
this.groupBox3.TabIndex = 3;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Response List";
//
// ClearResponses
//
this.ClearResponses.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ClearResponses.Location = new System.Drawing.Point(248, 216);
this.ClearResponses.Name = "ClearResponses";
this.ClearResponses.Size = new System.Drawing.Size(112, 23);
this.ClearResponses.TabIndex = 1;
this.ClearResponses.Text = "Clear Responses";
this.ClearResponses.Click += new System.EventHandler(this.ClearResponses_Click);
//
// groupBox4
//
this.groupBox4.Controls.Add(this.Zone);
this.groupBox4.Controls.Add(this.label5);
this.groupBox4.Controls.Add(this.label4);
this.groupBox4.Controls.Add(this.Password);
this.groupBox4.Controls.Add(this.label3);
this.groupBox4.Controls.Add(this.Username);
this.groupBox4.Controls.Add(this.Connect);
this.groupBox4.Controls.Add(this.label2);
this.groupBox4.Controls.Add(this.label1);
this.groupBox4.Controls.Add(this.Port);
this.groupBox4.Controls.Add(this.Server);
this.groupBox4.Location = new System.Drawing.Point(8, 8);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(456, 97);
this.groupBox4.TabIndex = 0;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "Connect";
//
// Zone
//
this.Zone.Location = new System.Drawing.Point(248, 39);
this.Zone.Name = "Zone";
this.Zone.Size = new System.Drawing.Size(40, 20);
this.Zone.TabIndex = 7;
this.Zone.Text = "1";
//
// label5
//
this.label5.Location = new System.Drawing.Point(181, 45);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(61, 23);
this.label5.TabIndex = 6;
this.label5.Text = "Zone:";
this.label5.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// label4
//
this.label4.Location = new System.Drawing.Point(8, 68);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(61, 23);
this.label4.TabIndex = 8;
this.label4.Text = "Password:";
this.label4.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// Password
//
this.Password.Location = new System.Drawing.Point(75, 65);
this.Password.Name = "Password";
this.Password.Size = new System.Drawing.Size(100, 20);
this.Password.TabIndex = 9;
this.Password.Text = "trms";
this.Password.UseSystemPasswordChar = true;
//
// label3
//
this.label3.Location = new System.Drawing.Point(8, 42);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(61, 23);
this.label3.TabIndex = 4;
this.label3.Text = "Username:";
this.label3.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// Username
//
this.Username.Location = new System.Drawing.Point(75, 39);
this.Username.Name = "Username";
this.Username.Size = new System.Drawing.Size(100, 20);
this.Username.TabIndex = 5;
this.Username.Text = "admin";
//
// Connect
//
this.Connect.Location = new System.Drawing.Point(344, 16);
this.Connect.Name = "Connect";
this.Connect.Size = new System.Drawing.Size(104, 23);
this.Connect.TabIndex = 10;
this.Connect.Text = "Connect";
this.Connect.Click += new System.EventHandler(this.Connect_Click);
//
// label2
//
this.label2.Location = new System.Drawing.Point(181, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(61, 23);
this.label2.TabIndex = 2;
this.label2.Text = "Port:";
this.label2.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(61, 23);
this.label1.TabIndex = 0;
this.label1.Text = "Server:";
this.label1.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// Port
//
this.Port.Location = new System.Drawing.Point(248, 13);
this.Port.Name = "Port";
this.Port.Size = new System.Drawing.Size(40, 20);
this.Port.TabIndex = 3;
this.Port.Text = "56906";
//
// Server
//
this.Server.Location = new System.Drawing.Point(75, 13);
this.Server.Name = "Server";
this.Server.Size = new System.Drawing.Size(100, 20);
this.Server.TabIndex = 1;
this.Server.Text = "demo.trms.com";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(848, 389);
this.Controls.Add(this.groupBox4);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
this.groupBox1.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
this.groupBox4.ResumeLayout(false);
this.groupBox4.PerformLayout();
this.ResumeLayout(false);
}
#endregion
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, System.EventArgs e)
{
Server.Text = Settings1.Default.Server;
Port.Text = Settings1.Default.Port;
Username.Text = Settings1.Default.Username;
Password.Text = Settings1.Default.Password;
Zone.Text = Settings1.Default.Zone;
CommandList.Items.Add("CreatePage1");
CommandList.Items.Add("CreatePage2");
CommandList.Items.Add("CreatePage3");
CommandList.Items.Add("UpdatePage");
CommandList.Items.Add("CreateAlertPage");
CommandList.Items.Add("CreateCrawl");
CommandList.Items.Add("CreateCrawlInvalidUser");
CommandList.Items.Add("CreateCrawl1Zone");
CommandList.Items.Add("CreateCrawlInvalidZone");
CommandList.Items.Add("ChangePageStatus");
CommandList.Items.Add("DeletePage");
CommandList.Items.Add("DeleteAllUserPages");
CommandList.Items.Add("DeactivateAllAlertPages");
CommandList.Items.Add("GetPlayerStatus");
CommandList.Items.Add("IllFormedCmd1");
CommandList.Items.Add("IllFormedCmd2");
CommandList.Items.Add("IllFormedCmd3");
CommandList.Items.Add("IllFormedCmd4");
CommandList.Items.Add("GetZoneList");
CommandList.Items.Add("GetTemplateList");
CommandList.Items.Add("GetBulletinList");
}
private void Connect_Click(object sender, System.EventArgs e)
{
try
{
if (Connect.Text == "Connect")
{
socket = new TcpClient();
socket.Connect(Server.Text, Int32.Parse(Port.Text));
ns = socket.GetStream();
ResponseBox.Text += "Connected." + crlf + crlf;
Connect.Text = "Disconnect";
return;
}
if (Connect.Text == "Disconnect")
{
ns.Close();
socket.Close();
Connect.Text = "Connect";
ResponseBox.Text += "Disconnected." + crlf + crlf;
return;
}
}
catch (Exception exc)
{
ResponseBox.Text += exc.Message + crlf + crlf;
}
}
private void ResponseBox_TextChanged(object sender, System.EventArgs e)
{
//scroll to bottom
ResponseBox.SelectionStart = ResponseBox.Text.Length;
ResponseBox.ScrollToCaret();
}
private string FixSample(string input)
{
string result = input.Replace("\n", Environment.NewLine);
result = Regex.Replace(result, "<ZoneID>[^<]*</ZoneID>", "<ZoneID>" + Zone.Text + "</ZoneID>");
result = Regex.Replace(result, "<Zone>[^<]*</Zone>", "<Zone>" + Zone.Text + "</Zone>");
result = Regex.Replace(result, "<UserName>[^<]*</UserName>", "<UserName>" + Username.Text + "</UserName>");
result = Regex.Replace(result, "<Password>[^<]*</Password>", "<Password>" + Password.Text + "</Password>");
return result;
}
private void PreMadeCommandBtn_Click(object sender, System.EventArgs e)
{
switch (CommandList.SelectedItem.ToString())
{
case "CreatePage1":
CommandBox.Text = FixSample(SampleCommand.CreatePage1());
break;
case "CreatePage2":
CommandBox.Text = FixSample(SampleCommand.CreatePage2());
break;
case "CreatePage3":
CommandBox.Text = FixSample(SampleCommand.CreatePage3());
break;
case "UpdatePage":
CommandBox.Text = FixSample(SampleCommand.UpdatePage());
break;
case "CreateAlertPage":
CommandBox.Text = FixSample(SampleCommand.CreateAlertPage());
break;
case "CreateCrawl":
CommandBox.Text = FixSample(SampleCommand.CreateCrawl());
break;
case "CreateCrawlInvalidUser":
CommandBox.Text = FixSample(SampleCommand.CreateCrawlInvalidUser());
break;
case "CreateCrawl1Zone":
CommandBox.Text = FixSample(SampleCommand.CreateCrawl1Zone());
break;
case "CreateCrawlInvalidZone":
CommandBox.Text = FixSample(SampleCommand.CreateCrawlInvalidZone());
break;
case "ChangePageStatus":
CommandBox.Text = FixSample(SampleCommand.ChangePageStatus());
break;
case "DeletePage":
CommandBox.Text = FixSample(SampleCommand.DeletePage());
break;
case "DeleteAllUserPages":
CommandBox.Text = FixSample(SampleCommand.DeleteAllUserPages());
break;
case "DeactivateAllAlertPages":
CommandBox.Text = FixSample(SampleCommand.DeactivateAllAlertPages());
break;
case "GetPlayerStatus":
CommandBox.Text = FixSample(SampleCommand.GetPlayerStatus());
break;
case "IllFormedCmd1":
CommandBox.Text = FixSample(SampleCommand.IllFormedCmd1());
break;
case "IllFormedCmd2":
CommandBox.Text = FixSample(SampleCommand.IllFormedCmd2());
break;
case "IllFormedCmd3":
CommandBox.Text = FixSample(SampleCommand.IllFormedCmd3());
break;
case "IllFormedCmd4":
CommandBox.Text = FixSample(SampleCommand.IllFormedCmd4());
break;
case "GetZoneList":
CommandBox.Text = FixSample(SampleCommand.GetZoneList());
break;
case "GetTemplateList":
CommandBox.Text = FixSample(SampleCommand.GetTemplateList());
break;
case "GetBulletinList":
CommandBox.Text = FixSample(SampleCommand.GetBulletinList());
break;
}
}
private void button1_Click(object sender, System.EventArgs e)
{
if (String.IsNullOrEmpty(CommandBox.Text.Trim()))
return;
if (ns != null && ns.CanWrite && ns.CanRead)
{
try
{
byte[] cmd;
byte[] response;
button1.Enabled = false;
ResponseBox.Text += "Sending Command..." + crlf;
cmd = Encoding.ASCII.GetBytes(CommandBox.Text.ToCharArray());
ns.Write(cmd, 0, cmd.Length);
// wait for data to be present
while(ns.DataAvailable == false)
System.Threading.Thread.Sleep(100);
response = new byte[socket.ReceiveBufferSize];
string XML = String.Empty;
while(ns.DataAvailable) {
int length = ns.Read(response, 0, socket.ReceiveBufferSize);
if (length <= 0)
break;
XML += Encoding.ASCII.GetString(response, 0, length).Trim().Replace("\0",""); //get rid of whitespace
}
//parse the return xml
StringReader sr = new StringReader(XML);
XmlDocument xdoc = new XmlDocument();
xdoc.Load(sr);
XmlNodeList result = xdoc.GetElementsByTagName("Result");
XmlNodeList description = xdoc.GetElementsByTagName("Description");
XmlNodeList guids = xdoc.GetElementsByTagName("GUID");
XmlNodeList playerStatuses = xdoc.GetElementsByTagName("PlayerStatus");
ResponseBox.Text += "Result: " + result[0].InnerText + crlf;
ResponseBox.Text += "Description: " + description[0].InnerText + crlf;
for (int i = 0; i<guids.Count; i++)
ResponseBox.Text += "GUID: " + guids[i].InnerText + crlf;
for (int i = 0; i < playerStatuses.Count; i++)
{
ResponseBox.Text += "PlayerStatus[0]:" + crlf;
XmlNodeList elements = playerStatuses[i].ChildNodes;
foreach (XmlNode node in elements)
{
ResponseBox.Text += " " + node.Name + ": " + node.InnerText + crlf;
}
}
ResponseBox.Text += crlf;
ResponseBox.Text += crlf;
ResponseBox.Text += "Raw Response:";
ResponseBox.Text += crlf;
ResponseBox.Text += XML;
}
catch(Exception exc)
{
ResponseBox.Text += exc.Message + crlf + crlf;
}
}
else
{
ResponseBox.Text += "Not Connected. " + crlf + crlf;
}
button1.Enabled = true;
}
private void ClearResponses_Click(object sender, System.EventArgs e)
{
ResponseBox.Text = "";
}
private void CommandBox_TextChanged(object sender, EventArgs e)
{
button1.Enabled = !String.IsNullOrEmpty(CommandBox.Text.Trim());
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Settings1.Default.Server = Server.Text;
Settings1.Default.Port = Port.Text;
Settings1.Default.Username = Username.Text;
Settings1.Default.Password = Password.Text;
Settings1.Default.Zone = Zone.Text;
Settings1.Default.Save();
}
}
/// <summary>
/// A storage class for commands
/// </summary>
public class SampleCommand
{
public SampleCommand(string CommandName)
{
}
public static string CreatePage1()
{
return @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<CarouselCommand xmlns=""http://www.trms.com/CarouselRemoteCommand"">
<CreatePage>
<UserName>xml</UserName>
<Password>trms</Password>
<Zone>1</Zone>
<AlwaysOn>false</AlwaysOn>
<DateTimeOn>2005-10-29T00:00:00</DateTimeOn>
<DateTimeOff>2005-12-29T23:59:59</DateTimeOff>
<CycleTimeOn>08:00:00</CycleTimeOn>
<CycleTimeOff>17:00:00</CycleTimeOff>
<DisplayDuration>5</DisplayDuration>
<Weekdays>127</Weekdays>
<WebEnabled>true</WebEnabled>
<Description>This is a sample page that we created via the remote command system.</Description>
<PageType>Standard</PageType>
<PageTemplate>
<TemplateName>a title and body</TemplateName>
<Block Name=""Title"" Value=""Hello"" />
<Block Name=""bOdY"" Value=""World!"" />
<Block Name=""test"" Value=""World!"" />
</PageTemplate>
</CreatePage>
</CarouselCommand>";
}
public static string CreatePage2()
{
return @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<CarouselCommand xmlns=""http://www.trms.com/CarouselRemoteCommand"">
<CreatePage>
<UserName>xml</UserName>
<Password>trms</Password>
<Zone>1</Zone>
<AlwaysOn>false</AlwaysOn>
<DateTimeOn>2005-10-29T00:00:00</DateTimeOn>
<DateTimeOff>2005-12-29T23:59:59</DateTimeOff>
<CycleTimeOn>08:00:00</CycleTimeOn>
<CycleTimeOff>17:00:00</CycleTimeOff>
<DisplayDuration>5</DisplayDuration>
<Weekdays>127</Weekdays>
<WebEnabled>true</WebEnabled>
<Description>This is a sample page that we created via the remote command system.</Description>
<PageType>Standard</PageType>
<PageTemplate>
<TemplateName>Picture Right</TemplateName>
<Block Name=""Title"" Value=""Sample"" />
<Block Name=""Description"" Value=""Carousel Page"" />
</PageTemplate>
</CreatePage>
</CarouselCommand>";
}
public static string CreatePage3()
{
return @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<CarouselCommand xmlns=""http://www.trms.com/CarouselRemoteCommand"">
<CreatePage>
<UserName>xml</UserName>
<Password>trms</Password>
<Zone>1</Zone>
<AlwaysOn>false</AlwaysOn>
<DateTimeOn>2005-10-29T00:00:00</DateTimeOn>
<DateTimeOff>2005-12-29T23:59:59</DateTimeOff>
<CycleTimeOn>08:00:00</CycleTimeOn>
<CycleTimeOff>17:00:00</CycleTimeOff>
<DisplayDuration>5</DisplayDuration>
<Weekdays>127</Weekdays>
<WebEnabled>true</WebEnabled>
<Description>This is a sample page that we created via the remote command system.</Description>
<PageType>Standard</PageType>
<PageTemplate>
<TemplateName>blue lines</TemplateName>
<Block Name=""Text"" Value=""TRMS!"" />
</PageTemplate>
</CreatePage>
</CarouselCommand>";
}
public static string UpdatePage()
{
return @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<CarouselCommand xmlns=""http://www.trms.com/CarouselRemoteCommand"">
<UpdatePage>
<UserName>xml</UserName>
<Password>trms</Password>
<UpdateGUID>3dc0f1cd-eb4c-4bad-8733-15a5a13eea08</UpdateGUID>
<AlwaysOn>false</AlwaysOn>
<DateTimeOn>2005-09-29T00:00:00</DateTimeOn>
<DateTimeOff>2005-12-05T23:59:59</DateTimeOff>
<CycleTimeOn>09:00:00</CycleTimeOn>
<CycleTimeOff>18:00:00</CycleTimeOff>
<Weekdays>32</Weekdays>
<WebEnabled>true</WebEnabled>
<PageType>Standard</PageType>
<Block Name=""left text area"" Value=""Left!"" />
<Block Name=""right text area"" Value=""Right!"" />
</UpdatePage>
</CarouselCommand>";
}
public static string CreateAlertPage()
{
return @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<CarouselCommand xmlns=""http://www.trms.com/CarouselRemoteCommand"">
<CreatePage>
<UserName>xml</UserName>
<Password>trms</Password>
<Zone>1</Zone>
<AlwaysOn>true</AlwaysOn>
<Weekdays>127</Weekdays>
<WebEnabled>true</WebEnabled>
<PageType>alert</PageType>
<PageTemplate>
<TemplateName>Simple Message</TemplateName>
<Block Name=""Simple Message"" Value=""ALERT PAGE"" />
</PageTemplate>
</CreatePage>
</CarouselCommand>";
}
public static string CreateCrawl()
{
return @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<CarouselCommand xmlns=""http://www.trms.com/CarouselRemoteCommand"">
<CreateCrawl>
<UserName>xml</UserName>
<Password>trms</Password>
<CrawlText>This is the text I'd like to see at the bottom of the screen.</CrawlText>
<Zone>all</Zone>
<AlwaysOn>false</AlwaysOn>
<DateTimeOn>2005-10-26T00:00:00</DateTimeOn>
<DateTimeOff>2005-12-29T23:59:59</DateTimeOff>
<CycleTimeOn>08:00:00</CycleTimeOn>
<CycleTimeOff>17:00:00</CycleTimeOff>
<Weekdays>127</Weekdays>
<WebEnabled>true</WebEnabled>
</CreateCrawl>
</CarouselCommand>";
}
public static string CreateCrawlInvalidUser()
{
return @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<CarouselCommand xmlns=""http://www.trms.com/CarouselRemoteCommand"">
<CreateCrawl>
<UserName>fakeName</UserName>
<Password>fakePassword</Password>
<CrawlText>This is the text I'd like to see at the bottom of the screen.</CrawlText>
<Zone>all</Zone>
<AlwaysOn>false</AlwaysOn>
<DateTimeOn>2005-10-26T00:00:00-06:00</DateTimeOn>
<DateTimeOff>2005-10-29T23:59:59-06:00</DateTimeOff>
<Weekdays>127</Weekdays>
<WebEnabled>true</WebEnabled>
</CreateCrawl>
</CarouselCommand>";
}
public static string CreateCrawl1Zone()
{
return @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<CarouselCommand xmlns=""http://www.trms.com/CarouselRemoteCommand"">
<CreateCrawl>
<UserName>xml</UserName>
<Password>trms</Password>
<CrawlText>Always on, MWF</CrawlText>
<Zone>1</Zone>
<AlwaysOn>true</AlwaysOn>
<Weekdays>42</Weekdays>
<WebEnabled>true</WebEnabled>
</CreateCrawl>
</CarouselCommand>";
}
public static string CreateCrawlInvalidZone()
{
return @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<CarouselCommand xmlns=""http://www.trms.com/CarouselRemoteCommand"">
<CreateCrawl>
<UserName>xml</UserName>
<Password>trms</Password>
<CrawlText>This is the text I'd like to see at the bottom of the screen.</CrawlText>
<Zone>9999</Zone>
<AlwaysOn>false</AlwaysOn>
<DateTimeOn>2005-10-26T00:00:00-06:00</DateTimeOn>
<DateTimeOff>2005-10-29T23:59:59-06:00</DateTimeOff>
<Weekdays>127</Weekdays>
<WebEnabled>true</WebEnabled>
</CreateCrawl>
</CarouselCommand>";
}
public static string ChangePageStatus()
{
return @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<CarouselCommand xmlns=""http://www.trms.com/CarouselRemoteCommand"">
<!-- This command will set the status of the specified page to on. -->
<ChangePageStatus>
<UserName>xml</UserName>
<Password>trms</Password>
<GUID>77c0592c-e13e-46de-b2dc-5617e119452a</GUID>
<Status>on</Status>
</ChangePageStatus>
</CarouselCommand>";
}
public static string DeletePage()
{
return @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<CarouselCommand xmlns=""http://www.trms.com/CarouselRemoteCommand"">
<!-- This command will delete the specified page, assuming that the user John has permission to do so. -->
<DeletePage>
<UserName>xml</UserName>
<Password>trms</Password>
<GUID>4f83e8f2-2b17-41de-8e7b-5e799280d388</GUID>
</DeletePage>
</CarouselCommand>";
}
public static string DeleteAllUserPages()
{
return @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<CarouselCommand xmlns=""http://www.trms.com/CarouselRemoteCommand"">
<!-- Sending this command will permanently delete ALL pages created by John -->
<DeleteAllUserPages>
<UserName>xml</UserName>
<Password>trms</Password>
</DeleteAllUserPages>
</CarouselCommand>";
}
public static string DeactivateAllAlertPages()
{
return @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<CarouselCommand xmlns=""http://www.trms.com/CarouselRemoteCommand"">
<!-- Sending this command will turn off all alert pages. -->
<DeactivateAllAlertPages>
<UserName>xml</UserName>
<Password>trms</Password>
<Zone>all</Zone>
</DeactivateAllAlertPages>
</CarouselCommand>";
}
public static string GetPlayerStatus()
{
return @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<CarouselCommand xmlns=""http://www.trms.com/CarouselRemoteCommand"">
<!-- Sending this command will turn off all alert pages. -->
<GetPlayerStatus>
<UserName>xml</UserName>
<Password>trms</Password>
</GetPlayerStatus>
</CarouselCommand>";
}
public static string IllFormedCmd1()
{
return @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<CarouselCommand xmlns=""http://www.trms.com/CarouselRemoteCommand"">
<CreatePage>
<!-- no username/password -->
<Zone>1</Zone>
<AlwaysOn>false</AlwaysOn>
<DateTimeOn>2005-10-29T00:00:00-06:00</DateTimeOn>
<DateTimeOff>2005-10-29T23:59:59-06:00</DateTimeOff>
<CycleTimeOn>08:00:00-06:00</CycleTimeOn>
<CycleTimeOff>17:00:00-06:00</CycleTimeOff>
<Weekdays>127</Weekdays>
<WebEnabled>true</WebEnabled>
<PageType>Standard</PageType>
<PageTemplate>
<TemplateName>Title Body</TemplateName>
<Block Name=""Title"" Value=""Hello"" />
<Block Name=""Body"" Value=""World!"" />
</PageTemplate>
</CreatePage>
</CarouselCommand>";
}
public static string IllFormedCmd2()
{
return @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<CarouselCommand xmlns=""http://www.trms.com/CarouselRemoteCommand"">
<CreatePage>
<UserName>xml</UserName>
<Password>trms</Password>
<Zone>1</Zone>
<AlwaysOn>hello</AlwaysOn> <!-- error here -->
<DateTimeOn>2005-10-29T00:00:00-06:00</DateTimeOn>
<DateTimeOff>2005-10-29T23:59:59-06:00</DateTimeOff>
<CycleTimeOn>08:00:00-06:00</CycleTimeOn>
<CycleTimeOff>17:00:00-06:00</CycleTimeOff>
<Weekdays>127</Weekdays>
<WebEnabled>true</WebEnabled>
<PageType>Standard</PageType>
<PageTemplate>
<TemplateName>Title Body</TemplateName>
<Block Name=""Title"" Value=""Hello"" />
<Block Name=""Body"" Value=""World!"" />
</PageTemplate>
</CreatePage>
</CarouselCommand>";
}
public static string IllFormedCmd3()
{
return @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<CarouselCommand xmlns=""http://www.trms.com/CarouselRemoteCommand"">
</CarouselCommand>";
}
public static string IllFormedCmd4()
{
return @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<CarouselCommand xmlns=""http://www.trms.com/CarouselRemoteCommand"">
<SomeStrangeCommand>
<Entity attribute1=""1"" />
</SomeStrangeCommand>
</CarouselCommand>";
}
public static string GetZoneList()
{
return @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<CarouselCommand xmlns=""http://www.trms.com/CarouselRemoteCommand"">
<GetZoneList>
<UserName>xml</UserName>
<Password>trms</Password>
</GetZoneList>
</CarouselCommand>";
}
public static string GetTemplateList()
{
return @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<CarouselCommand xmlns=""http://www.trms.com/CarouselRemoteCommand"">
<GetTemplateList>
<UserName>xml</UserName>
<Password>trms</Password>
<ZoneID>1</ZoneID>
</GetTemplateList>
</CarouselCommand>";
}
public static string GetBulletinList()
{
return @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<CarouselCommand xmlns=""http://www.trms.com/CarouselRemoteCommand"">
<GetBulletinList>
<UserName>xml</UserName>
<Password>trms</Password>
<ZoneID>1</ZoneID>
</GetBulletinList>
</CarouselCommand>";
}
}
}
| |
// 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.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal delegate BoundStatement GenerateMethodBody(EEMethodSymbol method, DiagnosticBag diagnostics);
/// <summary>
/// Synthesized expression evaluation method.
/// </summary>
internal sealed class EEMethodSymbol : MethodSymbol
{
internal readonly TypeMap TypeMap;
internal readonly MethodSymbol SubstitutedSourceMethod;
internal readonly ImmutableArray<LocalSymbol> Locals;
internal readonly ImmutableArray<LocalSymbol> LocalsForBinding;
private readonly EENamedTypeSymbol _container;
private readonly string _name;
private readonly ImmutableArray<Location> _locations;
private readonly ImmutableArray<TypeParameterSymbol> _typeParameters;
private readonly ImmutableArray<ParameterSymbol> _parameters;
private readonly ParameterSymbol _thisParameter;
private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables;
/// <summary>
/// Invoked at most once to generate the method body.
/// (If the compilation has no errors, it will be invoked
/// exactly once, otherwise it may be skipped.)
/// </summary>
private readonly GenerateMethodBody _generateMethodBody;
private TypeSymbol _lazyReturnType;
// NOTE: This is only used for asserts, so it could be conditional on DEBUG.
private readonly ImmutableArray<TypeParameterSymbol> _allTypeParameters;
internal EEMethodSymbol(
EENamedTypeSymbol container,
string name,
Location location,
MethodSymbol sourceMethod,
ImmutableArray<LocalSymbol> sourceLocals,
ImmutableArray<LocalSymbol> sourceLocalsForBinding,
ImmutableDictionary<string, DisplayClassVariable> sourceDisplayClassVariables,
GenerateMethodBody generateMethodBody)
{
Debug.Assert(sourceMethod.IsDefinition);
Debug.Assert(sourceMethod.ContainingSymbol == container.SubstitutedSourceType.OriginalDefinition);
Debug.Assert(sourceLocals.All(l => l.ContainingSymbol == sourceMethod));
_container = container;
_name = name;
_locations = ImmutableArray.Create(location);
// What we want is to map all original type parameters to the corresponding new type parameters
// (since the old ones have the wrong owners). Unfortunately, we have a circular dependency:
// 1) Each new type parameter requires the entire map in order to be able to construct its constraint list.
// 2) The map cannot be constructed until all new type parameters exist.
// Our solution is to pass each new type parameter a lazy reference to the type map. We then
// initialize the map as soon as the new type parameters are available - and before they are
// handed out - so that there is never a period where they can require the type map and find
// it uninitialized.
var sourceMethodTypeParameters = sourceMethod.TypeParameters;
var allSourceTypeParameters = container.SourceTypeParameters.Concat(sourceMethodTypeParameters);
var getTypeMap = new Func<TypeMap>(() => this.TypeMap);
_typeParameters = sourceMethodTypeParameters.SelectAsArray(
(tp, i, arg) => (TypeParameterSymbol)new EETypeParameterSymbol(this, tp, i, getTypeMap),
(object)null);
_allTypeParameters = container.TypeParameters.Concat(_typeParameters);
this.TypeMap = new TypeMap(allSourceTypeParameters, _allTypeParameters);
EENamedTypeSymbol.VerifyTypeParameters(this, _typeParameters);
var substitutedSourceType = container.SubstitutedSourceType;
this.SubstitutedSourceMethod = sourceMethod.AsMember(substitutedSourceType);
if (sourceMethod.Arity > 0)
{
this.SubstitutedSourceMethod = this.SubstitutedSourceMethod.Construct(_typeParameters.As<TypeSymbol>());
}
TypeParameterChecker.Check(this.SubstitutedSourceMethod, _allTypeParameters);
// Create a map from original parameter to target parameter.
var parameterBuilder = ArrayBuilder<ParameterSymbol>.GetInstance();
var substitutedSourceThisParameter = this.SubstitutedSourceMethod.ThisParameter;
var substitutedSourceHasThisParameter = (object)substitutedSourceThisParameter != null;
if (substitutedSourceHasThisParameter)
{
_thisParameter = MakeParameterSymbol(0, GeneratedNames.ThisProxyFieldName(), substitutedSourceThisParameter);
Debug.Assert(_thisParameter.Type == this.SubstitutedSourceMethod.ContainingType);
parameterBuilder.Add(_thisParameter);
}
var ordinalOffset = (substitutedSourceHasThisParameter ? 1 : 0);
foreach (var substitutedSourceParameter in this.SubstitutedSourceMethod.Parameters)
{
var ordinal = substitutedSourceParameter.Ordinal + ordinalOffset;
Debug.Assert(ordinal == parameterBuilder.Count);
var parameter = MakeParameterSymbol(ordinal, substitutedSourceParameter.Name, substitutedSourceParameter);
parameterBuilder.Add(parameter);
}
_parameters = parameterBuilder.ToImmutableAndFree();
var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance();
var localsMap = PooledDictionary<LocalSymbol, LocalSymbol>.GetInstance();
foreach (var sourceLocal in sourceLocals)
{
var local = sourceLocal.ToOtherMethod(this, this.TypeMap);
localsMap.Add(sourceLocal, local);
localsBuilder.Add(local);
}
this.Locals = localsBuilder.ToImmutableAndFree();
localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance();
foreach (var sourceLocal in sourceLocalsForBinding)
{
LocalSymbol local;
if (!localsMap.TryGetValue(sourceLocal, out local))
{
local = sourceLocal.ToOtherMethod(this, this.TypeMap);
localsMap.Add(sourceLocal, local);
}
localsBuilder.Add(local);
}
this.LocalsForBinding = localsBuilder.ToImmutableAndFree();
// Create a map from variable name to display class field.
var displayClassVariables = PooledDictionary<string, DisplayClassVariable>.GetInstance();
foreach (var pair in sourceDisplayClassVariables)
{
var variable = pair.Value;
var displayClassInstanceFromLocal = variable.DisplayClassInstance as DisplayClassInstanceFromLocal;
var displayClassInstance = (displayClassInstanceFromLocal == null) ?
(DisplayClassInstance)new DisplayClassInstanceFromThis(_parameters[0]) :
new DisplayClassInstanceFromLocal((EELocalSymbol)localsMap[displayClassInstanceFromLocal.Local]);
variable = variable.SubstituteFields(displayClassInstance, this.TypeMap);
displayClassVariables.Add(pair.Key, variable);
}
_displayClassVariables = displayClassVariables.ToImmutableDictionary();
displayClassVariables.Free();
localsMap.Free();
_generateMethodBody = generateMethodBody;
}
private ParameterSymbol MakeParameterSymbol(int ordinal, string name, ParameterSymbol sourceParameter)
{
return new SynthesizedParameterSymbol(this, sourceParameter.Type, ordinal, sourceParameter.RefKind, name, sourceParameter.CustomModifiers);
}
internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false)
{
return false;
}
internal override bool IsMetadataFinal
{
get { return false; }
}
public override MethodKind MethodKind
{
get { return MethodKind.Ordinary; }
}
public override string Name
{
get { return _name; }
}
public override int Arity
{
get { return _typeParameters.Length; }
}
public override bool IsExtensionMethod
{
get { return false; }
}
internal override bool HasSpecialName
{
get { return true; }
}
internal override System.Reflection.MethodImplAttributes ImplementationAttributes
{
get { return default(System.Reflection.MethodImplAttributes); }
}
internal override bool HasDeclarativeSecurity
{
get { return false; }
}
public override DllImportData GetDllImportData()
{
return null;
}
internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation()
{
throw ExceptionUtilities.Unreachable;
}
internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation
{
get { return null; }
}
internal override bool RequiresSecurityObject
{
get { return false; }
}
internal override bool TryGetThisParameter(out ParameterSymbol thisParameter)
{
thisParameter = null;
return true;
}
public override bool HidesBaseMethodsByName
{
get { return false; }
}
public override bool IsVararg
{
get { return this.SubstitutedSourceMethod.IsVararg; }
}
public override bool ReturnsVoid
{
get { return this.ReturnType.SpecialType == SpecialType.System_Void; }
}
public override bool IsAsync
{
get { return false; }
}
public override TypeSymbol ReturnType
{
get
{
if (_lazyReturnType == null)
{
throw new InvalidOperationException();
}
return _lazyReturnType;
}
}
public override ImmutableArray<TypeSymbol> TypeArguments
{
get { return _typeParameters.Cast<TypeParameterSymbol, TypeSymbol>(); }
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return _typeParameters; }
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get { return _parameters; }
}
public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations
{
get { return ImmutableArray<MethodSymbol>.Empty; }
}
public override ImmutableArray<CustomModifier> ReturnTypeCustomModifiers
{
get { return ImmutableArray<CustomModifier>.Empty; }
}
public override Symbol AssociatedSymbol
{
get { return null; }
}
internal override ImmutableArray<string> GetAppliedConditionalSymbols()
{
throw ExceptionUtilities.Unreachable;
}
internal override Cci.CallingConvention CallingConvention
{
get
{
Debug.Assert(this.IsStatic);
var cc = Cci.CallingConvention.Default;
if (this.IsVararg)
{
cc |= Cci.CallingConvention.ExtraArguments;
}
if (this.IsGenericMethod)
{
cc |= Cci.CallingConvention.Generic;
}
return cc;
}
}
internal override bool GenerateDebugInfo
{
get { return false; }
}
public override Symbol ContainingSymbol
{
get { return _container; }
}
public override ImmutableArray<Location> Locations
{
get { return _locations; }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get { throw ExceptionUtilities.Unreachable; }
}
public override Accessibility DeclaredAccessibility
{
get { return Accessibility.Internal; }
}
public override bool IsStatic
{
get { return true; }
}
public override bool IsVirtual
{
get { return false; }
}
public override bool IsOverride
{
get { return false; }
}
public override bool IsAbstract
{
get { return false; }
}
public override bool IsSealed
{
get { return false; }
}
public override bool IsExtern
{
get { return false; }
}
internal override ObsoleteAttributeData ObsoleteAttributeData
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override void GenerateMethodBody(TypeCompilationState compilationState, DiagnosticBag diagnostics)
{
var body = _generateMethodBody(this, diagnostics);
var compilation = compilationState.Compilation;
_lazyReturnType = CalculateReturnType(compilation, body);
// Can't do this until the return type has been computed.
TypeParameterChecker.Check(this, _allTypeParameters);
if (diagnostics.HasAnyErrors())
{
return;
}
DiagnosticsPass.IssueDiagnostics(compilation, body, diagnostics, this);
if (diagnostics.HasAnyErrors())
{
return;
}
// Check for use-site diagnostics (e.g. missing types in the signature).
DiagnosticInfo useSiteDiagnosticInfo = null;
this.CalculateUseSiteDiagnostic(ref useSiteDiagnosticInfo);
if (useSiteDiagnosticInfo != null && useSiteDiagnosticInfo.Severity == DiagnosticSeverity.Error)
{
diagnostics.Add(useSiteDiagnosticInfo, this.Locations[0]);
return;
}
var declaredLocals = PooledHashSet<LocalSymbol>.GetInstance();
try
{
// Rewrite local declaration statement.
body = (BoundStatement)LocalDeclarationRewriter.Rewrite(compilation, _container, declaredLocals, body);
// Verify local declaration names.
foreach (var local in declaredLocals)
{
Debug.Assert(local.Locations.Length > 0);
var name = local.Name;
if (name.StartsWith("$", StringComparison.Ordinal))
{
diagnostics.Add(ErrorCode.ERR_UnexpectedCharacter, local.Locations[0], name[0]);
return;
}
}
// Rewrite references to placeholder "locals".
body = (BoundStatement)PlaceholderLocalRewriter.Rewrite(compilation, _container, declaredLocals, body);
}
finally
{
declaredLocals.Free();
}
var syntax = body.Syntax;
var statementsBuilder = ArrayBuilder<BoundStatement>.GetInstance();
statementsBuilder.Add(body);
// Insert an implicit return statement if necessary.
if (body.Kind != BoundKind.ReturnStatement)
{
statementsBuilder.Add(new BoundReturnStatement(syntax, expressionOpt: null));
}
var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance();
var localsSet = PooledHashSet<LocalSymbol>.GetInstance();
foreach (var local in this.LocalsForBinding)
{
Debug.Assert(!localsSet.Contains(local));
localsBuilder.Add(local);
localsSet.Add(local);
}
foreach (var local in this.Locals)
{
if (!localsSet.Contains(local))
{
localsBuilder.Add(local);
}
}
localsSet.Free();
body = new BoundBlock(syntax, localsBuilder.ToImmutableAndFree(), statementsBuilder.ToImmutableAndFree()) { WasCompilerGenerated = true };
Debug.Assert(!diagnostics.HasAnyErrors());
Debug.Assert(!body.HasErrors);
bool sawLambdas;
bool sawAwaitInExceptionHandler;
body = LocalRewriter.Rewrite(
compilation: this.DeclaringCompilation,
method: this,
methodOrdinal: 0,
containingType: _container,
statement: body,
compilationState: compilationState,
previousSubmissionFields: null,
allowOmissionOfConditionalCalls: false,
diagnostics: diagnostics,
sawLambdas: out sawLambdas,
sawAwaitInExceptionHandler: out sawAwaitInExceptionHandler);
Debug.Assert(!sawAwaitInExceptionHandler);
if (body.HasErrors)
{
return;
}
// Variables may have been captured by lambdas in the original method
// or in the expression, and we need to preserve the existing values of
// those variables in the expression. This requires rewriting the variables
// in the expression based on the closure classes from both the original
// method and the expression, and generating a preamble that copies
// values into the expression closure classes.
//
// Consider the original method:
// static void M()
// {
// int x, y, z;
// ...
// F(() => x + y);
// }
// and the expression in the EE: "F(() => x + z)".
//
// The expression is first rewritten using the closure class and local <1>
// from the original method: F(() => <1>.x + z)
// Then lambda rewriting introduces a new closure class that includes
// the locals <1> and z, and a corresponding local <2>: F(() => <2>.<1>.x + <2>.z)
// And a preamble is added to initialize the fields of <2>:
// <2> = new <>c__DisplayClass0();
// <2>.<1> = <1>;
// <2>.z = z;
// Rewrite "this" and "base" references to parameter in this method.
// Rewrite variables within body to reference existing display classes.
body = (BoundStatement)CapturedVariableRewriter.Rewrite(
this.SubstitutedSourceMethod.IsStatic ? null : _parameters[0],
compilation.Conversions,
_displayClassVariables,
body,
diagnostics);
if (body.HasErrors)
{
Debug.Assert(false, "Please add a test case capturing whatever caused this assert.");
return;
}
if (diagnostics.HasAnyErrors())
{
return;
}
if (sawLambdas)
{
var closureDebugInfoBuilder = ArrayBuilder<ClosureDebugInfo>.GetInstance();
var lambdaDebugInfoBuilder = ArrayBuilder<LambdaDebugInfo>.GetInstance();
body = LambdaRewriter.Rewrite(
loweredBody: body,
thisType: this.SubstitutedSourceMethod.ContainingType,
thisParameter: _thisParameter,
method: this,
methodOrdinal: 0,
closureDebugInfoBuilder: closureDebugInfoBuilder,
lambdaDebugInfoBuilder: lambdaDebugInfoBuilder,
slotAllocatorOpt: null,
compilationState: compilationState,
diagnostics: diagnostics,
assignLocals: true);
// we don't need this information:
closureDebugInfoBuilder.Free();
lambdaDebugInfoBuilder.Free();
}
// Insert locals from the original method,
// followed by any new locals.
var block = (BoundBlock)body;
var localBuilder = ArrayBuilder<LocalSymbol>.GetInstance();
foreach (var local in this.Locals)
{
Debug.Assert(!(local is EELocalSymbol) || (((EELocalSymbol)local).Ordinal == localBuilder.Count));
localBuilder.Add(local);
}
foreach (var local in block.Locals)
{
var oldLocal = local as EELocalSymbol;
if (oldLocal != null)
{
Debug.Assert(localBuilder[oldLocal.Ordinal] == oldLocal);
continue;
}
localBuilder.Add(local);
}
body = block.Update(localBuilder.ToImmutableAndFree(), block.Statements);
TypeParameterChecker.Check(body, _allTypeParameters);
compilationState.AddSynthesizedMethod(this, body);
}
private static TypeSymbol CalculateReturnType(CSharpCompilation compilation, BoundStatement bodyOpt)
{
if (bodyOpt == null)
{
// If the method doesn't do anything, then it doesn't return anything.
return compilation.GetSpecialType(SpecialType.System_Void);
}
switch (bodyOpt.Kind)
{
case BoundKind.ReturnStatement:
return ((BoundReturnStatement)bodyOpt).ExpressionOpt.Type;
case BoundKind.ExpressionStatement:
case BoundKind.LocalDeclaration:
case BoundKind.MultipleLocalDeclarations:
return compilation.GetSpecialType(SpecialType.System_Void);
default:
throw ExceptionUtilities.UnexpectedValue(bodyOpt.Kind);
}
}
internal override void AddSynthesizedReturnTypeAttributes(ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
base.AddSynthesizedReturnTypeAttributes(ref attributes);
if (this.ReturnType.ContainsDynamic())
{
var compilation = this.DeclaringCompilation;
if ((object)compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_DynamicAttribute__ctor) != null)
{
AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(this.ReturnType, this.ReturnTypeCustomModifiers.Length));
}
}
}
internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree)
{
return localPosition;
}
}
}
| |
// 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.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Runtime.Serialization;
using System.Xml;
using System.ServiceModel.Diagnostics;
using System.Runtime;
namespace System.ServiceModel.Dispatcher
{
internal class PrimitiveOperationFormatter : IClientMessageFormatter, IDispatchMessageFormatter
{
private OperationDescription _operation;
private MessageDescription _responseMessage;
private MessageDescription _requestMessage;
private XmlDictionaryString _action;
private XmlDictionaryString _replyAction;
private ActionHeader _actionHeaderNone;
private ActionHeader _actionHeader10;
private ActionHeader _actionHeaderAugust2004;
private ActionHeader _replyActionHeaderNone;
private ActionHeader _replyActionHeader10;
private ActionHeader _replyActionHeaderAugust2004;
private XmlDictionaryString _requestWrapperName;
private XmlDictionaryString _requestWrapperNamespace;
private XmlDictionaryString _responseWrapperName;
private XmlDictionaryString _responseWrapperNamespace;
private PartInfo[] _requestParts;
private PartInfo[] _responseParts;
private PartInfo _returnPart;
private XmlDictionaryString _xsiNilLocalName;
private XmlDictionaryString _xsiNilNamespace;
public PrimitiveOperationFormatter(OperationDescription description, bool isRpc)
{
if (description == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(description));
}
OperationFormatter.Validate(description, isRpc, false/*isEncoded*/);
_operation = description;
_requestMessage = description.Messages[0];
if (description.Messages.Count == 2)
{
_responseMessage = description.Messages[1];
}
int stringCount = 3 + _requestMessage.Body.Parts.Count;
if (_responseMessage != null)
{
stringCount += 2 + _responseMessage.Body.Parts.Count;
}
XmlDictionary dictionary = new XmlDictionary(stringCount * 2);
_xsiNilLocalName = dictionary.Add("nil");
_xsiNilNamespace = dictionary.Add(EndpointAddressProcessor.XsiNs);
OperationFormatter.GetActions(description, dictionary, out _action, out _replyAction);
if (_requestMessage.Body.WrapperName != null)
{
_requestWrapperName = AddToDictionary(dictionary, _requestMessage.Body.WrapperName);
_requestWrapperNamespace = AddToDictionary(dictionary, _requestMessage.Body.WrapperNamespace);
}
_requestParts = AddToDictionary(dictionary, _requestMessage.Body.Parts, isRpc);
if (_responseMessage != null)
{
if (_responseMessage.Body.WrapperName != null)
{
_responseWrapperName = AddToDictionary(dictionary, _responseMessage.Body.WrapperName);
_responseWrapperNamespace = AddToDictionary(dictionary, _responseMessage.Body.WrapperNamespace);
}
_responseParts = AddToDictionary(dictionary, _responseMessage.Body.Parts, isRpc);
if (_responseMessage.Body.ReturnValue != null && _responseMessage.Body.ReturnValue.Type != typeof(void))
{
_returnPart = AddToDictionary(dictionary, _responseMessage.Body.ReturnValue, isRpc);
}
}
}
private ActionHeader ActionHeaderNone
{
get
{
if (_actionHeaderNone == null)
{
_actionHeaderNone =
ActionHeader.Create(_action, AddressingVersion.None);
}
return _actionHeaderNone;
}
}
private ActionHeader ActionHeader10
{
get
{
if (_actionHeader10 == null)
{
_actionHeader10 =
ActionHeader.Create(_action, AddressingVersion.WSAddressing10);
}
return _actionHeader10;
}
}
private ActionHeader ActionHeaderAugust2004
{
get
{
if (_actionHeaderAugust2004 == null)
{
_actionHeaderAugust2004 =
ActionHeader.Create(_action, AddressingVersion.WSAddressingAugust2004);
}
return _actionHeaderAugust2004;
}
}
private ActionHeader ReplyActionHeaderNone
{
get
{
if (_replyActionHeaderNone == null)
{
_replyActionHeaderNone =
ActionHeader.Create(_replyAction, AddressingVersion.None);
}
return _replyActionHeaderNone;
}
}
private ActionHeader ReplyActionHeader10
{
get
{
if (_replyActionHeader10 == null)
{
_replyActionHeader10 =
ActionHeader.Create(_replyAction, AddressingVersion.WSAddressing10);
}
return _replyActionHeader10;
}
}
private ActionHeader ReplyActionHeaderAugust2004
{
get
{
if (_replyActionHeaderAugust2004 == null)
{
_replyActionHeaderAugust2004 =
ActionHeader.Create(_replyAction, AddressingVersion.WSAddressingAugust2004);
}
return _replyActionHeaderAugust2004;
}
}
private static XmlDictionaryString AddToDictionary(XmlDictionary dictionary, string s)
{
XmlDictionaryString dictionaryString;
if (!dictionary.TryLookup(s, out dictionaryString))
{
dictionaryString = dictionary.Add(s);
}
return dictionaryString;
}
private static PartInfo[] AddToDictionary(XmlDictionary dictionary, MessagePartDescriptionCollection parts, bool isRpc)
{
PartInfo[] partInfos = new PartInfo[parts.Count];
for (int i = 0; i < parts.Count; i++)
{
partInfos[i] = AddToDictionary(dictionary, parts[i], isRpc);
}
return partInfos;
}
private ActionHeader GetActionHeader(AddressingVersion addressing)
{
if (_action == null)
{
return null;
}
if (addressing == AddressingVersion.WSAddressingAugust2004)
{
return ActionHeaderAugust2004;
}
else if (addressing == AddressingVersion.WSAddressing10)
{
return ActionHeader10;
}
else if (addressing == AddressingVersion.None)
{
return ActionHeaderNone;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.Format(SR.AddressingVersionNotSupported, addressing)));
}
}
private ActionHeader GetReplyActionHeader(AddressingVersion addressing)
{
if (_replyAction == null)
{
return null;
}
if (addressing == AddressingVersion.WSAddressingAugust2004)
{
return ReplyActionHeaderAugust2004;
}
else if (addressing == AddressingVersion.WSAddressing10)
{
return ReplyActionHeader10;
}
else if (addressing == AddressingVersion.None)
{
return ReplyActionHeaderNone;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.Format(SR.AddressingVersionNotSupported, addressing)));
}
}
private static string GetArrayItemName(Type type)
{
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
return "boolean";
case TypeCode.DateTime:
return "dateTime";
case TypeCode.Decimal:
return "decimal";
case TypeCode.Int32:
return "int";
case TypeCode.Int64:
return "long";
case TypeCode.Single:
return "float";
case TypeCode.Double:
return "double";
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxInvalidUseOfPrimitiveOperationFormatter));
}
}
private static PartInfo AddToDictionary(XmlDictionary dictionary, MessagePartDescription part, bool isRpc)
{
Type type = part.Type;
XmlDictionaryString itemName = null;
XmlDictionaryString itemNamespace = null;
if (type.IsArray && type != typeof(byte[]))
{
const string ns = "http://schemas.microsoft.com/2003/10/Serialization/Arrays";
string name = GetArrayItemName(type.GetElementType());
itemName = AddToDictionary(dictionary, name);
itemNamespace = AddToDictionary(dictionary, ns);
}
return new PartInfo(part,
AddToDictionary(dictionary, part.Name),
AddToDictionary(dictionary, isRpc ? string.Empty : part.Namespace),
itemName, itemNamespace);
}
public static bool IsContractSupported(OperationDescription description)
{
if (description == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(description));
}
OperationDescription operation = description;
MessageDescription requestMessage = description.Messages[0];
MessageDescription responseMessage = null;
if (description.Messages.Count == 2)
{
responseMessage = description.Messages[1];
}
if (requestMessage.Headers.Count > 0)
{
return false;
}
if (requestMessage.Properties.Count > 0)
{
return false;
}
if (requestMessage.IsTypedMessage)
{
return false;
}
if (responseMessage != null)
{
if (responseMessage.Headers.Count > 0)
{
return false;
}
if (responseMessage.Properties.Count > 0)
{
return false;
}
if (responseMessage.IsTypedMessage)
{
return false;
}
}
if (!AreTypesSupported(requestMessage.Body.Parts))
{
return false;
}
if (responseMessage != null)
{
if (!AreTypesSupported(responseMessage.Body.Parts))
{
return false;
}
if (responseMessage.Body.ReturnValue != null && !IsTypeSupported(responseMessage.Body.ReturnValue))
{
return false;
}
}
return true;
}
private static bool AreTypesSupported(MessagePartDescriptionCollection bodyDescriptions)
{
for (int i = 0; i < bodyDescriptions.Count; i++)
{
if (!IsTypeSupported(bodyDescriptions[i]))
{
return false;
}
}
return true;
}
private static bool IsTypeSupported(MessagePartDescription bodyDescription)
{
Fx.Assert(bodyDescription != null, "");
Type type = bodyDescription.Type;
if (type == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxMessagePartDescriptionMissingType, bodyDescription.Name, bodyDescription.Namespace)));
}
if (bodyDescription.Multiple)
{
return false;
}
if (type == typeof(void))
{
return true;
}
if (type.IsEnum())
{
return false;
}
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
case TypeCode.DateTime:
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.String:
return true;
case TypeCode.Object:
if (type.IsArray && type.GetArrayRank() == 1 && IsArrayTypeSupported(type.GetElementType()))
{
return true;
}
break;
default:
break;
}
return false;
}
private static bool IsArrayTypeSupported(Type type)
{
if (type.IsEnum())
{
return false;
}
switch (type.GetTypeCode())
{
case TypeCode.Byte:
case TypeCode.Boolean:
case TypeCode.DateTime:
case TypeCode.Decimal:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
return true;
default:
return false;
}
}
public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
{
if (messageVersion == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(messageVersion));
}
if (parameters == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(parameters));
}
return Message.CreateMessage(messageVersion, GetActionHeader(messageVersion.Addressing), new PrimitiveRequestBodyWriter(parameters, this));
}
public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
{
if (messageVersion == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(messageVersion));
}
if (parameters == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(parameters));
}
return Message.CreateMessage(messageVersion, GetReplyActionHeader(messageVersion.Addressing), new PrimitiveResponseBodyWriter(parameters, result, this));
}
public object DeserializeReply(Message message, object[] parameters)
{
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(message)));
}
if (parameters == null)
{
throw TraceUtility.ThrowHelperError(new ArgumentNullException(nameof(parameters)), message);
}
try
{
if (message.IsEmpty)
{
if (_responseWrapperName == null)
{
return null;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.SFxInvalidMessageBodyEmptyMessage));
}
XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();
using (bodyReader)
{
object returnValue = DeserializeResponse(bodyReader, parameters);
message.ReadFromBodyContentsToEnd(bodyReader);
return returnValue;
}
}
catch (XmlException xe)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
SR.Format(SR.SFxErrorDeserializingReplyBodyMore, _operation.Name, xe.Message), xe));
}
catch (FormatException fe)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
SR.Format(SR.SFxErrorDeserializingReplyBodyMore, _operation.Name, fe.Message), fe));
}
catch (SerializationException se)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
SR.Format(SR.SFxErrorDeserializingReplyBodyMore, _operation.Name, se.Message), se));
}
}
public void DeserializeRequest(Message message, object[] parameters)
{
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(message)));
}
if (parameters == null)
{
throw TraceUtility.ThrowHelperError(new ArgumentNullException(nameof(parameters)), message);
}
try
{
if (message.IsEmpty)
{
if (_requestWrapperName == null)
{
return;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.SFxInvalidMessageBodyEmptyMessage));
}
XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();
using (bodyReader)
{
DeserializeRequest(bodyReader, parameters);
message.ReadFromBodyContentsToEnd(bodyReader);
}
}
catch (XmlException xe)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
OperationFormatter.CreateDeserializationFailedFault(
SR.Format(SR.SFxErrorDeserializingRequestBodyMore, _operation.Name, xe.Message),
xe));
}
catch (FormatException fe)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
OperationFormatter.CreateDeserializationFailedFault(
SR.Format(SR.SFxErrorDeserializingRequestBodyMore, _operation.Name, fe.Message),
fe));
}
catch (SerializationException se)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
SR.Format(SR.SFxErrorDeserializingRequestBodyMore, _operation.Name, se.Message),
se));
}
}
private void DeserializeRequest(XmlDictionaryReader reader, object[] parameters)
{
if (_requestWrapperName != null)
{
if (!reader.IsStartElement(_requestWrapperName, _requestWrapperNamespace))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(SR.SFxInvalidMessageBody, _requestWrapperName, _requestWrapperNamespace, reader.NodeType, reader.Name, reader.NamespaceURI)));
}
bool isEmptyElement = reader.IsEmptyElement;
reader.Read();
if (isEmptyElement)
{
return;
}
}
DeserializeParameters(reader, _requestParts, parameters);
if (_requestWrapperName != null)
{
reader.ReadEndElement();
}
}
private object DeserializeResponse(XmlDictionaryReader reader, object[] parameters)
{
if (_responseWrapperName != null)
{
if (!reader.IsStartElement(_responseWrapperName, _responseWrapperNamespace))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(SR.SFxInvalidMessageBody, _responseWrapperName, _responseWrapperNamespace, reader.NodeType, reader.Name, reader.NamespaceURI)));
}
bool isEmptyElement = reader.IsEmptyElement;
reader.Read();
if (isEmptyElement)
{
return null;
}
}
object returnValue = null;
if (_returnPart != null)
{
while (true)
{
if (IsPartElement(reader, _returnPart))
{
returnValue = DeserializeParameter(reader, _returnPart);
break;
}
if (!reader.IsStartElement())
{
break;
}
if (IsPartElements(reader, _responseParts))
{
break;
}
OperationFormatter.TraceAndSkipElement(reader);
}
}
DeserializeParameters(reader, _responseParts, parameters);
if (_responseWrapperName != null)
{
reader.ReadEndElement();
}
return returnValue;
}
private void DeserializeParameters(XmlDictionaryReader reader, PartInfo[] parts, object[] parameters)
{
if (parts.Length != parameters.Length)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentException(SR.Format(SR.SFxParameterCountMismatch, "parts", parts.Length, "parameters", parameters.Length), "parameters"));
}
int nextPartIndex = 0;
while (reader.IsStartElement())
{
for (int i = nextPartIndex; i < parts.Length; i++)
{
PartInfo part = parts[i];
if (IsPartElement(reader, part))
{
parameters[part.Description.Index] = DeserializeParameter(reader, parts[i]);
nextPartIndex = i + 1;
}
else
{
parameters[part.Description.Index] = null;
}
}
if (reader.IsStartElement())
{
OperationFormatter.TraceAndSkipElement(reader);
}
}
}
private bool IsPartElements(XmlDictionaryReader reader, PartInfo[] parts)
{
foreach (PartInfo part in parts)
{
if (IsPartElement(reader, part))
{
return true;
}
}
return false;
}
private bool IsPartElement(XmlDictionaryReader reader, PartInfo part)
{
return reader.IsStartElement(part.DictionaryName, part.DictionaryNamespace);
}
private object DeserializeParameter(XmlDictionaryReader reader, PartInfo part)
{
if (reader.AttributeCount > 0 &&
reader.MoveToAttribute(_xsiNilLocalName.Value, _xsiNilNamespace.Value) &&
reader.ReadContentAsBoolean())
{
reader.Skip();
return null;
}
return part.ReadValue(reader);
}
private void SerializeParameter(XmlDictionaryWriter writer, PartInfo part, object graph)
{
writer.WriteStartElement(part.DictionaryName, part.DictionaryNamespace);
if (graph == null)
{
writer.WriteStartAttribute(_xsiNilLocalName, _xsiNilNamespace);
writer.WriteValue(true);
writer.WriteEndAttribute();
}
else
{
part.WriteValue(writer, graph);
}
writer.WriteEndElement();
}
private void SerializeParameters(XmlDictionaryWriter writer, PartInfo[] parts, object[] parameters)
{
if (parts.Length != parameters.Length)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentException(SR.Format(SR.SFxParameterCountMismatch, "parts", parts.Length, "parameters", parameters.Length), "parameters"));
}
for (int i = 0; i < parts.Length; i++)
{
PartInfo part = parts[i];
SerializeParameter(writer, part, parameters[part.Description.Index]);
}
}
private void SerializeRequest(XmlDictionaryWriter writer, object[] parameters)
{
if (_requestWrapperName != null)
{
writer.WriteStartElement(_requestWrapperName, _requestWrapperNamespace);
}
SerializeParameters(writer, _requestParts, parameters);
if (_requestWrapperName != null)
{
writer.WriteEndElement();
}
}
private void SerializeResponse(XmlDictionaryWriter writer, object returnValue, object[] parameters)
{
if (_responseWrapperName != null)
{
writer.WriteStartElement(_responseWrapperName, _responseWrapperNamespace);
}
if (_returnPart != null)
{
SerializeParameter(writer, _returnPart, returnValue);
}
SerializeParameters(writer, _responseParts, parameters);
if (_responseWrapperName != null)
{
writer.WriteEndElement();
}
}
internal class PartInfo
{
private XmlDictionaryString _itemName;
private XmlDictionaryString _itemNamespace;
private TypeCode _typeCode;
private bool _isArray;
public PartInfo(MessagePartDescription description, XmlDictionaryString dictionaryName, XmlDictionaryString dictionaryNamespace, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
{
DictionaryName = dictionaryName;
DictionaryNamespace = dictionaryNamespace;
_itemName = itemName;
_itemNamespace = itemNamespace;
Description = description;
if (description.Type.IsArray)
{
_isArray = true;
_typeCode = description.Type.GetElementType().GetTypeCode();
}
else
{
_isArray = false;
_typeCode = description.Type.GetTypeCode();
}
}
public MessagePartDescription Description { get; }
public XmlDictionaryString DictionaryName { get; }
public XmlDictionaryString DictionaryNamespace { get; }
public object ReadValue(XmlDictionaryReader reader)
{
object value;
if (_isArray)
{
switch (_typeCode)
{
case TypeCode.Byte:
value = reader.ReadElementContentAsBase64();
break;
case TypeCode.Boolean:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadBooleanArray(_itemName, _itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = Array.Empty<bool>();
}
break;
case TypeCode.DateTime:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadDateTimeArray(_itemName, _itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = Array.Empty<DateTime>();
}
break;
case TypeCode.Decimal:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadDecimalArray(_itemName, _itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = Array.Empty<Decimal>();
}
break;
case TypeCode.Int32:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadInt32Array(_itemName, _itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = Array.Empty<Int32>();
}
break;
case TypeCode.Int64:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadInt64Array(_itemName, _itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = Array.Empty<Int64>();
}
break;
case TypeCode.Single:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadSingleArray(_itemName, _itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = Array.Empty<Single>();
}
break;
case TypeCode.Double:
if (!reader.IsEmptyElement)
{
reader.ReadStartElement();
value = reader.ReadDoubleArray(_itemName, _itemNamespace);
reader.ReadEndElement();
}
else
{
reader.Read();
value = Array.Empty<Double>();
}
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxInvalidUseOfPrimitiveOperationFormatter));
}
}
else
{
switch (_typeCode)
{
case TypeCode.Boolean:
value = reader.ReadElementContentAsBoolean();
break;
case TypeCode.DateTime:
value = reader.ReadElementContentAsDateTime();
break;
case TypeCode.Decimal:
value = reader.ReadElementContentAsDecimal();
break;
case TypeCode.Double:
value = reader.ReadElementContentAsDouble();
break;
case TypeCode.Int32:
value = reader.ReadElementContentAsInt();
break;
case TypeCode.Int64:
value = reader.ReadElementContentAsLong();
break;
case TypeCode.Single:
value = reader.ReadElementContentAsFloat();
break;
case TypeCode.String:
return reader.ReadElementContentAsString();
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxInvalidUseOfPrimitiveOperationFormatter));
}
}
return value;
}
public void WriteValue(XmlDictionaryWriter writer, object value)
{
if (_isArray)
{
switch (_typeCode)
{
case TypeCode.Byte:
{
byte[] arrayValue = (byte[])value;
writer.WriteBase64(arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Boolean:
{
bool[] arrayValue = (bool[])value;
writer.WriteArray(null, _itemName, _itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.DateTime:
{
DateTime[] arrayValue = (DateTime[])value;
writer.WriteArray(null, _itemName, _itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Decimal:
{
decimal[] arrayValue = (decimal[])value;
writer.WriteArray(null, _itemName, _itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Int32:
{
Int32[] arrayValue = (Int32[])value;
writer.WriteArray(null, _itemName, _itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Int64:
{
Int64[] arrayValue = (Int64[])value;
writer.WriteArray(null, _itemName, _itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Single:
{
float[] arrayValue = (float[])value;
writer.WriteArray(null, _itemName, _itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
case TypeCode.Double:
{
double[] arrayValue = (double[])value;
writer.WriteArray(null, _itemName, _itemNamespace, arrayValue, 0, arrayValue.Length);
}
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxInvalidUseOfPrimitiveOperationFormatter));
}
}
else
{
switch (_typeCode)
{
case TypeCode.Boolean:
writer.WriteValue((bool)value);
break;
case TypeCode.DateTime:
writer.WriteValue((DateTime)value);
break;
case TypeCode.Decimal:
writer.WriteValue((Decimal)value);
break;
case TypeCode.Double:
writer.WriteValue((double)value);
break;
case TypeCode.Int32:
writer.WriteValue((int)value);
break;
case TypeCode.Int64:
writer.WriteValue((long)value);
break;
case TypeCode.Single:
writer.WriteValue((float)value);
break;
case TypeCode.String:
writer.WriteString((string)value);
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxInvalidUseOfPrimitiveOperationFormatter));
}
}
}
}
internal class PrimitiveRequestBodyWriter : BodyWriter
{
private object[] _parameters;
private PrimitiveOperationFormatter _primitiveOperationFormatter;
public PrimitiveRequestBodyWriter(object[] parameters, PrimitiveOperationFormatter primitiveOperationFormatter)
: base(true)
{
_parameters = parameters;
_primitiveOperationFormatter = primitiveOperationFormatter;
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
_primitiveOperationFormatter.SerializeRequest(writer, _parameters);
}
}
internal class PrimitiveResponseBodyWriter : BodyWriter
{
private object[] _parameters;
private object _returnValue;
private PrimitiveOperationFormatter _primitiveOperationFormatter;
public PrimitiveResponseBodyWriter(object[] parameters, object returnValue,
PrimitiveOperationFormatter primitiveOperationFormatter)
: base(true)
{
_parameters = parameters;
_returnValue = returnValue;
_primitiveOperationFormatter = primitiveOperationFormatter;
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
_primitiveOperationFormatter.SerializeResponse(writer, _returnValue, _parameters);
}
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using Avalonia.Controls.Platform;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Input.Raw;
using Avalonia.Layout;
using Avalonia.Logging;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.Styling;
using Avalonia.VisualTree;
using JetBrains.Annotations;
namespace Avalonia.Controls
{
/// <summary>
/// Base class for top-level widgets.
/// </summary>
/// <remarks>
/// This class acts as a base for top level widget.
/// It handles scheduling layout, styling and rendering as well as
/// tracking the widget's <see cref="ClientSize"/>.
/// </remarks>
public abstract class TopLevel : ContentControl, IInputRoot, ILayoutRoot, IRenderRoot, ICloseable, IStyleRoot
{
/// <summary>
/// Defines the <see cref="ClientSize"/> property.
/// </summary>
public static readonly DirectProperty<TopLevel, Size> ClientSizeProperty =
AvaloniaProperty.RegisterDirect<TopLevel, Size>(nameof(ClientSize), o => o.ClientSize);
/// <summary>
/// Defines the <see cref="IInputRoot.PointerOverElement"/> property.
/// </summary>
public static readonly StyledProperty<IInputElement> PointerOverElementProperty =
AvaloniaProperty.Register<TopLevel, IInputElement>(nameof(IInputRoot.PointerOverElement));
private readonly IInputManager _inputManager;
private readonly IAccessKeyHandler _accessKeyHandler;
private readonly IKeyboardNavigationHandler _keyboardNavigationHandler;
private readonly IApplicationLifecycle _applicationLifecycle;
private readonly IPlatformRenderInterface _renderInterface;
private Size _clientSize;
/// <summary>
/// Initializes static members of the <see cref="TopLevel"/> class.
/// </summary>
static TopLevel()
{
AffectsMeasure(ClientSizeProperty);
}
/// <summary>
/// Initializes a new instance of the <see cref="TopLevel"/> class.
/// </summary>
/// <param name="impl">The platform-specific window implementation.</param>
public TopLevel(ITopLevelImpl impl)
: this(impl, AvaloniaLocator.Current)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TopLevel"/> class.
/// </summary>
/// <param name="impl">The platform-specific window implementation.</param>
/// <param name="dependencyResolver">
/// The dependency resolver to use. If null the default dependency resolver will be used.
/// </param>
public TopLevel(ITopLevelImpl impl, IAvaloniaDependencyResolver dependencyResolver)
{
if (impl == null)
{
throw new InvalidOperationException(
"Could not create window implementation: maybe no windowing subsystem was initialized?");
}
PlatformImpl = impl;
dependencyResolver = dependencyResolver ?? AvaloniaLocator.Current;
var styler = TryGetService<IStyler>(dependencyResolver);
_accessKeyHandler = TryGetService<IAccessKeyHandler>(dependencyResolver);
_inputManager = TryGetService<IInputManager>(dependencyResolver);
_keyboardNavigationHandler = TryGetService<IKeyboardNavigationHandler>(dependencyResolver);
_applicationLifecycle = TryGetService<IApplicationLifecycle>(dependencyResolver);
_renderInterface = TryGetService<IPlatformRenderInterface>(dependencyResolver);
var renderLoop = TryGetService<IRenderLoop>(dependencyResolver);
Renderer = impl.CreateRenderer(this);
impl.SetInputRoot(this);
impl.Closed = HandleClosed;
impl.Input = HandleInput;
impl.Paint = HandlePaint;
impl.Resized = HandleResized;
impl.ScalingChanged = HandleScalingChanged;
_keyboardNavigationHandler?.SetOwner(this);
_accessKeyHandler?.SetOwner(this);
styler?.ApplyStyles(this);
ClientSize = impl.ClientSize;
this.GetObservable(PointerOverElementProperty)
.Select(
x => (x as InputElement)?.GetObservable(CursorProperty) ?? Observable.Empty<Cursor>())
.Switch().Subscribe(cursor => PlatformImpl?.SetCursor(cursor?.PlatformCursor));
if (_applicationLifecycle != null)
{
_applicationLifecycle.OnExit += OnApplicationExiting;
}
}
/// <summary>
/// Fired when the window is closed.
/// </summary>
public event EventHandler Closed;
/// <summary>
/// Gets or sets the client size of the window.
/// </summary>
public Size ClientSize
{
get { return _clientSize; }
protected set { SetAndRaise(ClientSizeProperty, ref _clientSize, value); }
}
/// <summary>
/// Gets the platform-specific window implementation.
/// </summary>
[CanBeNull]
public ITopLevelImpl PlatformImpl { get; private set; }
/// <summary>
/// Gets the renderer for the window.
/// </summary>
public IRenderer Renderer { get; private set; }
/// <summary>
/// Gets the access key handler for the window.
/// </summary>
IAccessKeyHandler IInputRoot.AccessKeyHandler => _accessKeyHandler;
/// <summary>
/// Gets or sets the keyboard navigation handler for the window.
/// </summary>
IKeyboardNavigationHandler IInputRoot.KeyboardNavigationHandler => _keyboardNavigationHandler;
/// <summary>
/// Gets or sets the input element that the pointer is currently over.
/// </summary>
IInputElement IInputRoot.PointerOverElement
{
get { return GetValue(PointerOverElementProperty); }
set { SetValue(PointerOverElementProperty, value); }
}
/// <inheritdoc/>
IMouseDevice IInputRoot.MouseDevice => PlatformImpl?.MouseDevice;
/// <summary>
/// Gets or sets a value indicating whether access keys are shown in the window.
/// </summary>
bool IInputRoot.ShowAccessKeys
{
get { return GetValue(AccessText.ShowAccessKeyProperty); }
set { SetValue(AccessText.ShowAccessKeyProperty, value); }
}
/// <inheritdoc/>
Size ILayoutRoot.MaxClientSize => Size.Infinity;
/// <inheritdoc/>
double ILayoutRoot.LayoutScaling => PlatformImpl?.Scaling ?? 1;
/// <inheritdoc/>
double IRenderRoot.RenderScaling => PlatformImpl?.Scaling ?? 1;
IStyleHost IStyleHost.StylingParent
{
get { return AvaloniaLocator.Current.GetService<IGlobalStyles>(); }
}
IRenderTarget IRenderRoot.CreateRenderTarget() => CreateRenderTarget();
/// <inheritdoc/>
protected virtual IRenderTarget CreateRenderTarget()
{
if(PlatformImpl == null)
throw new InvalidOperationException("Cann't create render target, PlatformImpl is null (might be already disposed)");
return _renderInterface.CreateRenderTarget(PlatformImpl.Surfaces);
}
/// <inheritdoc/>
void IRenderRoot.Invalidate(Rect rect)
{
PlatformImpl?.Invalidate(rect);
}
/// <inheritdoc/>
Point IRenderRoot.PointToClient(Point p)
{
return PlatformImpl?.PointToClient(p) ?? default(Point);
}
/// <inheritdoc/>
Point IRenderRoot.PointToScreen(Point p)
{
return PlatformImpl?.PointToScreen(p) ?? default(Point);
}
/// <summary>
/// Handles a paint notification from <see cref="ITopLevelImpl.Resized"/>.
/// </summary>
/// <param name="rect">The dirty area.</param>
protected virtual void HandlePaint(Rect rect)
{
Renderer?.Paint(rect);
}
/// <summary>
/// Handles a closed notification from <see cref="ITopLevelImpl.Closed"/>.
/// </summary>
protected virtual void HandleClosed()
{
PlatformImpl = null;
Closed?.Invoke(this, EventArgs.Empty);
Renderer?.Dispose();
Renderer = null;
_applicationLifecycle.OnExit -= OnApplicationExiting;
}
/// <summary>
/// Handles a resize notification from <see cref="ITopLevelImpl.Resized"/>.
/// </summary>
/// <param name="clientSize">The new client size.</param>
protected virtual void HandleResized(Size clientSize)
{
ClientSize = clientSize;
Width = clientSize.Width;
Height = clientSize.Height;
LayoutManager.Instance.ExecuteLayoutPass();
Renderer?.Resized(clientSize);
}
/// <summary>
/// Handles a window scaling change notification from
/// <see cref="ITopLevelImpl.ScalingChanged"/>.
/// </summary>
/// <param name="scaling">The window scaling.</param>
protected virtual void HandleScalingChanged(double scaling)
{
foreach (ILayoutable control in this.GetSelfAndVisualDescendants())
{
control.InvalidateMeasure();
}
}
/// <inheritdoc/>
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTree(e);
throw new InvalidOperationException(
$"Control '{GetType().Name}' is a top level control and cannot be added as a child.");
}
/// <summary>
/// Tries to get a service from an <see cref="IAvaloniaDependencyResolver"/>, logging a
/// warning if not found.
/// </summary>
/// <typeparam name="T">The service type.</typeparam>
/// <param name="resolver">The resolver.</param>
/// <returns>The service.</returns>
private T TryGetService<T>(IAvaloniaDependencyResolver resolver) where T : class
{
var result = resolver.GetService<T>();
if (result == null)
{
Logger.Warning(
LogArea.Control,
this,
"Could not create {Service} : maybe Application.RegisterServices() wasn't called?",
typeof(T));
}
return result;
}
private void OnApplicationExiting(object sender, EventArgs args)
{
HandleApplicationExiting();
}
/// <summary>
/// Handles the application exiting, either from the last window closing, or a call to <see cref="IApplicationLifecycle.Exit"/>.
/// </summary>
protected virtual void HandleApplicationExiting()
{
}
/// <summary>
/// Handles input from <see cref="ITopLevelImpl.Input"/>.
/// </summary>
/// <param name="e">The event args.</param>
private void HandleInput(RawInputEventArgs e)
{
_inputManager.ProcessInput(e);
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Microsoft Public License.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace SDKTemplate
{
/// <summary>
/// Scenario 3 keep aspect ratios the same
/// </summary>
public sealed partial class Scenario3_AspectRatio : Page
{
// Private MainPage object for status updates
private MainPage rootPage = MainPage.Current;
// Object to manage access to camera devices
private MediaCapturePreviewer _previewer = null;
// Folder in which the captures will be stored (initialized in InitializeCameraButton_Click)
private StorageFolder _captureFolder = null;
/// <summary>
/// Initializes a new instance of the <see cref="Scenario1_PreviewSettings"/> class.
/// </summary>
public Scenario3_AspectRatio()
{
this.InitializeComponent();
_previewer = new MediaCapturePreviewer(PreviewControl, Dispatcher);
}
protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
await _previewer.CleanupCameraAsync();
}
/// <summary>
/// On some devices there may not be seperate streams for preview/photo/video. In this case, changing any of them
/// will change all of them since they are the same stream
/// </summary>
private void CheckIfStreamsAreIdentical()
{
if (_previewer.MediaCapture.MediaCaptureSettings.VideoDeviceCharacteristic == VideoDeviceCharacteristic.AllStreamsIdentical ||
_previewer.MediaCapture.MediaCaptureSettings.VideoDeviceCharacteristic == VideoDeviceCharacteristic.PreviewRecordStreamsIdentical)
{
rootPage.NotifyUser("Warning: Preview and video streams for this device are identical, changing one will affect the other", NotifyType.ErrorMessage);
}
}
/// <summary>
/// Initializes the camera and populates the UI
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void InitializeCameraButton_Click(object sender, RoutedEventArgs e)
{
var button = sender as Button;
// Clear any previous message.
rootPage.NotifyUser("", NotifyType.StatusMessage);
button.IsEnabled = false;
await _previewer.InitializeCameraAsync();
button.IsEnabled = true;
if (_previewer.IsPreviewing)
{
if (string.IsNullOrEmpty(_previewer.MediaCapture.MediaCaptureSettings.AudioDeviceId))
{
rootPage.NotifyUser("No audio device available. Cannot capture.", NotifyType.ErrorMessage);
}
else
{
button.Visibility = Visibility.Collapsed;
PreviewControl.Visibility = Visibility.Visible;
CheckIfStreamsAreIdentical();
PopulateComboBoxes();
VideoButton.IsEnabled = true;
}
}
var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
// Fall back to the local app storage if the Pictures Library is not available
_captureFolder = picturesLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder;
}
/// <summary>
/// Event handler for Preview settings combo box. Updates stream resolution based on the selection.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void PreviewSettings_Changed(object sender, RoutedEventArgs e)
{
if (_previewer.IsPreviewing)
{
var selectedItem = (sender as ComboBox).SelectedItem as ComboBoxItem;
var encodingProperties = (selectedItem.Tag as StreamResolution).EncodingProperties;
await _previewer.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, encodingProperties);
// The preview just changed, update the video combo box
MatchPreviewAspectRatio();
}
}
/// <summary>
/// Event handler for Video settings combo box. Updates stream resolution based on the selection.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void VideoSettings_Changed(object sender, RoutedEventArgs e)
{
if (_previewer.IsPreviewing)
{
if (VideoSettings.SelectedIndex > -1)
{
var selectedItem = (sender as ComboBox).SelectedItem as ComboBoxItem;
var encodingProperties = (selectedItem.Tag as StreamResolution).EncodingProperties;
await _previewer.MediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoRecord, encodingProperties);
}
}
}
/// <summary>
/// Records an MP4 video to a StorageFile
/// </summary>
private async void VideoButton_Click(object sender, RoutedEventArgs e)
{
if (_previewer.IsPreviewing)
{
if (!_previewer.IsRecording)
{
try
{
// Create storage file in Video Library
var videoFile = await _captureFolder.CreateFileAsync("SimpleVideo.mp4", CreationCollisionOption.GenerateUniqueName);
var encodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
await _previewer.MediaCapture.StartRecordToStorageFileAsync(encodingProfile, videoFile);
// Reflect changes in the UI
VideoButton.Content = "Stop Video";
_previewer.IsRecording = true;
rootPage.NotifyUser("Recording file, saving to: " + videoFile.Path, NotifyType.StatusMessage);
}
catch (Exception ex)
{
// File I/O errors are reported as exceptions.
rootPage.NotifyUser("Exception when starting video recording: " + ex.Message, NotifyType.ErrorMessage);
}
}
else
{
// Reflect the changes in UI and stop recording
VideoButton.Content = "Record Video";
_previewer.IsRecording = false;
await _previewer.MediaCapture.StopRecordAsync();
rootPage.NotifyUser("Stopped recording!", NotifyType.StatusMessage);
}
}
}
/// <summary>
/// Populates the combo boxes with preview settings and matching ratio settings for the video stream
/// </summary>
private void PopulateComboBoxes()
{
// Query all properties of the device
IEnumerable<StreamResolution> allPreviewProperties = _previewer.MediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview).Select(x => new StreamResolution(x));
// Order them by resolution then frame rate
allPreviewProperties = allPreviewProperties.OrderByDescending(x => x.Height * x.Width).ThenByDescending(x => x.FrameRate);
// Populate the preview combo box with the entries
foreach (var property in allPreviewProperties)
{
ComboBoxItem comboBoxItem = new ComboBoxItem();
comboBoxItem.Content = property.GetFriendlyName() +
String.Format(" A. Ratio: {0}", property.AspectRatio.ToString("#.##"));
comboBoxItem.Tag = property;
PreviewSettings.Items.Add(comboBoxItem);
}
// Keep the same aspect ratio with the video stream
MatchPreviewAspectRatio();
}
/// <summary>
/// Finds all the available video resolutions that match the aspect ratio of the preview stream
/// Note: This should also be done with photos as well. This same method can be modified for photos
/// by changing the MediaStreamType from VideoPreview to Photo.
/// </summary>
private void MatchPreviewAspectRatio()
{
// Query all properties of the device
IEnumerable<StreamResolution> allVideoProperties = _previewer.MediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoRecord).Select(x => new StreamResolution(x));
// Query the current preview settings
StreamResolution previewProperties = new StreamResolution(_previewer.MediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview));
// Get all formats that have the same-ish aspect ratio as the preview
// Allow for some tolerance in the aspect ratio comparison
const double ASPECT_RATIO_TOLERANCE = 0.015;
var matchingFormats = allVideoProperties.Where(x => Math.Abs(x.AspectRatio - previewProperties.AspectRatio) < ASPECT_RATIO_TOLERANCE);
// Order them by resolution then frame rate
allVideoProperties = matchingFormats.OrderByDescending(x => x.Height * x.Width).ThenByDescending(x => x.FrameRate);
// Clear out old entries and populate the video combo box with new matching entries
VideoSettings.Items.Clear();
foreach (var property in allVideoProperties)
{
ComboBoxItem comboBoxItem = new ComboBoxItem();
comboBoxItem.Content = property.GetFriendlyName();
comboBoxItem.Tag = property;
VideoSettings.Items.Add(comboBoxItem);
}
VideoSettings.SelectedIndex = -1;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="TransferDownloadStream.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.DataMovement
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
class TransferDownloadStream : Stream
{
TransferDownloadBuffer firstBuffer;
MemoryStream firstStream;
int firstOffset;
TransferDownloadBuffer secondBuffer;
MemoryStream secondStream;
int secondOffset;
bool onSecondStream = false;
MemoryManager memoryManager;
public TransferDownloadStream(MemoryManager memoryManager, TransferDownloadBuffer buffer, int offset, int count)
:this(memoryManager, buffer, offset, count, null, 0, 0)
{
}
public TransferDownloadStream(
MemoryManager memoryManager,
TransferDownloadBuffer firstBuffer,
int firstOffset,
int firstCount,
TransferDownloadBuffer secondBuffer,
int secondOffset,
int secondCount)
{
this.memoryManager = memoryManager;
this.firstBuffer = firstBuffer;
this.firstOffset = firstOffset;
this.firstStream = new MemoryStream(this.firstBuffer.MemoryBuffer, firstOffset, firstCount);
if (null != secondBuffer)
{
this.secondBuffer = secondBuffer;
this.secondOffset = secondOffset;
this.secondStream = new MemoryStream(this.secondBuffer.MemoryBuffer, secondOffset, secondCount);
}
}
public override bool CanRead
{
get
{
return false;
}
}
public override bool CanWrite
{
get
{
return true;
}
}
public override bool CanSeek
{
get
{
return true;
}
}
public bool ReserveBuffer
{
get;
set;
}
public override long Length
{
get
{
if (null == this.secondStream)
{
return this.firstStream.Length;
}
return this.firstStream.Length + this.secondStream.Length;
}
}
public override long Position
{
get
{
if (!this.onSecondStream)
{
return this.firstStream.Position;
}
else
{
Debug.Assert(null != this.secondStream, "Second stream should exist when position is on the second stream");
return this.firstStream.Length + this.secondStream.Position;
}
}
set
{
long position = value;
if (position < this.firstStream.Length)
{
this.onSecondStream = false;
this.firstStream.Position = position;
}
else
{
position -= this.firstStream.Length;
this.onSecondStream = true;
this.secondStream.Position = position;
}
}
}
public override long Seek(long offset, SeekOrigin origin)
{
long position = 0;
switch (origin)
{
case SeekOrigin.End:
position = this.Length + offset;
break;
case SeekOrigin.Current:
position = this.Position + offset;
break;
default:
position = offset;
break;
}
this.Position = position;
return position;
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Flush()
{
// do nothing
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
int length = count;
int firstLength = 0;
if (!this.onSecondStream)
{
firstLength = Math.Min(length, (int)(this.firstStream.Length - this.firstStream.Position));
this.firstStream.Write(buffer, offset, firstLength);
length -= firstLength;
if (0 == length)
{
return;
}
else
{
if (null == this.secondStream)
{
throw new NotSupportedException(Resources.StreamNotExpandable);
}
this.onSecondStream = true;
}
}
Debug.Assert(null != this.secondStream, "Position is on the second stream, it should not be null");
this.secondStream.Write(buffer, offset + firstLength, length);
}
public void SetAllZero()
{
Array.Clear(this.firstBuffer.MemoryBuffer, this.firstOffset, (int)this.firstStream.Length);
if (null != this.secondBuffer)
{
Array.Clear(this.secondBuffer.MemoryBuffer, this.secondOffset, (int)this.secondStream.Length);
}
}
public void FinishWrite()
{
this.firstBuffer.ReadFinish((int)this.firstStream.Length);
if (null != this.secondBuffer)
{
this.secondBuffer.ReadFinish((int)this.secondStream.Length);
}
}
public IEnumerable<TransferDownloadBuffer> GetBuffers()
{
yield return this.firstBuffer;
if (null != this.secondBuffer)
{
yield return this.secondBuffer;
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
if (null != this.firstStream)
{
this.firstStream.Dispose();
this.firstStream = null;
}
if (null != this.secondStream)
{
this.secondStream.Dispose();
this.secondStream = null;
}
if (!this.ReserveBuffer)
{
if (null != this.firstBuffer)
{
this.memoryManager.ReleaseBuffer(this.firstBuffer.MemoryBuffer);
this.firstBuffer = null;
}
if (null != this.secondBuffer)
{
this.memoryManager.ReleaseBuffer(this.secondBuffer.MemoryBuffer);
this.secondBuffer = null;
}
}
}
}
}
}
| |
//#define Trace
// ParallelDeflateOutputStream.cs
// ------------------------------------------------------------------
//
// A DeflateStream that does compression only, it uses a
// divide-and-conquer approach with multiple threads to exploit multiple
// CPUs for the DEFLATE computation.
//
// last saved: <2011-July-31 14:49:40>
//
// ------------------------------------------------------------------
//
// Copyright (c) 2009-2011 by Dino Chiesa
// All rights reserved!
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Threading;
using Ionic.Zlib;
using System.IO;
namespace Ionic.Zlib
{
internal class WorkItem
{
public byte[] buffer;
public byte[] compressed;
public int crc;
public int index;
public int ordinal;
public int inputBytesAvailable;
public int compressedBytesAvailable;
public ZlibCodec compressor;
public WorkItem(int size,
Ionic.Zlib.CompressionLevel compressLevel,
CompressionStrategy strategy,
int ix)
{
this.buffer= new byte[size];
// alloc 5 bytes overhead for every block (margin of safety= 2)
int n = size + ((size / 32768)+1) * 5 * 2;
this.compressed = new byte[n];
this.compressor = new ZlibCodec();
this.compressor.InitializeDeflate(compressLevel, false);
this.compressor.OutputBuffer = this.compressed;
this.compressor.InputBuffer = this.buffer;
this.index = ix;
}
}
/// <summary>
/// A class for compressing streams using the
/// Deflate algorithm with multiple threads.
/// </summary>
///
/// <remarks>
/// <para>
/// This class performs DEFLATE compression through writing. For
/// more information on the Deflate algorithm, see IETF RFC 1951,
/// "DEFLATE Compressed Data Format Specification version 1.3."
/// </para>
///
/// <para>
/// This class is similar to <see cref="Ionic.Zlib.DeflateStream"/>, except
/// that this class is for compression only, and this implementation uses an
/// approach that employs multiple worker threads to perform the DEFLATE. On
/// a multi-cpu or multi-core computer, the performance of this class can be
/// significantly higher than the single-threaded DeflateStream, particularly
/// for larger streams. How large? Anything over 10mb is a good candidate
/// for parallel compression.
/// </para>
///
/// <para>
/// The tradeoff is that this class uses more memory and more CPU than the
/// vanilla DeflateStream, and also is less efficient as a compressor. For
/// large files the size of the compressed data stream can be less than 1%
/// larger than the size of a compressed data stream from the vanialla
/// DeflateStream. For smaller files the difference can be larger. The
/// difference will also be larger if you set the BufferSize to be lower than
/// the default value. Your mileage may vary. Finally, for small files, the
/// ParallelDeflateOutputStream can be much slower than the vanilla
/// DeflateStream, because of the overhead associated to using the thread
/// pool.
/// </para>
///
/// </remarks>
/// <seealso cref="Ionic.Zlib.DeflateStream" />
public class ParallelDeflateOutputStream : System.IO.Stream
{
private static readonly int IO_BUFFER_SIZE_DEFAULT = 64 * 1024; // 128k
private static readonly int BufferPairsPerCore = 4;
private System.Collections.Generic.List<WorkItem> _pool;
private bool _leaveOpen;
private bool emitting;
private System.IO.Stream _outStream;
private int _maxBufferPairs;
private int _bufferSize = IO_BUFFER_SIZE_DEFAULT;
private AutoResetEvent _newlyCompressedBlob;
//private ManualResetEvent _writingDone;
//private ManualResetEvent _sessionReset;
private object _outputLock = new object();
private bool _isClosed;
private bool _firstWriteDone;
private int _currentlyFilling;
private int _lastFilled;
private int _lastWritten;
private int _latestCompressed;
private int _Crc32;
private Ionic.Crc.CRC32 _runningCrc;
private object _latestLock = new object();
private System.Collections.Generic.Queue<int> _toWrite;
private System.Collections.Generic.Queue<int> _toFill;
private Int64 _totalBytesProcessed;
private Ionic.Zlib.CompressionLevel _compressLevel;
private volatile Exception _pendingException;
private bool _handlingException;
private object _eLock = new Object(); // protects _pendingException
// This bitfield is used only when Trace is defined.
//private TraceBits _DesiredTrace = TraceBits.Write | TraceBits.WriteBegin |
//TraceBits.WriteDone | TraceBits.Lifecycle | TraceBits.Fill | TraceBits.Flush |
//TraceBits.Session;
//private TraceBits _DesiredTrace = TraceBits.WriteBegin | TraceBits.WriteDone | TraceBits.Synch | TraceBits.Lifecycle | TraceBits.Session ;
private TraceBits _DesiredTrace =
TraceBits.Session |
TraceBits.Compress |
TraceBits.WriteTake |
TraceBits.WriteEnter |
TraceBits.EmitEnter |
TraceBits.EmitDone |
TraceBits.EmitLock |
TraceBits.EmitSkip |
TraceBits.EmitBegin;
/// <summary>
/// Create a ParallelDeflateOutputStream.
/// </summary>
/// <remarks>
///
/// <para>
/// This stream compresses data written into it via the DEFLATE
/// algorithm (see RFC 1951), and writes out the compressed byte stream.
/// </para>
///
/// <para>
/// The instance will use the default compression level, the default
/// buffer sizes and the default number of threads and buffers per
/// thread.
/// </para>
///
/// <para>
/// This class is similar to <see cref="Ionic.Zlib.DeflateStream"/>,
/// except that this implementation uses an approach that employs
/// multiple worker threads to perform the DEFLATE. On a multi-cpu or
/// multi-core computer, the performance of this class can be
/// significantly higher than the single-threaded DeflateStream,
/// particularly for larger streams. How large? Anything over 10mb is
/// a good candidate for parallel compression.
/// </para>
///
/// </remarks>
///
/// <example>
///
/// This example shows how to use a ParallelDeflateOutputStream to compress
/// data. It reads a file, compresses it, and writes the compressed data to
/// a second, output file.
///
/// <code>
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n= -1;
/// String outputFile = fileToCompress + ".compressed";
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(outputFile))
/// {
/// using (Stream compressor = new ParallelDeflateOutputStream(raw))
/// {
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// <code lang="VB">
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Dim outputFile As String = (fileToCompress & ".compressed")
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(outputFile)
/// Using compressor As Stream = New ParallelDeflateOutputStream(raw)
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
/// <param name="stream">The stream to which compressed data will be written.</param>
public ParallelDeflateOutputStream(System.IO.Stream stream)
: this(stream, CompressionLevel.Default, CompressionStrategy.Default, false)
{
}
/// <summary>
/// Create a ParallelDeflateOutputStream using the specified CompressionLevel.
/// </summary>
/// <remarks>
/// See the <see cref="ParallelDeflateOutputStream(System.IO.Stream)"/>
/// constructor for example code.
/// </remarks>
/// <param name="stream">The stream to which compressed data will be written.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
public ParallelDeflateOutputStream(System.IO.Stream stream, CompressionLevel level)
: this(stream, level, CompressionStrategy.Default, false)
{
}
/// <summary>
/// Create a ParallelDeflateOutputStream and specify whether to leave the captive stream open
/// when the ParallelDeflateOutputStream is closed.
/// </summary>
/// <remarks>
/// See the <see cref="ParallelDeflateOutputStream(System.IO.Stream)"/>
/// constructor for example code.
/// </remarks>
/// <param name="stream">The stream to which compressed data will be written.</param>
/// <param name="leaveOpen">
/// true if the application would like the stream to remain open after inflation/deflation.
/// </param>
public ParallelDeflateOutputStream(System.IO.Stream stream, bool leaveOpen)
: this(stream, CompressionLevel.Default, CompressionStrategy.Default, leaveOpen)
{
}
/// <summary>
/// Create a ParallelDeflateOutputStream and specify whether to leave the captive stream open
/// when the ParallelDeflateOutputStream is closed.
/// </summary>
/// <remarks>
/// See the <see cref="ParallelDeflateOutputStream(System.IO.Stream)"/>
/// constructor for example code.
/// </remarks>
/// <param name="stream">The stream to which compressed data will be written.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
/// <param name="leaveOpen">
/// true if the application would like the stream to remain open after inflation/deflation.
/// </param>
public ParallelDeflateOutputStream(System.IO.Stream stream, CompressionLevel level, bool leaveOpen)
: this(stream, CompressionLevel.Default, CompressionStrategy.Default, leaveOpen)
{
}
/// <summary>
/// Create a ParallelDeflateOutputStream using the specified
/// CompressionLevel and CompressionStrategy, and specifying whether to
/// leave the captive stream open when the ParallelDeflateOutputStream is
/// closed.
/// </summary>
/// <remarks>
/// See the <see cref="ParallelDeflateOutputStream(System.IO.Stream)"/>
/// constructor for example code.
/// </remarks>
/// <param name="stream">The stream to which compressed data will be written.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
/// <param name="strategy">
/// By tweaking this parameter, you may be able to optimize the compression for
/// data with particular characteristics.
/// </param>
/// <param name="leaveOpen">
/// true if the application would like the stream to remain open after inflation/deflation.
/// </param>
public ParallelDeflateOutputStream(System.IO.Stream stream,
CompressionLevel level,
CompressionStrategy strategy,
bool leaveOpen)
{
TraceOutput(TraceBits.Lifecycle | TraceBits.Session, "-------------------------------------------------------");
TraceOutput(TraceBits.Lifecycle | TraceBits.Session, "Create {0:X8}", this.GetHashCode());
_outStream = stream;
_compressLevel= level;
Strategy = strategy;
_leaveOpen = leaveOpen;
this.MaxBufferPairs = 16; // default
}
/// <summary>
/// The ZLIB strategy to be used during compression.
/// </summary>
///
public CompressionStrategy Strategy
{
get;
private set;
}
/// <summary>
/// The maximum number of buffer pairs to use.
/// </summary>
///
/// <remarks>
/// <para>
/// This property sets an upper limit on the number of memory buffer
/// pairs to create. The implementation of this stream allocates
/// multiple buffers to facilitate parallel compression. As each buffer
/// fills up, this stream uses <see
/// cref="System.Threading.ThreadPool.QueueUserWorkItem(WaitCallback)">
/// ThreadPool.QueueUserWorkItem()</see>
/// to compress those buffers in a background threadpool thread. After a
/// buffer is compressed, it is re-ordered and written to the output
/// stream.
/// </para>
///
/// <para>
/// A higher number of buffer pairs enables a higher degree of
/// parallelism, which tends to increase the speed of compression on
/// multi-cpu computers. On the other hand, a higher number of buffer
/// pairs also implies a larger memory consumption, more active worker
/// threads, and a higher cpu utilization for any compression. This
/// property enables the application to limit its memory consumption and
/// CPU utilization behavior depending on requirements.
/// </para>
///
/// <para>
/// For each compression "task" that occurs in parallel, there are 2
/// buffers allocated: one for input and one for output. This property
/// sets a limit for the number of pairs. The total amount of storage
/// space allocated for buffering will then be (N*S*2), where N is the
/// number of buffer pairs, S is the size of each buffer (<see
/// cref="BufferSize"/>). By default, DotNetZip allocates 4 buffer
/// pairs per CPU core, so if your machine has 4 cores, and you retain
/// the default buffer size of 128k, then the
/// ParallelDeflateOutputStream will use 4 * 4 * 2 * 128kb of buffer
/// memory in total, or 4mb, in blocks of 128kb. If you then set this
/// property to 8, then the number will be 8 * 2 * 128kb of buffer
/// memory, or 2mb.
/// </para>
///
/// <para>
/// CPU utilization will also go up with additional buffers, because a
/// larger number of buffer pairs allows a larger number of background
/// threads to compress in parallel. If you find that parallel
/// compression is consuming too much memory or CPU, you can adjust this
/// value downward.
/// </para>
///
/// <para>
/// The default value is 16. Different values may deliver better or
/// worse results, depending on your priorities and the dynamic
/// performance characteristics of your storage and compute resources.
/// </para>
///
/// <para>
/// This property is not the number of buffer pairs to use; it is an
/// upper limit. An illustration: Suppose you have an application that
/// uses the default value of this property (which is 16), and it runs
/// on a machine with 2 CPU cores. In that case, DotNetZip will allocate
/// 4 buffer pairs per CPU core, for a total of 8 pairs. The upper
/// limit specified by this property has no effect.
/// </para>
///
/// <para>
/// The application can set this value at any time, but it is effective
/// only before the first call to Write(), which is when the buffers are
/// allocated.
/// </para>
/// </remarks>
public int MaxBufferPairs
{
get
{
return _maxBufferPairs;
}
set
{
if (value < 4)
throw new ArgumentException("MaxBufferPairs",
"Value must be 4 or greater.");
_maxBufferPairs = value;
}
}
/// <summary>
/// The size of the buffers used by the compressor threads.
/// </summary>
/// <remarks>
///
/// <para>
/// The default buffer size is 128k. The application can set this value
/// at any time, but it is effective only before the first Write().
/// </para>
///
/// <para>
/// Larger buffer sizes implies larger memory consumption but allows
/// more efficient compression. Using smaller buffer sizes consumes less
/// memory but may result in less effective compression. For example,
/// using the default buffer size of 128k, the compression delivered is
/// within 1% of the compression delivered by the single-threaded <see
/// cref="Ionic.Zlib.DeflateStream"/>. On the other hand, using a
/// BufferSize of 8k can result in a compressed data stream that is 5%
/// larger than that delivered by the single-threaded
/// <c>DeflateStream</c>. Excessively small buffer sizes can also cause
/// the speed of the ParallelDeflateOutputStream to drop, because of
/// larger thread scheduling overhead dealing with many many small
/// buffers.
/// </para>
///
/// <para>
/// The total amount of storage space allocated for buffering will be
/// (N*S*2), where N is the number of buffer pairs, and S is the size of
/// each buffer (this property). There are 2 buffers used by the
/// compressor, one for input and one for output. By default, DotNetZip
/// allocates 4 buffer pairs per CPU core, so if your machine has 4
/// cores, then the number of buffer pairs used will be 16. If you
/// accept the default value of this property, 128k, then the
/// ParallelDeflateOutputStream will use 16 * 2 * 128kb of buffer memory
/// in total, or 4mb, in blocks of 128kb. If you set this property to
/// 64kb, then the number will be 16 * 2 * 64kb of buffer memory, or
/// 2mb.
/// </para>
///
/// </remarks>
public int BufferSize
{
get { return _bufferSize;}
set
{
if (value < 1024)
throw new ArgumentOutOfRangeException("BufferSize",
"BufferSize must be greater than 1024 bytes");
_bufferSize = value;
}
}
/// <summary>
/// The CRC32 for the data that was written out, prior to compression.
/// </summary>
/// <remarks>
/// This value is meaningful only after a call to Close().
/// </remarks>
public int Crc32 { get { return _Crc32; } }
/// <summary>
/// The total number of uncompressed bytes processed by the ParallelDeflateOutputStream.
/// </summary>
/// <remarks>
/// This value is meaningful only after a call to Close().
/// </remarks>
public Int64 BytesProcessed { get { return _totalBytesProcessed; } }
private void _InitializePoolOfWorkItems()
{
_toWrite = new Queue<int>();
_toFill = new Queue<int>();
_pool = new System.Collections.Generic.List<WorkItem>();
int nTasks = BufferPairsPerCore * Environment.ProcessorCount;
nTasks = Math.Min(nTasks, _maxBufferPairs);
for(int i=0; i < nTasks; i++)
{
_pool.Add(new WorkItem(_bufferSize, _compressLevel, Strategy, i));
_toFill.Enqueue(i);
}
_newlyCompressedBlob = new AutoResetEvent(false);
_runningCrc = new Ionic.Crc.CRC32();
_currentlyFilling = -1;
_lastFilled = -1;
_lastWritten = -1;
_latestCompressed = -1;
}
/// <summary>
/// Write data to the stream.
/// </summary>
///
/// <remarks>
///
/// <para>
/// To use the ParallelDeflateOutputStream to compress data, create a
/// ParallelDeflateOutputStream with CompressionMode.Compress, passing a
/// writable output stream. Then call Write() on that
/// ParallelDeflateOutputStream, providing uncompressed data as input. The
/// data sent to the output stream will be the compressed form of the data
/// written.
/// </para>
///
/// <para>
/// To decompress data, use the <see cref="Ionic.Zlib.DeflateStream"/> class.
/// </para>
///
/// </remarks>
/// <param name="buffer">The buffer holding data to write to the stream.</param>
/// <param name="offset">the offset within that data array to find the first byte to write.</param>
/// <param name="count">the number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
bool mustWait = false;
// This method does this:
// 0. handles any pending exceptions
// 1. write any buffers that are ready to be written,
// 2. fills a work buffer; when full, flip state to 'Filled',
// 3. if more data to be written, goto step 1
if (_isClosed)
throw new InvalidOperationException();
// dispense any exceptions that occurred on the BG threads
if (_pendingException != null)
{
_handlingException = true;
var pe = _pendingException;
_pendingException = null;
throw pe;
}
if (count == 0) return;
if (!_firstWriteDone)
{
// Want to do this on first Write, first session, and not in the
// constructor. We want to allow MaxBufferPairs to
// change after construction, but before first Write.
_InitializePoolOfWorkItems();
_firstWriteDone = true;
}
do
{
// may need to make buffers available
EmitPendingBuffers(false, mustWait);
mustWait = false;
// use current buffer, or get a new buffer to fill
int ix = -1;
if (_currentlyFilling >= 0)
{
ix = _currentlyFilling;
TraceOutput(TraceBits.WriteTake,
"Write notake wi({0}) lf({1})",
ix,
_lastFilled);
}
else
{
TraceOutput(TraceBits.WriteTake, "Write take?");
if (_toFill.Count == 0)
{
// no available buffers, so... need to emit
// compressed buffers.
mustWait = true;
continue;
}
ix = _toFill.Dequeue();
TraceOutput(TraceBits.WriteTake,
"Write take wi({0}) lf({1})",
ix,
_lastFilled);
++_lastFilled; // TODO: consider rollover?
}
WorkItem workitem = _pool[ix];
int limit = ((workitem.buffer.Length - workitem.inputBytesAvailable) > count)
? count
: (workitem.buffer.Length - workitem.inputBytesAvailable);
workitem.ordinal = _lastFilled;
TraceOutput(TraceBits.Write,
"Write lock wi({0}) ord({1}) iba({2})",
workitem.index,
workitem.ordinal,
workitem.inputBytesAvailable
);
// copy from the provided buffer to our workitem, starting at
// the tail end of whatever data we might have in there currently.
Buffer.BlockCopy(buffer,
offset,
workitem.buffer,
workitem.inputBytesAvailable,
limit);
count -= limit;
offset += limit;
workitem.inputBytesAvailable += limit;
if (workitem.inputBytesAvailable == workitem.buffer.Length)
{
// No need for interlocked.increment: the Write()
// method is documented as not multi-thread safe, so
// we can assume Write() calls come in from only one
// thread.
TraceOutput(TraceBits.Write,
"Write QUWI wi({0}) ord({1}) iba({2}) nf({3})",
workitem.index,
workitem.ordinal,
workitem.inputBytesAvailable );
if (!ThreadPool.QueueUserWorkItem( _DeflateOne, workitem ))
throw new Exception("Cannot enqueue workitem");
_currentlyFilling = -1; // will get a new buffer next time
}
else
_currentlyFilling = ix;
if (count > 0)
TraceOutput(TraceBits.WriteEnter, "Write more");
}
while (count > 0); // until no more to write
TraceOutput(TraceBits.WriteEnter, "Write exit");
return;
}
private void _FlushFinish()
{
// After writing a series of compressed buffers, each one closed
// with Flush.Sync, we now write the final one as Flush.Finish,
// and then stop.
byte[] buffer = new byte[128];
var compressor = new ZlibCodec();
int rc = compressor.InitializeDeflate(_compressLevel, false);
compressor.InputBuffer = null;
compressor.NextIn = 0;
compressor.AvailableBytesIn = 0;
compressor.OutputBuffer = buffer;
compressor.NextOut = 0;
compressor.AvailableBytesOut = buffer.Length;
rc = compressor.Deflate(FlushType.Finish);
if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
throw new Exception("deflating: " + compressor.Message);
if (buffer.Length - compressor.AvailableBytesOut > 0)
{
TraceOutput(TraceBits.EmitBegin,
"Emit begin flush bytes({0})",
buffer.Length - compressor.AvailableBytesOut);
_outStream.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut);
TraceOutput(TraceBits.EmitDone,
"Emit done flush");
}
compressor.EndDeflate();
_Crc32 = _runningCrc.Crc32Result;
}
private void _Flush(bool lastInput)
{
if (_isClosed)
throw new InvalidOperationException();
if (emitting) return;
// compress any partial buffer
if (_currentlyFilling >= 0)
{
WorkItem workitem = _pool[_currentlyFilling];
_DeflateOne(workitem);
_currentlyFilling = -1; // get a new buffer next Write()
}
if (lastInput)
{
EmitPendingBuffers(true, false);
_FlushFinish();
}
else
{
EmitPendingBuffers(false, false);
}
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
if (_pendingException != null)
{
_handlingException = true;
var pe = _pendingException;
_pendingException = null;
throw pe;
}
if (_handlingException)
return;
_Flush(false);
}
/// <summary>
/// Close the stream.
/// </summary>
/// <remarks>
/// You must call Close on the stream to guarantee that all of the data written in has
/// been compressed, and the compressed data has been written out.
/// </remarks>
public override void Close()
{
TraceOutput(TraceBits.Session, "Close {0:X8}", this.GetHashCode());
if (_pendingException != null)
{
_handlingException = true;
var pe = _pendingException;
_pendingException = null;
throw pe;
}
if (_handlingException)
return;
if (_isClosed) return;
_Flush(true);
if (!_leaveOpen)
_outStream.Close();
_isClosed= true;
}
// workitem 10030 - implement a new Dispose method
/// <summary>Dispose the object</summary>
/// <remarks>
/// <para>
/// Because ParallelDeflateOutputStream is IDisposable, the
/// application must call this method when finished using the instance.
/// </para>
/// <para>
/// This method is generally called implicitly upon exit from
/// a <c>using</c> scope in C# (<c>Using</c> in VB).
/// </para>
/// </remarks>
new public void Dispose()
{
TraceOutput(TraceBits.Lifecycle, "Dispose {0:X8}", this.GetHashCode());
Close();
_pool = null;
Dispose(true);
}
/// <summary>The Dispose method</summary>
/// <param name="disposing">
/// indicates whether the Dispose method was invoked by user code.
/// </param>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
/// <summary>
/// Resets the stream for use with another stream.
/// </summary>
/// <remarks>
/// Because the ParallelDeflateOutputStream is expensive to create, it
/// has been designed so that it can be recycled and re-used. You have
/// to call Close() on the stream first, then you can call Reset() on
/// it, to use it again on another stream.
/// </remarks>
///
/// <param name="stream">
/// The new output stream for this era.
/// </param>
///
/// <example>
/// <code>
/// ParallelDeflateOutputStream deflater = null;
/// foreach (var inputFile in listOfFiles)
/// {
/// string outputFile = inputFile + ".compressed";
/// using (System.IO.Stream input = System.IO.File.OpenRead(inputFile))
/// {
/// using (var outStream = System.IO.File.Create(outputFile))
/// {
/// if (deflater == null)
/// deflater = new ParallelDeflateOutputStream(outStream,
/// CompressionLevel.Best,
/// CompressionStrategy.Default,
/// true);
/// deflater.Reset(outStream);
///
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// deflater.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// </example>
public void Reset(Stream stream)
{
TraceOutput(TraceBits.Session, "-------------------------------------------------------");
TraceOutput(TraceBits.Session, "Reset {0:X8} firstDone({1})", this.GetHashCode(), _firstWriteDone);
if (!_firstWriteDone) return;
// reset all status
_toWrite.Clear();
_toFill.Clear();
foreach (var workitem in _pool)
{
_toFill.Enqueue(workitem.index);
workitem.ordinal = -1;
}
_firstWriteDone = false;
_totalBytesProcessed = 0L;
_runningCrc = new Ionic.Crc.CRC32();
_isClosed= false;
_currentlyFilling = -1;
_lastFilled = -1;
_lastWritten = -1;
_latestCompressed = -1;
_outStream = stream;
}
private void EmitPendingBuffers(bool doAll, bool mustWait)
{
// When combining parallel deflation with a ZipSegmentedStream, it's
// possible for the ZSS to throw from within this method. In that
// case, Close/Dispose will be called on this stream, if this stream
// is employed within a using or try/finally pair as required. But
// this stream is unaware of the pending exception, so the Close()
// method invokes this method AGAIN. This can lead to a deadlock.
// Therefore, failfast if re-entering.
if (emitting) return;
emitting = true;
if (doAll || mustWait)
_newlyCompressedBlob.WaitOne();
do
{
int firstSkip = -1;
int millisecondsToWait = doAll ? 200 : (mustWait ? -1 : 0);
int nextToWrite = -1;
do
{
if (Monitor.TryEnter(_toWrite, millisecondsToWait))
{
nextToWrite = -1;
try
{
if (_toWrite.Count > 0)
nextToWrite = _toWrite.Dequeue();
}
finally
{
Monitor.Exit(_toWrite);
}
if (nextToWrite >= 0)
{
WorkItem workitem = _pool[nextToWrite];
if (workitem.ordinal != _lastWritten + 1)
{
// out of order. requeue and try again.
TraceOutput(TraceBits.EmitSkip,
"Emit skip wi({0}) ord({1}) lw({2}) fs({3})",
workitem.index,
workitem.ordinal,
_lastWritten,
firstSkip);
lock(_toWrite)
{
_toWrite.Enqueue(nextToWrite);
}
if (firstSkip == nextToWrite)
{
// We went around the list once.
// None of the items in the list is the one we want.
// Now wait for a compressor to signal again.
_newlyCompressedBlob.WaitOne();
firstSkip = -1;
}
else if (firstSkip == -1)
firstSkip = nextToWrite;
continue;
}
firstSkip = -1;
TraceOutput(TraceBits.EmitBegin,
"Emit begin wi({0}) ord({1}) cba({2})",
workitem.index,
workitem.ordinal,
workitem.compressedBytesAvailable);
_outStream.Write(workitem.compressed, 0, workitem.compressedBytesAvailable);
_runningCrc.Combine(workitem.crc, workitem.inputBytesAvailable);
_totalBytesProcessed += workitem.inputBytesAvailable;
workitem.inputBytesAvailable = 0;
TraceOutput(TraceBits.EmitDone,
"Emit done wi({0}) ord({1}) cba({2}) mtw({3})",
workitem.index,
workitem.ordinal,
workitem.compressedBytesAvailable,
millisecondsToWait);
_lastWritten = workitem.ordinal;
_toFill.Enqueue(workitem.index);
// don't wait next time through
if (millisecondsToWait == -1) millisecondsToWait = 0;
}
}
else
nextToWrite = -1;
} while (nextToWrite >= 0);
} while (doAll && (_lastWritten != _latestCompressed));
emitting = false;
}
#if OLD
private void _PerpetualWriterMethod(object state)
{
TraceOutput(TraceBits.WriterThread, "_PerpetualWriterMethod START");
try
{
do
{
// wait for the next session
TraceOutput(TraceBits.Synch | TraceBits.WriterThread, "Synch _sessionReset.WaitOne(begin) PWM");
_sessionReset.WaitOne();
TraceOutput(TraceBits.Synch | TraceBits.WriterThread, "Synch _sessionReset.WaitOne(done) PWM");
if (_isDisposed) break;
TraceOutput(TraceBits.Synch | TraceBits.WriterThread, "Synch _sessionReset.Reset() PWM");
_sessionReset.Reset();
// repeatedly write buffers as they become ready
WorkItem workitem = null;
Ionic.Zlib.CRC32 c= new Ionic.Zlib.CRC32();
do
{
workitem = _pool[_nextToWrite % _pc];
lock(workitem)
{
if (_noMoreInputForThisSegment)
TraceOutput(TraceBits.Write,
"Write drain wi({0}) stat({1}) canuse({2}) cba({3})",
workitem.index,
workitem.status,
(workitem.status == (int)WorkItem.Status.Compressed),
workitem.compressedBytesAvailable);
do
{
if (workitem.status == (int)WorkItem.Status.Compressed)
{
TraceOutput(TraceBits.WriteBegin,
"Write begin wi({0}) stat({1}) cba({2})",
workitem.index,
workitem.status,
workitem.compressedBytesAvailable);
workitem.status = (int)WorkItem.Status.Writing;
_outStream.Write(workitem.compressed, 0, workitem.compressedBytesAvailable);
c.Combine(workitem.crc, workitem.inputBytesAvailable);
_totalBytesProcessed += workitem.inputBytesAvailable;
_nextToWrite++;
workitem.inputBytesAvailable= 0;
workitem.status = (int)WorkItem.Status.Done;
TraceOutput(TraceBits.WriteDone,
"Write done wi({0}) stat({1}) cba({2})",
workitem.index,
workitem.status,
workitem.compressedBytesAvailable);
Monitor.Pulse(workitem);
break;
}
else
{
int wcycles = 0;
// I've locked a workitem I cannot use.
// Therefore, wake someone else up, and then release the lock.
while (workitem.status != (int)WorkItem.Status.Compressed)
{
TraceOutput(TraceBits.WriteWait,
"Write waiting wi({0}) stat({1}) nw({2}) nf({3}) nomore({4})",
workitem.index,
workitem.status,
_nextToWrite, _nextToFill,
_noMoreInputForThisSegment );
if (_noMoreInputForThisSegment && _nextToWrite == _nextToFill)
break;
wcycles++;
// wake up someone else
Monitor.Pulse(workitem);
// release and wait
Monitor.Wait(workitem);
if (workitem.status == (int)WorkItem.Status.Compressed)
TraceOutput(TraceBits.WriteWait,
"Write A-OK wi({0}) stat({1}) iba({2}) cba({3}) cyc({4})",
workitem.index,
workitem.status,
workitem.inputBytesAvailable,
workitem.compressedBytesAvailable,
wcycles);
}
if (_noMoreInputForThisSegment && _nextToWrite == _nextToFill)
break;
}
}
while (true);
}
if (_noMoreInputForThisSegment)
TraceOutput(TraceBits.Write,
"Write nomore nw({0}) nf({1}) break({2})",
_nextToWrite, _nextToFill, (_nextToWrite == _nextToFill));
if (_noMoreInputForThisSegment && _nextToWrite == _nextToFill)
break;
} while (true);
// Finish:
// After writing a series of buffers, closing each one with
// Flush.Sync, we now write the final one as Flush.Finish, and
// then stop.
byte[] buffer = new byte[128];
ZlibCodec compressor = new ZlibCodec();
int rc = compressor.InitializeDeflate(_compressLevel, false);
compressor.InputBuffer = null;
compressor.NextIn = 0;
compressor.AvailableBytesIn = 0;
compressor.OutputBuffer = buffer;
compressor.NextOut = 0;
compressor.AvailableBytesOut = buffer.Length;
rc = compressor.Deflate(FlushType.Finish);
if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
throw new Exception("deflating: " + compressor.Message);
if (buffer.Length - compressor.AvailableBytesOut > 0)
{
TraceOutput(TraceBits.WriteBegin,
"Write begin flush bytes({0})",
buffer.Length - compressor.AvailableBytesOut);
_outStream.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut);
TraceOutput(TraceBits.WriteBegin,
"Write done flush");
}
compressor.EndDeflate();
_Crc32 = c.Crc32Result;
// signal that writing is complete:
TraceOutput(TraceBits.Synch, "Synch _writingDone.Set() PWM");
_writingDone.Set();
}
while (true);
}
catch (System.Exception exc1)
{
lock(_eLock)
{
// expose the exception to the main thread
if (_pendingException!=null)
_pendingException = exc1;
}
}
TraceOutput(TraceBits.WriterThread, "_PerpetualWriterMethod FINIS");
}
#endif
private void _DeflateOne(Object wi)
{
// compress one buffer
WorkItem workitem = (WorkItem) wi;
try
{
int myItem = workitem.index;
Ionic.Crc.CRC32 crc = new Ionic.Crc.CRC32();
// calc CRC on the buffer
crc.SlurpBlock(workitem.buffer, 0, workitem.inputBytesAvailable);
// deflate it
DeflateOneSegment(workitem);
// update status
workitem.crc = crc.Crc32Result;
TraceOutput(TraceBits.Compress,
"Compress wi({0}) ord({1}) len({2})",
workitem.index,
workitem.ordinal,
workitem.compressedBytesAvailable
);
lock(_latestLock)
{
if (workitem.ordinal > _latestCompressed)
_latestCompressed = workitem.ordinal;
}
lock (_toWrite)
{
_toWrite.Enqueue(workitem.index);
}
_newlyCompressedBlob.Set();
}
catch (System.Exception exc1)
{
lock(_eLock)
{
// expose the exception to the main thread
if (_pendingException!=null)
_pendingException = exc1;
}
}
}
private bool DeflateOneSegment(WorkItem workitem)
{
ZlibCodec compressor = workitem.compressor;
int rc= 0;
compressor.ResetDeflate();
compressor.NextIn = 0;
compressor.AvailableBytesIn = workitem.inputBytesAvailable;
// step 1: deflate the buffer
compressor.NextOut = 0;
compressor.AvailableBytesOut = workitem.compressed.Length;
do
{
compressor.Deflate(FlushType.None);
}
while (compressor.AvailableBytesIn > 0 || compressor.AvailableBytesOut == 0);
// step 2: flush (sync)
rc = compressor.Deflate(FlushType.Sync);
workitem.compressedBytesAvailable= (int) compressor.TotalBytesOut;
return true;
}
[System.Diagnostics.ConditionalAttribute("Trace")]
private void TraceOutput(TraceBits bits, string format, params object[] varParams)
{
if ((bits & _DesiredTrace) != 0)
{
lock(_outputLock)
{
int tid = Thread.CurrentThread.GetHashCode();
#if !SILVERLIGHT
// Console.ForegroundColor = (ConsoleColor) (tid % 8 + 8);
#endif
Console.Write("{0:000} PDOS ", tid);
Console.WriteLine(format, varParams);
#if !SILVERLIGHT
// Console.ResetColor();
#endif
}
}
}
// used only when Trace is defined
[Flags]
enum TraceBits : uint
{
None = 0,
NotUsed1 = 1,
EmitLock = 2,
EmitEnter = 4, // enter _EmitPending
EmitBegin = 8, // begin to write out
EmitDone = 16, // done writing out
EmitSkip = 32, // writer skipping a workitem
EmitAll = 58, // All Emit flags
Flush = 64,
Lifecycle = 128, // constructor/disposer
Session = 256, // Close/Reset
Synch = 512, // thread synchronization
Instance = 1024, // instance settings
Compress = 2048, // compress task
Write = 4096, // filling buffers, when caller invokes Write()
WriteEnter = 8192, // upon entry to Write()
WriteTake = 16384, // on _toFill.Take()
All = 0xffffffff,
}
/// <summary>
/// Indicates whether the stream supports Seek operations.
/// </summary>
/// <remarks>
/// Always returns false.
/// </remarks>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream supports Read operations.
/// </summary>
/// <remarks>
/// Always returns false.
/// </remarks>
public override bool CanRead
{
get {return false;}
}
/// <summary>
/// Indicates whether the stream supports Write operations.
/// </summary>
/// <remarks>
/// Returns true if the provided stream is writable.
/// </remarks>
public override bool CanWrite
{
get { return _outStream.CanWrite; }
}
/// <summary>
/// Reading this property always throws a NotSupportedException.
/// </summary>
public override long Length
{
get { throw new NotSupportedException(); }
}
/// <summary>
/// Returns the current position of the output stream.
/// </summary>
/// <remarks>
/// <para>
/// Because the output gets written by a background thread,
/// the value may change asynchronously. Setting this
/// property always throws a NotSupportedException.
/// </para>
/// </remarks>
public override long Position
{
get { return _outStream.Position; }
set { throw new NotSupportedException(); }
}
/// <summary>
/// This method always throws a NotSupportedException.
/// </summary>
/// <param name="buffer">
/// The buffer into which data would be read, IF THIS METHOD
/// ACTUALLY DID ANYTHING.
/// </param>
/// <param name="offset">
/// The offset within that data array at which to insert the
/// data that is read, IF THIS METHOD ACTUALLY DID
/// ANYTHING.
/// </param>
/// <param name="count">
/// The number of bytes to write, IF THIS METHOD ACTUALLY DID
/// ANYTHING.
/// </param>
/// <returns>nothing.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
/// <summary>
/// This method always throws a NotSupportedException.
/// </summary>
/// <param name="offset">
/// The offset to seek to....
/// IF THIS METHOD ACTUALLY DID ANYTHING.
/// </param>
/// <param name="origin">
/// The reference specifying how to apply the offset.... IF
/// THIS METHOD ACTUALLY DID ANYTHING.
/// </param>
/// <returns>nothing. It always throws.</returns>
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// This method always throws a NotSupportedException.
/// </summary>
/// <param name="value">
/// The new value for the stream length.... IF
/// THIS METHOD ACTUALLY DID ANYTHING.
/// </param>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
}
}
| |
// 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.Xml.Schema
{
using System;
using System.Collections;
using System.Globalization;
using System.Text;
using System.IO;
using System.Diagnostics;
internal sealed partial class Parser
{
private SchemaType _schemaType;
private XmlNameTable _nameTable;
private SchemaNames _schemaNames;
private ValidationEventHandler _eventHandler;
private XmlNamespaceManager _namespaceManager;
private XmlReader _reader;
private PositionInfo _positionInfo;
private bool _isProcessNamespaces;
private int _schemaXmlDepth = 0;
private int _markupDepth;
private SchemaBuilder _builder;
private XmlSchema _schema;
private SchemaInfo _xdrSchema;
private XmlResolver _xmlResolver = null; //to be used only by XDRBuilder
//xs:Annotation perf fix
private XmlDocument _dummyDocument;
private bool _processMarkup;
private XmlNode _parentNode;
private XmlNamespaceManager _annotationNSManager;
private string _xmlns;
//Whitespace check for text nodes
private XmlCharType _xmlCharType = XmlCharType.Instance;
public Parser(SchemaType schemaType, XmlNameTable nameTable, SchemaNames schemaNames, ValidationEventHandler eventHandler)
{
_schemaType = schemaType;
_nameTable = nameTable;
_schemaNames = schemaNames;
_eventHandler = eventHandler;
_xmlResolver = null;
_processMarkup = true;
_dummyDocument = new XmlDocument();
}
public SchemaType Parse(XmlReader reader, string targetNamespace)
{
StartParsing(reader, targetNamespace);
while (ParseReaderNode() && reader.Read()) { }
return FinishParsing();
}
public void StartParsing(XmlReader reader, string targetNamespace)
{
_reader = reader;
_positionInfo = PositionInfo.GetPositionInfo(reader);
_namespaceManager = reader.NamespaceManager;
if (_namespaceManager == null)
{
_namespaceManager = new XmlNamespaceManager(_nameTable);
_isProcessNamespaces = true;
}
else
{
_isProcessNamespaces = false;
}
while (reader.NodeType != XmlNodeType.Element && reader.Read()) { }
_markupDepth = int.MaxValue;
_schemaXmlDepth = reader.Depth;
SchemaType rootType = _schemaNames.SchemaTypeFromRoot(reader.LocalName, reader.NamespaceURI);
string code;
if (!CheckSchemaRoot(rootType, out code))
{
throw new XmlSchemaException(code, reader.BaseURI, _positionInfo.LineNumber, _positionInfo.LinePosition);
}
if (_schemaType == SchemaType.XSD)
{
_schema = new XmlSchema();
_schema.BaseUri = new Uri(reader.BaseURI, UriKind.RelativeOrAbsolute);
_builder = new XsdBuilder(reader, _namespaceManager, _schema, _nameTable, _schemaNames, _eventHandler);
}
else
{
Debug.Assert(_schemaType == SchemaType.XDR);
_xdrSchema = new SchemaInfo();
_xdrSchema.SchemaType = SchemaType.XDR;
_builder = new XdrBuilder(reader, _namespaceManager, _xdrSchema, targetNamespace, _nameTable, _schemaNames, _eventHandler);
((XdrBuilder)_builder).XmlResolver = _xmlResolver;
}
}
private bool CheckSchemaRoot(SchemaType rootType, out string code)
{
code = null;
if (_schemaType == SchemaType.None)
{
_schemaType = rootType;
}
switch (rootType)
{
case SchemaType.XSD:
if (_schemaType != SchemaType.XSD)
{
code = SR.Sch_MixSchemaTypes;
return false;
}
break;
case SchemaType.XDR:
if (_schemaType == SchemaType.XSD)
{
code = SR.Sch_XSDSchemaOnly;
return false;
}
else if (_schemaType != SchemaType.XDR)
{
code = SR.Sch_MixSchemaTypes;
return false;
}
break;
case SchemaType.DTD: //Did not detect schema type that can be parsed by this parser
case SchemaType.None:
code = SR.Sch_SchemaRootExpected;
if (_schemaType == SchemaType.XSD)
{
code = SR.Sch_XSDSchemaRootExpected;
}
return false;
default:
Debug.Assert(false);
break;
}
return true;
}
public SchemaType FinishParsing()
{
return _schemaType;
}
public XmlSchema XmlSchema
{
get { return _schema; }
}
internal XmlResolver XmlResolver
{
set
{
_xmlResolver = value;
}
}
public SchemaInfo XdrSchema
{
get { return _xdrSchema; }
}
public bool ParseReaderNode()
{
if (_reader.Depth > _markupDepth)
{
if (_processMarkup)
{
ProcessAppInfoDocMarkup(false);
}
return true;
}
else if (_reader.NodeType == XmlNodeType.Element)
{
if (_builder.ProcessElement(_reader.Prefix, _reader.LocalName, _reader.NamespaceURI))
{
_namespaceManager.PushScope();
if (_reader.MoveToFirstAttribute())
{
do
{
_builder.ProcessAttribute(_reader.Prefix, _reader.LocalName, _reader.NamespaceURI, _reader.Value);
if (Ref.Equal(_reader.NamespaceURI, _schemaNames.NsXmlNs) && _isProcessNamespaces)
{
_namespaceManager.AddNamespace(_reader.Prefix.Length == 0 ? string.Empty : _reader.LocalName, _reader.Value);
}
}
while (_reader.MoveToNextAttribute());
_reader.MoveToElement(); // get back to the element
}
_builder.StartChildren();
if (_reader.IsEmptyElement)
{
_namespaceManager.PopScope();
_builder.EndChildren();
if (_reader.Depth == _schemaXmlDepth)
{
return false; // done
}
}
else if (!_builder.IsContentParsed())
{ //AppInfo and Documentation
_markupDepth = _reader.Depth;
_processMarkup = true;
if (_annotationNSManager == null)
{
_annotationNSManager = new XmlNamespaceManager(_nameTable);
_xmlns = _nameTable.Add("xmlns");
}
ProcessAppInfoDocMarkup(true);
}
}
else if (!_reader.IsEmptyElement)
{ //UnsupportedElement in that context
_markupDepth = _reader.Depth;
_processMarkup = false; //Hack to not process unsupported elements
}
}
else if (_reader.NodeType == XmlNodeType.Text)
{ //Check for whitespace
if (!_xmlCharType.IsOnlyWhitespace(_reader.Value))
{
_builder.ProcessCData(_reader.Value);
}
}
else if (_reader.NodeType == XmlNodeType.EntityReference ||
_reader.NodeType == XmlNodeType.SignificantWhitespace ||
_reader.NodeType == XmlNodeType.CDATA)
{
_builder.ProcessCData(_reader.Value);
}
else if (_reader.NodeType == XmlNodeType.EndElement)
{
if (_reader.Depth == _markupDepth)
{
if (_processMarkup)
{
Debug.Assert(_parentNode != null);
XmlNodeList list = _parentNode.ChildNodes;
XmlNode[] markup = new XmlNode[list.Count];
for (int i = 0; i < list.Count; i++)
{
markup[i] = list[i];
}
_builder.ProcessMarkup(markup);
_namespaceManager.PopScope();
_builder.EndChildren();
}
_markupDepth = int.MaxValue;
}
else
{
_namespaceManager.PopScope();
_builder.EndChildren();
}
if (_reader.Depth == _schemaXmlDepth)
{
return false; // done
}
}
return true;
}
private void ProcessAppInfoDocMarkup(bool root)
{
//First time reader is positioned on AppInfo or Documentation element
XmlNode currentNode = null;
switch (_reader.NodeType)
{
case XmlNodeType.Element:
_annotationNSManager.PushScope();
currentNode = LoadElementNode(root);
// Dev10 (TFS) #479761: The following code was to address the issue of where an in-scope namespace delaration attribute
// was not added when an element follows an empty element. This fix will result in persisting schema in a consistent form
// although it does not change the semantic meaning of the schema.
// Since it is as a breaking change and Dev10 needs to maintain the backward compatibility, this fix is being reverted.
// if (reader.IsEmptyElement) {
// annotationNSManager.PopScope();
// }
break;
case XmlNodeType.Text:
currentNode = _dummyDocument.CreateTextNode(_reader.Value);
goto default;
case XmlNodeType.SignificantWhitespace:
currentNode = _dummyDocument.CreateSignificantWhitespace(_reader.Value);
goto default;
case XmlNodeType.CDATA:
currentNode = _dummyDocument.CreateCDataSection(_reader.Value);
goto default;
case XmlNodeType.EntityReference:
currentNode = _dummyDocument.CreateEntityReference(_reader.Name);
goto default;
case XmlNodeType.Comment:
currentNode = _dummyDocument.CreateComment(_reader.Value);
goto default;
case XmlNodeType.ProcessingInstruction:
currentNode = _dummyDocument.CreateProcessingInstruction(_reader.Name, _reader.Value);
goto default;
case XmlNodeType.EndEntity:
break;
case XmlNodeType.Whitespace:
break;
case XmlNodeType.EndElement:
_annotationNSManager.PopScope();
_parentNode = _parentNode.ParentNode;
break;
default: //other possible node types: Document/DocType/DocumentFrag/Entity/Notation/Xmldecl cannot appear as children of xs:appInfo or xs:doc
Debug.Assert(currentNode != null);
Debug.Assert(_parentNode != null);
_parentNode.AppendChild(currentNode);
break;
}
}
private XmlElement LoadElementNode(bool root)
{
Debug.Assert(_reader.NodeType == XmlNodeType.Element);
XmlReader r = _reader;
bool fEmptyElement = r.IsEmptyElement;
XmlElement element = _dummyDocument.CreateElement(r.Prefix, r.LocalName, r.NamespaceURI);
element.IsEmpty = fEmptyElement;
if (root)
{
_parentNode = element;
}
else
{
XmlAttributeCollection attributes = element.Attributes;
if (r.MoveToFirstAttribute())
{
do
{
if (Ref.Equal(r.NamespaceURI, _schemaNames.NsXmlNs))
{ //Namespace Attribute
_annotationNSManager.AddNamespace(r.Prefix.Length == 0 ? string.Empty : _reader.LocalName, _reader.Value);
}
XmlAttribute attr = LoadAttributeNode();
attributes.Append(attr);
} while (r.MoveToNextAttribute());
}
r.MoveToElement();
string ns = _annotationNSManager.LookupNamespace(r.Prefix);
if (ns == null)
{
XmlAttribute attr = CreateXmlNsAttribute(r.Prefix, _namespaceManager.LookupNamespace(r.Prefix));
attributes.Append(attr);
}
else if (ns.Length == 0)
{ //string.Empty prefix is mapped to string.Empty NS by default
string elemNS = _namespaceManager.LookupNamespace(r.Prefix);
if (elemNS != string.Empty)
{
XmlAttribute attr = CreateXmlNsAttribute(r.Prefix, elemNS);
attributes.Append(attr);
}
}
while (r.MoveToNextAttribute())
{
if (r.Prefix.Length != 0)
{
string attNS = _annotationNSManager.LookupNamespace(r.Prefix);
if (attNS == null)
{
XmlAttribute attr = CreateXmlNsAttribute(r.Prefix, _namespaceManager.LookupNamespace(r.Prefix));
attributes.Append(attr);
}
}
}
r.MoveToElement();
_parentNode.AppendChild(element);
if (!r.IsEmptyElement)
{
_parentNode = element;
}
}
return element;
}
private XmlAttribute CreateXmlNsAttribute(string prefix, string value)
{
XmlAttribute attr;
if (prefix.Length == 0)
{
attr = _dummyDocument.CreateAttribute(string.Empty, _xmlns, XmlReservedNs.NsXmlNs);
}
else
{
attr = _dummyDocument.CreateAttribute(_xmlns, prefix, XmlReservedNs.NsXmlNs);
}
attr.AppendChild(_dummyDocument.CreateTextNode(value));
_annotationNSManager.AddNamespace(prefix, value);
return attr;
}
private XmlAttribute LoadAttributeNode()
{
Debug.Assert(_reader.NodeType == XmlNodeType.Attribute);
XmlReader r = _reader;
XmlAttribute attr = _dummyDocument.CreateAttribute(r.Prefix, r.LocalName, r.NamespaceURI);
while (r.ReadAttributeValue())
{
switch (r.NodeType)
{
case XmlNodeType.Text:
attr.AppendChild(_dummyDocument.CreateTextNode(r.Value));
continue;
case XmlNodeType.EntityReference:
attr.AppendChild(LoadEntityReferenceInAttribute());
continue;
default:
throw XmlLoader.UnexpectedNodeType(r.NodeType);
}
}
return attr;
}
private XmlEntityReference LoadEntityReferenceInAttribute()
{
Debug.Assert(_reader.NodeType == XmlNodeType.EntityReference);
XmlEntityReference eref = _dummyDocument.CreateEntityReference(_reader.LocalName);
if (!_reader.CanResolveEntity)
{
return eref;
}
_reader.ResolveEntity();
while (_reader.ReadAttributeValue())
{
switch (_reader.NodeType)
{
case XmlNodeType.Text:
eref.AppendChild(_dummyDocument.CreateTextNode(_reader.Value));
continue;
case XmlNodeType.EndEntity:
if (eref.ChildNodes.Count == 0)
{
eref.AppendChild(_dummyDocument.CreateTextNode(String.Empty));
}
return eref;
case XmlNodeType.EntityReference:
eref.AppendChild(LoadEntityReferenceInAttribute());
break;
default:
throw XmlLoader.UnexpectedNodeType(_reader.NodeType);
}
}
return eref;
}
};
} // namespace System.Xml
| |
// Copyright 2017 (c) [Denis Da Silva]. All rights reserved.
// See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Prolix.Data;
using Prolix.Domain;
namespace Prolix.Logic
{
/// <summary>
/// Business service for read-only repository with numeric Id.
/// This service works with <seealso cref="IDbContext"/> from the data layer.
/// Most of times the database context is managed by an Ioc container, implemented from <see cref="Resolver" />
/// </summary>
/// <typeparam name="TM">The model type</typeparam>
/// <typeparam name="TC">The daabase context type</typeparam>
public abstract class RepositoryService<TM, TC> : RepositoryService<TM, int, TC>
where TM : class, IIdentifiable
where TC : class, IDbContext
{
public RepositoryService(TC context) : base(context)
{
}
}
/// <summary>
/// Business service for read-only repository with generic Id.
/// This service works with <seealso cref="IDbContext"/> from the data layer.
/// Most of times the database context is managed by an Ioc container, implemented from <see cref="Resolver" />
/// </summary>
/// <typeparam name="TM">The model type</typeparam>
/// <typeparam name="TK">The model Id type</typeparam>
/// <typeparam name="TC">The database context type</typeparam>
public abstract class RepositoryService<TM, TK, TC> : IRepositoryService<TM, TK>
where TM : class, IIdentifiable<TK>
where TK : struct, IComparable<TK>, IEquatable<TK>
where TC : class, IDbContext
{
#region Constructors
/// <summary>
/// Creates a new <see cref="RepositoryService{TM, TK, TC}"/>
/// </summary>
/// <param name="context">The database context</param>
public RepositoryService(TC context)
{
Context = context;
}
#endregion
#region Properties
/// <summary>
/// The database context
/// </summary>
protected TC Context { get; }
/// <summary>
/// The model entity set
/// </summary>
protected IEntitySet<TM> Set => Context?.Set<TM>();
/// <summary>
/// The rule validation instance
/// </summary>
public RuleValidation Rule { get; } = new RuleValidation();
#endregion
#region Public Methods
/// <summary>
/// Gets the first ocurrence of the specificed criteria.
/// </summary>
/// <param name="criteria">Criteria expression.</param>
/// <returns>The first ocurrence of the model, or null, if the criteria doesn't match.</returns>
public virtual TM Get(Expression<Func<TM, bool>> criteria)
{
return Set.FirstOrDefault(criteria);
}
/// <summary>
/// Gets a model based on its Id.
/// </summary>
/// <param name="id">The model Id</param>
/// <returns>The first ocurrence of the model, or null, if the model doesn't exist.</returns>
public virtual TM Get(TK id)
{
return Set.FirstOrDefault(i => i.Id.Equals(id));
}
/// <summary>
/// Gets all ocurrences of a model from the database.
/// </summary>
public virtual IQueryable<TM> List()
{
return Set;
}
/// <summary>
/// Gets all ocurrences of the specificed criteria.
/// </summary>
/// <param name="criteria">Criteria expression.</param>
/// <returns>All ocurrences of the model, or a empty list, if the criteria doesn't match.</returns>
public virtual IQueryable<TM> Find(Expression<Func<TM, bool>> criteria)
{
return Set.Where(criteria);
}
/// <summary>
/// Checks if a model exists in the database based on its Id.
/// </summary>
/// <param name="id">The model Id</param>
/// <returns>TRUE if the model exists. Otherwise FALSE.</returns>
public virtual bool Exists(TK id)
{
return Exists(i => id.Equals(i.Id));
}
/// <summary>
/// Checks if a model exists in the database based on given criteria.
/// </summary>
/// <param name="criteria">Criteria expression.</param>
/// <returns>TRUE if the model exists. Otherwise FALSE.</returns>
public virtual bool Exists(Expression<Func<TM, bool>> criteria)
{
return Set.Any(criteria);
}
/// <summary>
/// Checks if other model exists in the database based on its Id.
/// This method is useful when trying to query other models without instantiating other services.
/// </summary>
/// <param name="id">The model Id</param>
/// <typeparam name="T">The target model type</typeparam>
/// <returns>TRUE if the model exists. Otherwise FALSE.</returns>
public bool Exists<T>(TK? id)
where T : class, IIdentifiable
{
if (id == null || !id.HasValue)
return false;
var value = id.Value;
var set = Context.Set<T>();
if (set == null)
return false;
return set.Any(i => value.Equals(i.Id));
}
/// <summary>
/// Adds a model to the database
/// </summary>
/// <param name="model">The model to be saved</param>
async public virtual Task Add(TM model)
{
if (model == null)
throw new ArgumentNullException(nameof(model));
Set.Add(model);
await Context.SaveChanges();
}
/// <summary>
/// Updates a model
/// </summary>
/// <param name="model">The model to be saved</param>
/// <returns>True if data has been changed in the database.</returns>
async public virtual Task<bool> Update(TM model)
{
if (model == null)
throw new ArgumentNullException(nameof(model));
var existing = Get(model.Id);
if (existing == null)
throw new ArgumentOutOfRangeException(nameof(model), "The model does not exists in the database.");
Set.Update(model, existing);
int affected = await Context.SaveChanges();
return affected > 0;
}
/// <summary>
/// Deletes a model from the database
/// </summary>
/// <param name="id">The Id of the model to be saved</param>
/// <returns>True if data has been deleted in the database.</returns>
async public virtual Task<bool> Delete(TK id)
{
var model = Get(id);
return await Delete(model);
}
/// <summary>
/// Deletes a model from the database
/// </summary>
/// <param name="model">The model to be saved</param>
/// <returns>True if data has been deleted in the database.</returns>
async public virtual Task<bool> Delete(TM model)
{
if (model == null)
throw new ArgumentNullException(nameof(model));
Set.Remove(model);
int affected = await Context.SaveChanges();
return affected > 0;
}
#endregion
#region Protected Methods
/// <summary>
/// Check if there are errors on <see cref="RuleValidation" />.
/// If yes, throws a <see cref="RuleException"/>
/// </summary>
/// <param name="message">Parent error message.</param>
protected void CheckRule(string message)
{
Rule?.Check(message);
}
/// <summary>
/// Check if there are errors on <see cref="RuleValidation" />.
/// If yes, throws a <see cref="RuleException"/>
/// </summary>
protected void CheckRule()
{
CheckRule(RuleValidation.DefaultMessage);
}
/// <summary>
/// Validates an entity againt it's descriptor
/// </summary>
/// <param name="entity">The entity model</param>
/// <param name="errorMessage">The error message to be displayed</param>
/// <returns>True if no broken rules were found.</returns>
protected bool Validate(TM entity, string errorMessage = null)
{
// Create a RuleValidation object
RuleValidation rule = Validate<TM>(entity);
Rule.Merge(rule);
if (!string.IsNullOrWhiteSpace(errorMessage))
{
Rule.Check(errorMessage);
}
return !Rule.HasErrors();
}
/// <summary>
/// Validates an entity againt it's descriptor
/// </summary>
/// <typeparam name="T">The Model Model type</typeparam>
/// <param name="entity">The entity model</param>
/// <param name="errorMessage">The error message to be displayed</param>
/// <returns>The resulting RuleValidation object</returns>
protected RuleValidation Validate<T>(T entity, string errorMessage = null)
where T : class
{
RuleValidation result = new RuleValidation();
ModelDescriptor<T> descriptor = DescriptorManager.Get<T>();
if (descriptor == null)
return result;
// Create a RuleValidation object
RuleValidation rule = descriptor.Build(entity);
if (!string.IsNullOrWhiteSpace(errorMessage))
{
rule.Check(errorMessage);
}
return rule;
}
#endregion
}
}
| |
using UnityEngine;
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Generic;
namespace Stratus
{
/// <summary>
/// A Variant is a dynamic value type which represent a variety of types.
/// It can be used in situtations where you need a common interface
/// for your types to represent a variety of data.
/// </summary>
[Serializable]
public struct StratusVariant
{
//--------------------------------------------------------------------/
// Declarations
//--------------------------------------------------------------------/
public enum VariantType
{
Integer, Boolean, Float, String, Vector3
}
//--------------------------------------------------------------------/
// Fields
//--------------------------------------------------------------------/
//[FieldOffset(0), SerializeField]
[SerializeField]
private VariantType type;
//[FieldOffset(4), SerializeField]
[SerializeField]
private int integerValue;
//[FieldOffset(4), SerializeField]
[SerializeField]
private float floatValue;
//[FieldOffset(4), SerializeField]
[SerializeField]
private bool booleanValue;
//[FieldOffset(4), SerializeField]
[SerializeField]
private Vector3 vector3Value;
//[FieldOffset(16), SerializeField]
[SerializeField]
private string stringValue;
//--------------------------------------------------------------------/
// Properties
//--------------------------------------------------------------------/
/// <summary>
/// Retrieves the current type of this Variant
/// </summary>
public VariantType currentType { get { return type; } }
//--------------------------------------------------------------------/
// Constructors
//--------------------------------------------------------------------/
public StratusVariant(int value) : this()
{
type = VariantType.Integer;
this.integerValue = value;
}
public StratusVariant(float value) : this()
{
type = VariantType.Float;
this.floatValue = value;
}
public StratusVariant(bool value) : this()
{
type = VariantType.Boolean;
this.booleanValue = value;
}
public StratusVariant(string value) : this()
{
type = VariantType.String;
this.stringValue = value;
}
public StratusVariant(Vector3 value) : this()
{
type = VariantType.Vector3;
this.vector3Value = value;
}
public StratusVariant(StratusVariant variant) : this()
{
type = variant.type;
this.Set(variant.Get());
}
//--------------------------------------------------------------------/
// Static Methods
//--------------------------------------------------------------------/
/// <summary>
/// Constructs a variant based from a given value. It only accepts supported types,
/// which are found in the Types enum.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static StratusVariant Make<T>(T value)
{
var type = typeof(T);
if (type == typeof(int))
return new StratusVariant((int)(object)value);
else if (type == typeof(float))
return new StratusVariant((float)(object)value);
else if (type == typeof(bool))
return new StratusVariant((bool)(object)value);
else if (type == typeof(string))
return new StratusVariant((string)(object)value);
else if (type == typeof(Vector3))
return new StratusVariant((Vector3)(object)value);
throw new Exception("Unsupported type being used (" + type.Name + ")");
}
//public static bool IsInteger(Type type) => (type == typeof(int) && this.type == Types.Integer)
//--------------------------------------------------------------------/
// Methods: Accessors - Generic
//--------------------------------------------------------------------/
/// <summary>
/// Gets the current value of this variant
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T Get<T>()
{
var givenType = typeof(T);
if (!Match(givenType))
throw new ArgumentException("The provided type '" + givenType.Name + "' is not the correct type for this value (" + this.type.ToString() + ")");
object value = null;
switch (this.type)
{
case VariantType.Integer:
value = integerValue;
break;
case VariantType.Boolean:
value = booleanValue;
break;
case VariantType.Float:
value = floatValue;
break;
case VariantType.String:
value = stringValue;
break;
case VariantType.Vector3:
value = vector3Value;
break;
}
return (T)Convert.ChangeType(value, typeof(T));
}
/// <summary>
/// Gets the current value of this variant
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public object Get()
{
object value = null;
switch (type)
{
case VariantType.Integer:
value = integerValue;
break;
case VariantType.Boolean:
value = booleanValue;
break;
case VariantType.Float:
value = floatValue;
break;
case VariantType.String:
value = stringValue;
break;
case VariantType.Vector3:
value = vector3Value;
break;
}
return value;
}
/// <summary>
/// Sets the current value of this variant, by deducing the given value type
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public void Set(object value)
{
var givenType = value.GetType();
if (!Match(givenType))
throw new ArgumentException("The provided type '" + givenType.Name + "' is not the correct type for this value (" + this.type.ToString() + ")");
switch (type)
{
case VariantType.Integer:
integerValue = (int)value;
break;
case VariantType.Boolean:
booleanValue = (bool)value;
break;
case VariantType.Float:
floatValue = (float)value;
break;
case VariantType.String:
stringValue = value as string;
break;
case VariantType.Vector3:
vector3Value = (Vector3)value;
break;
}
}
//--------------------------------------------------------------------/
// Methods: Accessors - Specific
//--------------------------------------------------------------------/
public void SetInteger(int value)
{
if (type != VariantType.Integer)
throw new ArgumentException("This variant has not been set as an integer type");
integerValue = value;
}
public int GetInteger()
{
if (type != VariantType.Integer)
throw new ArgumentException("This variant has not been set as an integer type");
return integerValue;
}
public void SetFloat(float value)
{
if (type != VariantType.Float)
throw new ArgumentException("This variant has not been set as a float type");
floatValue = value;
}
public float GetFloat()
{
if (type != VariantType.Integer)
throw new ArgumentException("This variant has not been set as a float type");
return floatValue;
}
public void SetString(string value)
{
if (type != VariantType.String)
throw new ArgumentException("This variant has not been set as a string type");
stringValue = value;
}
public string GetString()
{
if (type != VariantType.String)
throw new ArgumentException("This variant has not been set as a string type");
return stringValue;
}
public void SetBool(bool value)
{
if (type != VariantType.Boolean)
throw new ArgumentException("This variant has not been set as a boolean type");
booleanValue = value;
}
public bool GetBool()
{
if (type != VariantType.Boolean)
throw new ArgumentException("This variant has not been set as a boolean type");
return booleanValue;
}
public void SetVector3(Vector3 value)
{
if (type != VariantType.Vector3)
throw new ArgumentException("This variant has not been set as a Vector3 type");
vector3Value = value;
}
public Vector3 GetVector3()
{
if (type != VariantType.Vector3)
throw new ArgumentException("This variant has not been set as a Vector3 type");
return vector3Value;
}
//--------------------------------------------------------------------/
// Methods: Helper
//--------------------------------------------------------------------/
/// <summary>
/// Prints the current value of this variant
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public override string ToString()
{
var builder = new StringBuilder();
switch (this.type)
{
case VariantType.Integer:
builder.Append(integerValue.ToString());
break;
case VariantType.Float:
builder.Append(floatValue.ToString());
break;
case VariantType.Boolean:
builder.Append(booleanValue.ToString());
break;
case VariantType.String:
builder.Append(stringValue);
break;
case VariantType.Vector3:
builder.Append(vector3Value.ToString());
break;
}
return builder.ToString();
}
/// <summary>
/// Compares the value of this variant with another
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Compare(StratusVariant other)
{
if (this.type != other.type)
throw new Exception("Mismatching variants are being compared!");
switch (other.type)
{
case VariantType.Boolean:
return this.booleanValue == other.booleanValue;
case VariantType.Integer:
return this.integerValue == other.integerValue;
case VariantType.Float:
return this.floatValue == other.floatValue;
case VariantType.String:
return this.stringValue == other.stringValue;
case VariantType.Vector3:
return this.vector3Value == other.vector3Value;
}
throw new Exception("Wrong type?");
}
/// <summary>
/// Checks whether the given type matches that of the variant
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private bool Match(Type type)
{
VariantType givenVariantType = VariantUtilities.Convert(type);
return givenVariantType == this.type;
}
}
public static class VariantUtilities
{
private static Dictionary<Type, StratusVariant.VariantType> systemTypeToVariantType { get; } = new Dictionary<Type, StratusVariant.VariantType>()
{
{typeof(int), StratusVariant.VariantType.Integer},
{typeof(bool), StratusVariant.VariantType.Boolean},
{typeof(float), StratusVariant.VariantType.Float},
{typeof(string), StratusVariant.VariantType.String},
{typeof(Vector3), StratusVariant.VariantType.Vector3},
};
private static Dictionary<StratusVariant.VariantType, Type> variantTypeToSystemType { get; } = new Dictionary<StratusVariant.VariantType, Type>()
{
{StratusVariant.VariantType.Integer, typeof(int)},
{StratusVariant.VariantType.Boolean, typeof(bool)},
{StratusVariant.VariantType.Float, typeof(float)},
{StratusVariant.VariantType.String, typeof(string)},
{StratusVariant.VariantType.Vector3, typeof(Vector3)},
};
public static Type Convert(this StratusVariant.VariantType type) => variantTypeToSystemType[type];
public static StratusVariant.VariantType Convert(Type type) => systemTypeToVariantType[type];
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Versions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal partial class SolutionCrawlerRegistrationService
{
private partial class WorkCoordinator
{
private const int MinimumDelayInMS = 50;
private readonly Registration _registration;
private readonly LogAggregator _logAggregator;
private readonly IAsynchronousOperationListener _listener;
private readonly IOptionService _optionService;
private readonly CancellationTokenSource _shutdownNotificationSource;
private readonly CancellationToken _shutdownToken;
private readonly SimpleTaskQueue _eventProcessingQueue;
// points to processor task
private readonly IncrementalAnalyzerProcessor _documentAndProjectWorkerProcessor;
private readonly SemanticChangeProcessor _semanticChangeProcessor;
public WorkCoordinator(
IAsynchronousOperationListener listener,
IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders,
Registration registration)
{
_logAggregator = new LogAggregator();
_registration = registration;
_listener = listener;
_optionService = _registration.GetService<IOptionService>();
// event and worker queues
_shutdownNotificationSource = new CancellationTokenSource();
_shutdownToken = _shutdownNotificationSource.Token;
_eventProcessingQueue = new SimpleTaskQueue(TaskScheduler.Default);
var activeFileBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.ActiveFileWorkerBackOffTimeSpanInMS);
var allFilesWorkerBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.AllFilesWorkerBackOffTimeSpanInMS);
var entireProjectWorkerBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.EntireProjectWorkerBackOffTimeSpanInMS);
_documentAndProjectWorkerProcessor = new IncrementalAnalyzerProcessor(
listener, analyzerProviders, _registration,
activeFileBackOffTimeSpanInMS, allFilesWorkerBackOffTimeSpanInMS, entireProjectWorkerBackOffTimeSpanInMS, _shutdownToken);
var semanticBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.SemanticChangeBackOffTimeSpanInMS);
var projectBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.ProjectPropagationBackOffTimeSpanInMS);
_semanticChangeProcessor = new SemanticChangeProcessor(listener, _registration, _documentAndProjectWorkerProcessor, semanticBackOffTimeSpanInMS, projectBackOffTimeSpanInMS, _shutdownToken);
// if option is on
if (_optionService.GetOption(InternalSolutionCrawlerOptions.SolutionCrawler))
{
_registration.Workspace.WorkspaceChanged += OnWorkspaceChanged;
_registration.Workspace.DocumentOpened += OnDocumentOpened;
_registration.Workspace.DocumentClosed += OnDocumentClosed;
}
// subscribe to option changed event after all required fields are set
// otherwise, we can get null exception when running OnOptionChanged handler
_optionService.OptionChanged += OnOptionChanged;
}
public int CorrelationId
{
get { return _registration.CorrelationId; }
}
public void AddAnalyzer(IIncrementalAnalyzer analyzer, bool highPriorityForActiveFile)
{
// add analyzer
_documentAndProjectWorkerProcessor.AddAnalyzer(analyzer, highPriorityForActiveFile);
// and ask to re-analyze whole solution for the given analyzer
var set = _registration.CurrentSolution.Projects.SelectMany(p => p.DocumentIds).ToSet();
Reanalyze(analyzer, set);
}
public void Shutdown(bool blockingShutdown)
{
_optionService.OptionChanged -= OnOptionChanged;
// detach from the workspace
_registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged;
_registration.Workspace.DocumentOpened -= OnDocumentOpened;
_registration.Workspace.DocumentClosed -= OnDocumentClosed;
// cancel any pending blocks
_shutdownNotificationSource.Cancel();
_documentAndProjectWorkerProcessor.Shutdown();
SolutionCrawlerLogger.LogWorkCoordinatorShutdown(CorrelationId, _logAggregator);
if (blockingShutdown)
{
var shutdownTask = Task.WhenAll(
_eventProcessingQueue.LastScheduledTask,
_documentAndProjectWorkerProcessor.AsyncProcessorTask,
_semanticChangeProcessor.AsyncProcessorTask);
shutdownTask.Wait(TimeSpan.FromSeconds(5));
if (!shutdownTask.IsCompleted)
{
SolutionCrawlerLogger.LogWorkCoordinatorShutdownTimeout(CorrelationId);
}
}
}
private void OnOptionChanged(object sender, OptionChangedEventArgs e)
{
// if solution crawler got turned off or on.
if (e.Option == InternalSolutionCrawlerOptions.SolutionCrawler)
{
var value = (bool)e.Value;
if (value)
{
_registration.Workspace.WorkspaceChanged += OnWorkspaceChanged;
_registration.Workspace.DocumentOpened += OnDocumentOpened;
_registration.Workspace.DocumentClosed += OnDocumentClosed;
}
else
{
_registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged;
_registration.Workspace.DocumentOpened -= OnDocumentOpened;
_registration.Workspace.DocumentClosed -= OnDocumentClosed;
}
SolutionCrawlerLogger.LogOptionChanged(CorrelationId, value);
return;
}
// Changing the UseV2Engine option is a no-op as we have a single engine now.
if (e.Option == Diagnostics.InternalDiagnosticsOptions.UseDiagnosticEngineV2)
{
_documentAndProjectWorkerProcessor.ChangeDiagnosticsEngine((bool)e.Value);
}
ReanalyzeOnOptionChange(sender, e);
}
private void ReanalyzeOnOptionChange(object sender, OptionChangedEventArgs e)
{
// otherwise, let each analyzer decide what they want on option change
ISet<DocumentId> set = null;
foreach (var analyzer in _documentAndProjectWorkerProcessor.Analyzers)
{
if (analyzer.NeedsReanalysisOnOptionChanged(sender, e))
{
set = set ?? _registration.CurrentSolution.Projects.SelectMany(p => p.DocumentIds).ToSet();
this.Reanalyze(analyzer, set);
}
}
}
public void Reanalyze(IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds, bool highPriority = false)
{
var asyncToken = _listener.BeginAsyncOperation("Reanalyze");
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAsync(analyzer, documentIds, highPriority), _shutdownToken).CompletesAsyncOperation(asyncToken);
SolutionCrawlerLogger.LogReanalyze(CorrelationId, analyzer, documentIds, highPriority);
}
private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs args)
{
// guard us from cancellation
try
{
ProcessEvents(args, _listener.BeginAsyncOperation("OnWorkspaceChanged"));
}
catch (OperationCanceledException oce)
{
if (NotOurShutdownToken(oce))
{
throw;
}
// it is our cancellation, ignore
}
catch (AggregateException ae)
{
ae = ae.Flatten();
// If we had a mix of exceptions, don't eat it
if (ae.InnerExceptions.Any(e => !(e is OperationCanceledException)) ||
ae.InnerExceptions.Cast<OperationCanceledException>().Any(NotOurShutdownToken))
{
// We had a cancellation with a different token, so don't eat it
throw;
}
// it is our cancellation, ignore
}
}
private bool NotOurShutdownToken(OperationCanceledException oce)
{
return oce.CancellationToken == _shutdownToken;
}
private void ProcessEvents(WorkspaceChangeEventArgs args, IAsyncToken asyncToken)
{
SolutionCrawlerLogger.LogWorkspaceEvent(_logAggregator, (int)args.Kind);
// TODO: add telemetry that record how much it takes to process an event (max, min, average and etc)
switch (args.Kind)
{
case WorkspaceChangeKind.SolutionAdded:
case WorkspaceChangeKind.SolutionChanged:
case WorkspaceChangeKind.SolutionReloaded:
case WorkspaceChangeKind.SolutionRemoved:
case WorkspaceChangeKind.SolutionCleared:
ProcessSolutionEvent(args, asyncToken);
break;
case WorkspaceChangeKind.ProjectAdded:
case WorkspaceChangeKind.ProjectChanged:
case WorkspaceChangeKind.ProjectReloaded:
case WorkspaceChangeKind.ProjectRemoved:
ProcessProjectEvent(args, asyncToken);
break;
case WorkspaceChangeKind.DocumentAdded:
case WorkspaceChangeKind.DocumentReloaded:
case WorkspaceChangeKind.DocumentChanged:
case WorkspaceChangeKind.DocumentRemoved:
case WorkspaceChangeKind.AdditionalDocumentAdded:
case WorkspaceChangeKind.AdditionalDocumentRemoved:
case WorkspaceChangeKind.AdditionalDocumentChanged:
case WorkspaceChangeKind.AdditionalDocumentReloaded:
ProcessDocumentEvent(args, asyncToken);
break;
default:
throw ExceptionUtilities.Unreachable;
}
}
private void OnDocumentOpened(object sender, DocumentEventArgs e)
{
var asyncToken = _listener.BeginAsyncOperation("OnDocumentOpened");
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAsync(e.Document, InvocationReasons.DocumentOpened), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void OnDocumentClosed(object sender, DocumentEventArgs e)
{
var asyncToken = _listener.BeginAsyncOperation("OnDocumentClosed");
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAsync(e.Document, InvocationReasons.DocumentClosed), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void ProcessDocumentEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken)
{
switch (e.Kind)
{
case WorkspaceChangeKind.DocumentAdded:
EnqueueEvent(e.NewSolution, e.DocumentId, InvocationReasons.DocumentAdded, asyncToken);
break;
case WorkspaceChangeKind.DocumentRemoved:
EnqueueEvent(e.OldSolution, e.DocumentId, InvocationReasons.DocumentRemoved, asyncToken);
break;
case WorkspaceChangeKind.DocumentReloaded:
case WorkspaceChangeKind.DocumentChanged:
EnqueueEvent(e.OldSolution, e.NewSolution, e.DocumentId, asyncToken);
break;
case WorkspaceChangeKind.AdditionalDocumentAdded:
case WorkspaceChangeKind.AdditionalDocumentRemoved:
case WorkspaceChangeKind.AdditionalDocumentChanged:
case WorkspaceChangeKind.AdditionalDocumentReloaded:
// If an additional file has changed we need to reanalyze the entire project.
EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.AdditionalDocumentChanged, asyncToken);
break;
default:
throw ExceptionUtilities.Unreachable;
}
}
private void ProcessProjectEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken)
{
switch (e.Kind)
{
case WorkspaceChangeKind.ProjectAdded:
OnProjectAdded(e.NewSolution.GetProject(e.ProjectId));
EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.DocumentAdded, asyncToken);
break;
case WorkspaceChangeKind.ProjectRemoved:
EnqueueEvent(e.OldSolution, e.ProjectId, InvocationReasons.DocumentRemoved, asyncToken);
break;
case WorkspaceChangeKind.ProjectChanged:
case WorkspaceChangeKind.ProjectReloaded:
EnqueueEvent(e.OldSolution, e.NewSolution, e.ProjectId, asyncToken);
break;
default:
throw ExceptionUtilities.Unreachable;
}
}
private void ProcessSolutionEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken)
{
switch (e.Kind)
{
case WorkspaceChangeKind.SolutionAdded:
OnSolutionAdded(e.NewSolution);
EnqueueEvent(e.NewSolution, InvocationReasons.DocumentAdded, asyncToken);
break;
case WorkspaceChangeKind.SolutionRemoved:
EnqueueEvent(e.OldSolution, InvocationReasons.SolutionRemoved, asyncToken);
break;
case WorkspaceChangeKind.SolutionCleared:
EnqueueEvent(e.OldSolution, InvocationReasons.DocumentRemoved, asyncToken);
break;
case WorkspaceChangeKind.SolutionChanged:
case WorkspaceChangeKind.SolutionReloaded:
EnqueueEvent(e.OldSolution, e.NewSolution, asyncToken);
break;
default:
throw ExceptionUtilities.Unreachable;
}
}
private void OnSolutionAdded(Solution solution)
{
var asyncToken = _listener.BeginAsyncOperation("OnSolutionAdded");
_eventProcessingQueue.ScheduleTask(() =>
{
var semanticVersionTrackingService = solution.Workspace.Services.GetService<ISemanticVersionTrackingService>();
if (semanticVersionTrackingService != null)
{
semanticVersionTrackingService.LoadInitialSemanticVersions(solution);
}
}, _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void OnProjectAdded(Project project)
{
var asyncToken = _listener.BeginAsyncOperation("OnProjectAdded");
_eventProcessingQueue.ScheduleTask(() =>
{
var semanticVersionTrackingService = project.Solution.Workspace.Services.GetService<ISemanticVersionTrackingService>();
if (semanticVersionTrackingService != null)
{
semanticVersionTrackingService.LoadInitialSemanticVersions(project);
}
}, _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution oldSolution, Solution newSolution, IAsyncToken asyncToken)
{
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAsync(oldSolution, newSolution), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution solution, InvocationReasons invocationReasons, IAsyncToken asyncToken)
{
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemForSolutionAsync(solution, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution oldSolution, Solution newSolution, ProjectId projectId, IAsyncToken asyncToken)
{
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, projectId), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution solution, ProjectId projectId, InvocationReasons invocationReasons, IAsyncToken asyncToken)
{
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution solution, DocumentId documentId, InvocationReasons invocationReasons, IAsyncToken asyncToken)
{
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemForDocumentAsync(solution, documentId, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution oldSolution, Solution newSolution, DocumentId documentId, IAsyncToken asyncToken)
{
// document changed event is the special one.
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, documentId), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private async Task EnqueueWorkItemAsync(Document document, InvocationReasons invocationReasons, SyntaxNode changedMember = null)
{
// we are shutting down
_shutdownToken.ThrowIfCancellationRequested();
var priorityService = document.GetLanguageService<IWorkCoordinatorPriorityService>();
var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(document, _shutdownToken).ConfigureAwait(false);
var currentMember = GetSyntaxPath(changedMember);
// call to this method is serialized. and only this method does the writing.
_documentAndProjectWorkerProcessor.Enqueue(
new WorkItem(document.Id, document.Project.Language, invocationReasons,
isLowPriority, currentMember, _listener.BeginAsyncOperation("WorkItem")));
// enqueue semantic work planner
if (invocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged))
{
// must use "Document" here so that the snapshot doesn't go away. we need the snapshot to calculate p2p dependency graph later.
// due to this, we might hold onto solution (and things kept alive by it) little bit longer than usual.
_semanticChangeProcessor.Enqueue(document, currentMember);
}
}
private SyntaxPath GetSyntaxPath(SyntaxNode changedMember)
{
// using syntax path might be too expansive since it will be created on every keystroke.
// but currently, we have no other way to track a node between two different tree (even for incrementally parsed one)
if (changedMember == null)
{
return null;
}
return new SyntaxPath(changedMember);
}
private async Task EnqueueWorkItemAsync(Project project, InvocationReasons invocationReasons)
{
foreach (var documentId in project.DocumentIds)
{
var document = project.GetDocument(documentId);
await EnqueueWorkItemAsync(document, invocationReasons).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAsync(IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds, bool highPriority)
{
var solution = _registration.CurrentSolution;
foreach (var documentId in documentIds)
{
var document = solution.GetDocument(documentId);
if (document == null)
{
continue;
}
var priorityService = document.GetLanguageService<IWorkCoordinatorPriorityService>();
var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(document, _shutdownToken).ConfigureAwait(false);
var invocationReasons = highPriority ? InvocationReasons.ReanalyzeHighPriority : InvocationReasons.Reanalyze;
_documentAndProjectWorkerProcessor.Enqueue(
new WorkItem(documentId, document.Project.Language, invocationReasons,
isLowPriority, analyzer, _listener.BeginAsyncOperation("WorkItem")));
}
}
private async Task EnqueueWorkItemAsync(Solution oldSolution, Solution newSolution)
{
var solutionChanges = newSolution.GetChanges(oldSolution);
// TODO: Async version for GetXXX methods?
foreach (var addedProject in solutionChanges.GetAddedProjects())
{
await EnqueueWorkItemAsync(addedProject, InvocationReasons.DocumentAdded).ConfigureAwait(false);
}
foreach (var projectChanges in solutionChanges.GetProjectChanges())
{
await EnqueueWorkItemAsync(projectChanges).ConfigureAwait(continueOnCapturedContext: false);
}
foreach (var removedProject in solutionChanges.GetRemovedProjects())
{
await EnqueueWorkItemAsync(removedProject, InvocationReasons.DocumentRemoved).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAsync(ProjectChanges projectChanges)
{
await EnqueueProjectConfigurationChangeWorkItemAsync(projectChanges).ConfigureAwait(false);
foreach (var addedDocumentId in projectChanges.GetAddedDocuments())
{
await EnqueueWorkItemAsync(projectChanges.NewProject.GetDocument(addedDocumentId), InvocationReasons.DocumentAdded).ConfigureAwait(false);
}
foreach (var changedDocumentId in projectChanges.GetChangedDocuments())
{
await EnqueueWorkItemAsync(projectChanges.OldProject.GetDocument(changedDocumentId), projectChanges.NewProject.GetDocument(changedDocumentId))
.ConfigureAwait(continueOnCapturedContext: false);
}
foreach (var removedDocumentId in projectChanges.GetRemovedDocuments())
{
await EnqueueWorkItemAsync(projectChanges.OldProject.GetDocument(removedDocumentId), InvocationReasons.DocumentRemoved).ConfigureAwait(false);
}
}
private async Task EnqueueProjectConfigurationChangeWorkItemAsync(ProjectChanges projectChanges)
{
var oldProject = projectChanges.OldProject;
var newProject = projectChanges.NewProject;
// TODO: why solution changes return Project not ProjectId but ProjectChanges return DocumentId not Document?
var projectConfigurationChange = InvocationReasons.Empty;
if (!object.Equals(oldProject.ParseOptions, newProject.ParseOptions))
{
projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectParseOptionChanged);
}
if (projectChanges.GetAddedMetadataReferences().Any() ||
projectChanges.GetAddedProjectReferences().Any() ||
projectChanges.GetAddedAnalyzerReferences().Any() ||
projectChanges.GetRemovedMetadataReferences().Any() ||
projectChanges.GetRemovedProjectReferences().Any() ||
projectChanges.GetRemovedAnalyzerReferences().Any() ||
!object.Equals(oldProject.CompilationOptions, newProject.CompilationOptions) ||
!object.Equals(oldProject.AssemblyName, newProject.AssemblyName) ||
!object.Equals(oldProject.Name, newProject.Name) ||
!object.Equals(oldProject.AnalyzerOptions, newProject.AnalyzerOptions))
{
projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectConfigurationChanged);
}
if (!projectConfigurationChange.IsEmpty)
{
await EnqueueWorkItemAsync(projectChanges.NewProject, projectConfigurationChange).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAsync(Document oldDocument, Document newDocument)
{
var differenceService = newDocument.GetLanguageService<IDocumentDifferenceService>();
if (differenceService == null)
{
// For languages that don't use a Roslyn syntax tree, they don't export a document difference service.
// The whole document should be considered as changed in that case.
await EnqueueWorkItemAsync(newDocument, InvocationReasons.DocumentChanged).ConfigureAwait(false);
}
else
{
var differenceResult = await differenceService.GetDifferenceAsync(oldDocument, newDocument, _shutdownToken).ConfigureAwait(false);
if (differenceResult != null)
{
await EnqueueWorkItemAsync(newDocument, differenceResult.ChangeType, differenceResult.ChangedMember).ConfigureAwait(false);
}
}
}
private Task EnqueueWorkItemForDocumentAsync(Solution solution, DocumentId documentId, InvocationReasons invocationReasons)
{
var document = solution.GetDocument(documentId);
return EnqueueWorkItemAsync(document, invocationReasons);
}
private Task EnqueueWorkItemForProjectAsync(Solution solution, ProjectId projectId, InvocationReasons invocationReasons)
{
var project = solution.GetProject(projectId);
return EnqueueWorkItemAsync(project, invocationReasons);
}
private async Task EnqueueWorkItemForSolutionAsync(Solution solution, InvocationReasons invocationReasons)
{
foreach (var projectId in solution.ProjectIds)
{
await EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, ProjectId projectId)
{
var oldProject = oldSolution.GetProject(projectId);
var newProject = newSolution.GetProject(projectId);
await EnqueueWorkItemAsync(newProject.GetChanges(oldProject)).ConfigureAwait(continueOnCapturedContext: false);
}
private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, DocumentId documentId)
{
var oldProject = oldSolution.GetProject(documentId.ProjectId);
var newProject = newSolution.GetProject(documentId.ProjectId);
await EnqueueWorkItemAsync(oldProject.GetDocument(documentId), newProject.GetDocument(documentId)).ConfigureAwait(continueOnCapturedContext: false);
}
internal void WaitUntilCompletion_ForTestingPurposesOnly(ImmutableArray<IIncrementalAnalyzer> workers)
{
var solution = _registration.CurrentSolution;
var list = new List<WorkItem>();
foreach (var project in solution.Projects)
{
foreach (var document in project.Documents)
{
list.Add(new WorkItem(document.Id, document.Project.Language, InvocationReasons.DocumentAdded, false, EmptyAsyncToken.Instance));
}
}
_documentAndProjectWorkerProcessor.WaitUntilCompletion_ForTestingPurposesOnly(workers, list);
}
internal void WaitUntilCompletion_ForTestingPurposesOnly()
{
_documentAndProjectWorkerProcessor.WaitUntilCompletion_ForTestingPurposesOnly();
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="MetadataCacheItem.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Provides a class to cache metadata information.
// </summary>
//
// @owner [....]
//---------------------------------------------------------------------
namespace System.Data.Services.Caching
{
using System;
using System.Collections.Generic;
using System.Data.Services.Common;
using System.Data.Services.Providers;
using System.Diagnostics;
/// <summary>Use this class to cache metadata for providers.</summary>
internal class MetadataCacheItem
{
#region Private fields.
/// <summary> list of top level entity sets</summary>
private readonly Dictionary<string, ResourceSet> entitySets;
/// <summary>Collection of service operations, keyed by name.</summary>
private readonly Dictionary<string, ServiceOperation> serviceOperations;
/// <summary>Target type for the data provider.</summary>
private readonly Type type;
/// <summary>Cache of resource properties per type.</summary>
private readonly Dictionary<Type, ResourceType> typeCache;
/// <summary>Cache of immediate derived types per type.</summary>
private readonly Dictionary<ResourceType, List<ResourceType>> childTypesCache;
/// <summary>Service configuration information.</summary>
private DataServiceConfiguration configuration;
/// <summary>Whether all EPM properties serialize in an Astoria V1-compatible way.</summary>
private bool epmIsV1Compatible;
/// <summary>
/// Keep track of the calculated visibility of resource types.
/// </summary>
private Dictionary<string, ResourceType> visibleTypeCache;
/// <summary>
/// Maps resource set names to ResourceSetWrappers.
/// </summary>
private Dictionary<string, ResourceSetWrapper> resourceSetWrapperCache;
/// <summary>
/// Maps service operation names to ServiceOperationWrappers.
/// </summary>
private Dictionary<string, ServiceOperationWrapper> serviceOperationWrapperCache;
/// <summary>
/// Maps names to ResourceAssociationSets.
/// </summary>
private Dictionary<string, ResourceAssociationSet> resourceAssociationSetCache;
/// <summary>
/// Mapes "resourceSetName_resourceTypeName" to the list of visible properties from the set.
/// </summary>
private Dictionary<string, List<ResourceProperty>> resourcePropertyCache;
/// <summary>
/// Mapes "resourceSetName_resourceTypeName" to boolean of whether resourceType is allowed for resourceSet
/// </summary>
private Dictionary<string, object> entityTypeDisallowedForSet;
#endregion Private fields.
/// <summary>Initializes a new <see cref="MetadataCacheItem"/> instance.</summary>
/// <param name='type'>Type of data context for which metadata will be generated.</param>
internal MetadataCacheItem(Type type)
{
Debug.Assert(type != null, "type != null");
this.serviceOperations = new Dictionary<string, ServiceOperation>(EqualityComparer<string>.Default);
this.typeCache = new Dictionary<Type, ResourceType>(EqualityComparer<Type>.Default);
this.childTypesCache = new Dictionary<ResourceType, List<ResourceType>>(ReferenceEqualityComparer<ResourceType>.Instance);
this.entitySets = new Dictionary<string, ResourceSet>(EqualityComparer<string>.Default);
this.epmIsV1Compatible = true;
this.resourceSetWrapperCache = new Dictionary<string, ResourceSetWrapper>(EqualityComparer<string>.Default);
this.serviceOperationWrapperCache = new Dictionary<string, ServiceOperationWrapper>(EqualityComparer<string>.Default);
this.visibleTypeCache = new Dictionary<string, ResourceType>(EqualityComparer<string>.Default);
this.resourceAssociationSetCache = new Dictionary<string, ResourceAssociationSet>(EqualityComparer<string>.Default);
this.resourcePropertyCache = new Dictionary<string, List<ResourceProperty>>(EqualityComparer<string>.Default);
this.entityTypeDisallowedForSet = new Dictionary<string, object>(EqualityComparer<string>.Default);
this.type = type;
this.EdmSchemaVersion = MetadataEdmSchemaVersion.Version1Dot0;
}
#region Properties.
/// <summary>Service configuration information.</summary>
internal DataServiceConfiguration Configuration
{
[DebuggerStepThrough]
get
{
return this.configuration;
}
set
{
Debug.Assert(value != null, "value != null");
Debug.Assert(this.configuration == null, "this.configuration == null -- otherwise it's being set more than once");
this.configuration = value;
}
}
/// <summary>
/// Keep track of the calculated visibility of resource types.
/// </summary>
internal Dictionary<string, ResourceType> VisibleTypeCache
{
[DebuggerStepThrough]
get { return this.visibleTypeCache; }
}
/// <summary>
/// Maps resource set names to ResourceSetWrappers.
/// </summary>
internal Dictionary<string, ResourceSetWrapper> ResourceSetWrapperCache
{
[DebuggerStepThrough]
get { return this.resourceSetWrapperCache; }
}
/// <summary>
/// Maps service operation names to ServiceOperationWrappers.
/// </summary>
internal Dictionary<string, ServiceOperationWrapper> ServiceOperationWrapperCache
{
[DebuggerStepThrough]
get { return this.serviceOperationWrapperCache; }
}
/// <summary>
/// Maps names to ResourceAssociationSets.
/// </summary>
internal Dictionary<string, ResourceAssociationSet> ResourceAssociationSetCache
{
[DebuggerStepThrough]
get { return this.resourceAssociationSetCache; }
}
/// <summary>
/// Mapes "resourceSetName_resourceTypeName" to the list of visible properties from the set.
/// </summary>
internal Dictionary<string, List<ResourceProperty>> ResourcePropertyCache
{
[DebuggerStepThrough]
get { return this.resourcePropertyCache; }
}
/// <summary>
/// Mapes "resourceSetName_resourceTypeName" to boolean of whether resourceType is allowed for resourceSet
/// </summary>
internal Dictionary<string, object> EntityTypeDisallowedForSet
{
[DebuggerStepThrough]
get { return this.entityTypeDisallowedForSet; }
}
/// <summary>Collection of service operations, keyed by name.</summary>
internal Dictionary<string, ServiceOperation> ServiceOperations
{
[DebuggerStepThrough]
get { return this.serviceOperations; }
}
/// <summary>Cache of resource properties per type.</summary>
internal Dictionary<Type, ResourceType> TypeCache
{
[DebuggerStepThrough]
get { return this.typeCache; }
}
/// <summary>Cache of immediate derived types per type.</summary>
internal Dictionary<ResourceType, List<ResourceType>> ChildTypesCache
{
[DebuggerStepThrough]
get { return this.childTypesCache; }
}
/// <summary> list of top level entity sets</summary>
internal Dictionary<string, ResourceSet> EntitySets
{
[DebuggerStepThrough]
get { return this.entitySets; }
}
/// <summary>Target type for the data provider.</summary>
internal Type Type
{
[DebuggerStepThrough]
get { return this.type; }
}
/// <summary>EDM version to which metadata is compatible.</summary>
/// <remarks>
/// For example, a service operation of type Void is not acceptable 1.0 CSDL,
/// so it should use 1.1 CSDL instead. Similarly, OpenTypes are supported
/// in 1.2 and not before.
/// </remarks>
internal MetadataEdmSchemaVersion EdmSchemaVersion
{
get;
set;
}
/// <summary>Whether all EPM properties serialize in an Astoria V1-compatible way.</summary>
/// <remarks>
/// This property is false if any property has KeepInContent set to false.
/// </remarks>
internal bool EpmIsV1Compatible
{
get { return this.epmIsV1Compatible; }
set { this.epmIsV1Compatible = value; }
}
#endregion Properties.
}
}
| |
/************************************************************************************
Filename : OSPAudioSource.cs
Content : Interface into the Oculus Spatializer Plugin (from audio source)
Created : Novemnber 11, 2014
Authors : Peter Giokaris
opyright : Copyright 2014 Oculus VR, Inc. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.1 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.1
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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.
************************************************************************************/
// Add Minor releases as they come on-line
#if UNITY_5_0 || UNITY_5_1 || UNITY_5_2
#define UNITY5
#elif UNITY_6_0
#error support this!
#endif
//#define DEBUG_AudioSource
using UnityEngine;
/// <summary>
/// OSP audio source.
/// This component should be added to a scene with an audio source
/// </summary>
public class OSPAudioSource : MonoBehaviour
{
// Public members
public AudioSource audioSource = null;
[SerializeField]
private bool bypass = false;
public bool Bypass
{
get{return bypass;}
set{bypass = value;}
}
[SerializeField]
private bool playOnAwake = false;
public bool PlayOnAwake
{
get{return playOnAwake;}
set{playOnAwake = value;}
}
[SerializeField]
private int frequencyHint = 0;
public int FrequencyHint
{
get{return frequencyHint;}
set{frequencyHint = value;
if(frequencyHint < 0) frequencyHint = 0;
if(frequencyHint > 2) frequencyHint = 2;}
}
[SerializeField]
private bool useSimple = false;
public bool UseSimple
{
get{return useSimple; }
set{useSimple = value;}
}
[SerializeField]
private bool disableReflections = false;
public bool DisableReflections
{
get{return disableReflections; }
set{disableReflections = value;}
}
// Private members
AudioListener audioListener = null;
private int context = sNoContext;
private bool isPlaying = false;
private float panLevel = 0.0f;
private float spread = 0.0f;
// We must account for the early reflection tail, don't but the
// context back until it's been rendered
private bool drain = false;
private float drainTime = 0.0f;
// We will set the relative position in the Update function
// Capture the previous so that we can interpolate into the
// latest position in AudioFilterRead
private Vector3 relPos = new Vector3(0,0,0);
private Vector3 relVel = new Vector3(0,0,0);
private float relPosTime = 0.0f;
// Consts
private const int sNoContext = -1;
private const float sSetPanLevel = 1.0f;
private const float sSetSpread = 180.0f;
#if DEBUG_AudioSource
// Debug
private const bool debugOn = false; // TURN THIS OFF FOR NO VERBOSE
private float dTimeMainLoop = 0.0f;
private int audioFrames = 100;
private float PrevAudioTime = 0.0f;
#endif
//* * * * * * * * * * * * *
// MonoBehaviour functions
//* * * * * * * * * * * * *
/// <summary>
/// Awake this instance.
/// </summary>
void Awake()
{
// First thing to do, cache the unity audio source (can be managed by the
// user if audio source can change)
if (!audioSource) audioSource = GetComponent<AudioSource>();
if (!audioSource) return;
// Set this in Start; we need to ensure spatializer has been initialized
// It's MUCH better to set playOnAwake in the audio source script, will avoid
// having the sound play then stop and then play again)
if (audioSource.playOnAwake == true || playOnAwake == true)
{
audioSource.Stop();
}
}
/// <summary>
/// Start this instance.
/// </summary>
void Start()
{
if(!audioSource)
{
Debug.LogWarning ("Start - Warning: No assigned AudioSource");
return;
}
// Start a play on awake sound here, after spatializer has been initialized
// Only do this IF it didn't happen in Awake
if (((audioSource.playOnAwake == true) || playOnAwake == true) &&
(isPlaying == false))
Play();
}
/// <summary>
/// Update this instance.
/// </summary>
void Update()
{
if(!audioSource)return;
// If user called Play on the acutal AudioSource, account for this
// NOTE: There may be a potential issue with calling AudioSource.Stop on a
// looping sound, since the Update may not catch this. We might need to catch
// this edge case at some point; a one-shot sound will stop automatically and
// return spatialization resources.
if((isPlaying == false) && (audioSource.isPlaying))
{
// This is a copy of OSPAudioSource Play function, minus
// calling Play on audio source since it's already been called
// Bail if manager has not even started
if (OSPManager.IsInitialized () == false)
return;
// We will grab a context at this point, and set the right values
// to allow for spatialization to take effect
Aquire();
// We will set the relative position of this sound now before we start playing
SetRelativeSoundPos(true);
// We are ready to play the sound
// Commented out, kept for readability
// audioSource.Play();
lock(this) isPlaying = true;
}
// If sound is playing on it's own and dies off, we need to
// Reset
if (isPlaying == true)
{
// If we stopped the sound using AudioSource, Release resources
if(audioSource.isPlaying == false)
{
lock (this) isPlaying = false;
Release();
return;
}
// We will go back and forth between spatial processing
// and native 2D panning
if((Bypass == true) || (OSPManager.GetBypass() == true))
{
#if (!UNITY5)
audioSource.panLevel = panLevel;
#else
audioSource.spatialBlend = panLevel;
#endif
audioSource.spread = spread;
}
else
{
#if (!UNITY5)
audioSource.panLevel = sSetPanLevel;
#else
audioSource.spatialBlend = sSetPanLevel;
#endif
audioSource.spread = sSetSpread;
}
// Update FrequencyHints and local reflection enable/disable
if(context != sNoContext)
{
OSPManager.SetFrequencyHint(context, frequencyHint);
OSPManager.SetDisableReflectionsOnSound(context, disableReflections);
}
// return the context when the sound has finished playing
if((audioSource.time >= audioSource.clip.length) && (audioSource.loop == false))
{
// One last pass to allow for the tail portion of the sound
// to finish
drainTime = OSPManager.GetDrainTime(context);
drain = true;
}
else
{
// We must set all positional properties here, not in
// OnAudioFilterRead. We might consider a better approach
// to interpolate the current location for better localization,
// should the resolution of setting it here sound jittery due
// to thread frequency mismatch.
SetRelativeSoundPos(false);
#if DEBUG_AudioSource
// Time main thread and audio thread
if(debugOn)
{
// Get audio frequency
if(audioFrames == 0)
{
float ct = 1.0f / (GetTime(false) - dTimeMainLoop);
Debug.LogWarning (System.String.Format ("U: {0:F0}", ct));
ct = 100.0f / (GetTime(true) - PrevAudioTime);
Debug.LogWarning (System.String.Format ("A: {0:F0}", ct));
audioFrames = 100;
PrevAudioTime = (float)GetTime(true);
}
dTimeMainLoop = (float)GetTime(false);
}
#endif
}
if(drain == true)
{
// Keep playing until we safely drain out the early reflections
drainTime -= Time.deltaTime;
if(drainTime < 0.0f)
{
drain = false;
lock (this) isPlaying = false;
// Stop will both stop audio from playing (keeping OnAudioFilterRead from
// running with a held audio source) as well as release the spatialization
// resources via Release()
Stop();
}
}
}
}
/// <summary>
/// Raises the enable event.
/// </summary>
void OnEnable()
{
// MonoBehaviour function, contains all calls to
// start a playing sound
Start();
}
/// <summary>
/// Raises the disable event.
/// </summary>
void OnDisable()
{
// Public OSPAudioSource call
Stop();
}
/// <summary>
/// Raises the destroy event.
/// </summary>
void OnDestroy()
{
if(!audioSource)return;
lock (this) isPlaying = false;
Release();
}
//* * * * * * * * * * * * *
// Private functions
//* * * * * * * * * * * * *
/// <summary>
/// Aquire resources for spatialization
/// </summary>
private void Aquire()
{
if(!audioSource)return;
// Cache pan and spread
#if (!UNITY5)
panLevel = audioSource.panLevel;
#else
panLevel = audioSource.spatialBlend;
#endif
spread = audioSource.spread;
// override to use simple spatializer
bool prevUseSimple = OSPManager.GetUseSimple();
if(useSimple == true)
OSPManager.SetUseSimple (useSimple);
// Reserve a context in OSP that will be used for spatializing sound
// (Don't grab a new one if is already has a context attached to it)
if(context == sNoContext)
context = OSPManager.AquireContext ();
OSPManager.SetUseSimple (prevUseSimple); // reset
// We don't have a context here, so bail
if(context == sNoContext)
return;
// Set pan to full (spread at 180 will keep attenuation curve working, but all 2D
// panning will be removed)
#if (!UNITY5)
audioSource.panLevel = sSetPanLevel;
#else
audioSource.spatialBlend = sSetPanLevel;
#endif
// set spread to 180
audioSource.spread = sSetSpread;
}
/// <summary>
/// Reset cached variables and free the sound context back to OSPManger
/// </summary>
private void Release()
{
if(!audioSource)return;
// Reset all audio variables that were changed during play
#if (!UNITY5)
audioSource.panLevel = panLevel;
#else
audioSource.spatialBlend = panLevel;
#endif
audioSource.spread = spread;
// Put context back into pool
if(context != sNoContext)
{
OSPManager.ReleaseContext (context);
context = sNoContext;
}
}
/// <summary>
/// Set the position of the sound relative to the listener
/// </summary>
/// <param name="firstTime">If set to <c>true</c> first time.</param>
private void SetRelativeSoundPos(bool firstTime)
{
// Find the audio listener (first time used)
if(audioListener == null)
{
audioListener = FindObjectOfType<AudioListener>();
// If still null, then we have a problem;
if(audioListener == null)
{
Debug.LogWarning ("SetRelativeSoundPos - Warning: No AudioListener present");
return;
}
}
// Get the location of this sound
Vector3 sp = transform.position;
// Get the main camera in the scene
Vector3 cp = audioListener.transform.position;
Quaternion cq = audioListener.transform.rotation;
// transform the vector relative to the camera
Quaternion cqi = Quaternion.Inverse (cq);
// Get the vector between the sound and camera
lock (this)
{
if(firstTime)
{
relPos = cqi * (sp - cp);
relVel.x = relVel.y = relVel.z = 0.0f;
relPosTime = GetTime(true);
}
else
{
Vector3 prevRelPos = relPos;
float prevRelPosTime = relPosTime;
relPos = cqi * (sp - cp);
// Reverse z (Unity is left-handed co-ordinates)
relPos.z = -relPos.z;
relPosTime = GetTime(true);
// Calculate velocity
relVel = relPos - prevRelPos;
float dTime = relPosTime - prevRelPosTime;
relVel *= dTime;
}
}
}
//* * * * * * * * * * * * *
// Public functions
//* * * * * * * * * * * * *
/// <summary>
/// Play this sound.
/// </summary>
public void Play()
{
if(!audioSource)
{
Debug.LogWarning ("Play - Warning: No AudioSource assigned");
return;
}
// Bail if manager has not even started
if (OSPManager.IsInitialized () == false)
return;
// We will grab a context at this point, and set the right values
// to allow for spatialization to take effect
Aquire();
// We will set the relative position of this sound now before we start playing
SetRelativeSoundPos(true);
// We are ready to play the sound
audioSource.Play();
lock(this) isPlaying = true;
}
/// <summary>
/// Plays the sound with a delay (in sec.)
/// </summary>
/// <param name="delay">Delay.</param>
public void PlayDelayed(float delay)
{
if(!audioSource)
{
Debug.LogWarning ("PlayDelayed - Warning: No AudioSource assigned");
return;
}
// Bail if manager has not even started
if (OSPManager.IsInitialized () == false)
return;
// We will grab a context at this point, and set the right values
// to allow for spatialization to take effect
Aquire();
// We will set the relative position of this sound now before we start playing
SetRelativeSoundPos(true);
// We are ready to play the sound
audioSource.PlayDelayed(delay);
lock(this) isPlaying = true;
}
/// <summary>
/// Plays the time scheduled relative to current AudioSettings.dspTime.
/// </summary>
/// <param name="time">Time.</param>
public void PlayScheduled(double time)
{
if(!audioSource)
{
Debug.LogWarning ("PlayScheduled - Warning: No AudioSource assigned");
return;
}
// Bail if manager has not even started
if (OSPManager.IsInitialized () == false)
return;
// We will grab a context at this point, and set the right values
// to allow for spatialization to take effect
Aquire();
// We will set the relative position of this sound now before we start playing
SetRelativeSoundPos(true);
// We are ready to play the sound
audioSource.PlayScheduled(time);
lock(this) isPlaying = true;
}
/// <summary>
/// Stop this instance.
/// </summary>
public void Stop()
{
if(!audioSource)
{
Debug.LogWarning ("Stop - Warning: No AudioSource assigned");
return;
}
lock(this) isPlaying = false;
// Stop audio from playing, and reset any cached values that we
// have set from Play
audioSource.Stop();
// Return spatializer context
Release();
}
/// <summary>
/// Pause this instance.
/// </summary>
public void Pause()
{
if(!audioSource)
{
Debug.LogWarning ("Pause - Warning: No AudioSource assigned");
return;
}
audioSource.Pause();
}
//* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
// OnAudioFilterRead (separate thread)
//* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
/// <summary>
/// Raises the audio filter read event.
/// We will spatialize the audio here
/// NOTE: It's important that we get the audio attenuation curve for volume,
/// that way we can feed it into our spatializer and have things sound match
/// with bypass on/off
/// </summary>
/// <param name="data">Data.</param>
/// <param name="channels">Channels.</param>
///
void OnAudioFilterRead(float[] data, int channels)
{
#if DEBUG_AudioSource
if(debugOn)
if(audioFrames > 0)
audioFrames--;
#endif
// Problem: We cannot read timer here.
// However, we can read time-stamp via plugin
// This is required to smooth out the position,
// since the main loop is only allowed to update position
// of sound, but is running at a different frequency then
// the audio loop.
//
// Therefore, we will need to dead reckon the position of the sound.
// Do not spatialize if we are not playing
if ((isPlaying == false) ||
(Bypass == true) ||
(OSPManager.GetBypass () == true) ||
OSPManager.IsInitialized() == false)
return;
float dTime = GetTime(true) - relPosTime;
lock(this)
{
relPos += relVel * dTime;
relPosTime = GetTime(true);
}
// TODO: Need to ensure that sound is not played before context is
// legal
if(context != sNoContext)
{
// Set the position for this context and sound
OSPManager.SetPositionRel (context, relPos.x, relPos.y, relPos.z);
//Spatialize
OSPManager.Spatialize (context, data);
}
}
/// <summary>
/// Gets the time.
/// We can bounce between Time and AudioSettings.dspTime
/// </summary>
/// <returns>The time.</returns>
/// <param name="dspTime">If set to <c>true</c> dsp time.</param>
float GetTime(bool dspTime)
{
if(dspTime == true)
return (float)AudioSettings.dspTime;
return Time.time;
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using OpenMetaverse;
using OpenSim.Region.Framework.Interfaces;
using Nini.Config;
using Aurora.Framework;
using System.Timers;
using Timer = System.Timers.Timer;
namespace OpenSim.Region.Framework.Scenes
{
#region Delegates
public delegate void NewScene (IScene scene);
public delegate void NoParam ();
#endregion
#region Enums
public enum ShutdownType
{
Immediate,
Delayed
}
#endregion
/// <summary>
/// Manager for adding, closing, reseting, and restarting scenes.
/// </summary>
public class SceneManager : IApplicationPlugin
{
#region Declares
#region Events
public event NewScene OnAddedScene;
public event NewScene OnCloseScene;
#endregion
private ISimulationBase m_OpenSimBase;
private int RegionsFinishedStarting = 0;
public int AllRegions = 0;
protected ISimulationDataStore m_simulationDataService;
public ISimulationDataStore SimulationDataService
{
get { return m_simulationDataService; }
set { m_simulationDataService = value; }
}
private IConfigSource m_config = null;
public IConfigSource ConfigSource
{
get { return m_config; }
}
private readonly List<IScene> m_localScenes = new List<IScene> ();
public List<IScene> Scenes
{
get { return m_localScenes; }
}
public IScene CurrentOrFirstScene
{
get
{
if (MainConsole.Instance.ConsoleScene == null)
{
if (m_localScenes.Count > 0)
{
return m_localScenes[0];
}
return null;
}
return MainConsole.Instance.ConsoleScene;
}
}
#endregion
#region IApplicationPlugin members
public void PreStartup(ISimulationBase simBase)
{
}
public void Initialize(ISimulationBase openSim)
{
m_OpenSimBase = openSim;
IConfig handlerConfig = openSim.ConfigSource.Configs["ApplicationPlugins"];
if (handlerConfig.GetString("SceneManager", "") != Name)
return;
m_config = openSim.ConfigSource;
string name = String.Empty;
// Try reading the [SimulationDataStore] section
IConfig simConfig = openSim.ConfigSource.Configs["SimulationDataStore"];
if (simConfig != null)
{
name = simConfig.GetString("DatabaseLoaderName", "FileBasedDatabase");
}
ISimulationDataStore[] stores = AuroraModuleLoader.PickupModules<ISimulationDataStore> ().ToArray ();
List<string> storeNames = new List<string>();
foreach (ISimulationDataStore store in stores)
{
if (store.Name.ToLower() == name.ToLower())
{
m_simulationDataService = store;
break;
}
storeNames.Add(store.Name);
}
if (m_simulationDataService == null)
{
MainConsole.Instance.ErrorFormat("[SceneManager]: FAILED TO LOAD THE SIMULATION SERVICE AT '{0}', ONLY OPTIONS ARE {1}, QUITING...", name, string.Join(", ", storeNames.ToArray()));
Console.Read ();//Wait till they see
Environment.Exit(0);
}
m_simulationDataService.Initialise();
AddConsoleCommands();
//Load the startup modules for the region
m_startupPlugins = AuroraModuleLoader.PickupModules<ISharedRegionStartupModule>();
//Register us!
m_OpenSimBase.ApplicationRegistry.RegisterModuleInterface<SceneManager>(this);
m_OpenSimBase.EventManager.RegisterEventHandler("RegionInfoChanged", RegionInfoChanged);
}
public void ReloadConfiguration(IConfigSource config)
{
//Update this
m_config = config;
if (m_localScenes == null)
return;
foreach (IScene scene in m_localScenes)
{
scene.Config = config;
scene.PhysicsScene.PostInitialise(config);
}
}
public void PostInitialise()
{
}
public void Start()
{
}
public void PostStart()
{
}
public string Name
{
get { return "SceneManager"; }
}
public void Dispose()
{
}
public void Close()
{
if (m_localScenes == null)
return;
IScene[] scenes = new IScene[m_localScenes.Count];
m_localScenes.CopyTo(scenes, 0);
// collect known shared modules in sharedModules
foreach (IScene t in scenes)
{
// close scene/region
CloseRegion (t, ShutdownType.Immediate, 0);
}
}
#endregion
#region Startup complete
public void HandleStartupComplete(IScene scene, List<string> data)
{
MainConsole.Instance.Info("[SceneManager]: Startup Complete in region " + scene.RegionInfo.RegionName);
RegionsFinishedStarting++;
if (RegionsFinishedStarting >= AllRegions)
{
FinishStartUp();
}
}
private void FinishStartUp()
{
//Tell modules about it
StartupCompleteModules();
m_OpenSimBase.RunStartupCommands();
TimeSpan timeTaken = DateTime.Now - m_OpenSimBase.StartupTime;
MainConsole.Instance.InfoFormat ("[SceneManager]: All regions are started. This took {0}m {1}.{2}s", timeTaken.Minutes, timeTaken.Seconds, timeTaken.Milliseconds);
AuroraModuleLoader.ClearCache ();
// In 99.9% of cases it is a bad idea to manually force garbage collection. However,
// this is a rare case where we know we have just went through a long cycle of heap
// allocations, and there is no more work to be done until someone logs in
GC.Collect ();
}
#endregion
#region ForEach functions
public void ForEachCurrentScene(Action<IScene> func)
{
if (MainConsole.Instance.ConsoleScene == null)
{
m_localScenes.ForEach(func);
}
else
{
func (MainConsole.Instance.ConsoleScene);
}
}
public void ForEachScene(Action<IScene> action)
{
m_localScenes.ForEach(action);
}
#endregion
#region TrySetScene functions
/// <summary>
/// Checks to see whether a region with the given name exists, and then sets the MainConsole.Instance.ConsoleScene ref
/// </summary>
/// <param name="regionName"></param>
/// <returns></returns>
private bool TrySetConsoleScene(string regionName)
{
if ((String.Compare(regionName, "root") == 0))
{
MainConsole.Instance.ConsoleScene = null;
return true;
}
#if (!ISWIN)
foreach (IScene scene in m_localScenes)
{
if (String.Compare(scene.RegionInfo.RegionName, regionName, true) == 0)
{
MainConsole.Instance.ConsoleScene = scene;
return true;
}
}
#else
foreach (IScene scene in m_localScenes.Where(scene => String.Compare(scene.RegionInfo.RegionName, regionName, true) == 0))
{
MainConsole.Instance.ConsoleScene = scene;
return true;
}
#endif
return false;
}
/// <summary>
/// Changes the console scene to a new region, also can pass 'root' down to set it to no console scene
/// </summary>
/// <param name="newRegionName"></param>
/// <returns></returns>
public bool ChangeConsoleRegion(string newRegionName)
{
if (!TrySetConsoleScene(newRegionName))
{
MainConsole.Instance.Info (String.Format ("Couldn't select region {0}", newRegionName));
return false;
}
string regionName = (MainConsole.Instance.ConsoleScene == null ?
"root" : MainConsole.Instance.ConsoleScene.RegionInfo.RegionName);
if (MainConsole.Instance != null)
MainConsole.Instance.DefaultPrompt = String.Format ("Region ({0}) ", regionName);
return true;
}
#endregion
#region TryGet functions
/// <summary>
/// Gets a region by its region name
/// </summary>
/// <param name="regionName"></param>
/// <param name="scene"></param>
/// <returns></returns>
public bool TryGetScene (string regionName, out IScene scene)
{
foreach (IScene mscene in m_localScenes)
{
if (String.Compare(mscene.RegionInfo.RegionName, regionName, true) == 0)
{
scene = mscene;
return true;
}
}
scene = null;
return false;
}
/// <summary>
/// Gets a region by its region UUID
/// </summary>
/// <param name="regionID"></param>
/// <param name="scene"></param>
/// <returns></returns>
public bool TryGetScene(UUID regionID, out IScene scene)
{
foreach (IScene mscene in m_localScenes)
{
if (mscene.RegionInfo.RegionID == regionID)
{
scene = mscene;
return true;
}
}
scene = null;
return false;
}
/// <summary>
/// Gets a region at the given location
/// </summary>
/// <param name="locX">In meters</param>
/// <param name="locY">In meters</param>
/// <param name="scene"></param>
/// <returns></returns>
public bool TryGetScene(int locX, int locY, out IScene scene)
{
foreach (IScene mscene in m_localScenes)
{
if (mscene.RegionInfo.RegionLocX == locX &&
mscene.RegionInfo.RegionLocY == locY)
{
scene = mscene;
return true;
}
}
scene = null;
return false;
}
/// <summary>
/// Gets a region at the given location
/// </summary>
/// <param name="RegionHandle"></param>
/// <param name="scene"></param>
/// <returns></returns>
public bool TryGetScene(ulong RegionHandle, out IScene scene)
{
int X, Y;
Util.UlongToInts (RegionHandle, out X, out Y);
return TryGetScene (X, Y, out scene);
}
#endregion
#region Add a region
public IScene StartNewRegion (RegionInfo regionInfo)
{
MainConsole.Instance.InfoFormat("[SceneManager]: Starting region \"{0}\" at @ {1},{2}", regionInfo.RegionName,
regionInfo.RegionLocX / 256, regionInfo.RegionLocY / 256);
ISceneLoader sceneLoader = m_OpenSimBase.ApplicationRegistry.RequestModuleInterface<ISceneLoader> ();
if (sceneLoader == null)
throw new Exception ("No Scene Loader Interface!");
//Get the new scene from the interface
IScene scene = sceneLoader.CreateScene (regionInfo);
#if (!ISWIN)
foreach (IScene loadedScene in m_localScenes)
{
if (loadedScene.RegionInfo.RegionName == regionInfo.RegionName && loadedScene.RegionInfo.RegionHandle == regionInfo.RegionHandle)
{
throw new Exception("Duplicate region!");
}
}
#else
if (m_localScenes.Any(loadedScene => loadedScene.RegionInfo.RegionName == regionInfo.RegionName &&
loadedScene.RegionInfo.RegionHandle == regionInfo.RegionHandle))
{
throw new Exception("Duplicate region!");
}
#endif
StartNewRegion (scene);
return scene;
}
/// <summary>
/// Execute the region creation process. This includes setting up scene infrastructure.
/// </summary>
/// <param name="scene"></param>
/// <returns></returns>
public void StartNewRegion(IScene scene)
{
//Do this here so that we don't have issues later when startup complete messages start coming in
m_localScenes.Add (scene);
StartModules (scene);
//Start the heartbeats
scene.StartHeartbeat();
//Tell the scene that the startup is complete
// Note: this event is added in the scene constructor
scene.FinishedStartup("Startup", new List<string>());
}
/// <summary>
/// Gets a new copy of the simulation data store, keep one per region
/// </summary>
/// <returns></returns>
public ISimulationDataStore GetNewSimulationDataStore()
{
return m_simulationDataService.Copy();
}
#endregion
#region Reset a region
public void ResetRegion (IScene scene)
{
if (scene == null)
{
MainConsole.Instance.Warn("You must use this command on a region. Use 'change region' to change to the region you would like to change");
return;
}
IBackupModule backup = scene.RequestModuleInterface<IBackupModule> ();
if(backup != null)
backup.DeleteAllSceneObjects();//Remove all the objects from the region
ITerrainModule module = scene.RequestModuleInterface<ITerrainModule> ();
if (module != null)
module.ResetTerrain();//Then remove the terrain
//Then reset the textures
scene.RegionInfo.RegionSettings.TerrainTexture1 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_1;
scene.RegionInfo.RegionSettings.TerrainTexture2 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_2;
scene.RegionInfo.RegionSettings.TerrainTexture3 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_3;
scene.RegionInfo.RegionSettings.TerrainTexture4 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_4;
scene.RegionInfo.RegionSettings.Save ();
MainConsole.Instance.Warn ("Region " + scene.RegionInfo.RegionName + " was reset");
}
#endregion
#region Restart a region
public void RestartRegion (IScene scene)
{
CloseRegion (scene, ShutdownType.Immediate, 0);
StartNewRegion (scene.RegionInfo);
}
#endregion
#region Shutdown regions
/// <summary>
/// Shuts down and permanently removes all info associated with the region
/// </summary>
/// <param name="scene"></param>
/// <param name="cleanup"></param>
public void RemoveRegion (IScene scene, bool cleanup)
{
IBackupModule backup = scene.RequestModuleInterface<IBackupModule>();
if (backup != null)
backup.DeleteAllSceneObjects();
CloseRegion (scene, ShutdownType.Immediate, 0);
if (!cleanup)
return;
IRegionLoader[] loaders = m_OpenSimBase.ApplicationRegistry.RequestModuleInterfaces<IRegionLoader>();
foreach (IRegionLoader loader in loaders)
{
loader.DeleteRegion(scene.RegionInfo);
}
}
/// <summary>
/// Shuts down a region and removes it from all running modules
/// </summary>
/// <param name="scene"></param>
/// <param name="type"></param>
/// <param name="seconds"></param>
/// <returns></returns>
public void CloseRegion (IScene scene, ShutdownType type, int seconds)
{
if (type == ShutdownType.Immediate)
{
InnerCloseRegion (scene);
}
else
{
Timer t = new Timer (seconds * 1000);//Millisecond conversion
#if (!ISWIN)
t.Elapsed +=
delegate(object sender, ElapsedEventArgs e)
{
CloseRegion(scene, ShutdownType.Immediate, 0);
};
#else
t.Elapsed += (sender, e) => CloseRegion(scene, ShutdownType.Immediate, 0);
#endif
t.AutoReset = false;
t.Start ();
}
}
private void InnerCloseRegion (IScene scene)
{
//Make sure that if we are set on the console, that we are removed from it
if ((MainConsole.Instance.ConsoleScene != null) &&
(MainConsole.Instance.ConsoleScene.RegionInfo.RegionID == scene.RegionInfo.RegionID))
ChangeConsoleRegion ("root");
m_localScenes.Remove (scene);
scene.Close ();
CloseModules (scene);
}
#endregion
#region Update region info
public object RegionInfoChanged(string funcName, object param)
{
UpdateRegionInfo((RegionInfo)((object[])param)[0], (RegionInfo)((object[])param)[1]);
return null;
}
public void UpdateRegionInfo (RegionInfo oldRegion, RegionInfo region)
{
foreach(IScene scene in m_localScenes)
{
if(scene.RegionInfo.RegionID == region.RegionID)
{
bool needsGridUpdate =
scene.RegionInfo.RegionName != region.RegionName ||
scene.RegionInfo.RegionLocX != region.RegionLocX ||
scene.RegionInfo.RegionLocY != region.RegionLocY ||
scene.RegionInfo.RegionLocZ != region.RegionLocZ ||
scene.RegionInfo.AccessLevel != region.AccessLevel ||
scene.RegionInfo.RegionType != region.RegionType// ||
//scene.RegionInfo.RegionSizeX != region.RegionSizeX //Don't allow for size updates on the fly, that needs a restart
//scene.RegionInfo.RegionSizeY != region.RegionSizeY
//scene.RegionInfo.RegionSizeZ != region.RegionSizeZ
;
bool needsRegistration =
scene.RegionInfo.RegionName != region.RegionName ||
scene.RegionInfo.RegionLocX != region.RegionLocX ||
scene.RegionInfo.RegionLocY != region.RegionLocY
;
region.RegionSettings = scene.RegionInfo.RegionSettings;
region.EstateSettings = scene.RegionInfo.EstateSettings;
region.GridSecureSessionID = scene.RegionInfo.GridSecureSessionID;
scene.RegionInfo = region;
if(needsRegistration)
scene.RequestModuleInterface<IGridRegisterModule>().RegisterRegionWithGrid(scene, false, false);
else if(needsGridUpdate)
scene.RequestModuleInterface<IGridRegisterModule>().UpdateGridRegion(scene);
//Tell clients about the changes
IEstateModule es = scene.RequestModuleInterface<IEstateModule>();
if(es != null)
es.sendRegionHandshakeToAll();
}
}
}
#endregion
#region ISharedRegionStartupModule plugins
protected List<ISharedRegionStartupModule> m_startupPlugins = new List<ISharedRegionStartupModule> ();
protected void StartModules(IScene scene)
{
//Run all the initialization
//First, Initialize the SharedRegionStartupModule
foreach (ISharedRegionStartupModule module in m_startupPlugins)
{
module.Initialise(scene, m_config, m_OpenSimBase);
}
//Then do the ISharedRegionModule and INonSharedRegionModules
MainConsole.Instance.Debug ("[Modules]: Loading region modules");
IRegionModulesController controller;
if (m_OpenSimBase.ApplicationRegistry.TryRequestModuleInterface (out controller))
{
controller.AddRegionToModules (scene);
}
else
MainConsole.Instance.Error ("[Modules]: The new RegionModulesController is missing...");
//Then finish the rest of the SharedRegionStartupModules
foreach (ISharedRegionStartupModule module in m_startupPlugins)
{
module.PostInitialise(scene, m_config, m_OpenSimBase);
}
foreach (ISharedRegionStartupModule module in m_startupPlugins)
{
module.FinishStartup(scene, m_config, m_OpenSimBase);
}
foreach (ISharedRegionStartupModule module in m_startupPlugins)
{
module.PostFinishStartup(scene, m_config, m_OpenSimBase);
}
if (OnAddedScene != null)
OnAddedScene (scene);
}
protected void StartupCompleteModules()
{
foreach (ISharedRegionStartupModule module in m_startupPlugins)
{
try
{
module.StartupComplete();
}
catch (Exception ex) { MainConsole.Instance.Warn("[SceneManager]: Exception running StartupComplete, " + ex); }
}
}
protected void CloseModules(IScene scene)
{
IRegionModulesController controller;
if (m_OpenSimBase.ApplicationRegistry.TryRequestModuleInterface(out controller))
controller.RemoveRegionFromModules(scene);
foreach (ISharedRegionStartupModule module in m_startupPlugins)
{
module.Close(scene);
}
if (OnCloseScene != null)
OnCloseScene(scene);
}
public void DeleteRegion(RegionInfo region)
{
IScene scene;
if (TryGetScene(region.RegionID, out scene))
DeleteSceneFromModules(scene);
}
protected void DeleteSceneFromModules(IScene scene)
{
foreach (ISharedRegionStartupModule module in m_startupPlugins)
{
module.DeleteRegion(scene);
}
}
#endregion
#region Console Commands
private void AddConsoleCommands()
{
if (MainConsole.Instance == null)
return;
MainConsole.Instance.Commands.AddCommand ("show users", "show users [full]", "Shows users in the given region (if full is added, child agents are shown as well)", HandleShowUsers);
MainConsole.Instance.Commands.AddCommand ("show regions", "show regions", "Show information about all regions in this instance", HandleShowRegions);
MainConsole.Instance.Commands.AddCommand ("show maturity", "show maturity", "Show all region's maturity levels", HandleShowMaturity);
MainConsole.Instance.Commands.AddCommand ("force update", "force update", "Force the update of all objects on clients", HandleForceUpdate);
MainConsole.Instance.Commands.AddCommand("debug packet", "debug packet [level]", "Turn on packet debugging", Debug);
MainConsole.Instance.Commands.AddCommand("debug scene", "debug scene [scripting] [collisions] [physics]", "Turn on scene debugging", Debug);
MainConsole.Instance.Commands.AddCommand("change region", "change region [region name]", "Change current console region", ChangeSelectedRegion);
MainConsole.Instance.Commands.AddCommand("load xml2", "load xml2", "Load a region's data from XML2 format", LoadXml2);
MainConsole.Instance.Commands.AddCommand("save xml2", "save xml2", "Save a region's data in XML2 format", SaveXml2);
MainConsole.Instance.Commands.AddCommand("load oar", "load oar [oar name] [--merge] [--skip-assets] [--OffsetX=#] [--OffsetY=#] [--OffsetZ=#] [--FlipX] [--FlipY] [--UseParcelOwnership] [--CheckOwnership]",
"Load a region's data from OAR archive. \n" +
"--merge will merge the oar with the existing scene (including parcels). \n" +
"--skip-assets will load the oar but ignore the assets it contains. \n" +
"--OffsetX will change where the X location of the oar is loaded, and the same for Y and Z. \n" +
"--FlipX flips the region on the X axis. \n" +
"--FlipY flips the region on the Y axis. \n" +
"--UseParcelOwnership changes who the default owner of objects whose owner cannot be found from the Estate Owner to the parcel owner on which the object is found. \n" +
"--CheckOwnership asks for each UUID that is not found on the grid what user it should be changed to (useful for changing UUIDs from other grids, but very long with many users). ", LoadOar);
MainConsole.Instance.Commands.AddCommand("save oar", "save oar [<OAR path>] [--perm=<permissions>] ", "Save a region's data to an OAR archive" + Environment.NewLine
+ "<OAR path> The OAR path must be a filesystem path."
+ " If this is not given then the oar is saved to region.oar in the current directory." + Environment.NewLine
+ "--perm stops objects with insufficient permissions from being saved to the OAR." + Environment.NewLine
+ " <permissions> can contain one or more of these characters: \"C\" = Copy, \"T\" = Transfer" + Environment.NewLine, SaveOar);
MainConsole.Instance.Commands.AddCommand("kick user", "kick user [first] [last] [message]", "Kick a user off the simulator", KickUserCommand);
MainConsole.Instance.Commands.AddCommand("reset region", "reset region", "Reset region to the default terrain, wipe all prims, etc.", RunCommand);
MainConsole.Instance.Commands.AddCommand("restart-instance", "restart-instance", "Restarts the instance (as if you closed and re-opened Aurora)", RunCommand);
MainConsole.Instance.Commands.AddCommand("command-script", "command-script [script]", "Run a command script from file", RunCommand);
MainConsole.Instance.Commands.AddCommand("remove-region", "remove-region [name]", "Remove a region from this simulator", RunCommand);
MainConsole.Instance.Commands.AddCommand("delete-region", "delete-region [name]", "Delete a region from disk", RunCommand);
MainConsole.Instance.Commands.AddCommand ("modules list", "modules list", "Lists all simulator modules", HandleModulesList);
MainConsole.Instance.Commands.AddCommand ("modules unload", "modules unload [module]", "Unload the given simulator module", HandleModulesUnload);
}
/// <summary>
/// Kicks users off the region
/// </summary>
/// <param name="cmdparams">name of avatar to kick</param>
private void KickUserCommand(string[] cmdparams)
{
string alert = null;
IList agents = new List<IScenePresence>(CurrentOrFirstScene.GetScenePresences ());
if (cmdparams.Length < 4)
{
if (cmdparams.Length < 3)
return;
UUID avID = UUID.Zero;
if (cmdparams[2] == "all")
{
foreach (IScenePresence presence in agents)
{
RegionInfo regionInfo = presence.Scene.RegionInfo;
MainConsole.Instance.Info (String.Format ("Kicking user: {0,-16}{1,-37} in region: {2,-16}", presence.Name, presence.UUID, regionInfo.RegionName));
// kick client...
if (alert != null)
presence.ControllingClient.Kick(alert);
else
presence.ControllingClient.Kick("\nThe Aurora manager kicked you out.\n");
// ...and close on our side
IEntityTransferModule transferModule = presence.Scene.RequestModuleInterface<IEntityTransferModule> ();
if(transferModule != null)
transferModule.IncomingCloseAgent (presence.Scene, presence.UUID);
}
}
else if(UUID.TryParse(cmdparams[2], out avID))
{
foreach (IScenePresence presence in agents)
{
if (presence.UUID == avID)
{
RegionInfo regionInfo = presence.Scene.RegionInfo;
MainConsole.Instance.Info (String.Format ("Kicking user: {0,-16}{1,-37} in region: {2,-16}", presence.Name, presence.UUID, regionInfo.RegionName));
// kick client...
if (alert != null)
presence.ControllingClient.Kick (alert);
else
presence.ControllingClient.Kick ("\nThe Aurora manager kicked you out.\n");
// ...and close on our side
IEntityTransferModule transferModule = presence.Scene.RequestModuleInterface<IEntityTransferModule> ();
if (transferModule != null)
transferModule.IncomingCloseAgent (presence.Scene, presence.UUID);
}
}
}
}
if (cmdparams.Length > 4)
alert = String.Format("\n{0}\n", String.Join(" ", cmdparams, 4, cmdparams.Length - 4));
foreach (IScenePresence presence in agents)
{
RegionInfo regionInfo = presence.Scene.RegionInfo;
string param = Util.CombineParams (cmdparams, 2);
if (presence.Name.ToLower().Contains (param.ToLower ()) ||
(presence.Firstname.ToLower ().Contains (cmdparams[2].ToLower ()) && presence.Lastname.ToLower ().Contains (cmdparams[3].ToLower ())))
{
MainConsole.Instance.Info (String.Format ("Kicking user: {0,-16}{1,-37} in region: {2,-16}", presence.Name, presence.UUID, regionInfo.RegionName));
// kick client...
if (alert != null)
presence.ControllingClient.Kick(alert);
else
presence.ControllingClient.Kick("\nThe Aurora manager kicked you out.\n");
// ...and close on our side
IEntityTransferModule transferModule = presence.Scene.RequestModuleInterface<IEntityTransferModule> ();
if (transferModule != null)
transferModule.IncomingCloseAgent (presence.Scene, presence.UUID);
}
}
MainConsole.Instance.Info ("");
}
/// <summary>
/// Force resending of all updates to all clients in active region(s)
/// </summary>
/// <param name="module"></param>
/// <param name="args"></param>
private void HandleForceUpdate(string[] args)
{
MainConsole.Instance.Info ("Updating all clients");
ForEachCurrentScene(delegate(IScene scene)
{
ISceneEntity[] EntityList = scene.Entities.GetEntities ();
foreach (ISceneEntity ent in EntityList)
{
if (ent is SceneObjectGroup)
{
((SceneObjectGroup)ent).ScheduleGroupUpdate (PrimUpdateFlags.ForcedFullUpdate);
}
}
List<IScenePresence> presences = scene.Entities.GetPresences ();
foreach(IScenePresence presence in presences)
{
if(!presence.IsChildAgent)
scene.ForEachClient(delegate(IClientAPI client)
{
client.SendAvatarDataImmediate(presence);
});
}
});
}
/// <summary>
/// Load, Unload, and list Region modules in use
/// </summary>
/// <param name="module"></param>
/// <param name="cmd"></param>
private void HandleModulesUnload(string[] cmd)
{
List<string> args = new List<string> (cmd);
args.RemoveAt (0);
string[] cmdparams = args.ToArray ();
IRegionModulesController controller = m_OpenSimBase.ApplicationRegistry.RequestModuleInterface<IRegionModulesController> ();
if (cmdparams.Length > 1)
{
foreach (IRegionModuleBase irm in controller.AllModules)
{
if (irm.Name.ToLower () == cmdparams[1].ToLower ())
{
MainConsole.Instance.Info (String.Format ("Unloading module: {0}", irm.Name));
foreach (IScene scene in Scenes)
irm.RemoveRegion (scene);
irm.Close ();
}
}
}
}
/// <summary>
/// Load, Unload, and list Region modules in use
/// </summary>
/// <param name="module"></param>
/// <param name="cmd"></param>
private void HandleModulesList (string[] cmd)
{
List<string> args = new List<string> (cmd);
args.RemoveAt (0);
IRegionModulesController controller = m_OpenSimBase.ApplicationRegistry.RequestModuleInterface<IRegionModulesController> ();
foreach (IRegionModuleBase irm in controller.AllModules)
{
if (irm is ISharedRegionModule)
MainConsole.Instance.Info (String.Format ("Shared region module: {0}", irm.Name));
else if (irm is INonSharedRegionModule)
MainConsole.Instance.Info (String.Format ("Nonshared region module: {0}", irm.Name));
else
MainConsole.Instance.Info (String.Format ("Unknown type " + irm.GetType ().ToString () + " region module: {0}", irm.Name));
}
}
/// <summary>
/// Serialize region data to XML2Format
/// </summary>
/// <param name="module"></param>
/// <param name="cmdparams"></param>
protected void SaveXml2(string[] cmdparams)
{
if (cmdparams.Length > 2)
{
IRegionSerialiserModule serialiser = CurrentOrFirstScene.RequestModuleInterface<IRegionSerialiserModule>();
if (serialiser != null)
serialiser.SavePrimsToXml2(CurrentOrFirstScene, cmdparams[2]);
}
else
{
MainConsole.Instance.Warn("Wrong number of parameters!");
}
}
/// <summary>
/// Runs commands issued by the server console from the operator
/// </summary>
/// <param name="command">The first argument of the parameter (the command)</param>
/// <param name="cmdparams">Additional arguments passed to the command</param>
private void RunCommand (string[] cmdparams)
{
List<string> args = new List<string>(cmdparams);
if (args.Count < 1)
return;
string command = args[0];
args.RemoveAt(0);
cmdparams = args.ToArray();
switch (command)
{
case "reset":
if (cmdparams.Length > 0)
if (cmdparams[0] == "region")
{
if (MainConsole.Instance.Prompt ("Are you sure you want to reset the region?", "yes") != "yes")
return;
ResetRegion (MainConsole.Instance.ConsoleScene);
}
break;
case "command-script":
if (cmdparams.Length > 0)
{
m_OpenSimBase.RunCommandScript(cmdparams[0]);
}
break;
case "remove-region":
string regRemoveName = Util.CombineParams(cmdparams, 0);
IScene removeScene;
if (TryGetScene(regRemoveName, out removeScene))
RemoveRegion(removeScene, false);
else
MainConsole.Instance.Info ("no region with that name");
break;
case "delete-region":
string regDeleteName = Util.CombineParams(cmdparams, 0);
IScene killScene;
if (TryGetScene(regDeleteName, out killScene))
RemoveRegion(killScene, true);
else
MainConsole.Instance.Info ("no region with that name");
break;
case "restart-instance":
//This kills the instance and restarts it
MainConsole.Instance.EndConsoleProcessing();
break;
}
}
/// <summary>
/// Change the currently selected region. The selected region is that operated upon by single region commands.
/// </summary>
/// <param name="cmdParams"></param>
protected void ChangeSelectedRegion(string[] cmdparams)
{
if (cmdparams.Length > 2)
{
string newRegionName = Util.CombineParams(cmdparams, 2);
ChangeConsoleRegion(newRegionName);
}
else
{
MainConsole.Instance.Info ("Usage: change region <region name>");
}
}
/// <summary>
/// Turn on some debugging values for OpenSim.
/// </summary>
/// <param name="args"></param>
protected void Debug(string[] args)
{
if (args.Length == 1)
return;
switch (args[1])
{
case "packet":
if (args.Length > 2)
{
int newDebug;
if (int.TryParse(args[2], out newDebug))
{
SetDebugPacketLevelOnCurrentScene(newDebug);
}
else
{
MainConsole.Instance.Info ("packet debug should be 0..255");
}
MainConsole.Instance.Info (String.Format ("New packet debug: {0}", newDebug));
}
break;
default:
MainConsole.Instance.Info ("Unknown debug");
break;
}
}
/// <summary>
/// Set the debug packet level on the current scene. This level governs which packets are printed out to the
/// console.
/// </summary>
/// <param name="newDebug"></param>
private void SetDebugPacketLevelOnCurrentScene(int newDebug)
{
ForEachCurrentScene(
delegate(IScene scene)
{
scene.ForEachScenePresence (delegate (IScenePresence scenePresence)
{
if (!scenePresence.IsChildAgent)
{
MainConsole.Instance.DebugFormat("Packet debug for {0} set to {1}",
scenePresence.Name,
newDebug);
scenePresence.ControllingClient.SetDebugPacketLevel(newDebug);
}
});
}
);
}
private void HandleShowUsers (string[] cmd)
{
List<string> args = new List<string> (cmd);
args.RemoveAt (0);
string[] showParams = args.ToArray ();
List<IScenePresence> agents = new List<IScenePresence>();
if(showParams.Length > 1 && showParams[1] == "full")
{
if(MainConsole.Instance.ConsoleScene == null)
{
foreach(IScene scene in m_localScenes)
{
agents.AddRange(scene.GetScenePresences());
}
}
else
agents = CurrentOrFirstScene.GetScenePresences();
}
else
{
if(MainConsole.Instance.ConsoleScene == null)
{
foreach(IScene scene in m_localScenes)
{
agents.AddRange(scene.GetScenePresences());
}
}
else
agents = CurrentOrFirstScene.GetScenePresences();
agents.RemoveAll(delegate(IScenePresence sp)
{
return sp.IsChildAgent;
});
}
MainConsole.Instance.Info (String.Format ("\nAgents connected: {0}\n", agents.Count));
MainConsole.Instance.Info (String.Format ("{0,-16}{1,-16}{2,-37}{3,-11}{4,-16}{5,-30}", "Firstname", "Lastname", "Agent ID", "Root/Child", "Region", "Position"));
foreach (IScenePresence presence in agents)
{
RegionInfo regionInfo = presence.Scene.RegionInfo;
string regionName;
if (regionInfo == null)
{
regionName = "Unresolvable";
}
else
{
regionName = regionInfo.RegionName;
}
MainConsole.Instance.Info (String.Format ("{0,-16}{1,-37}{2,-11}{3,-16}{4,-30}", presence.Name, presence.UUID, presence.IsChildAgent ? "Child" : "Root", regionName, presence.AbsolutePosition.ToString ()));
}
MainConsole.Instance.Info (String.Empty);
MainConsole.Instance.Info (String.Empty);
}
private void HandleShowRegions (string[] cmd)
{
ForEachScene (delegate (IScene scene)
{
MainConsole.Instance.Info (scene.ToString ());
});
}
private void HandleShowMaturity (string[] cmd)
{
ForEachCurrentScene (delegate (IScene scene)
{
string rating = "";
if (scene.RegionInfo.RegionSettings.Maturity == 1)
{
rating = "Mature";
}
else if (scene.RegionInfo.RegionSettings.Maturity == 2)
{
rating = "Adult";
}
else
{
rating = "PG";
}
MainConsole.Instance.Info (String.Format ("Region Name: {0}, Region Rating {1}", scene.RegionInfo.RegionName, rating));
});
}
private void SendCommandToPluginModules (string[] cmdparams)
{
ForEachCurrentScene(delegate(IScene scene) { scene.EventManager.TriggerOnPluginConsole(cmdparams); });
}
private void SetBypassPermissionsOnCurrentScene (bool bypassPermissions)
{
ForEachCurrentScene(delegate(IScene scene) { scene.Permissions.SetBypassPermissions(bypassPermissions); });
}
/// <summary>
/// Load region data from Xml2Format
/// </summary>
/// <param name="module"></param>
/// <param name="cmdparams"></param>
protected void LoadXml2(string[] cmdparams)
{
if (cmdparams.Length > 2)
{
try
{
IRegionSerialiserModule serialiser = CurrentOrFirstScene.RequestModuleInterface<IRegionSerialiserModule>();
if (serialiser != null)
serialiser.LoadPrimsFromXml2(CurrentOrFirstScene, cmdparams[2]);
}
catch (FileNotFoundException)
{
MainConsole.Instance.Info ("Specified xml not found. Usage: load xml2 <filename>");
}
}
else
{
MainConsole.Instance.Warn("Not enough parameters!");
}
}
/// <summary>
/// Load a whole region from an opensimulator archive.
/// </summary>
/// <param name="cmdparams"></param>
protected void LoadOar(string[] cmdparams)
{
try
{
IRegionArchiverModule archiver = CurrentOrFirstScene.RequestModuleInterface<IRegionArchiverModule>();
if (archiver != null)
archiver.HandleLoadOarConsoleCommand(cmdparams);
}
catch (Exception e)
{
MainConsole.Instance.Error (e.ToString ());
}
}
/// <summary>
/// Save a region to a file, including all the assets needed to restore it.
/// </summary>
/// <param name="cmdparams"></param>
protected void SaveOar(string[] cmdparams)
{
IRegionArchiverModule archiver = CurrentOrFirstScene.RequestModuleInterface<IRegionArchiverModule>();
if (archiver != null)
archiver.HandleSaveOarConsoleCommand(cmdparams);
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using OpenMetaverse;
namespace OpenSim.Framework
{
// The delegate we will use for performing fetch from backing store
//
public delegate Object FetchDelegate(string index);
public delegate bool ExpireDelegate(string index);
// Strategy
//
// Conservative = Minimize memory. Expire items quickly.
// Balanced = Expire items with few hits quickly.
// Aggressive = Keep cache full. Expire only when over 90% and adding
//
public enum CacheStrategy
{
Conservative = 0,
Balanced = 1,
Aggressive = 2
}
// Select classes to store data on different media
//
public enum CacheMedium
{
Memory = 0,
File = 1
}
public enum CacheFlags
{
CacheMissing = 1,
AllowUpdate = 2
}
// The base class of all cache objects. Implements comparison and sorting
// by the string member.
//
// This is not abstract because we need to instantiate it briefly as a
// method parameter
//
public class CacheItemBase : IEquatable<CacheItemBase>, IComparable<CacheItemBase>
{
public string uuid;
public DateTime entered;
public DateTime lastUsed;
public DateTime expires = new DateTime(0);
public int hits = 0;
public virtual Object Retrieve()
{
return null;
}
public virtual void Store(Object data)
{
}
public CacheItemBase(string index)
{
uuid = index;
entered = DateTime.UtcNow;
lastUsed = entered;
}
public CacheItemBase(string index, DateTime ttl)
{
uuid = index;
entered = DateTime.UtcNow;
lastUsed = entered;
expires = ttl;
}
public virtual bool Equals(CacheItemBase item)
{
return uuid == item.uuid;
}
public virtual int CompareTo(CacheItemBase item)
{
return uuid.CompareTo(item.uuid);
}
public virtual bool IsLocked()
{
return false;
}
}
// Simple in-memory storage. Boxes the object and stores it in a variable
//
public class MemoryCacheItem : CacheItemBase
{
private Object m_Data;
public MemoryCacheItem(string index) :
base(index)
{
}
public MemoryCacheItem(string index, DateTime ttl) :
base(index, ttl)
{
}
public MemoryCacheItem(string index, Object data) :
base(index)
{
Store(data);
}
public MemoryCacheItem(string index, DateTime ttl, Object data) :
base(index, ttl)
{
Store(data);
}
public override Object Retrieve()
{
return m_Data;
}
public override void Store(Object data)
{
m_Data = data;
}
}
// Simple persistent file storage
//
public class FileCacheItem : CacheItemBase
{
public FileCacheItem(string index) :
base(index)
{
}
public FileCacheItem(string index, DateTime ttl) :
base(index, ttl)
{
}
public FileCacheItem(string index, Object data) :
base(index)
{
Store(data);
}
public FileCacheItem(string index, DateTime ttl, Object data) :
base(index, ttl)
{
Store(data);
}
public override Object Retrieve()
{
//TODO: Add file access code
return null;
}
public override void Store(Object data)
{
//TODO: Add file access code
}
}
// The main cache class. This is the class you instantiate to create
// a cache
//
public class Cache
{
/// <summary>
/// Must only be accessed under lock.
/// </summary>
private List<CacheItemBase> m_Index = new List<CacheItemBase>();
/// <summary>
/// Must only be accessed under m_Index lock.
/// </summary>
private Dictionary<string, CacheItemBase> m_Lookup =
new Dictionary<string, CacheItemBase>();
private CacheStrategy m_Strategy;
private CacheMedium m_Medium;
private CacheFlags m_Flags = 0;
private int m_Size = 1024;
private TimeSpan m_DefaultTTL = new TimeSpan(0);
private DateTime m_nextExpire;
private TimeSpan m_expiresTime = new TimeSpan(0,0,30);
public ExpireDelegate OnExpire;
// Comparison interfaces
//
private class SortLRU : IComparer<CacheItemBase>
{
public int Compare(CacheItemBase a, CacheItemBase b)
{
if (a == null && b == null)
return 0;
if (a == null)
return -1;
if (b == null)
return 1;
return(a.lastUsed.CompareTo(b.lastUsed));
}
}
// same as above, reverse order
private class SortLRUrev : IComparer<CacheItemBase>
{
public int Compare(CacheItemBase a, CacheItemBase b)
{
if (a == null && b == null)
return 0;
if (a == null)
return -1;
if (b == null)
return 1;
return(b.lastUsed.CompareTo(a.lastUsed));
}
}
// Convenience constructors
//
public Cache()
{
m_Strategy = CacheStrategy.Balanced;
m_Medium = CacheMedium.Memory;
m_Flags = 0;
m_nextExpire = DateTime.UtcNow + m_expiresTime;
m_Strategy = CacheStrategy.Aggressive;
}
public Cache(CacheMedium medium) :
this(medium, CacheStrategy.Balanced)
{
}
public Cache(CacheMedium medium, CacheFlags flags) :
this(medium, CacheStrategy.Balanced, flags)
{
}
public Cache(CacheMedium medium, CacheStrategy strategy) :
this(medium, strategy, 0)
{
}
public Cache(CacheStrategy strategy, CacheFlags flags) :
this(CacheMedium.Memory, strategy, flags)
{
}
public Cache(CacheFlags flags) :
this(CacheMedium.Memory, CacheStrategy.Balanced, flags)
{
}
public Cache(CacheMedium medium, CacheStrategy strategy,
CacheFlags flags)
{
m_Strategy = strategy;
m_Medium = medium;
m_Flags = flags;
}
// Count of the items currently in cache
//
public int Count
{
get { lock (m_Index) { return m_Index.Count; } }
}
// Maximum number of items this cache will hold
//
public int Size
{
get { return m_Size; }
set { SetSize(value); }
}
private void SetSize(int newSize)
{
lock (m_Index)
{
int target = newSize;
if(m_Strategy == CacheStrategy.Aggressive)
target = (int)(newSize * 0.9);
if(Count > target)
{
m_Index.Sort(new SortLRUrev());
m_Index.RemoveRange(newSize, Count - target);
m_Lookup.Clear();
foreach (CacheItemBase item in m_Index)
m_Lookup[item.uuid] = item;
}
m_Size = newSize;
}
}
public TimeSpan DefaultTTL
{
get { return m_DefaultTTL; }
set { m_DefaultTTL = value; }
}
// Get an item from cache. Return the raw item, not it's data
//
protected virtual CacheItemBase GetItem(string index)
{
CacheItemBase item = null;
lock (m_Index)
{
if (m_Lookup.ContainsKey(index))
item = m_Lookup[index];
if (item == null)
{
Expire(true);
return null;
}
item.hits++;
item.lastUsed = DateTime.UtcNow;
Expire(true);
}
return item;
}
// Get an item from cache. Do not try to fetch from source if not
// present. Just return null
//
public virtual Object Get(string index)
{
CacheItemBase item = GetItem(index);
if (item == null)
return null;
return item.Retrieve();
}
// Fetch an object from backing store if not cached, serve from
// cache if it is.
//
public virtual Object Get(string index, FetchDelegate fetch)
{
CacheItemBase item = GetItem(index);
if (item != null)
return item.Retrieve();
Object data = fetch(index);
if (data == null && (m_Flags & CacheFlags.CacheMissing) == 0)
return null;
lock (m_Index)
{
CacheItemBase missing = new CacheItemBase(index);
if (!m_Index.Contains(missing))
{
m_Index.Add(missing);
m_Lookup[index] = missing;
}
}
Store(index, data);
return data;
}
// Find an object in cache by delegate.
//
public Object Find(Predicate<CacheItemBase> d)
{
CacheItemBase item;
lock (m_Index)
item = m_Index.Find(d);
if (item == null)
return null;
return item.Retrieve();
}
public virtual void Store(string index, Object data)
{
Type container;
switch (m_Medium)
{
case CacheMedium.Memory:
container = typeof(MemoryCacheItem);
break;
case CacheMedium.File:
return;
default:
return;
}
Store(index, data, container);
}
public virtual void Store(string index, Object data, Type container)
{
Store(index, data, container, new Object[] { index });
}
public virtual void Store(string index, Object data, Type container,
Object[] parameters)
{
CacheItemBase item;
lock (m_Index)
{
Expire(false);
if (m_Index.Contains(new CacheItemBase(index)))
{
if ((m_Flags & CacheFlags.AllowUpdate) != 0)
{
item = GetItem(index);
item.hits++;
item.lastUsed = DateTime.UtcNow;
if (m_DefaultTTL.Ticks != 0)
item.expires = DateTime.UtcNow + m_DefaultTTL;
item.Store(data);
}
return;
}
item = (CacheItemBase)Activator.CreateInstance(container,
parameters);
if (m_DefaultTTL.Ticks != 0)
item.expires = DateTime.UtcNow + m_DefaultTTL;
m_Index.Add(item);
m_Lookup[index] = item;
}
item.Store(data);
}
/// <summary>
/// Expire items as appropriate.
/// </summary>
/// <remarks>
/// Callers must lock m_Index.
/// </remarks>
/// <param name='getting'></param>
protected virtual void Expire(bool getting)
{
if (getting && (m_Strategy == CacheStrategy.Aggressive))
return;
DateTime now = DateTime.UtcNow;
if(now < m_nextExpire)
return;
m_nextExpire = now + m_expiresTime;
if (m_DefaultTTL.Ticks != 0)
{
foreach (CacheItemBase item in new List<CacheItemBase>(m_Index))
{
if (item.expires.Ticks == 0 ||
item.expires <= now)
{
m_Index.Remove(item);
m_Lookup.Remove(item.uuid);
}
}
}
switch (m_Strategy)
{
case CacheStrategy.Aggressive:
int target = (int)((float)Size * 0.9);
if (Count < target) // Cover ridiculous cache sizes
return;
target = (int)((float)Size * 0.8);
m_Index.Sort(new SortLRUrev());
ExpireDelegate doExpire = OnExpire;
if (doExpire != null)
{
List<CacheItemBase> candidates =
m_Index.GetRange(target, Count - target);
foreach (CacheItemBase i in candidates)
{
if (doExpire(i.uuid))
{
m_Index.Remove(i);
m_Lookup.Remove(i.uuid);
}
}
}
else
{
m_Index.RemoveRange(target, Count - target);
m_Lookup.Clear();
foreach (CacheItemBase item in m_Index)
m_Lookup[item.uuid] = item;
}
break;
default:
break;
}
}
public void Invalidate(string uuid)
{
lock (m_Index)
{
if (!m_Lookup.ContainsKey(uuid))
return;
CacheItemBase item = m_Lookup[uuid];
m_Lookup.Remove(uuid);
m_Index.Remove(item);
}
}
public void Clear()
{
lock (m_Index)
{
m_Index.Clear();
m_Lookup.Clear();
}
}
}
}
| |
/*
The MIT License (MIT)
Copyright (c) 2014 Microsoft Corporation
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.
*/
#define UseLargePages
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace COST
{
public interface GraphScanner
{
void ForEach(Action<int, int> perVertexLogic);
void ForEach(Action<int, int, int, int[]> perVertexLogic);
}
public class FileGraphScanner : GraphScanner
{
private readonly string filePrefix;
public FileGraphScanner(string prefix) { this.filePrefix = prefix; }
public void ForEach(Action<int, int, int, int[]> perVertexLogic)
{
var metadata = UnbufferedIO.ReadFile<int>(this.filePrefix + "-nodes");
var maxDegree = 0;
for (int i = 0; i < metadata.Length; i += 2)
maxDegree = Math.Max(maxDegree, metadata[i + 1]);
var neighbors = new int[2 * maxDegree];
var neighborsOffset = 0;
using (var reader = new UnbufferedIO.SequentialReader(this.filePrefix + "-edges"))
{
reader.Read(neighbors, 0, neighbors.Length);
for (int i = 0; i < metadata.Length; i += 2)
{
var vertex = metadata[i + 0];
var degree = metadata[i + 1];
if (neighborsOffset + degree > neighbors.Length - 1)
{
Array.Copy(neighbors, neighborsOffset, neighbors, 0, neighbors.Length - neighborsOffset);
reader.Read(neighbors, neighbors.Length - neighborsOffset, neighborsOffset);
neighborsOffset = 0;
}
perVertexLogic(vertex, degree, neighborsOffset, neighbors);
neighborsOffset += degree;
}
}
}
public void ForEach(Action<int, int> perVertexLogic)
{
var metadata = UnbufferedIO.ReadFile<int>(this.filePrefix + "-nodes");
for (int i = 0; i < metadata.Length; i += 2)
perVertexLogic(metadata[i], metadata[i + 1]);
}
}
public class MemoryGraphScanner : GraphScanner
{
private readonly int[] metadata;
private readonly int[] neighbors;
public MemoryGraphScanner(string prefix)
{
this.metadata = UnbufferedIO.ReadFile<int>(prefix + "-nodes");
this.neighbors = UnbufferedIO.ReadFile<int>(prefix + "-edges");
}
public void ForEach(Action<int, int> perVertexLogic)
{
for (int i = 0; i < this.metadata.Length; i += 2)
perVertexLogic(this.metadata[i], this.metadata[i + 1]);
}
public void ForEach(Action<int, int, int, int[]> perVertexLogic)
{
var offset = 0;
for (int i = 0; i < metadata.Length; i += 2)
{
var vertex = metadata[i + 0];
var degree = metadata[i + 1];
perVertexLogic(vertex, degree, offset, neighbors);
offset += degree;
}
}
}
class SingleThreaded
{
#region graph scanning patterns
public static void ScanGraph(string filename, Action<int, int, int, int[]> perVertexLogic)
{
var metadata = UnbufferedIO.ReadFile<int>(filename + "-nodes");
var maxDegree = 0;
for (int i = 0; i < metadata.Length; i += 2)
maxDegree = Math.Max(maxDegree, metadata[i + 1]);
var neighbors = new int[2 * maxDegree];
var neighborsOffset = 0;
using (var reader = new UnbufferedIO.SequentialReader(filename + "-edges"))
{
reader.Read(neighbors, 0, neighbors.Length);
for (int i = 0; i < metadata.Length; i += 2)
{
var vertex = metadata[i + 0];
var degree = metadata[i + 1];
if (neighborsOffset + degree > neighbors.Length - 1)
{
Array.Copy(neighbors, neighborsOffset, neighbors, 0, neighbors.Length - neighborsOffset);
reader.Read(neighbors, neighbors.Length - neighborsOffset, neighborsOffset);
neighborsOffset = 0;
}
perVertexLogic(vertex, degree, neighborsOffset, neighbors);
neighborsOffset += degree;
}
}
}
public static void ScanGraph(string filename, Action<int, int> perVertexLogic)
{
var metadata = UnbufferedIO.ReadFile<int>(filename + "-nodes");
for (int i = 0; i < metadata.Length; i += 2)
perVertexLogic(metadata[i], metadata[i + 1]);
}
public static void ScanGraph(int[] metadata, int[] neighbors, Action<int, int, int, int[]> perVertexLogic)
{
var offset = 0;
for (int i = 0; i < metadata.Length; i += 2)
{
var vertex = metadata[i + 0];
var degree = metadata[i + 1];
perVertexLogic(vertex, degree, offset, neighbors);
offset += degree;
}
}
public static void ScanGraphHilbert(string filename, Action<uint, uint, uint, uint, uint[]> perVertexLogic)
{
var metadata = UnbufferedIO.ReadFile<uint>(filename + "-upper");
var maxCount = (uint)0;
for (int i = 0; i < metadata.Length; i += 3)
maxCount = Math.Max(maxCount, metadata[i + 2]);
var edges = new uint[2 * maxCount];
var edgesOffset = (uint)0;
using (var reader = new UnbufferedIO.SequentialReader(filename + "-lower"))
{
reader.Read(edges, 0, edges.Length);
for (int i = 0; i < metadata.Length; i += 3)
{
var sourceUpper = metadata[i + 0] << 16;
var targetUpper = metadata[i + 1] << 16;
var count = metadata[i + 2];
if (edgesOffset + count > edges.Length - 1)
{
Array.Copy(edges, edgesOffset, edges, 0, edges.Length - edgesOffset);
reader.Read(edges, (int)(edges.Length - edgesOffset), (int)edgesOffset);
edgesOffset = 0;
}
perVertexLogic(sourceUpper, targetUpper, edgesOffset, count, edges);
edgesOffset += count;
}
}
}
public static void ScanGraphHilbert(uint[] metadata, uint[] edges, Action<uint, uint, uint, uint, uint[]> perVertexLogic)
{
var edgesOffset = (uint)0;
for (int i = 0; i < metadata.Length; i += 3)
{
var sourceUpper = metadata[i + 0] << 16;
var targetUpper = metadata[i + 1] << 16;
var count = metadata[i + 2];
perVertexLogic(sourceUpper, targetUpper, edgesOffset, count, edges);
edgesOffset += count;
}
}
#endregion
#region graph manipulation / transformation
public static void PartitionGraph(string filename, int parts, Func<int, int, int> partitionFunction, string newFormat)
{
var nodeStreams = new System.IO.BinaryWriter[parts];
var edgeStreams = new System.IO.BinaryWriter[parts];
for (int i = 0; i < parts; i++)
{
nodeStreams[i] = new System.IO.BinaryWriter(System.IO.File.OpenWrite(string.Format(newFormat + "-nodes", i, parts)));
edgeStreams[i] = new System.IO.BinaryWriter(System.IO.File.OpenWrite(string.Format(newFormat + "-edges", i, parts)));
}
var counters = new int[parts];
ScanGraph(filename, (vertex, degree, offset, edges) =>
{
for (int i = 0; i < parts; i++)
counters[i] = 0;
for (int i = 0; i < degree; i++)
counters[partitionFunction(vertex, edges[offset + i]) % parts]++;
for (int i = 0; i < parts; i++)
{
if (counters[i] > 0)
{
nodeStreams[i].Write(vertex);
nodeStreams[i].Write(counters[i]);
}
}
for (int i = 0; i < degree; i++)
edgeStreams[partitionFunction(vertex, edges[offset + i]) % parts].Write(edges[offset + i]);
});
for (int i = 0; i < parts; i++)
{
nodeStreams[i].Close();
edgeStreams[i].Close();
}
}
public static void TransposeGraph(string filename, int nodecount)
{
var nodes = new int[nodecount + 1];
ScanGraph(filename, (vertex, degree, offset, neighbors) =>
{
for (int i = 0; i < degree; i++)
nodes[neighbors[offset + i]]++;
});
// accumulate to determine ending offsets
for (int i = 1; i < nodes.Length; i++)
nodes[i] += nodes[i - 1];
// shift to determine starting offsets
for (int i = nodes.Length - 1; i > 0; i--)
nodes[i] = nodes[i - 1];
nodes[0] = 0;
var edges = new int[nodes[nodecount - 1]];
var buffer = new BufferTrie<int>.Pair[5000000];
var edgeTrie = new BufferTrie<int>(26, (array, offset, length) =>
{
for (int i = 0; i < length; i++)
edges[nodes[array[i].Index]++] = array[i].Value;
});
ScanGraph(filename, (vertex, degree, offset, neighbors) =>
{
for (int i = 0; i < degree; i++)
buffer[i] = new BufferTrie<int>.Pair(neighbors[offset + i], vertex);
edgeTrie.Insert(buffer, 0, degree);
});
edgeTrie.Flush();
}
public static void ConvertGraph(string filename)
{
using (var nodeWriter = new BinaryWriter(File.OpenWrite(filename + "-nodes")))
{
using (var edgeWriter = new BinaryWriter(File.OpenWrite(filename + "-edges")))
{
using (var reader = new UnbufferedIO.SequentialReader(filename))
{
var ints = new int[2];
var bytesToRead = reader.Length - 8;
// read vertex name and degree
reader.Read(ints, 0, 2);
var vertex = ints[0];
var degree = ints[1];
while (bytesToRead > 0)
{
// allocate space if needed
if (ints.Length < degree + 2)
ints = new int[degree + 2];
bytesToRead -= 4 * reader.Read(ints, 0, (degree + 2));
nodeWriter.Write(vertex);
nodeWriter.Write(degree);
for (int i = 0; i < degree; i++)
edgeWriter.Write(ints[i]);
vertex = ints[degree];
degree = ints[degree + 1];
}
}
}
}
}
#endregion
public static unsafe void MultiHilbertPagerank(string filename, float* a, float* b, uint nodes, float reset)
{
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
var degrees = LargePages.AllocateInts(nodes);
var scanner = new MultiHilbertScanner(filename);
scanner.Scan((xUpper, yUpper, count, offset, edges) =>
{
for (var j = offset; j < offset + count; j++)
degrees[xUpper + ((edges[j] & 0xF0) >> 4)]++;
});
Console.WriteLine("{0}\tDegrees calculated", stopwatch.Elapsed);
for (int iteration = 0; iteration < 20; iteration++)
{
var startTime = stopwatch.Elapsed;
for (int i = 0; i < nodes; i++)
{
b[i] = (1.0f - reset) * a[i] / degrees[i];
a[i] = reset;
}
scanner.Scan((xUpper, yUpper, count, offset, edges) =>
{
for (var j = offset; j < offset + count; j++)
a[yUpper + (edges[j] & 0x0F)] += b[xUpper + ((edges[j] & 0xF0) >> 4)];
});
Console.WriteLine("{0}\tIteration {1} in {2}", stopwatch.Elapsed, iteration, stopwatch.Elapsed - startTime);
}
}
public static unsafe void MultiHilbertCC(string filename, uint nodes)
{
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
var roots = LargePages.AllocateInts(nodes);
var ranks = LargePages.AllocateBytes(nodes);
for (int i = 0; i < nodes; i++)
roots[i] = i;
var scanner = new MultiHilbertScanner(filename);
scanner.Scan((xUpper, yUpper, count, offset, edges) =>
{
for (int j = 0; j < count; j++)
{
var source = (int)(xUpper + ((edges[offset + j] & 0xF0) >> 4));
var target = (int)(yUpper + ((edges[offset + j] & 0x0F) >> 0));
if (source != target)
{
while (source != roots[source])
source = roots[source];
while (target != roots[target])
target = roots[target];
// union(source, target)
if (source != target)
{
// there may be a tie in ranks
if (ranks[source] == ranks[target])
{
// break ties towards lower ids
if (source < target)
{
ranks[source]++;
roots[target] = source;
}
else
{
ranks[target]++;
roots[source] = target;
}
}
else
{
// attatch lower rank to higher
if (ranks[source] < ranks[target])
roots[source] = target;
else
roots[target] = source;
}
}
}
}
});
// path compress all vertices to roots.
for (int i = 0; i < nodes; i++)
while (roots[i] != roots[roots[i]])
roots[i] = roots[roots[i]];
var counter = 0;
for (int i = 0; i < nodes; i++)
if (roots[i] != i)
counter++;
Console.WriteLine("{1}\tEdges found: {0}", counter, stopwatch.Elapsed);
}
public static unsafe void HilbertPagerank(string filename, float* a, float* b, uint nodes, float reset)
{
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
var degrees = LargePages.AllocateInts(nodes);
//var degrees = new int[nodes];
var metadata = UnbufferedIO.ReadFile<uint>(filename + "-upper");
var edges = UnbufferedIO.ReadFile<uint>(filename + "-lower");
Console.WriteLine("{2}\tRead header of {0} blocks, for {1} edges", metadata.Length / 3, edges.Length, stopwatch.Elapsed);
ScanGraphHilbert(metadata, edges, (srcUpper, tgtUpper, offset, count, edgeArray) =>
{
for (var j = offset; j < offset + count; j++)
degrees[srcUpper + (edges[j] & 0xFFFF)]++;
});
Console.WriteLine("{0}\tDegrees calculated", stopwatch.Elapsed);
for (int iteration = 0; iteration < 20; iteration++)
{
var startTime = stopwatch.Elapsed;
for (int i = 0; i < nodes; i++)
{
b[i] = (1.0f - reset) * a[i] / degrees[i];
a[i] = reset;
}
ScanGraphHilbert(metadata, edges, (sourceUpper, targetUpper, offset, count, edgeArray) =>
{
for (var j = offset; j < offset + count; j++)
a[targetUpper + (edges[j] >> 16)] += b[sourceUpper + (edges[j] & 0xFFFF)];
});
Console.WriteLine("{0}\tIteration {1} in {2}", stopwatch.Elapsed, iteration, stopwatch.Elapsed - startTime);
}
}
public static unsafe void HilbertPagerankFromDisk(string filename, float[] a, float[] b, uint nodes, float reset)
{
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
#if UseLargePages
var degrees = LargePages.AllocateInts(nodes);
#else
var degrees = new int[nodes];
#endif
ScanGraphHilbert(filename, (srcUpper, tgtUpper, offset, count, edges) =>
{
for (int i = 0; i < count; i++)
degrees[srcUpper + (edges[offset + i] >> 16)]++;
});
Console.WriteLine("{0}\tDegrees calculated", stopwatch.Elapsed);
for (int iteration = 0; iteration < 20; iteration++)
{
var startTime = stopwatch.Elapsed;
ScanGraphHilbert(filename, (srcUpper, tgtUpper, offset, count, edges) =>
{
for (int i = 0; i < count; i++)
a[tgtUpper + (edges[offset + i] >> 16)] += b[srcUpper + (edges[offset + i] & 0xFFFF)];
});
for (int i = 0; i < nodes; i++)
a[i] = a[i] / degrees[i];
Console.WriteLine("{0}\tIteration {1} in {2}", stopwatch.Elapsed, iteration, stopwatch.Elapsed - startTime);
}
}
public static unsafe void HilbertUnionFind(string filenameUpper, string filenameLower, uint nodes)
{
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
using (var upper = System.IO.File.OpenRead(filenameUpper))
{
using (var lower = System.IO.File.OpenRead(filenameLower))
{
var bytes = new byte[upper.Length];
upper.Read(bytes, 0, bytes.Length);
var uppers = new int[bytes.Length / 4];
Buffer.BlockCopy(bytes, 0, uppers, 0, bytes.Length);
var maxEdges = 0;
for (int i = 0; i < uppers.Length; i += 3)
maxEdges = Math.Max(maxEdges, uppers[i + 2]);
Console.WriteLine("{1}\tRead header of {0} blocks", uppers.Length / 3, stopwatch.Elapsed);
bytes = new byte[8 * maxEdges];
var lowers = new UInt16[2 * maxEdges];
var edges = new Int32[2 * maxEdges];
#if UseLargePages
var roots = LargePages.AllocateInts(nodes);
var ranks = LargePages.AllocateBytes(nodes);
#else
var roots = new int[nodes];
var ranks = new byte[nodes];
#endif
for (int i = 0; i < nodes; i++)
roots[i] = i;
for (int i = 0; i < uppers.Length; i += 3)
{
var read = lower.Read(bytes, 0, 4 * uppers[i + 2]);
Buffer.BlockCopy(bytes, 0, lowers, 0, read);
var sourceUpper = uppers[i + 0] << 16;
var targetUpper = uppers[i + 1] << 16;
var count = uppers[i + 2];
for (int j = 0; j < count; j++)
{
edges[2 * j + 0] = roots[sourceUpper + lowers[2 * j + 0]];
edges[2 * j + 1] = roots[targetUpper + lowers[2 * j + 1]];
}
for (int j = 0; j < count; j++)
{
var source = edges[2 * j + 0];
var target = edges[2 * j + 1];
if (source != target)
{
while (source != roots[source])
source = roots[source];
while (target != roots[target])
target = roots[target];
// union(source, target)
if (source != target)
{
// there may be a tie in ranks
if (ranks[source] == ranks[target])
{
// break ties towards lower ids
if (source < target)
{
ranks[source]++;
roots[target] = source;
}
else
{
ranks[target]++;
roots[source] = target;
}
}
else
{
// attatch lower rank to higher
if (ranks[source] < ranks[target])
roots[source] = target;
else
roots[target] = source;
}
}
}
}
}
// path compress all vertices to roots.
for (int i = 0; i < nodes; i++)
while (roots[i] != roots[roots[i]])
roots[i] = roots[roots[i]];
var counter = 0;
for (int i = 0; i < nodes; i++)
if (roots[i] != i)
counter++;
Console.WriteLine("Edges found: {0}", counter);
}
}
}
public static unsafe void HilbertUnionFind2(string filename, uint nodes)
{
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
#if UseLargePages
var roots = LargePages.AllocateInts(nodes);
var ranks = LargePages.AllocateBytes(nodes);
#else
var roots = new int[nodes];
var ranks = new byte[nodes];
#endif
for (int i = 0; i < nodes; i++)
roots[i] = i;
ScanGraphHilbert(filename, (sourceUpper, targetUpper, offset, count, edges) =>
{
for (int j = 0; j < count; j++)
{
var source = (int)(sourceUpper + (edges[offset + j] & 0xFFFF));
var target = (int)(targetUpper + (edges[offset + j] >> 16));
if (source != target)
{
while (source != roots[source])
source = roots[source];
while (target != roots[target])
target = roots[target];
// union(source, target)
if (source != target)
{
// there may be a tie in ranks
if (ranks[source] == ranks[target])
{
// break ties towards lower ids
if (source < target)
{
ranks[source]++;
roots[target] = source;
}
else
{
ranks[target]++;
roots[source] = target;
}
}
else
{
// attatch lower rank to higher
if (ranks[source] < ranks[target])
roots[source] = target;
else
roots[target] = source;
}
}
}
}
});
// path compress all vertices to roots.
for (int i = 0; i < nodes; i++)
while (roots[i] != roots[roots[i]])
roots[i] = roots[roots[i]];
var counter = 0;
for (int i = 0; i < nodes; i++)
if (roots[i] != i)
counter++;
Console.WriteLine("Edges found: {0}", counter);
}
public static void PageRankStep(string filename, float[] a, float[] b, uint nodes, float reset)
{
for (int i = 0; i < a.Length; i++)
a[i] = reset;
// apply per-vertex pagerank logic across the graph
ScanGraph(filename, (vertex, degree, offset, neighbors) =>
{
var update = (1.0f - reset) * b[vertex] / degree;
for (int i = 0; i < degree; i++)
a[neighbors[offset + i]] += update;
});
}
public unsafe static void PageRankStepFromDisk(string filename, float* a, float* b, uint nodes, float reset)
{
for (int i = 0; i < nodes; i++)
a[i] = reset;
// apply per-vertex pagerank logic across the graph
ScanGraph(filename, (vertex, degree, offset, neighbors) =>
{
var update = (1.0f - reset) * b[vertex] / degree;
for (int i = 0; i < degree; i++)
a[neighbors[offset + i]] += update;
});
}
public unsafe static void PageRankFromDisk(string filename, float* a, float* b, uint nodes, float reset)
{
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
for (int i = 0; i < nodes; i++)
a[i] = reset;
var graph = new FileGraphScanner(filename);
for (int iteration = 0; iteration < 20; iteration++)
{
var startTime = stopwatch.Elapsed;
graph.ForEach((vertex, degree) =>
{
b[vertex] = (1.0f - reset) * a[vertex] / degree;
a[vertex] = reset;
});
graph.ForEach((vertex, degree, offset, neighbors) =>
{
for (int i = 0; i < degree; i++)
a[neighbors[offset + i]] += b[vertex];
});
Console.WriteLine("{0}\tIteration {1}", stopwatch.Elapsed - startTime, iteration);
}
Console.WriteLine(stopwatch.Elapsed);
}
public unsafe static void PageRankStep(string filename, float* a, float* b, uint nodes, float reset)
{
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
var nodeArray = UnbufferedIO.ReadFile<int>(filename + "-nodes");
var edgeArray = UnbufferedIO.ReadFile<int>(filename + "-edges");
for (int i = 0; i < nodes; i++)
a[i] = reset;
for (int iteration = 0; iteration < 20; iteration++)
{
var startTime = stopwatch.Elapsed;
for (int i = 0; i < nodes; i++)
{
b[i] = a[i];
a[i] = 0.0f;
}
// apply per-vertex pagerank logic across the graph
ScanGraph(nodeArray, edgeArray, (vertex, degree, offset, neighbors) =>
{
if (b[vertex] > 0.0f)
{
var update = (1.0f - reset) * b[vertex] / degree;
for (int i = 0; i < degree; i++)
a[neighbors[offset + i]] += update;
}
});
Console.WriteLine("{0}\tIteration {1}", stopwatch.Elapsed - startTime, iteration);
}
Console.WriteLine(stopwatch.Elapsed);
}
public unsafe static void ClumsyCC(string filename, uint nodes)
{
var labels = LargePages.AllocateInts(nodes);
for (int i = 0; i < nodes; i++)
labels[i] = i;
var oldSum = Int64.MaxValue;
var newSum = 0L;
for (int i = 0; i < nodes; i++)
newSum += labels[i];
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
while (newSum < oldSum)
{
var startTime = stopwatch.Elapsed;
// apply per-vertex pagerank logic across the graph
ScanGraph(filename, (vertex, degree, offset, neighbors) =>
{
var label = labels[vertex];
for (int i = 0; i < degree; i++)
label = Math.Min(label, labels[neighbors[offset + i]]);
labels[vertex] = label;
for (int i = 0; i < degree; i++)
labels[neighbors[offset + i]] = label;
});
oldSum = newSum;
newSum = 0L;
for (int i = 0; i < nodes; i++)
newSum += labels[i];
Console.WriteLine("{0}", stopwatch.Elapsed - startTime);
}
}
public unsafe static void ConnectedComponents(string filename, uint nodes)
{
#if UseLargePages
var roots = LargePages.AllocateInts(nodes);
var ranks = LargePages.AllocateBytes(nodes);
#else
var roots = new int[nodes];
var ranks = new byte[nodes];
#endif
for (int i = 0; i < nodes; i++)
roots[i] = i;
// apply per-vertex union-find logic across the graph
ScanGraph(filename, (vertex, degree, offset, neighbors) =>
{
// find(vertex)
var source = roots[vertex];
while (source != roots[source])
source = roots[source];
for (int i = 0; i < degree; i++)
{
// find(neighbors[i])
var target = roots[neighbors[offset + i]];
while (target != roots[target])
target = roots[target];
// union(source, target)
if (source != target)
{
// there may be a tie in ranks
if (ranks[source] == ranks[target])
{
// break ties towards lower ids
if (source < target)
{
ranks[source]++;
roots[target] = source;
}
else
{
ranks[target]++;
roots[source] = target;
source = target;
}
}
else
{
// attatch lower rank to higher
if (ranks[source] < ranks[target])
{
roots[source] = target;
source = target;
}
else
{
roots[target] = source;
}
}
}
}
});
var counter = 0;
for (int i = 0; i < nodes; i++)
if (roots[i] != i)
counter++;
Console.WriteLine("Edges found: {0}", counter);
}
public static void MaximalIndependentSet(string filename, int nodes)
{
var active = new bool[nodes];
ScanGraph(filename, (vertex, degree, offset, neighbors) =>
{
active[vertex] = true;
for (int i = 0; i < degree; i++)
if (neighbors[offset + i] < i && active[neighbors[offset + i]])
active[vertex] = false;
});
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Repeater.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.WebControls {
using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Web;
using System.Web.UI;
using System.Web.Util;
/// <devdoc>
/// <para>Defines the properties, methods, and events of a <see cref='System.Web.UI.WebControls.Repeater'/> class.</para>
/// </devdoc>
[
DefaultEvent("ItemCommand"),
DefaultProperty("DataSource"),
Designer("System.Web.UI.Design.WebControls.RepeaterDesigner, " + AssemblyRef.SystemDesign),
ParseChildren(true),
PersistChildren(false)
]
public class Repeater : Control, INamingContainer {
private static readonly object EventItemCreated = new object();
private static readonly object EventItemDataBound = new object();
private static readonly object EventItemCommand = new object();
private static readonly object EventCreatingModelDataSource = new object();
private static readonly object EventCallingDataMethods = new object();
internal const string ItemCountViewStateKey = "_!ItemCount";
private object dataSource;
private ITemplate headerTemplate;
private ITemplate footerTemplate;
private ITemplate itemTemplate;
private ITemplate alternatingItemTemplate;
private ITemplate separatorTemplate;
private ArrayList itemsArray;
private RepeaterItemCollection itemsCollection;
private bool _requiresDataBinding;
private bool _inited;
private bool _throwOnDataPropertyChange;
private DataSourceView _currentView;
private bool _currentViewIsFromDataSourceID;
private bool _currentViewValid;
private DataSourceSelectArguments _arguments;
private bool _pagePreLoadFired;
private string _itemType;
private string _selectMethod;
private ModelDataSource _modelDataSource;
private bool _asyncSelectPending;
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Web.UI.WebControls.Repeater'/> class.</para>
/// </devdoc>
public Repeater() {
}
private bool IsUsingModelBinders {
get {
return !String.IsNullOrEmpty(SelectMethod);
}
}
private void UpdateModelDataSourceProperties(ModelDataSource modelDataSource) {
if (modelDataSource == null) {
throw new ArgumentNullException("modelDataSource");
}
modelDataSource.UpdateProperties(ItemType, SelectMethod);
}
private ModelDataSource ModelDataSource {
get {
if (_modelDataSource == null) {
_modelDataSource = new ModelDataSource(this);
}
return _modelDataSource;
}
set {
if (value == null) {
throw new ArgumentNullException("value");
}
_modelDataSource = value;
}
}
protected virtual void OnCreatingModelDataSource(CreatingModelDataSourceEventArgs e) {
CreatingModelDataSourceEventHandler handler = Events[EventCreatingModelDataSource] as CreatingModelDataSourceEventHandler;
if (handler != null) {
handler(this, e);
}
}
[
WebCategory("Data"),
WebSysDescription(SR.DataBoundControl_OnCreatingModelDataSource)
]
public event CreatingModelDataSourceEventHandler CreatingModelDataSource {
add {
Events.AddHandler(EventCreatingModelDataSource, value);
}
remove {
Events.RemoveHandler(EventCreatingModelDataSource, value);
}
}
/// <summary>
/// The name of the model type used in the SelectMethod, InsertMethod, UpdateMethod, and DeleteMethod.
/// </summary>
[
DefaultValue(""),
Themeable(false),
WebCategory("Data"),
WebSysDescription(SR.DataBoundControl_ItemType)
]
public virtual string ItemType {
get {
return _itemType ?? String.Empty;
}
set {
if (!String.Equals(_itemType, value, StringComparison.OrdinalIgnoreCase)) {
_itemType = value;
OnDataPropertyChanged();
}
}
}
/// <summary>
/// The name of the method on the page which is called when this Control does a select operation.
/// </summary>
[
DefaultValue(""),
Themeable(false),
WebCategory("Data"),
WebSysDescription(SR.DataBoundControl_SelectMethod)
]
public virtual string SelectMethod {
get {
return _selectMethod ?? String.Empty;
}
set {
if (!String.Equals(_selectMethod, value, StringComparison.OrdinalIgnoreCase)) {
_selectMethod = value;
OnDataPropertyChanged();
}
}
}
/// <summary>
/// Occurs before model methods are invoked for data operations.
/// Handle this event if the model methods are defined on a custom type other than the code behind file.
/// </summary>
[
WebCategory("Data"),
WebSysDescription(SR.DataBoundControl_CallingDataMethods)
]
public event CallingDataMethodsEventHandler CallingDataMethods {
add {
Events.AddHandler(EventCallingDataMethods, value);
}
remove {
Events.RemoveHandler(EventCallingDataMethods, value);
if (_modelDataSource != null) {
_modelDataSource.CallingDataMethods -= value;
}
}
}
/// <devdoc>
/// <para>Gets or sets the <see cref='System.Web.UI.ITemplate' qualify='true'/> that defines how alternating (even-indexed) items
/// are rendered. </para>
/// </devdoc>
[
Browsable(false),
DefaultValue(null),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(RepeaterItem)),
WebSysDescription(SR.Repeater_AlternatingItemTemplate)
]
public virtual ITemplate AlternatingItemTemplate {
get {
return alternatingItemTemplate;
}
set {
alternatingItemTemplate = value;
}
}
public override ControlCollection Controls {
get {
EnsureChildControls();
return base.Controls;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[
DefaultValue(""),
WebCategory("Data"),
WebSysDescription(SR.Repeater_DataMember)
]
public virtual string DataMember {
get {
object o = ViewState["DataMember"];
if (o != null)
return (string)o;
return String.Empty;
}
set {
ViewState["DataMember"] = value;
OnDataPropertyChanged();
}
}
/// <devdoc>
/// <para> Gets or sets the data source that provides data for
/// populating the list.</para>
/// </devdoc>
[
Bindable(true),
WebCategory("Data"),
DefaultValue(null),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
WebSysDescription(SR.BaseDataBoundControl_DataSource)
]
public virtual object DataSource {
get {
return dataSource;
}
set {
if ((value == null) || (value is IListSource) || (value is IEnumerable)) {
dataSource = value;
OnDataPropertyChanged();
}
else {
throw new ArgumentException(SR.GetString(SR.Invalid_DataSource_Type, ID));
}
}
}
/// <summary>
/// The ID of the DataControl that this control should use to retrieve
/// its data source. When the control is bound to a DataControl, it
/// can retrieve a data source instance on-demand, and thereby attempt
/// to work in auto-DataBind mode.
/// </summary>
[
DefaultValue(""),
IDReferenceProperty(typeof(DataSourceControl)),
WebCategory("Data"),
WebSysDescription(SR.BaseDataBoundControl_DataSourceID)
]
public virtual string DataSourceID {
get {
object o = ViewState["DataSourceID"];
if (o != null) {
return (string)o;
}
return String.Empty;
}
set {
ViewState["DataSourceID"] = value;
OnDataPropertyChanged();
}
}
/// <devdoc>
/// <para>Gets and sets a value indicating whether theme is enabled.</para>
/// </devdoc>
[
Browsable(true)
]
public override bool EnableTheming {
get {
return base.EnableTheming;
}
set {
base.EnableTheming = value;
}
}
/// <devdoc>
/// <para>Gets or sets the <see cref='System.Web.UI.ITemplate' qualify='true'/> that defines how the control footer is
/// rendered. </para>
/// </devdoc>
[
Browsable(false),
DefaultValue(null),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(RepeaterItem)),
WebSysDescription(SR.Repeater_FooterTemplate)
]
public virtual ITemplate FooterTemplate {
get {
return footerTemplate;
}
set {
footerTemplate = value;
}
}
/// <devdoc>
/// <para>Gets or sets the <see cref='System.Web.UI.ITemplate' qualify='true'/> that defines how the control header is rendered. </para>
/// </devdoc>
[
Browsable(false),
DefaultValue(null),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(RepeaterItem)),
WebSysDescription(SR.WebControl_HeaderTemplate)
]
public virtual ITemplate HeaderTemplate {
get {
return headerTemplate;
}
set {
headerTemplate = value;
}
}
protected bool Initialized {
get {
return _inited;
}
}
protected bool IsBoundUsingDataSourceID {
get {
return (DataSourceID.Length > 0);
}
}
protected bool IsDataBindingAutomatic {
get {
return IsBoundUsingDataSourceID || IsUsingModelBinders;
}
}
/// <devdoc>
/// Gets the <see cref='System.Web.UI.WebControls.RepeaterItem'/> collection.
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
WebSysDescription(SR.Repeater_Items)
]
public virtual RepeaterItemCollection Items {
get {
if (itemsCollection == null) {
if (itemsArray == null) {
EnsureChildControls();
}
itemsCollection = new RepeaterItemCollection(itemsArray);
}
return itemsCollection;
}
}
/// <devdoc>
/// <para>Gets or sets the <see cref='System.Web.UI.ITemplate' qualify='true'/> that defines how items are rendered. </para>
/// </devdoc>
[
Browsable(false),
DefaultValue(null),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(RepeaterItem)),
WebSysDescription(SR.Repeater_ItemTemplate)
]
public virtual ITemplate ItemTemplate {
get {
return itemTemplate;
}
set {
itemTemplate = value;
}
}
protected bool RequiresDataBinding {
get {
return _requiresDataBinding;
}
set {
_requiresDataBinding = value;
}
}
protected DataSourceSelectArguments SelectArguments {
get {
if (_arguments == null) {
_arguments = CreateDataSourceSelectArguments();
}
return _arguments;
}
}
/// <devdoc>
/// <para>Gets or sets the <see cref='System.Web.UI.ITemplate' qualify='true'/> that defines how separators
/// in between items are rendered.</para>
/// </devdoc>
[
Browsable(false),
DefaultValue(null),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(RepeaterItem)),
WebSysDescription(SR.Repeater_SeparatorTemplate)
]
public virtual ITemplate SeparatorTemplate {
get {
return separatorTemplate;
}
set {
separatorTemplate = value;
}
}
/// <devdoc>
/// <para>Occurs when a button is clicked within the <see cref='System.Web.UI.WebControls.Repeater'/> control tree.</para>
/// </devdoc>
[
WebCategory("Action"),
WebSysDescription(SR.Repeater_OnItemCommand)
]
public event RepeaterCommandEventHandler ItemCommand {
add {
Events.AddHandler(EventItemCommand, value);
}
remove {
Events.RemoveHandler(EventItemCommand, value);
}
}
/// <devdoc>
/// <para> Occurs when an item is created within the <see cref='System.Web.UI.WebControls.Repeater'/> control tree.</para>
/// </devdoc>
[
WebCategory("Behavior"),
WebSysDescription(SR.DataControls_OnItemCreated)
]
public event RepeaterItemEventHandler ItemCreated {
add {
Events.AddHandler(EventItemCreated, value);
}
remove {
Events.RemoveHandler(EventItemCreated, value);
}
}
/// <devdoc>
/// <para>Occurs when an item is databound within a <see cref='System.Web.UI.WebControls.Repeater'/> control tree.</para>
/// </devdoc>
[
WebCategory("Behavior"),
WebSysDescription(SR.DataControls_OnItemDataBound)
]
public event RepeaterItemEventHandler ItemDataBound {
add {
Events.AddHandler(EventItemDataBound, value);
}
remove {
Events.RemoveHandler(EventItemDataBound, value);
}
}
/// <devdoc>
/// Connects this data bound control to the appropriate DataSourceView
/// and hooks up the appropriate event listener for the
/// DataSourceViewChanged event. The return value is the new view (if
/// any) that was connected to. An exception is thrown if there is
/// a problem finding the requested view or data source.
/// </devdoc>
private DataSourceView ConnectToDataSourceView() {
if (_currentViewValid && !DesignMode) {
// If the current view is correct, there is no need to reconnect
return _currentView;
}
// Disconnect from old view, if necessary
if ((_currentView != null) && (_currentViewIsFromDataSourceID)) {
// We only care about this event if we are bound through the DataSourceID property
_currentView.DataSourceViewChanged -= new EventHandler(OnDataSourceViewChanged);
}
// Connect to new view
IDataSource ds = null;
if (!DesignMode && IsUsingModelBinders) {
if (DataSourceID.Length != 0 || DataSource != null) {
throw new InvalidOperationException(SR.GetString(SR.DataControl_ItemType_MultipleDataSources, ID));
}
//Let the developer choose a custom ModelDataSource.
CreatingModelDataSourceEventArgs e = new CreatingModelDataSourceEventArgs();
OnCreatingModelDataSource(e);
if (e.ModelDataSource != null) {
ModelDataSource = e.ModelDataSource;
}
//Update the properties of ModelDataSource so that it's ready for data-binding.
UpdateModelDataSourceProperties(ModelDataSource);
//Add the CallingDataMethodsEvent
CallingDataMethodsEventHandler handler = Events[EventCallingDataMethods] as CallingDataMethodsEventHandler;
if (handler != null) {
ModelDataSource.CallingDataMethods += handler;
}
ds = ModelDataSource;
}
else {
string dataSourceID = DataSourceID;
if (dataSourceID.Length != 0) {
// Try to find a DataSource control with the ID specified in DataSourceID
Control control = DataBoundControlHelper.FindControl(this, dataSourceID);
if (control == null) {
throw new HttpException(SR.GetString(SR.DataControl_DataSourceDoesntExist, ID, dataSourceID));
}
ds = control as IDataSource;
if (ds == null) {
throw new HttpException(SR.GetString(SR.DataControl_DataSourceIDMustBeDataControl, ID, dataSourceID));
}
}
}
if (ds == null) {
// DataSource control was not found, construct a temporary data source to wrap the data
ds = new ReadOnlyDataSource(DataSource, DataMember);
}
else {
// Ensure that both DataSourceID as well as DataSource are not set at the same time
if (DataSource != null) {
throw new InvalidOperationException(SR.GetString(SR.DataControl_MultipleDataSources, ID));
}
}
// IDataSource was found, extract the appropriate view and return it
DataSourceView newView = ds.GetView(DataMember);
if (newView == null) {
throw new InvalidOperationException(SR.GetString(SR.DataControl_ViewNotFound, ID));
}
_currentViewIsFromDataSourceID = IsDataBindingAutomatic;
_currentView = newView;
if ((_currentView != null) && (_currentViewIsFromDataSourceID)) {
// We only care about this event if we are bound through the DataSourceID property
_currentView.DataSourceViewChanged += new EventHandler(OnDataSourceViewChanged);
}
_currentViewValid = true;
return _currentView;
}
/// <devdoc>
/// </devdoc>
protected internal override void CreateChildControls() {
Controls.Clear();
if (ViewState[ItemCountViewStateKey] != null) {
// create the control hierarchy using the view state (and
// not the datasource)
CreateControlHierarchy(false);
}
else {
itemsArray = new ArrayList();
}
ClearChildViewState();
}
/// <devdoc>
/// A protected method. Creates a control
/// hierarchy, with or without the data source as specified.
/// </devdoc>
protected virtual void CreateControlHierarchy(bool useDataSource) {
IEnumerable dataSource = null;
if (itemsArray != null) {
itemsArray.Clear();
}
else {
itemsArray = new ArrayList();
}
if (!useDataSource) {
// ViewState must have a non-null value for ItemCount because we check for
// this in CreateChildControls
int count = (int)ViewState[ItemCountViewStateKey];
if (count != -1) {
dataSource = new DummyDataSource(count);
itemsArray.Capacity = count;
}
AddDataItemsIntoItemsArray(dataSource, useDataSource);
}
else {
dataSource = GetData();
PostGetDataAction(dataSource);
}
}
private void OnDataSourceViewSelectCallback(IEnumerable data) {
_asyncSelectPending = false;
PostGetDataAction(data);
}
private void PostGetDataAction(IEnumerable dataSource) {
if (_asyncSelectPending)
return;
ICollection collection = dataSource as ICollection;
if (collection != null) {
itemsArray.Capacity = collection.Count;
}
int addedItemCount = AddDataItemsIntoItemsArray(dataSource, true/*useDataSource*/);
ViewState[ItemCountViewStateKey] = addedItemCount;
}
private int AddDataItemsIntoItemsArray(IEnumerable dataSource, bool useDataSource) {
int dataItemCount = -1;
if (dataSource != null) {
RepeaterItem item;
ListItemType itemType;
int index = 0;
bool hasSeparators = (separatorTemplate != null);
dataItemCount = 0;
if (headerTemplate != null) {
CreateItem(-1, ListItemType.Header, useDataSource, null);
}
foreach (object dataItem in dataSource) {
// rather than creating separators after the item, we create the separator
// for the previous item in all iterations of this loop.
// this is so that we don't create a separator for the last item
if (hasSeparators && (dataItemCount > 0)) {
CreateItem(index - 1, ListItemType.Separator, useDataSource, null);
}
itemType = (index % 2 == 0) ? ListItemType.Item : ListItemType.AlternatingItem;
item = CreateItem(index, itemType, useDataSource, dataItem);
itemsArray.Add(item);
dataItemCount++;
index++;
}
if (footerTemplate != null) {
CreateItem(-1, ListItemType.Footer, useDataSource, null);
}
}
return dataItemCount;
}
protected virtual DataSourceSelectArguments CreateDataSourceSelectArguments() {
return DataSourceSelectArguments.Empty;
}
/// <devdoc>
/// </devdoc>
private RepeaterItem CreateItem(int itemIndex, ListItemType itemType, bool dataBind, object dataItem) {
RepeaterItem item = CreateItem(itemIndex, itemType);
RepeaterItemEventArgs e = new RepeaterItemEventArgs(item);
InitializeItem(item);
if (dataBind) {
item.DataItem = dataItem;
}
OnItemCreated(e);
Controls.Add(item);
if (dataBind) {
item.DataBind();
OnItemDataBound(e);
item.DataItem = null;
}
return item;
}
/// <devdoc>
/// <para>A protected method. Creates a <see cref='System.Web.UI.WebControls.RepeaterItem'/> with the specified item type and
/// location within the <see cref='System.Web.UI.WebControls.Repeater'/>.</para>
/// </devdoc>
protected virtual RepeaterItem CreateItem(int itemIndex, ListItemType itemType) {
return new RepeaterItem(itemIndex, itemType);
}
/// <internalonly/>
/// <devdoc>
/// </devdoc>
public override void DataBind() {
// Don't databind to a data source control when the control is in the designer but not top-level
if (IsDataBindingAutomatic && DesignMode && (Site == null)) {
return;
}
// do our own databinding
RequiresDataBinding = false;
OnDataBinding(EventArgs.Empty);
// contained items will be databound after they have been created,
// so we don't want to walk the hierarchy here.
}
protected void EnsureDataBound() {
try {
_throwOnDataPropertyChange = true;
if (RequiresDataBinding && IsDataBindingAutomatic) {
DataBind();
}
}
finally {
_throwOnDataPropertyChange = false;
}
}
/// <devdoc>
/// Returns an IEnumerable that is the DataSource, which either came
/// from the DataSource property or from the control bound via the
/// DataSourceID property.
/// </devdoc>
protected virtual IEnumerable GetData() {
DataSourceView view = ConnectToDataSourceView();
Debug.Assert(_currentViewValid);
if (view != null) {
// DevDiv 1070535: enable async model binding for Repeater
bool useAsyncSelect = false;
if (AppSettings.EnableAsyncModelBinding) {
var modelDataView = view as ModelDataSourceView;
useAsyncSelect = modelDataView != null && modelDataView.IsSelectMethodAsync;
}
if (useAsyncSelect) {
_asyncSelectPending = true; // disable post data binding action until the callback is invoked
view.Select(SelectArguments, OnDataSourceViewSelectCallback);
}
else {
return view.ExecuteSelect(SelectArguments);
}
}
return null;
}
/// <devdoc>
/// <para>A protected method. Populates iteratively the specified <see cref='System.Web.UI.WebControls.RepeaterItem'/> with a
/// sub-hierarchy of child controls.</para>
/// </devdoc>
protected virtual void InitializeItem(RepeaterItem item) {
ITemplate contentTemplate = null;
switch (item.ItemType) {
case ListItemType.Header:
contentTemplate = headerTemplate;
break;
case ListItemType.Footer:
contentTemplate = footerTemplate;
break;
case ListItemType.Item:
contentTemplate = itemTemplate;
break;
case ListItemType.AlternatingItem:
contentTemplate = alternatingItemTemplate;
if (contentTemplate == null)
goto case ListItemType.Item;
break;
case ListItemType.Separator:
contentTemplate = separatorTemplate;
break;
}
if (contentTemplate != null) {
contentTemplate.InstantiateIn(item);
}
}
/// <internalonly/>
/// <devdoc>
/// </devdoc>
protected override bool OnBubbleEvent(object sender, EventArgs e) {
bool handled = false;
if (e is RepeaterCommandEventArgs) {
OnItemCommand((RepeaterCommandEventArgs)e);
handled = true;
}
return handled;
}
/// <internalonly/>
/// <devdoc>
/// <para>A protected method. Raises the <see langword='DataBinding'/> event.</para>
/// </devdoc>
protected override void OnDataBinding(EventArgs e) {
base.OnDataBinding(e);
// reset the control state
Controls.Clear();
ClearChildViewState();
// and then create the control hierarchy using the datasource
CreateControlHierarchy(true);
ChildControlsCreated = true;
}
/// <devdoc>
/// This method is called when DataMember, DataSource, or DataSourceID is changed.
/// </devdoc>
protected virtual void OnDataPropertyChanged() {
if (_throwOnDataPropertyChange) {
throw new HttpException(SR.GetString(SR.DataBoundControl_InvalidDataPropertyChange, ID));
}
if (_inited) {
RequiresDataBinding = true;
}
_currentViewValid = false;
}
protected virtual void OnDataSourceViewChanged(object sender, EventArgs e) {
RequiresDataBinding = true;
}
protected internal override void OnInit(EventArgs e) {
base.OnInit(e);
if (Page != null) {
Page.PreLoad += new EventHandler(this.OnPagePreLoad);
if (!IsViewStateEnabled && Page.IsPostBack) {
RequiresDataBinding = true;
}
}
if (!DesignMode && !String.IsNullOrEmpty(ItemType)) {
DataBoundControlHelper.EnableDynamicData(this, ItemType);
}
}
/// <devdoc>
/// <para>A protected method. Raises the <see langword='ItemCommand'/> event.</para>
/// </devdoc>
protected virtual void OnItemCommand(RepeaterCommandEventArgs e) {
RepeaterCommandEventHandler onItemCommandHandler = (RepeaterCommandEventHandler)Events[EventItemCommand];
if (onItemCommandHandler != null) onItemCommandHandler(this, e);
}
/// <devdoc>
/// <para>A protected method. Raises the <see langword='ItemCreated'/> event.</para>
/// </devdoc>
protected virtual void OnItemCreated(RepeaterItemEventArgs e) {
RepeaterItemEventHandler onItemCreatedHandler = (RepeaterItemEventHandler)Events[EventItemCreated];
if (onItemCreatedHandler != null) onItemCreatedHandler(this, e);
}
/// <devdoc>
/// <para>A protected method. Raises the <see langword='ItemDataBound'/>
/// event.</para>
/// </devdoc>
protected virtual void OnItemDataBound(RepeaterItemEventArgs e) {
RepeaterItemEventHandler onItemDataBoundHandler = (RepeaterItemEventHandler)Events[EventItemDataBound];
if (onItemDataBoundHandler != null) onItemDataBoundHandler(this, e);
}
protected internal override void OnLoad(EventArgs e) {
_inited = true; // just in case we were added to the page after PreLoad
ConnectToDataSourceView();
if (Page != null && !_pagePreLoadFired && ViewState[ItemCountViewStateKey] == null) {
// If the control was added after PagePreLoad, we still need to databind it because it missed its
// first change in PagePreLoad. If this control was created by a call to a parent control's DataBind
// in Page_Load (with is relatively common), this control will already have been databound even
// though pagePreLoad never fired and the page isn't a postback.
if (!Page.IsPostBack) {
RequiresDataBinding = true;
}
// If the control was added to the page after page.PreLoad, we'll never get the event and we'll
// never databind the control. So if we're catching up and Load happens but PreLoad never happened,
// call DataBind. This may make the control get databound twice if the user called DataBind on the control
// directly in Page.OnLoad, but better to bind twice than never to bind at all.
else if (IsViewStateEnabled) {
RequiresDataBinding = true;
}
}
base.OnLoad(e);
}
private void OnPagePreLoad(object sender, EventArgs e) {
_inited = true;
if (Page != null) {
Page.PreLoad -= new EventHandler(this.OnPagePreLoad);
// Setting RequiresDataBinding to true in OnLoad is too late because the OnLoad page event
// happens before the control.OnLoad method gets called. So a page_load handler on the page
// that calls DataBind won't prevent DataBind from getting called again in PreRender.
if (!Page.IsPostBack) {
RequiresDataBinding = true;
}
// If this is a postback and viewstate is enabled, but we have never bound the control
// before, it is probably because its visibility was changed in the postback. In this
// case, we need to bind the control or it will never appear. This is a common scenario
// for Wizard and MultiView.
if (Page.IsPostBack && IsViewStateEnabled && ViewState[ItemCountViewStateKey] == null) {
RequiresDataBinding = true;
}
_pagePreLoadFired = true;
}
}
protected internal override void OnPreRender(EventArgs e) {
EnsureDataBound();
base.OnPreRender(e);
}
/// <devdoc>
/// Loads view state.
/// </devdoc>
protected override void LoadViewState(object savedState) {
if (IsUsingModelBinders) {
Pair myState = (Pair)savedState;
if (savedState == null) {
base.LoadViewState(null);
}
else {
base.LoadViewState(myState.First);
if (myState.Second != null) {
((IStateManager)ModelDataSource).LoadViewState(myState.Second);
}
}
}
else {
base.LoadViewState(savedState);
}
}
/// <devdoc>
/// Saves view state.
/// </devdoc>
protected override object SaveViewState() {
// Bug 322689: In the web farms scenario, if a web site is hosted in 4.0 and 4.5 servers
// (though this is not a really supported scenario, we are fixing this instance),
// the View state created by 4.0 should be able to be understood by 4.5 controls.
// So, we create a Pair only if we are using model binding and otherwise fallback to 4.0 behavior.
object baseViewState = base.SaveViewState();
if (IsUsingModelBinders) {
Pair myState = new Pair();
myState.First = baseViewState;
myState.Second = ((IStateManager)ModelDataSource).SaveViewState();
if ((myState.First == null) &&
(myState.Second == null)) {
return null;
}
return myState;
}
else {
return baseViewState;
}
}
/// <devdoc>
/// Starts tracking view state.
/// </devdoc>
protected override void TrackViewState() {
base.TrackViewState();
if (IsUsingModelBinders) {
((IStateManager)ModelDataSource).TrackViewState();
}
}
}
}
| |
/*
* Copyright (c) .NET Foundation and Contributors
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
* https://github.com/piranhacms/piranha.core
*
*/
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Piranha.Extend.Fields
{
/// <summary>
/// Generic select field.
/// </summary>
[FieldType(Name = "Select", Shorthand = "Select", Component = "select-field")]
public class SelectField<T> : SelectFieldBase, IEquatable<SelectField<T>> where T : struct
{
/// <summary>
/// The static list of available items.
/// </summary>
private static readonly List<SelectFieldItem> _items = new List<SelectFieldItem>();
/// <summary>
/// Initialization mutex.
/// </summary>
private static readonly object Mutex = new object();
/// <summary>
/// The initialization state.
/// </summary>
private static bool IsInitialized;
/// <summary>
/// Gets/sets the selected value.
/// </summary>
public T Value { get; set; }
/// <summary>
/// Gets the current enum type.
/// </summary>
public override Type EnumType
{
get { return typeof(T); }
}
/// <summary>
/// Gets/sets the selected value as a string.
/// </summary>
public override string EnumValue
{
get { return Value.ToString(); }
set { Value = (T)Enum.Parse(typeof(T), value); }
}
/// <summary>
/// Gets the available items to choose from. Primarily used
/// from the manager interface.
/// </summary>
public override List<SelectFieldItem> Items
{
get
{
InitMetaData();
return _items;
}
}
/// <summary>
/// Gets the list item title if this field is used in
/// a collection regions.
/// </summary>
public override string GetTitle()
{
return GetEnumTitle((Enum)(object)Value);
}
/// <summary>
/// Initializes the field for client use.
/// </summary>
/// <param name="api">The current api</param>
public override void Init(IApi api)
{
InitMetaData();
}
/// <summary>
/// Gets the hash code for the field.
/// </summary>
public override int GetHashCode()
{
return Value.GetHashCode();
}
/// <summary>
/// Checks if the given object is equal to the field.
/// </summary>
/// <param name="obj">The object</param>
/// <returns>True if the fields are equal</returns>
public override bool Equals(object obj)
{
if (obj is SelectField<T> field)
{
return Equals(field);
}
return false;
}
/// <summary>
/// Checks if the given field is equal to the field.
/// </summary>
/// <param name="obj">The field</param>
/// <returns>True if the fields are equal</returns>
public virtual bool Equals(SelectField<T> obj)
{
if (obj == null)
{
return false;
}
return EqualityComparer<T>.Default.Equals(Value, obj.Value);
}
/// <summary>
/// Checks if the fields are equal.
/// </summary>
/// <param name="field1">The first field</param>
/// <param name="field2">The second field</param>
/// <returns>True if the fields are equal</returns>
public static bool operator ==(SelectField<T> field1, SelectField<T> field2)
{
if ((object)field1 != null && (object)field2 != null)
{
return field1.Equals(field2);
}
if ((object)field1 == null && (object)field2 == null)
{
return true;
}
return false;
}
/// <summary>
/// Checks if the fields are not equal.
/// </summary>
/// <param name="field1">The first field</param>
/// <param name="field2">The second field</param>
/// <returns>True if the fields are equal</returns>
public static bool operator !=(SelectField<T> field1, SelectField<T> field2)
{
return !(field1 == field2);
}
/// <summary>
/// Gets the display title for the given enum. If the DisplayAttribute
/// is present it's description is returned, otherwise the string
/// representation of the enum.
/// </summary>
/// <param name="val">The enum value</param>
/// <returns>The display title</returns>
private string GetEnumTitle(Enum val)
{
var members = typeof(T).GetMember(val.ToString());
if (members != null && members.Length > 0)
{
var attrs = members[0].GetCustomAttributes(false);
foreach (var attr in attrs)
{
if (attr is DisplayAttribute)
{
return ((DisplayAttribute)attr).Description;
}
}
}
return val.ToString();
}
/// <summary>
/// Initializes the meta data needed in the manager interface.
/// </summary>
private void InitMetaData()
{
if (IsInitialized)
return;
lock (Mutex)
{
if (IsInitialized)
{
return;
}
foreach (var val in Enum.GetValues(typeof(T)))
{
_items.Add(new SelectFieldItem
{
Title = GetEnumTitle((Enum)val),
Value = (Enum)val
});
}
IsInitialized = true;
}
}
}
}
| |
using System;
using System.IO;
using System.Security.Cryptography;
namespace Platform.IO
{
/// <summary>
/// A stream wrapper implementation that implements support cryptography
/// that supports tream flushing even if the current cryptographic buffer
/// has not yet been filled.
/// </summary>
/// <remarks>
/// Cryptographic blocks that have not yet been filled when <see cref="Flush()"/>
/// is called will be filled with random data. Cryptographic blocks are marked
/// with the length of the real data.
/// </remarks>
public class InteractiveCryptoStream
: StreamWrapper
{
private readonly byte[] readOneByte = new byte[1];
private readonly byte[] writeOneByte = new byte[1];
private readonly byte[] readPreBuffer;
private readonly byte[] readBuffer;
private int readBufferCount;
private int readBufferIndex;
private readonly byte[] writeBuffer;
private readonly byte[] writeBlockBuffer;
private int writeBufferCount;
private readonly ICryptoTransform transform;
private readonly CryptoStreamMode mode;
public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } }
public override long Length { get { throw new NotSupportedException(); } }
public override bool CanRead { get { return this.mode == CryptoStreamMode.Read; } }
public override bool CanWrite { get { return this.mode == CryptoStreamMode.Write; } }
public override bool CanSeek
{
get
{
return false;
}
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public InteractiveCryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode)
: this(stream, transform, mode, 255)
{
}
public InteractiveCryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode, int bufferSizeInBlocks)
: base(stream)
{
if (bufferSizeInBlocks < 0)
{
throw new ArgumentOutOfRangeException("bufferSizeInBlocks", bufferSizeInBlocks, "BufferSize can't be less than 0");
}
if (bufferSizeInBlocks > 255)
{
bufferSizeInBlocks = 255;
}
this.mode = mode;
this.transform = transform;
this.writeBuffer = new byte[2 + transform.InputBlockSize * bufferSizeInBlocks];
this.writeBlockBuffer = new byte[transform.OutputBlockSize];
this.readPreBuffer = new byte[transform.OutputBlockSize * 5];
this.readBuffer = new byte[transform.InputBlockSize * 5];
this.writeBufferCount = 2;
this.readBufferCount = 0;
this.readBufferIndex = 0;
}
public override void WriteByte(byte value)
{
this.writeOneByte[0] = value;
this.Write(this.writeOneByte, 0, 1);
}
public override void Write(byte[] buffer, int offset, int count)
{
if (!this.CanWrite)
{
throw new NotSupportedException("Reading not supported");
}
if (count == 0)
{
return;
}
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (offset + count > buffer.Length)
{
throw new ArgumentException("offset and length exceed buffer size");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset", offset, "can not be negative");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", count, "can not be negative");
}
while (count > 0)
{
var length = Math.Min(count, this.writeBuffer.Length - this.writeBufferCount);
if (length == 0)
{
this.Flush();
continue;
}
Array.Copy(buffer, offset, this.writeBuffer, this.writeBufferCount, length);
this.writeBufferCount += length;
count -= length;
}
}
private int bytesLeftInSuperBlock = 0;
private int bytesPaddingSuperBlock = 0;
public override int ReadByte()
{
var x = this.Read(this.readOneByte, 0, 1);
if (x == -1)
{
return -1;
}
return this.readOneByte[0];
}
private int ReadAndConvertBlocks()
{
int x;
var read = 0;
while (true)
{
x = base.Read(this.readPreBuffer, 0, this.readPreBuffer.Length - read);
if (x == 0)
{
return -1;
}
read += x;
if (read % this.transform.OutputBlockSize == 0)
{
break;
}
}
if (this.transform.CanTransformMultipleBlocks)
{
return this.transform.TransformBlock(this.readPreBuffer, 0, read, this.readBuffer, 0);
}
else
{
x = 0;
for (int i = 0; i < read / this.transform.OutputBlockSize; i++)
{
x += this.transform.TransformBlock(this.readPreBuffer,
i * this.transform.OutputBlockSize,
this.transform.OutputBlockSize,
this.readBuffer,
i * this.transform.InputBlockSize);
}
return x;
}
}
public override int Read(byte[] buffer, int offset, int count)
{
if (!this.CanRead)
{
throw new NotSupportedException("Reading not supported");
}
if (count == 0)
{
return 0;
}
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (offset + count > buffer.Length)
{
throw new ArgumentException("offset and length exceed buffer size");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset", offset, "can not be negative");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", count, "can not be negative");
}
while (true)
{
if (this.readBufferCount == 0)
{
while (true)
{
var x = this.ReadAndConvertBlocks();
if (x == 0)
{
continue;
}
else if (x == -1)
{
this.readBufferIndex = 0;
this.readBufferCount = 0;
return 0;
}
this.readBufferIndex = 0;
this.readBufferCount = x;
break;
}
}
if (this.bytesLeftInSuperBlock == 0)
{
this.bytesLeftInSuperBlock = this.readBuffer[this.readBufferIndex];
this.bytesLeftInSuperBlock |= this.readBuffer[this.readBufferIndex + 1] << 8;
this.bytesLeftInSuperBlock += 2;
if (this.bytesLeftInSuperBlock == 2)
{
this.bytesLeftInSuperBlock = 0;
this.readBufferIndex += this.transform.InputBlockSize;
this.readBufferCount -= this.transform.InputBlockSize;
continue;
}
this.readBufferCount -= 2;
this.readBufferIndex += 2;
this.bytesPaddingSuperBlock = (((this.bytesLeftInSuperBlock + 15) / 16) * 16) - this.bytesLeftInSuperBlock;
this.bytesLeftInSuperBlock -= 2;
}
var length = MathUtils.Min(this.bytesLeftInSuperBlock, this.readBufferCount, count);
Array.Copy(this.readBuffer, this.readBufferIndex, buffer, offset, length);
this.bytesLeftInSuperBlock -= length;
this.readBufferCount -= length;
this.readBufferIndex += length;
if (this.bytesLeftInSuperBlock == 0)
{
this.readBufferIndex += this.bytesPaddingSuperBlock;
this.readBufferCount -= this.bytesPaddingSuperBlock;
}
return length;
}
}
private readonly Random random = new Random();
public override void Flush()
{
this.PrivateFlush();
// The ICryptoTransform always keeps the most recent block
// in memory so we have to write an empty block to get the
// result of the encryption of the last useful block.
this.writeBuffer[0] = 0;
this.writeBuffer[1] = 0;
for (int i = 2; i < this.transform.InputBlockSize; i++)
{
this.writeBuffer[i] = (byte)this.random.Next(0, 255);
}
this.transform.TransformBlock(this.writeBuffer, 0, this.transform.InputBlockSize, this.writeBlockBuffer, 0);
base.Write(this.writeBlockBuffer, 0, this.writeBlockBuffer.Length);
base.Flush();
}
private void PrivateFlush()
{
if (this.writeBufferCount == 2)
{
return;
}
var numberOfBlocks = ((this.writeBufferCount - 1) / this.transform.InputBlockSize) + 1;
if (numberOfBlocks == 0)
{
return;
}
this.writeBuffer[0] = ((byte)((this.writeBufferCount - 2) & 0xff));
this.writeBuffer[1] = ((byte)(((this.writeBufferCount - 2) & 0xff00) >> 8));
for (var i = 0; i < numberOfBlocks; i++)
{
if (i == numberOfBlocks - 1)
{
if (this.writeBuffer.Length - this.writeBufferCount < this.transform.InputBlockSize)
{
Array.Clear(this.writeBuffer, this.writeBufferCount, this.writeBuffer.Length - this.writeBufferCount);
}
}
var x = this.transform.TransformBlock(this.writeBuffer, i * this.transform.InputBlockSize, this.transform.InputBlockSize, this.writeBlockBuffer, 0);
if (x != this.transform.InputBlockSize)
{
throw new Exception();
}
base.Write(this.writeBlockBuffer, 0, this.writeBlockBuffer.Length);
}
this.writeBufferCount = 2;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Netsaimada.IoT.CloudService.StatsViewer.Areas.HelpPage.ModelDescriptions;
using Netsaimada.IoT.CloudService.StatsViewer.Areas.HelpPage.Models;
namespace Netsaimada.IoT.CloudService.StatsViewer.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Localization;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Notify;
using OrchardCore.Navigation;
using OrchardCore.Queries.ViewModels;
using OrchardCore.Routing;
using OrchardCore.Settings;
namespace OrchardCore.Queries.Controllers
{
public class AdminController : Controller
{
private readonly IAuthorizationService _authorizationService;
private readonly ISiteService _siteService;
private readonly INotifier _notifier;
private readonly IQueryManager _queryManager;
private readonly IEnumerable<IQuerySource> _querySources;
private readonly IDisplayManager<Query> _displayManager;
private readonly IUpdateModelAccessor _updateModelAccessor;
private readonly IStringLocalizer S;
private readonly IHtmlLocalizer H;
private readonly dynamic New;
public AdminController(
IDisplayManager<Query> displayManager,
IAuthorizationService authorizationService,
ISiteService siteService,
IShapeFactory shapeFactory,
IStringLocalizer<AdminController> stringLocalizer,
IHtmlLocalizer<AdminController> htmlLocalizer,
INotifier notifier,
IQueryManager queryManager,
IEnumerable<IQuerySource> querySources,
IUpdateModelAccessor updateModelAccessor)
{
_displayManager = displayManager;
_authorizationService = authorizationService;
_siteService = siteService;
_queryManager = queryManager;
_querySources = querySources;
_updateModelAccessor = updateModelAccessor;
New = shapeFactory;
_notifier = notifier;
S = stringLocalizer;
H = htmlLocalizer;
}
public async Task<IActionResult> Index(ContentOptions options, PagerParameters pagerParameters)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageQueries))
{
return Forbid();
}
var siteSettings = await _siteService.GetSiteSettingsAsync();
var pager = new Pager(pagerParameters, siteSettings.PageSize);
var queries = await _queryManager.ListQueriesAsync();
queries = queries.OrderBy(x => x.Name);
if (!string.IsNullOrWhiteSpace(options.Search))
{
queries = queries.Where(q => q.Name.IndexOf(options.Search, StringComparison.OrdinalIgnoreCase) >= 0);
}
var results = queries
.Skip(pager.GetStartIndex())
.Take(pager.PageSize)
.ToList();
// Maintain previous route data when generating page links
var routeData = new RouteData();
routeData.Values.Add("Options.Search", options.Search);
var pagerShape = (await New.Pager(pager)).TotalItemCount(queries.Count()).RouteData(routeData);
var model = new QueriesIndexViewModel
{
Queries = new List<QueryEntry>(),
Options = options,
Pager = pagerShape,
QuerySourceNames = _querySources.Select(x => x.Name).ToList()
};
foreach (var query in results)
{
model.Queries.Add(new QueryEntry
{
Query = query,
Shape = await _displayManager.BuildDisplayAsync(query, _updateModelAccessor.ModelUpdater, "SummaryAdmin")
});
}
model.Options.ContentsBulkAction = new List<SelectListItem>() {
new SelectListItem() { Text = S["Delete"], Value = nameof(ContentsBulkAction.Remove) }
};
return View(model);
}
[HttpPost, ActionName("Index")]
[FormValueRequired("submit.Filter")]
public ActionResult IndexFilterPOST(QueriesIndexViewModel model)
{
return RedirectToAction(nameof(Index), new RouteValueDictionary {
{ "Options.Search", model.Options.Search }
});
}
public async Task<IActionResult> Create(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageQueries))
{
return Forbid();
}
var query = _querySources.FirstOrDefault(x => x.Name == id)?.Create();
if (query == null)
{
return NotFound();
}
var model = new QueriesCreateViewModel
{
Editor = await _displayManager.BuildEditorAsync(query, updater: _updateModelAccessor.ModelUpdater, isNew: true),
SourceName = id
};
return View(model);
}
[HttpPost, ActionName(nameof(Create))]
public async Task<IActionResult> CreatePost(QueriesCreateViewModel model)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageQueries))
{
return Forbid();
}
var query = _querySources.FirstOrDefault(x => x.Name == model.SourceName)?.Create();
if (query == null)
{
return NotFound();
}
var editor = await _displayManager.UpdateEditorAsync(query, updater: _updateModelAccessor.ModelUpdater, isNew: true);
if (ModelState.IsValid)
{
await _queryManager.SaveQueryAsync(query.Name, query);
await _notifier.SuccessAsync(H["Query created successfully."]);
return RedirectToAction(nameof(Index));
}
// If we got this far, something failed, redisplay form
model.Editor = editor;
return View(model);
}
public async Task<IActionResult> Edit(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageQueries))
{
return Forbid();
}
var query = await _queryManager.GetQueryAsync(id);
if (query == null)
{
return NotFound();
}
var model = new QueriesEditViewModel
{
SourceName = query.Source,
Name = query.Name,
Schema = query.Schema,
Editor = await _displayManager.BuildEditorAsync(query, updater: _updateModelAccessor.ModelUpdater, isNew: false)
};
return View(model);
}
[HttpPost, ActionName("Edit")]
public async Task<IActionResult> EditPost(QueriesEditViewModel model)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageQueries))
{
return Forbid();
}
var query = (await _queryManager.LoadQueryAsync(model.Name));
if (query == null)
{
return NotFound();
}
var editor = await _displayManager.UpdateEditorAsync(query, updater: _updateModelAccessor.ModelUpdater, isNew: false);
if (ModelState.IsValid)
{
await _queryManager.SaveQueryAsync(model.Name, query);
await _notifier.SuccessAsync(H["Query updated successfully."]);
return RedirectToAction(nameof(Index));
}
model.Editor = editor;
// If we got this far, something failed, redisplay form
return View(model);
}
[HttpPost]
public async Task<IActionResult> Delete(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageQueries))
{
return Forbid();
}
var query = await _queryManager.LoadQueryAsync(id);
if (query == null)
{
return NotFound();
}
await _queryManager.DeleteQueryAsync(id);
await _notifier.SuccessAsync(H["Query deleted successfully."]);
return RedirectToAction(nameof(Index));
}
[HttpPost, ActionName("Index")]
[FormValueRequired("submit.BulkAction")]
public async Task<ActionResult> IndexPost(ViewModels.ContentOptions options, IEnumerable<string> itemIds)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageQueries))
{
return Forbid();
}
if (itemIds?.Count() > 0)
{
var queriesList = await _queryManager.ListQueriesAsync();
var checkedContentItems = queriesList.Where(x => itemIds.Contains(x.Name));
switch (options.BulkAction)
{
case ContentsBulkAction.None:
break;
case ContentsBulkAction.Remove:
foreach (var item in checkedContentItems)
{
await _queryManager.DeleteQueryAsync(item.Name);
}
await _notifier.SuccessAsync(H["Queries successfully removed."]);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
return RedirectToAction(nameof(Index));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Support.V4.App;
using Android.Support.V7.Widget;
using Android.Views;
using Android.Widget;
using Java.Lang;
namespace Android.Utilities
{
public abstract class GenericResourceBinder<T>
{
public abstract void Bind(View view, T item);
public abstract void Unbind(View view, T item);
}
public class GenericResourceAutoBinder<T> : GenericResourceBinder<T>
{
private Dictionary<int, Action<View, T>> resourceBinders = new Dictionary<int, Action<View, T>>();
private Dictionary<View, Dictionary<int, View>> resourceViews = new Dictionary<View, Dictionary<int, View>>();
public GenericResourceAutoBinder(IDictionary<int, Action<View, T>> resourceBinders)
{
this.resourceBinders = resourceBinders.ToDictionary();
}
public override void Bind(View view, T item)
{
Dictionary<int, View> views;
if (!resourceViews.TryGetValue(view, out views))
resourceViews.Add(view, views = new Dictionary<int, View>());
foreach (var pair in resourceBinders)
{
View binderView;
if (!views.TryGetValue(pair.Key, out binderView))
views.Add(pair.Key, binderView = view.FindViewById(pair.Key));
pair.Value(binderView, item);
}
}
public override void Unbind(View view, T item)
{
}
}
public class GenericResourceManualBinder<T> : GenericResourceBinder<T>
{
private Action<View, T> bind, unbind;
public GenericResourceManualBinder(Action<View, T> bind)
{
this.bind = bind;
}
public GenericResourceManualBinder(Action<View, T> bind, Action<View, T> unbind)
{
this.bind = bind;
this.unbind = unbind;
}
public override void Bind(View view, T item)
{
bind?.Invoke(view, item);
}
public override void Unbind(View view, T item)
{
unbind?.Invoke(view, item);
}
}
public delegate void GenericAdapterCallback<T>(GenericAdapter<T> adapter, View view, T item) where T : class;
public delegate void GenericAdapterItemCallback<T>(View view, T item) where T : class;
public delegate bool GenericAdapterFilter<T>(T item, string filter) where T : class;
public class GenericAdapter<T> where T : class
{
public IEnumerable<T> Items
{
get
{
return rawItems;
}
set
{
rawItems = value?.ToArray();
ApplyFilter(false);
ApplySorting(false);
Refresh();
}
}
public GenericAdapterFilter<T> Filter
{
get
{
return filter;
}
set
{
filter = value;
ApplyFilter(false);
ApplySorting(false);
Refresh();
}
}
public string FilterText
{
get
{
return filterText;
}
set
{
filterText = value;
ApplyFilter(false);
ApplySorting(false);
Refresh();
}
}
public Comparer<T> Sort
{
get
{
return sort;
}
set
{
sort = value;
ApplySorting(false);
Refresh();
}
}
public event GenericAdapterCallback<T> Click;
private int layoutId;
private GenericResourceBinder<T> resourceBinder;
private T[] rawItems;
private T[] filteredItems;
private GenericAdapterFilter<T> filter;
private string filterText;
private Comparer<T> sort;
protected GenericAdapter(int layoutId) : this(Enumerable.Empty<T>(), layoutId) { }
protected GenericAdapter(IEnumerable<T> items, int layoutId)
{
Items = items;
this.layoutId = layoutId;
this.resourceBinder = new GenericResourceManualBinder<T>(OnBind, OnUnbind);
}
public GenericAdapter(int layoutId, Action<View, T> resourceBinder) : this(Enumerable.Empty<T>(), layoutId, new GenericResourceManualBinder<T>(resourceBinder)) { }
public GenericAdapter(int layoutId, GenericResourceBinder<T> resourceBinder) : this(Enumerable.Empty<T>(), layoutId, resourceBinder) { }
public GenericAdapter(IEnumerable<T> items, int layoutId, Action<View, T> resourceBinder) : this(items, layoutId, new GenericResourceManualBinder<T>(resourceBinder)) { }
public GenericAdapter(IEnumerable<T> items, int layoutId, GenericResourceBinder<T> resourceBinder)
{
Items = items;
this.layoutId = layoutId;
this.resourceBinder = resourceBinder;
}
protected virtual void OnBind(View view, T item) { }
protected virtual void OnUnbind(View view, T item) { }
protected virtual void OnClick(View view, T item)
{
Click?.Invoke(this, view, item);
}
protected virtual T GetItemFromView(View view)
{
foreach (GenericRecyclerViewAdapter<T> adapter in recyclerViewAdapters)
{
T item = adapter.GetItemFromView(view);
if (item != null)
return item;
}
return null;
}
protected virtual T GetItemFromSubView(View view)
{
while (view != null)
{
T item = GetItemFromView(view);
if (item != null)
return item;
view = view.Parent as View;
}
return null;
}
private void ApplyFilter(bool refresh = true)
{
if (filter == null)
filteredItems = rawItems;
else if (string.IsNullOrWhiteSpace(filterText))
filteredItems = rawItems.ToArray();
else
filteredItems = rawItems.Where(i => filter(i, filterText)).ToArray();
if (refresh)
Refresh();
}
private void ApplySorting(bool refresh = true)
{
if (sort != null)
Array.Sort(filteredItems, sort);
if (refresh)
Refresh();
}
private void Refresh()
{
foreach (GenericRecyclerViewAdapter<T> adapter in recyclerViewAdapters)
adapter.Refresh(filteredItems);
}
private List<GenericRecyclerViewAdapter<T>> recyclerViewAdapters = new List<GenericRecyclerViewAdapter<T>>();
public static implicit operator RecyclerView.Adapter(GenericAdapter<T> me)
{
GenericRecyclerViewAdapter<T> adapter = new GenericRecyclerViewAdapter<T>(me.filteredItems, me.layoutId, me.resourceBinder);
adapter.Click += me.OnClick;
me.recyclerViewAdapters.Add(adapter);
return adapter;
}
}
public class GenericRecyclerViewAdapter<T> : RecyclerView.Adapter where T : class
{
private class GenericRecyclerViewHolder<T> : RecyclerView.ViewHolder
{
public GenericRecyclerViewHolder(View view) : base(view) { }
}
public override int ItemCount
{
get
{
return items.Length;
}
}
public event GenericAdapterItemCallback<T> Click;
private T[] items;
private int layoutId;
private GenericResourceBinder<T> resourceBinder;
private Association<View, GenericRecyclerViewHolder<T>> viewHolders = new Association<View, GenericRecyclerViewHolder<T>>();
private Association<GenericRecyclerViewHolder<T>, T> viewHolderItems = new Association<GenericRecyclerViewHolder<T>, T>();
public GenericRecyclerViewAdapter(T[] items, int layoutId, GenericResourceBinder<T> resourceBinder)
{
this.items = items;
this.layoutId = layoutId;
this.resourceBinder = resourceBinder;
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.From(parent.Context).Inflate(layoutId, parent, false);
GenericRecyclerViewHolder<T> viewHolder = new GenericRecyclerViewHolder<T>(view);
viewHolders.Add(view, viewHolder);
return viewHolder;
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
GenericRecyclerViewHolder<T> viewHolder = holder as GenericRecyclerViewHolder<T>;
T item = items[position];
viewHolderItems[viewHolder] = item;
resourceBinder.Bind(viewHolder.ItemView, item);
}
public override void OnViewAttachedToWindow(Java.Lang.Object holder)
{
GenericRecyclerViewHolder<T> viewHolder = holder as GenericRecyclerViewHolder<T>;
viewHolder.ItemView.Click += View_Click;
}
public override void OnViewDetachedFromWindow(Java.Lang.Object holder)
{
GenericRecyclerViewHolder<T> viewHolder = holder as GenericRecyclerViewHolder<T>;
viewHolder.ItemView.Click -= View_Click;
T item;
if (viewHolderItems.TryGetRight(viewHolder, out item))
resourceBinder.Unbind(viewHolder.ItemView, item);
}
private void View_Click(object sender, EventArgs e)
{
View view = sender as View;
GenericRecyclerViewHolder<T> viewHolder = viewHolders[view];
T item = viewHolderItems[viewHolder];
Click?.Invoke(view, item);
}
public void Refresh(T[] items)
{
this.items = items;
NotifyDataSetChanged();
}
public T GetItemFromView(View view)
{
GenericRecyclerViewHolder<T> viewHolder;
if (!viewHolders.TryGetRight(view, out viewHolder))
return null;
T item;
if (!viewHolderItems.TryGetRight(viewHolder, out item))
return null;
return item;
}
}
public class GenericBaseAdapter<T> : BaseAdapter<T>, IFilterable, View.IOnClickListener where T : class
{
public class GenericBaseAdapterFilter : Filter
{
private GenericBaseAdapter<T> adapter;
public GenericBaseAdapterFilter(GenericBaseAdapter<T> adapter)
{
this.adapter = adapter;
}
protected override FilterResults PerformFiltering(ICharSequence constraint)
{
FilterResults filterResults = new FilterResults();
if (constraint == null)
return filterResults;
string filterText = new string(constraint.Select(c => c).ToArray());
GenericAdapterFilter<T> filter = adapter.adapter.Filter;
T[] filteredItems = adapter.items.Where(i => filter(i, filterText)).ToArray();
filterResults.Values = FromArray(filteredItems.Select(i => new Java.Lang.String(i.ToString())).ToArray());
filterResults.Count = filteredItems.Length;
constraint.Dispose();
return filterResults;
}
protected override void PublishResults(ICharSequence constraint, FilterResults results)
{
string filterText = constraint == null ? null : new string(constraint.Select(c => c).ToArray());
adapter.adapter.FilterText = filterText;
constraint?.Dispose();
results.Dispose();
}
}
public override int Count
{
get { return items.Length; }
}
public Filter Filter { get; private set; }
public override T this[int position]
{
get
{
return items[position];
}
}
public event GenericAdapterItemCallback<T> Click;
private GenericAdapter<T> adapter;
private T[] items;
private int layoutId;
private GenericResourceBinder<T> resourceBinder;
private Dictionary<int, View> itemViews = new Dictionary<int, View>();
public GenericBaseAdapter(GenericAdapter<T> adapter, T[] items, int layoutId, GenericResourceBinder<T> resourceBinder)
{
this.adapter = adapter;
this.items = items;
this.layoutId = layoutId;
this.resourceBinder = resourceBinder;
Filter = new GenericBaseAdapterFilter(this);
}
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
T item = items[position];
View view = LayoutInflater.From(parent.Context).Inflate(layoutId, parent, false);
view.SetOnClickListener(this);
resourceBinder.Bind(view, item);
return view;
}
public override void NotifyDataSetChanged()
{
// If you are using cool stuff like sections
// remember to update the indices here!
base.NotifyDataSetChanged();
}
public void Refresh(T[] items)
{
this.items = items;
NotifyDataSetChanged();
}
void View.IOnClickListener.OnClick(View view)
{
int position = itemViews.Values.IndexOf(view);
T item = items[position];
Click?.Invoke(view, item);
}
}
}
| |
using System.Collections;
using System.Linq.Expressions;
using JetBrains.Annotations;
using JsonApiDotNetCore.Errors;
using JsonApiDotNetCore.Queries.Expressions;
using JsonApiDotNetCore.Resources.Internal;
namespace JsonApiDotNetCore.Queries.Internal.QueryableBuilding;
/// <summary>
/// Transforms <see cref="FilterExpression" /> into
/// <see cref="Queryable.Where{TSource}(IQueryable{TSource}, System.Linq.Expressions.Expression{System.Func{TSource,bool}})" /> calls.
/// </summary>
[PublicAPI]
public class WhereClauseBuilder : QueryClauseBuilder<Type?>
{
private static readonly CollectionConverter CollectionConverter = new();
private static readonly ConstantExpression NullConstant = Expression.Constant(null);
private readonly Expression _source;
private readonly Type _extensionType;
private readonly LambdaParameterNameFactory _nameFactory;
public WhereClauseBuilder(Expression source, LambdaScope lambdaScope, Type extensionType, LambdaParameterNameFactory nameFactory)
: base(lambdaScope)
{
ArgumentGuard.NotNull(source, nameof(source));
ArgumentGuard.NotNull(extensionType, nameof(extensionType));
ArgumentGuard.NotNull(nameFactory, nameof(nameFactory));
_source = source;
_extensionType = extensionType;
_nameFactory = nameFactory;
}
public Expression ApplyWhere(FilterExpression filter)
{
ArgumentGuard.NotNull(filter, nameof(filter));
LambdaExpression lambda = GetPredicateLambda(filter);
return WhereExtensionMethodCall(lambda);
}
private LambdaExpression GetPredicateLambda(FilterExpression filter)
{
Expression body = Visit(filter, null);
return Expression.Lambda(body, LambdaScope.Parameter);
}
private Expression WhereExtensionMethodCall(LambdaExpression predicate)
{
return Expression.Call(_extensionType, "Where", LambdaScope.Parameter.Type.AsArray(), _source, predicate);
}
public override Expression VisitHas(HasExpression expression, Type? argument)
{
Expression property = Visit(expression.TargetCollection, argument);
Type? elementType = CollectionConverter.FindCollectionElementType(property.Type);
if (elementType == null)
{
throw new InvalidOperationException("Expression must be a collection.");
}
Expression? predicate = null;
if (expression.Filter != null)
{
var lambdaScopeFactory = new LambdaScopeFactory(_nameFactory);
using LambdaScope lambdaScope = lambdaScopeFactory.CreateScope(elementType);
var builder = new WhereClauseBuilder(property, lambdaScope, typeof(Enumerable), _nameFactory);
predicate = builder.GetPredicateLambda(expression.Filter);
}
return AnyExtensionMethodCall(elementType, property, predicate);
}
private static MethodCallExpression AnyExtensionMethodCall(Type elementType, Expression source, Expression? predicate)
{
return predicate != null
? Expression.Call(typeof(Enumerable), "Any", elementType.AsArray(), source, predicate)
: Expression.Call(typeof(Enumerable), "Any", elementType.AsArray(), source);
}
public override Expression VisitMatchText(MatchTextExpression expression, Type? argument)
{
Expression property = Visit(expression.TargetAttribute, argument);
if (property.Type != typeof(string))
{
throw new InvalidOperationException("Expression must be a string.");
}
Expression text = Visit(expression.TextValue, property.Type);
if (expression.MatchKind == TextMatchKind.StartsWith)
{
return Expression.Call(property, "StartsWith", null, text);
}
if (expression.MatchKind == TextMatchKind.EndsWith)
{
return Expression.Call(property, "EndsWith", null, text);
}
return Expression.Call(property, "Contains", null, text);
}
public override Expression VisitAny(AnyExpression expression, Type? argument)
{
Expression property = Visit(expression.TargetAttribute, argument);
var valueList = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(property.Type))!;
foreach (LiteralConstantExpression constant in expression.Constants)
{
object? value = ConvertTextToTargetType(constant.Value, property.Type);
valueList.Add(value);
}
ConstantExpression collection = Expression.Constant(valueList);
return ContainsExtensionMethodCall(collection, property);
}
private static Expression ContainsExtensionMethodCall(Expression collection, Expression value)
{
return Expression.Call(typeof(Enumerable), "Contains", value.Type.AsArray(), collection, value);
}
public override Expression VisitLogical(LogicalExpression expression, Type? argument)
{
var termQueue = new Queue<Expression>(expression.Terms.Select(filter => Visit(filter, argument)));
if (expression.Operator == LogicalOperator.And)
{
return Compose(termQueue, Expression.AndAlso);
}
if (expression.Operator == LogicalOperator.Or)
{
return Compose(termQueue, Expression.OrElse);
}
throw new InvalidOperationException($"Unknown logical operator '{expression.Operator}'.");
}
private static BinaryExpression Compose(Queue<Expression> argumentQueue, Func<Expression, Expression, BinaryExpression> applyOperator)
{
Expression left = argumentQueue.Dequeue();
Expression right = argumentQueue.Dequeue();
BinaryExpression tempExpression = applyOperator(left, right);
while (argumentQueue.Any())
{
Expression nextArgument = argumentQueue.Dequeue();
tempExpression = applyOperator(tempExpression, nextArgument);
}
return tempExpression;
}
public override Expression VisitNot(NotExpression expression, Type? argument)
{
Expression child = Visit(expression.Child, argument);
return Expression.Not(child);
}
public override Expression VisitComparison(ComparisonExpression expression, Type? argument)
{
Type commonType = ResolveCommonType(expression.Left, expression.Right);
Expression left = WrapInConvert(Visit(expression.Left, commonType), commonType);
Expression right = WrapInConvert(Visit(expression.Right, commonType), commonType);
switch (expression.Operator)
{
case ComparisonOperator.Equals:
{
return Expression.Equal(left, right);
}
case ComparisonOperator.LessThan:
{
return Expression.LessThan(left, right);
}
case ComparisonOperator.LessOrEqual:
{
return Expression.LessThanOrEqual(left, right);
}
case ComparisonOperator.GreaterThan:
{
return Expression.GreaterThan(left, right);
}
case ComparisonOperator.GreaterOrEqual:
{
return Expression.GreaterThanOrEqual(left, right);
}
}
throw new InvalidOperationException($"Unknown comparison operator '{expression.Operator}'.");
}
private Type ResolveCommonType(QueryExpression left, QueryExpression right)
{
Type leftType = ResolveFixedType(left);
if (RuntimeTypeConverter.CanContainNull(leftType))
{
return leftType;
}
if (right is NullConstantExpression)
{
return typeof(Nullable<>).MakeGenericType(leftType);
}
Type? rightType = TryResolveFixedType(right);
if (rightType != null && RuntimeTypeConverter.CanContainNull(rightType))
{
return rightType;
}
return leftType;
}
private Type ResolveFixedType(QueryExpression expression)
{
Expression result = Visit(expression, null);
return result.Type;
}
private Type? TryResolveFixedType(QueryExpression expression)
{
if (expression is CountExpression)
{
return typeof(int);
}
if (expression is ResourceFieldChainExpression chain)
{
Expression child = Visit(chain, null);
return child.Type;
}
return null;
}
private static Expression WrapInConvert(Expression expression, Type? targetType)
{
try
{
return targetType != null && expression.Type != targetType ? Expression.Convert(expression, targetType) : expression;
}
catch (InvalidOperationException exception)
{
throw new InvalidQueryException("Query creation failed due to incompatible types.", exception);
}
}
public override Expression VisitNullConstant(NullConstantExpression expression, Type? expressionType)
{
return NullConstant;
}
public override Expression VisitLiteralConstant(LiteralConstantExpression expression, Type? expressionType)
{
object? convertedValue = expressionType != null ? ConvertTextToTargetType(expression.Value, expressionType) : expression.Value;
return convertedValue.CreateTupleAccessExpressionForConstant(expressionType ?? typeof(string));
}
private static object? ConvertTextToTargetType(string text, Type targetType)
{
try
{
return RuntimeTypeConverter.ConvertType(text, targetType);
}
catch (FormatException exception)
{
throw new InvalidQueryException("Query creation failed due to incompatible types.", exception);
}
}
}
| |
using System.Text.RegularExpressions;
using System.Diagnostics;
using System;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Collections;
using System.Drawing;
using Microsoft.VisualBasic;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
using WeifenLuo.WinFormsUI;
using Microsoft.Win32;
using WeifenLuo;
using System.ComponentModel;
namespace SoftLogik.Win.UI.Controls
{
[Description("Data Aware MenuStrip Component")]
[ToolboxBitmap(typeof(MenuStrip), "DataMenuStrip")]
public partial class DataMenuStrip
{
protected override void OnPaint(PaintEventArgs pe)
{
// Calling the base class OnPaint
base.OnPaint(pe);
}
private bool m_autoBuild = true;
public bool AutoBuildTree
{
get
{
return this.m_autoBuild;
}
set
{
this.m_autoBuild = value;
}
}
#region Data Binding
private CurrencyManager m_currencyManager = null;
private string m_ValueMember;
private string m_DisplayMember;
private object m_oDataSource;
[Category("Data")]public object DataSource
{
get
{
return m_oDataSource;
}
set
{
if (value == null)
{
this.m_currencyManager = null;
this.Items.Clear();
}
else
{
if (!(value is IList|| m_oDataSource is IListSource))
{
throw (new System.Exception("Invalid DataSource"));
}
else
{
if (value is IListSource)
{
IListSource myListSource = (IListSource) value;
if (myListSource.ContainsListCollection == true)
{
throw (new System.Exception("Invalid DataSource"));
}
}
this.m_oDataSource = value;
this.m_currencyManager = (CurrencyManager) (this.BindingContext[value]);
if (this.AutoBuildTree)
{
BuildTree();
}
}
}
}
} // end of DataSource property
[Category("Data")]public string ValueMember
{
get
{
return this.m_ValueMember;
}
set
{
this.m_ValueMember = value;
}
}
[Category("Data")]public string DisplayMember
{
get
{
return this.m_DisplayMember;
}
set
{
this.m_DisplayMember = value;
}
}
public object GetValue(int index)
{
IList innerList = this.m_currencyManager.List;
if (innerList != null)
{
if ((this.ValueMember != "") && (index >= 0 && 0 < innerList.Count))
{
PropertyDescriptor pdValueMember;
pdValueMember = this.m_currencyManager.GetItemProperties()[this.ValueMember];
return pdValueMember.GetValue(innerList[index]);
}
}
return null;
}
public object GetDisplay(int index)
{
IList innerList = this.m_currencyManager.List;
if (innerList != null)
{
if ((this.DisplayMember != "") && (index >= 0 && 0 < innerList.Count))
{
PropertyDescriptor pdDisplayMember;
pdDisplayMember = this.m_currencyManager.GetItemProperties()[this.ValueMember];
return pdDisplayMember.GetValue(innerList[index]);
}
}
return null;
}
#endregion
#region Building the Tree
private ArrayList treeGroups = new ArrayList();
public void BuildTree()
{
this.Items.Clear();
if ((this.m_currencyManager != null) && (this.m_currencyManager.List != null))
{
IList innerList = this.m_currencyManager.List;
ToolStripItemCollection currNode = this.Items;
int currGroupIndex = 0;
int currListIndex = 0;
if (this.treeGroups.Count > currGroupIndex)
{
DataTreeNodeGroup currGroup = (DataTreeNodeGroup) (treeGroups[currGroupIndex]);
MenuStripItem myFirstNode = null;
PropertyDescriptor pdGroupBy;
PropertyDescriptor pdValue;
PropertyDescriptor pdDisplay;
pdGroupBy = this.m_currencyManager.GetItemProperties()[currGroup.GroupBy];
pdValue = this.m_currencyManager.GetItemProperties()[currGroup.ValueMember];
pdDisplay = this.m_currencyManager.GetItemProperties()[currGroup.DisplayMember];
string currGroupBy = null;
if (innerList.Count > currListIndex)
{
object currObject;
while (currListIndex < innerList.Count)
{
currObject = innerList[currListIndex];
if (pdGroupBy.GetValue(currObject).ToString() != currGroupBy)
{
currGroupBy = pdGroupBy.GetValue(currObject).ToString();
myFirstNode = new MenuStripItem(currGroup.Name, pdDisplay.GetValue(currObject).ToString(), currObject, pdValue.GetValue(innerList[currListIndex]), currGroup.ImageIndex, currListIndex);
currNode.Add((ToolStripItem) myFirstNode);
}
else
{
AddMenuItems(currGroupIndex, ref currListIndex, this.Items, currGroup.GroupBy);
}
} // end while
} // end if
}
else
{
while (currListIndex < innerList.Count)
{
AddMenuItems(currGroupIndex, ref currListIndex, this.Items, "");
}
} // end else
} // end if
}
private void AddMenuItems(int currGroupIndex, ref int currentListIndex, ToolStripItemCollection currNodes, string prevGroupByField)
{
IList innerList = this.m_currencyManager.List;
System.ComponentModel.PropertyDescriptor pdPrevGroupBy = null;
string prevGroupByValue = null;
DataTreeNodeGroup currGroup;
if (prevGroupByField != "")
{
pdPrevGroupBy = this.m_currencyManager.GetItemProperties()[prevGroupByField];
}
currGroupIndex++;
if (treeGroups.Count > currGroupIndex)
{
currGroup = (DataTreeNodeGroup) (treeGroups[currGroupIndex]);
PropertyDescriptor pdGroupBy = null;
PropertyDescriptor pdValue = null;
PropertyDescriptor pdDisplay = null;
pdGroupBy = this.m_currencyManager.GetItemProperties()[currGroup.GroupBy];
pdValue = this.m_currencyManager.GetItemProperties()[currGroup.ValueMember];
pdDisplay = this.m_currencyManager.GetItemProperties()[currGroup.DisplayMember];
string currGroupBy = null;
if (innerList.Count > currentListIndex)
{
if (pdPrevGroupBy != null)
{
prevGroupByValue = pdPrevGroupBy.GetValue(innerList[currentListIndex]).ToString();
}
MenuStripItem myFirstNode = null;
object currObject = null;
while ((currentListIndex < innerList.Count) && (pdPrevGroupBy != null) && (pdPrevGroupBy.GetValue(innerList[currentListIndex]).ToString() == prevGroupByValue))
{
currObject = innerList[currentListIndex];
if (pdGroupBy.GetValue(currObject).ToString() != currGroupBy)
{
currGroupBy = pdGroupBy.GetValue(currObject).ToString();
myFirstNode = new MenuStripItem(currGroup.Name, pdDisplay.GetValue(currObject).ToString(), currObject, pdValue.GetValue(innerList[currentListIndex]), currGroup.ImageIndex, currentListIndex);
currNodes.Add(myFirstNode);
}
else
{
AddMenuItems(currGroupIndex, ref currentListIndex, this.Items, currGroup.GroupBy);
}
}
}
}
else
{
MenuStripItem myNewLeafNode;
object currObject = this.m_currencyManager.List[currentListIndex];
if ((this.DisplayMember != null) && (this.ValueMember != null) && (this.DisplayMember != "") && (this.ValueMember != ""))
{
PropertyDescriptor pdDisplayloc = this.m_currencyManager.GetItemProperties()[this.DisplayMember];
PropertyDescriptor pdValueloc = this.m_currencyManager.GetItemProperties()[this.ValueMember];
if (this.Tag == null)
{
myNewLeafNode = new MenuStripItem("", pdDisplayloc.GetValue(currObject).ToString(), currObject, pdValueloc.GetValue(currObject), currentListIndex);
}
else
{
myNewLeafNode = new MenuStripItem(this.Tag.ToString(), pdDisplayloc.GetValue(currObject).ToString(), currObject, pdValueloc.GetValue(currObject), currentListIndex);
}
}
else
{
myNewLeafNode = new MenuStripItem("", currentListIndex.ToString(), currObject, currObject, currentListIndex, currentListIndex);
}
currNodes.Add(myNewLeafNode);
currentListIndex++;
}
}
#endregion
}
[Description("Specify Grouping for a collection of Menu Items in MenuStrip")]public class MenuStripItemGroup
{
private string groupName;
private string groupByMember;
private string groupByDisplayMember;
private string groupByValueMember;
private int groupImageIndex;
public MenuStripItemGroup(string name, string groupBy, string displayMember, string valueMember, int imageIndex)
{
this.ImageIndex = imageIndex;
this.Name = name;
this.GroupBy = groupBy;
this.DisplayMember = displayMember;
this.ValueMember = valueMember;
}
public MenuStripItemGroup(string name, string groupBy) : this(name, groupBy, groupBy, groupBy, - 1)
{
}
public int ImageIndex
{
get
{
return groupImageIndex;
}
set
{
groupImageIndex = value;
}
}
public string Name
{
get
{
return groupName;
}
set
{
groupName = value;
}
}
public string GroupBy
{
get
{
return groupByMember;
}
set
{
groupByMember = value;
}
}
public string DisplayMember
{
get
{
return groupByDisplayMember;
}
set
{
groupByDisplayMember = value;
}
}
public string ValueMember
{
get
{
return groupByValueMember;
}
set
{
groupByValueMember = value;
}
}
}
[Description("A menu item in the MenuStrip")]public class MenuStripItem : ToolStripMenuItem
{
private string m_groupName;
private object m_value;
private object m_item;
private int m_position;
public MenuStripItem()
{
}
public MenuStripItem(string GroupName, string text, object item, object value, int imageIndex, int position)
{
this.GroupName = GroupName;
this.Text = text;
this.Item = item;
this.Value = value;
this.ImageIndex = imageIndex;
this.m_position = position;
}
public MenuStripItem(string groupName, string text, object item, object value, int position)
{
this.GroupName = groupName;
this.Text = text;
this.Item = item;
this.Value = value;
this.m_position = position;
}
public string GroupName
{
get
{
return m_groupName;
}
set
{
this.m_groupName = value;
}
}
public object Item
{
get
{
return m_item;
}
set
{
m_item = value;
}
}
public object Value
{
get
{
return m_value;
}
set
{
m_value = value;
}
}
public int Position
{
get
{
return m_position;
}
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Indicators.Algo
File: IIndicatorValue.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.Indicators
{
using System;
using System.Collections.Generic;
using System.Linq;
using Ecng.Common;
using StockSharp.Algo.Candles;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
using StockSharp.Localization;
/// <summary>
/// The indicator input value, based on which it will renew its value, as well as value, containing result of indicator calculation.
/// </summary>
public interface IIndicatorValue : IComparable<IIndicatorValue>, IComparable
{
/// <summary>
/// Indicator.
/// </summary>
IIndicator Indicator { get; }
/// <summary>
/// No indicator value.
/// </summary>
bool IsEmpty { get; }
/// <summary>
/// Is the value final (indicator finalizes its value and will not be changed anymore in the given point of time).
/// </summary>
bool IsFinal { get; set; }
/// <summary>
/// Whether the indicator is set.
/// </summary>
bool IsFormed { get; }
/// <summary>
/// The input value.
/// </summary>
IIndicatorValue InputValue { get; set; }
/// <summary>
/// Does value support data type, required for the indicator.
/// </summary>
/// <param name="valueType">The data type, operated by indicator.</param>
/// <returns><see langword="true" />, if data type is supported, otherwise, <see langword="false" />.</returns>
bool IsSupport(Type valueType);
/// <summary>
/// To get the value by the data type.
/// </summary>
/// <typeparam name="T">The data type, operated by indicator.</typeparam>
/// <returns>Value.</returns>
T GetValue<T>();
/// <summary>
/// To replace the indicator input value by new one (for example it is received from another indicator).
/// </summary>
/// <typeparam name="T">The data type, operated by indicator.</typeparam>
/// <param name="indicator">Indicator.</param>
/// <param name="value">Value.</param>
/// <returns>New object, containing input value.</returns>
IIndicatorValue SetValue<T>(IIndicator indicator, T value);
}
/// <summary>
/// The base class for the indicator value.
/// </summary>
public abstract class BaseIndicatorValue : IIndicatorValue
{
/// <summary>
/// Initialize <see cref="BaseIndicatorValue"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
protected BaseIndicatorValue(IIndicator indicator)
{
if (indicator == null)
throw new ArgumentNullException(nameof(indicator));
Indicator = indicator;
IsFormed = indicator.IsFormed;
}
/// <summary>
/// Indicator.
/// </summary>
public IIndicator Indicator { get; }
/// <summary>
/// No indicator value.
/// </summary>
public abstract bool IsEmpty { get; set; }
/// <summary>
/// Is the value final (indicator finalizes its value and will not be changed anymore in the given point of time).
/// </summary>
public abstract bool IsFinal { get; set; }
/// <summary>
/// Whether the indicator is set.
/// </summary>
public bool IsFormed { get; }
/// <summary>
/// The input value.
/// </summary>
public abstract IIndicatorValue InputValue { get; set; }
/// <summary>
/// Does value support data type, required for the indicator.
/// </summary>
/// <param name="valueType">The data type, operated by indicator.</param>
/// <returns><see langword="true" />, if data type is supported, otherwise, <see langword="false" />.</returns>
public abstract bool IsSupport(Type valueType);
/// <summary>
/// To get the value by the data type.
/// </summary>
/// <typeparam name="T">The data type, operated by indicator.</typeparam>
/// <returns>Value.</returns>
public abstract T GetValue<T>();
/// <summary>
/// To replace the indicator input value by new one (for example it is received from another indicator).
/// </summary>
/// <typeparam name="T">The data type, operated by indicator.</typeparam>
/// <param name="indicator">Indicator.</param>
/// <param name="value">Value.</param>
/// <returns>New object, containing input value.</returns>
public abstract IIndicatorValue SetValue<T>(IIndicator indicator, T value);
/// <summary>
/// Compare <see cref="IIndicatorValue"/> on the equivalence.
/// </summary>
/// <param name="other">Another value with which to compare.</param>
/// <returns>The result of the comparison.</returns>
public abstract int CompareTo(IIndicatorValue other);
/// <summary>
/// Compare <see cref="IIndicatorValue"/> on the equivalence.
/// </summary>
/// <param name="other">Another value with which to compare.</param>
/// <returns>The result of the comparison.</returns>
int IComparable.CompareTo(object other)
{
var value = other as IIndicatorValue;
if (other == null)
throw new ArgumentException(LocalizedStrings.Str911, nameof(other));
return CompareTo(value);
}
}
/// <summary>
/// The base value of the indicator, operating with one data type.
/// </summary>
/// <typeparam name="TValue">Value type.</typeparam>
public class SingleIndicatorValue<TValue> : BaseIndicatorValue
{
/// <summary>
/// Initializes a new instance of the <see cref="SingleIndicatorValue{T}"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
/// <param name="value">Value.</param>
public SingleIndicatorValue(IIndicator indicator, TValue value)
: base(indicator)
{
Value = value;
IsEmpty = value.IsNull();
}
/// <summary>
/// Initializes a new instance of the <see cref="SingleIndicatorValue{T}"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
public SingleIndicatorValue(IIndicator indicator)
: base(indicator)
{
IsEmpty = true;
}
/// <summary>
/// Value.
/// </summary>
public TValue Value { get; }
/// <summary>
/// No indicator value.
/// </summary>
public override bool IsEmpty { get; set; }
/// <summary>
/// Is the value final (indicator finalizes its value and will not be changed anymore in the given point of time).
/// </summary>
public override bool IsFinal { get; set; }
/// <summary>
/// The input value.
/// </summary>
public override IIndicatorValue InputValue { get; set; }
/// <summary>
/// Does value support data type, required for the indicator.
/// </summary>
/// <param name="valueType">The data type, operated by indicator.</param>
/// <returns><see langword="true" />, if data type is supported, otherwise, <see langword="false" />.</returns>
public override bool IsSupport(Type valueType)
{
return valueType == typeof(TValue);
}
/// <summary>
/// To get the value by the data type.
/// </summary>
/// <typeparam name="T">The data type, operated by indicator.</typeparam>
/// <returns>Value.</returns>
public override T GetValue<T>()
{
//ThrowIfEmpty();
if(IsEmpty)
return default(T);
return Value.To<T>();
}
/// <summary>
/// To replace the indicator input value by new one (for example it is received from another indicator).
/// </summary>
/// <typeparam name="T">The data type, operated by indicator.</typeparam>
/// <param name="indicator">Indicator.</param>
/// <param name="value">Value.</param>
/// <returns>New object, containing input value.</returns>
public override IIndicatorValue SetValue<T>(IIndicator indicator, T value)
{
return new SingleIndicatorValue<T>(indicator, value) { IsFinal = IsFinal, InputValue = this };
}
private void ThrowIfEmpty()
{
if (IsEmpty)
throw new InvalidOperationException(LocalizedStrings.Str910);
}
/// <summary>
/// Compare <see cref="SingleIndicatorValue{T}"/> on the equivalence.
/// </summary>
/// <param name="other">Another value with which to compare.</param>
/// <returns>The result of the comparison.</returns>
public override int CompareTo(IIndicatorValue other)
{
return Value.Compare(other.GetValue<TValue>());
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>A string that represents the current object.</returns>
public override string ToString()
{
return IsEmpty ? "Empty" : Value.ToString();
}
}
/// <summary>
/// The indicator value, operating with data type <see cref="Decimal"/>.
/// </summary>
public class DecimalIndicatorValue : SingleIndicatorValue<decimal>
{
/// <summary>
/// Initializes a new instance of the <see cref="DecimalIndicatorValue"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
/// <param name="value">Value.</param>
public DecimalIndicatorValue(IIndicator indicator, decimal value)
: base(indicator, value)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DecimalIndicatorValue"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
public DecimalIndicatorValue(IIndicator indicator)
: base(indicator)
{
}
/// <summary>
/// To replace the indicator input value by new one (for example it is received from another indicator).
/// </summary>
/// <typeparam name="T">The data type, operated by indicator.</typeparam>
/// <param name="indicator">Indicator.</param>
/// <param name="value">Value.</param>
/// <returns>New object, containing input value.</returns>
public override IIndicatorValue SetValue<T>(IIndicator indicator, T value)
{
return typeof(T) == typeof(decimal)
? new DecimalIndicatorValue(indicator, value.To<decimal>()) { IsFinal = IsFinal, InputValue = this }
: base.SetValue(indicator, value);
}
}
/// <summary>
/// The indicator value, operating with data type <see cref="Candle"/>.
/// </summary>
public class CandleIndicatorValue : SingleIndicatorValue<Candle>
{
private readonly Func<Candle, decimal> _getPart;
/// <summary>
/// Initializes a new instance of the <see cref="CandleIndicatorValue"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
/// <param name="value">Value.</param>
public CandleIndicatorValue(IIndicator indicator, Candle value)
: this(indicator, value, ByClose)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CandleIndicatorValue"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
/// <param name="value">Value.</param>
/// <param name="getPart">The candle converter, through which its parameter can be got. By default, the <see cref="CandleIndicatorValue.ByClose"/> is used.</param>
public CandleIndicatorValue(IIndicator indicator, Candle value, Func<Candle, decimal> getPart)
: base(indicator, value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (getPart == null)
throw new ArgumentNullException(nameof(getPart));
_getPart = getPart;
IsFinal = value.State == CandleStates.Finished;
}
/// <summary>
/// Initializes a new instance of the <see cref="CandleIndicatorValue"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
private CandleIndicatorValue(IIndicator indicator)
: base(indicator)
{
}
/// <summary>
/// The converter, taking from candle closing price <see cref="Candle.ClosePrice"/>.
/// </summary>
public static readonly Func<Candle, decimal> ByClose = c => c.ClosePrice;
/// <summary>
/// The converter, taking from candle opening price <see cref="Candle.OpenPrice"/>.
/// </summary>
public static readonly Func<Candle, decimal> ByOpen = c => c.OpenPrice;
/// <summary>
/// The converter, taking from candle middle of the body (<see cref="Candle.OpenPrice"/> + <see cref="Candle.ClosePrice"/>) / 2.
/// </summary>
public static readonly Func<Candle, decimal> ByMiddle = c => (c.ClosePrice + c.OpenPrice) / 2;
/// <summary>
/// Does value support data type, required for the indicator.
/// </summary>
/// <param name="valueType">The data type, operated by indicator.</param>
/// <returns><see langword="true" />, if data type is supported, otherwise, <see langword="false" />.</returns>
public override bool IsSupport(Type valueType)
{
return valueType == typeof(decimal) || base.IsSupport(valueType);
}
/// <summary>
/// To get the value by the data type.
/// </summary>
/// <typeparam name="T">The data type, operated by indicator.</typeparam>
/// <returns>Value.</returns>
public override T GetValue<T>()
{
var candle = base.GetValue<Candle>();
return typeof(T) == typeof(decimal) ? _getPart(candle).To<T>() : candle.To<T>();
}
/// <summary>
/// To replace the indicator input value by new one (for example it is received from another indicator).
/// </summary>
/// <typeparam name="T">The data type, operated by indicator.</typeparam>
/// <param name="indicator">Indicator.</param>
/// <param name="value">Value.</param>
/// <returns>New object, containing input value.</returns>
public override IIndicatorValue SetValue<T>(IIndicator indicator, T value)
{
var candle = value as Candle;
return candle != null
? new CandleIndicatorValue(indicator, candle) { InputValue = this }
: value.IsNull() ? new CandleIndicatorValue(indicator) : base.SetValue(indicator, value);
}
}
/// <summary>
/// The indicator value, operating with data type <see cref="MarketDepth"/>.
/// </summary>
public class MarketDepthIndicatorValue : SingleIndicatorValue<MarketDepth>
{
private readonly Func<MarketDepth, decimal?> _getPart;
/// <summary>
/// Initializes a new instance of the <see cref="MarketDepthIndicatorValue"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
/// <param name="depth">Market depth.</param>
public MarketDepthIndicatorValue(IIndicator indicator, MarketDepth depth)
: this(indicator, depth, ByMiddle)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MarketDepthIndicatorValue"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
/// <param name="depth">Market depth.</param>
/// <param name="getPart">The order book converter, through which its parameter can be got. By default, the <see cref="MarketDepthIndicatorValue.ByMiddle"/> is used.</param>
public MarketDepthIndicatorValue(IIndicator indicator, MarketDepth depth, Func<MarketDepth, decimal?> getPart)
: base(indicator, depth)
{
if (depth == null)
throw new ArgumentNullException(nameof(depth));
if (getPart == null)
throw new ArgumentNullException(nameof(getPart));
_getPart = getPart;
}
/// <summary>
/// The converter, taking from the order book the best bid price <see cref="MarketDepth.BestBid"/>.
/// </summary>
public static readonly Func<MarketDepth, decimal?> ByBestBid = d => d.BestBid != null ? d.BestBid.Price : (decimal?)null;
/// <summary>
/// The converter, taking from the order book the best offer price <see cref="MarketDepth.BestAsk"/>.
/// </summary>
public static readonly Func<MarketDepth, decimal?> ByBestAsk = d => d.BestAsk != null ? d.BestAsk.Price : (decimal?)null;
/// <summary>
/// The converter, taking from the order book the middle of the spread <see cref="MarketDepthPair.MiddlePrice"/>.
/// </summary>
public static readonly Func<MarketDepth, decimal?> ByMiddle = d => d.BestPair == null ? (decimal?)null : d.BestPair.MiddlePrice;
/// <summary>
/// Does value support data type, required for the indicator.
/// </summary>
/// <param name="valueType">The data type, operated by indicator.</param>
/// <returns><see langword="true" />, if data type is supported, otherwise, <see langword="false" />.</returns>
public override bool IsSupport(Type valueType)
{
return valueType == typeof(decimal) || base.IsSupport(valueType);
}
/// <summary>
/// To get the value by the data type.
/// </summary>
/// <typeparam name="T">The data type, operated by indicator.</typeparam>
/// <returns>Value.</returns>
public override T GetValue<T>()
{
var depth = base.GetValue<MarketDepth>();
return typeof(T) == typeof(decimal) ? (_getPart(depth) ?? 0).To<T>() : depth.To<T>();
}
/// <summary>
/// To replace the indicator input value by new one (for example it is received from another indicator).
/// </summary>
/// <typeparam name="T">The data type, operated by indicator.</typeparam>
/// <param name="indicator">Indicator.</param>
/// <param name="value">Value.</param>
/// <returns>New object, containing input value.</returns>
public override IIndicatorValue SetValue<T>(IIndicator indicator, T value)
{
return new MarketDepthIndicatorValue(indicator, base.GetValue<MarketDepth>(), _getPart)
{
IsFinal = IsFinal,
InputValue = this
};
}
}
/// <summary>
/// The value of the indicator, operating with pair <see ref="Tuple{TValue, TValue}" />.
/// </summary>
public class PairIndicatorValue<TValue> : SingleIndicatorValue<Tuple<TValue, TValue>>
{
/// <summary>
/// Initializes a new instance of the <see cref="PairIndicatorValue{T}"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
/// <param name="value">Value.</param>
public PairIndicatorValue(IIndicator indicator, Tuple<TValue, TValue> value)
: base(indicator, value)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="PairIndicatorValue{T}"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
public PairIndicatorValue(IIndicator indicator)
: base(indicator)
{
}
/// <summary>
/// To replace the indicator input value by new one (for example it is received from another indicator).
/// </summary>
/// <typeparam name="T">The data type, operated by indicator.</typeparam>
/// <param name="indicator">Indicator.</param>
/// <param name="value">Value.</param>
/// <returns>New object, containing input value.</returns>
public override IIndicatorValue SetValue<T>(IIndicator indicator, T value)
{
return new PairIndicatorValue<TValue>(indicator, GetValue<Tuple<TValue, TValue>>())
{
IsFinal = IsFinal,
InputValue = this
};
}
}
/// <summary>
/// The complex value of the indicator <see cref="IComplexIndicator"/>, derived as result of calculation.
/// </summary>
public class ComplexIndicatorValue : BaseIndicatorValue
{
/// <summary>
/// Initializes a new instance of the <see cref="ComplexIndicatorValue"/>.
/// </summary>
/// <param name="indicator">Indicator.</param>
public ComplexIndicatorValue(IIndicator indicator)
: base(indicator)
{
InnerValues = new Dictionary<IIndicator, IIndicatorValue>();
}
/// <summary>
/// No indicator value.
/// </summary>
public override bool IsEmpty { get; set; }
/// <summary>
/// Is the value final (indicator finalizes its value and will not be changed anymore in the given point of time).
/// </summary>
public override bool IsFinal { get; set; }
/// <summary>
/// The input value.
/// </summary>
public override IIndicatorValue InputValue { get; set; }
/// <summary>
/// Embedded values.
/// </summary>
public IDictionary<IIndicator, IIndicatorValue> InnerValues { get; }
/// <summary>
/// Does value support data type, required for the indicator.
/// </summary>
/// <param name="valueType">The data type, operated by indicator.</param>
/// <returns><see langword="true" />, if data type is supported, otherwise, <see langword="false" />.</returns>
public override bool IsSupport(Type valueType)
{
return InnerValues.Any(v => v.Value.IsSupport(valueType));
}
/// <summary>
/// To get the value by the data type.
/// </summary>
/// <typeparam name="T">The data type, operated by indicator.</typeparam>
/// <returns>Value.</returns>
public override T GetValue<T>()
{
throw new NotSupportedException();
}
/// <summary>
/// To replace the indicator input value by new one (for example it is received from another indicator).
/// </summary>
/// <typeparam name="T">The data type, operated by indicator.</typeparam>
/// <param name="indicator">Indicator.</param>
/// <param name="value">Value.</param>
/// <returns>Replaced copy of the input value.</returns>
public override IIndicatorValue SetValue<T>(IIndicator indicator, T value)
{
throw new NotSupportedException();
}
/// <summary>
/// Compare <see cref="ComplexIndicatorValue"/> on the equivalence.
/// </summary>
/// <param name="other">Another value with which to compare.</param>
/// <returns>The result of the comparison.</returns>
public override int CompareTo(IIndicatorValue other)
{
throw new NotSupportedException();
}
}
}
| |
#region Imports
#define INSTANT_DETECTION_DEATH
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Diagnostics;
using System;
using System.Threading;
using Ros_CSharp;
using XmlRpc_Wrapper;
using Int32 = Messages.std_msgs.Int32;
using m = Messages.std_msgs;
using gm = Messages.geometry_msgs;
using nm = Messages.nav_msgs;
using sm = Messages.sensor_msgs;
using Messages.rock_publisher;
using am = Messages.sample_acquisition;
// for threading
using System.Windows.Threading;
// for controller; don't forget to include Microsoft.Xna.Framework in References
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
// for timer
#endregion
namespace WpfApplication1
{
public partial class MainWindow : Window
{
int[] tilt_prev = new int[4] {0,0,0,0};
Publisher<m.Bool> mast_pub;
Publisher<m.Int32>[] tilt_pub;
Publisher<m.Bool> ArmON;
// controller
GamePadState currentState;
// nodes
NodeHandle nh;
Publisher<m.Byte> multiplexPub;
Publisher<gm.Twist> velPub;
Publisher<am.ArmMovement> armPub;
TabItem[] mainCameras, subCameras;
public ROS_ImageWPF.CompressedImageControl[] mainImages;
public ROS_ImageWPF.SlaveImage[] subImages;
DispatcherTimer controllerUpdater;
private const int back_cam = 1;
private const int front_cam = 0;
//Stopwatch
Stopwatch sw = new Stopwatch();
//
//private DetectionHelper[] detectors;
private bool _adr;
private void adr(bool status)
{
if (_adr != status)
{
_adr = status;
mainImages[back_cam].guts.Transform(status ? -1.0 : 1.0, 1.0);
subImages[back_cam].guts.Transform(status ? -1.0 : 1.0, 1);
subImages[front_cam].guts.Transform(status ? 1.0 : -1.0, 1.0);
}
}
// initialize stuff for MainWindow
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
controllerUpdater = new DispatcherTimer() { Interval = new TimeSpan(0, 0, 0, 0, 10) };
controllerUpdater.Tick += Link;
controllerUpdater.Start();
new Thread(() =>
{
XmlRpcUtil.ShowOutputFromXmlRpcPInvoke();
// ROS stuff
ROS.Init(new string[0], "The_UI_" + System.Environment.MachineName.Replace("-", "__"));
nh = new NodeHandle();
Dispatcher.Invoke(new Action(() =>
{
battvolt.startListening(nh);
EStop.startListening(nh);
MotorGraph.startListening(nh);
rosout_control.startListening(nh);
spinningstuff.startListening(nh, "/imu/data");
}));
velPub = nh.advertise<gm.Twist>("/cmd_vel", 1);
multiplexPub = nh.advertise<m.Byte>("/cam_select", 1);
armPub = nh.advertise<am.ArmMovement>("/arm/movement", 1);
ArmON = nh.advertise<m.Bool>("arm/on", 1);
mast_pub = nh.advertise<m.Bool>("raise_camera_mast", 1);
tilt_pub = new Publisher<m.Int32>[4];
for (int i = 0; i < 4; i++)
{
tilt_pub[i] = nh.advertise<m.Int32>("camera" + i + "/tilt", 1);
}
Dispatcher.Invoke(new Action(() =>
{
mainCameras = new TabItem[] { MainCamera1, MainCamera2, MainCamera3, MainCamera4 };
subCameras = new TabItem[] { SubCamera1, SubCamera2, SubCamera3, SubCamera4 };
mainImages = new ROS_ImageWPF.CompressedImageControl[] { camImage0, camImage1, camImage2, camImage3 };
subImages = new ROS_ImageWPF.SlaveImage[] { camImageSlave0, camImageSlave1, camImageSlave2, camImageSlave3 };
for (int i = 0; i < mainCameras.Length; i++)
{
mainImages[i].AddSlave(subImages[i]);
}
subCameras[1].Focus();
adr(false);
// instantiating some global helpers
/*detectors = new DetectionHelper[4];
for (int i = 0; i < 4; ++i)
{
detectors[i] = new DetectionHelper(nh, i, this);
}*/
}));
#if !INSTANT_DETECTION_DEATH
while (ROS.ok)
{
Dispatcher.Invoke(new Action(() =>
{
for (int i = 0; i < 4; ++i)
{
detectors[i].churnAndBurn();
}
}));
Thread.Sleep(100);
}
#endif
}).Start();
}
// close ros when application closes
protected override void OnClosed(EventArgs e)
{
ROS.shutdown();
base.OnClosed(e);
}
bool engaged = false;
// controller link dispatcher
public void Link(object sender, EventArgs dontcare)
{
// get state of player one
currentState = GamePad.GetState(PlayerIndex.One);
// if controller is connected...
if (currentState.IsConnected)
{
// ...say its connected in the textbloxk, color it green cuz its good to go
LinkTextBlock.Text = "Controller: Connected";
LinkTextBlock.Foreground = Brushes.Green;
foreach (Buttons b in Enum.GetValues(typeof(Buttons)))
{
Button(b);
}
double left_y = currentState.ThumbSticks.Left.Y;
double left_x = -currentState.ThumbSticks.Left.X;
if (_adr)
{
//left_x *= -1;
left_y *= -1;
}
gm.Twist vel = new gm.Twist { linear = new gm.Vector3 { x = left_y * _trans.Value }, angular = new gm.Vector3 { z = left_x * _rot.Value } };
if(velPub != null)
velPub.publish(vel);
//arm controls via joystick are done here.
double right_y = currentState.ThumbSticks.Right.Y;
// this is inverted to reflect mikes arm driver. right requires a negative number, not the default positive value
double right_x = -1 * currentState.ThumbSticks.Right.X;
double right_trigger = currentState.Triggers.Right;
if (!engaged && (Math.Abs(right_y) > .1 || Math.Abs(right_x) > .1 ))
{
engaged = true;
ArmON.publish(new m.Bool() { data = true });
Arm_Engaged.Content = "Arm Engaged";
Arm_Engaged.Background = Brushes.White;
Arm_Engaged.Foreground = Brushes.Green;
}
//if trigger is not pressed, send close signal ( -1 ). Th goal is to have the gripper
// going to a close state when the right trigger is not being pressed.
if (right_trigger == 0)
right_trigger = -1;
/*Console.WriteLine( "joy_right_x: " + right_x.ToString());
Console.WriteLine( "joy_right_y: " + right_y.ToString());
Console.WriteLine( "right trigger: " + right_trigger.ToString());*/
am.ArmMovement armmove = new am.ArmMovement();
armmove.pan_motor_velocity = right_x;
armmove.tilt_motor_velocity = right_y;
armmove.gripper_open = (right_trigger >= 0.5);
if (armPub != null)
armPub.publish(armmove);
}
// unless if controller is not connected...
else if (!currentState.IsConnected)
{
// ...have program complain controller is disconnected
LinkTextBlock.Text = "Controller: Disconnected";
LinkTextBlock.Foreground = Brushes.Red;
}
}
private byte maincameramask, secondcameramask;
// when MainCameraControl tabs are selected
private void MainCameraTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
maincameramask = (byte)Math.Round(Math.Pow(2.0, MainCameraTabControl.SelectedIndex));
//Console.WriteLine("************************Camera Selected: " + MainCameraTabControl.SelectedIndex.ToString() + "********************************");
Tilt_Slider.Value = tilt_prev[MainCameraTabControl.SelectedIndex];
//enter ADR?
if (MainCameraTabControl.SelectedIndex == back_cam)
{
SubCameraTabControl.SelectedIndex = front_cam;
adr(true);
}
else
adr(false);
JimCarry();
}
// When SubCameraTabControl tabs are selected
private void SubCameraTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
secondcameramask = (byte)Math.Round(Math.Pow(2.0, SubCameraTabControl.SelectedIndex));
JimCarry();
}
//What an odd name to give a function...
private void JimCarry()
{
if (multiplexPub == null) return;
m.Byte msg = new m.Byte { data = (byte)(maincameramask | secondcameramask) };
Console.WriteLine("SENDING CAM SELECT: " + msg.data);
multiplexPub.publish(msg);
}
private List<Buttons> knownToBeDown = new List<Buttons>();
public void Button(Buttons b)
{
// if a is pressed
if (currentState.IsButtonDown(b))
{
if (knownToBeDown.Contains(b))
return;
knownToBeDown.Add(b);
//Console.WriteLine("" + b.ToString() + " pressed");
switch (b)
{
case Buttons.Start: break;
case Buttons.Back: break;
case Buttons.DPadDown: _trans.DPadButton( UberSlider.VerticalUberSlider.DPadDirection.Down, true); break; //rockCounter.DPadButton(RockCounterUC.RockCounter.DPadDirection.Down, true);
case Buttons.DPadUp: _trans.DPadButton(UberSlider.VerticalUberSlider.DPadDirection.Up, true); break; //rockCounter.DPadButton(RockCounterUC.RockCounter.DPadDirection.Up, true); break;
case Buttons.DPadLeft: _rot.DPadButton( UberSlider.UberSlider.DPadDirection.Left, true); break; // rockCounter.DPadButton(RockCounterUC.RockCounter.DPadDirection.Left, true); break;
case Buttons.DPadRight: _rot.DPadButton( UberSlider.UberSlider.DPadDirection.Right, true); break;//rockCounter.DPadButton(RockCounterUC.RockCounter.DPadDirection.Right, true); break;
case Buttons.RightStick: RightStickButton(); break;
case Buttons.RightShoulder: tilt_change(1); break;
case Buttons.LeftShoulder: tilt_change(0); break;
}
}
else
knownToBeDown.Remove(b);
}
public void tilt_change(int i)
{
if (i == 1 && Tilt_Slider.Value < 36000) Tilt_Slider.Value += 3600;
if (i == 0 && Tilt_Slider.Value > -36000) Tilt_Slider.Value += -3600;
}
// right stick function; reset timer
public void RightStickButton()
{
// if right stick is clicked/pressed
if (currentState.Buttons.RightStick == ButtonState.Pressed && engaged)
{
engaged = false;
ArmON.publish(new m.Bool { data = false });
Arm_Engaged.Content = "Arm NOT Engaged";
Arm_Engaged.Background = Brushes.Black;
Arm_Engaged.Foreground = Brushes.Red;
}
}
private void Tilt_Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
int tilt = (int)Tilt_Slider.Value;
tilt_prev[MainCameraTabControl.SelectedIndex] = tilt;
Tilt_Lvl.Content = tilt.ToString();
if (tilt_pub != null) tilt_pub[MainCameraTabControl.SelectedIndex].publish(new Int32 { data = tilt });
}
private void Raise_Mast_Click(object sender, RoutedEventArgs e)
{
mast_pub.publish(new m.Bool() { data = true });
//Raise_mast.Visibility = Visibility.Hidden;
Raise_mast.Width = 164;
Raise_mast.Height = 50;
Canvas.SetLeft(Raise_mast, 1217);
Canvas.SetTop(Raise_mast, 41);
Raise_mast.FontSize = 16;
}
//
// User recalibration starts here
//
System.Windows.Point mouseDownPoint;
System.Windows.Point mousePos;
System.Windows.Shapes.Rectangle mouseBox;
bool leftButtonDown = false;
bool leftButtonDownInBounds = false;
int boxColor = 0;
Brush brushColor = Brushes.Blue;
private int whichIsIt(object sender)
{
ROS_ImageWPF.CompressedImageControl c = (sender as ROS_ImageWPF.CompressedImageControl);
if (c == null) return -1;
for (int i = 0; i < mainImages.Length; i++)
if (mainImages[i] == c)
return i;
return -1;
}
#region radio buttons
/*private void RadioButton_Checked_B(object sender, RoutedEventArgs e)
{
boxColor = 0;
brushColor = Brushes.Blue;
}
private void RadioButton_Checked_G(object sender, RoutedEventArgs e)
{
boxColor = 1;
brushColor = Brushes.Green;
}
private void RadioButton_Checked_R(object sender, RoutedEventArgs e)
{
boxColor = 2;
brushColor = Brushes.Red;
}
private void RadioButton_Checked_O(object sender, RoutedEventArgs e)
{
boxColor = 3;
brushColor = Brushes.Orange;
}
private void RadioButton_Checked_P(object sender, RoutedEventArgs e)
{
boxColor = 4;
brushColor = Brushes.Purple;
}
private void RadioButton_Checked_Y(object sender, RoutedEventArgs e)
{
boxColor = 5;
brushColor = Brushes.Yellow;
}
#endregion
#region send & clear
private void Button_Click_Send(object sender, RoutedEventArgs e)
{
// hopefully not broken
PublishRecalibration(MainCameraTabControl.SelectedIndex);
camRect0.Children.Clear();
camRect1.Children.Clear();
camRect2.Children.Clear();
camRect3.Children.Clear();
}
private void Button_Click_Clear(object sender, RoutedEventArgs e)
{
camRect0.Children.Clear();
camRect1.Children.Clear();
camRect2.Children.Clear();
camRect3.Children.Clear();
}
#endregion
#region restore default calibrations
recalibrateMsg MakeBogusRestoreMessage()
{
recalibrateMsg theMsg = new recalibrateMsg();
theMsg.data = new imgData();
theMsg.img = new sm.CompressedImage();
theMsg.data.cameraID = -1;
theMsg.data.width = -1;
theMsg.data.height = -1;
theMsg.data.x = -1;
theMsg.data.y = -1;
theMsg.data.color = new m.ColorRGBA();
theMsg.data.color.r = -1;
theMsg.data.color.g = -1;
theMsg.data.color.b = -1;
theMsg.data.color.a = -1;
return theMsg;
}
private void Button_Click_Restore0(object sender, RoutedEventArgs e)
{
Dispatcher.Invoke(new Action(() =>
{
recalPub0.publish(MakeBogusRestoreMessage());
}));
}
private void Button_Click_Restore1(object sender, RoutedEventArgs e)
{
Dispatcher.Invoke(new Action(() =>
{
recalPub1.publish(MakeBogusRestoreMessage());
}));
}
private void Button_Click_Restore2(object sender, RoutedEventArgs e)
{
Dispatcher.Invoke(new Action(() =>
{
recalPub2.publish(MakeBogusRestoreMessage());
}));
}
private void Button_Click_Restore3(object sender, RoutedEventArgs e)
{
Dispatcher.Invoke(new Action(() =>
{
recalPub3.publish(MakeBogusRestoreMessage());
}));
}*/
#endregion
}
}
| |
#region Copyright & License
//
// Copyright 2004-2005 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Text;
using System.Globalization;
using log4net.Core;
using log4net.Layout;
using log4net.Util;
namespace log4net.Appender
{
/// <summary>
/// Appends logging events to the terminal using ANSI color escape sequences.
/// </summary>
/// <remarks>
/// <para>
/// AnsiColorTerminalAppender appends log events to the standard output stream
/// or the error output stream using a layout specified by the
/// user. It also allows the color of a specific level of message to be set.
/// </para>
/// <note>
/// This appender expects the terminal to understand the VT100 control set
/// in order to interpret the color codes. If the terminal or console does not
/// understand the control codes the behavior is not defined.
/// </note>
/// <para>
/// By default, all output is written to the console's standard output stream.
/// The <see cref="Target"/> property can be set to direct the output to the
/// error stream.
/// </para>
/// <para>
/// NOTE: This appender writes each message to the <c>System.Console.Out</c> or
/// <c>System.Console.Error</c> that is set at the time the event is appended.
/// Therefore it is possible to programmatically redirect the output of this appender
/// (for example NUnit does this to capture program output). While this is the desired
/// behavior of this appender it may have security implications in your application.
/// </para>
/// <para>
/// When configuring the ANSI colored terminal appender, a mapping should be
/// specified to map a logging level to a color. For example:
/// </para>
/// <code lang="XML" escaped="true">
/// <mapping>
/// <level value="ERROR" />
/// <foreColor value="White" />
/// <backColor value="Red" />
/// <attributes value="Bright,Underscore" />
/// </mapping>
/// <mapping>
/// <level value="DEBUG" />
/// <backColor value="Green" />
/// </mapping>
/// </code>
/// <para>
/// The Level is the standard log4net logging level and ForeColor and BackColor can be any
/// of the following values:
/// <list type="bullet">
/// <item><term>Blue</term><description></description></item>
/// <item><term>Green</term><description></description></item>
/// <item><term>Red</term><description></description></item>
/// <item><term>White</term><description></description></item>
/// <item><term>Yellow</term><description></description></item>
/// <item><term>Purple</term><description></description></item>
/// <item><term>Cyan</term><description></description></item>
/// </list>
/// These color values cannot be combined together to make new colors.
/// </para>
/// <para>
/// The attributes can be any combination of the following:
/// <list type="bullet">
/// <item><term>Bright</term><description>foreground is brighter</description></item>
/// <item><term>Dim</term><description>foreground is dimmer</description></item>
/// <item><term>Underscore</term><description>message is underlined</description></item>
/// <item><term>Blink</term><description>foreground is blinking (does not work on all terminals)</description></item>
/// <item><term>Reverse</term><description>foreground and background are reversed</description></item>
/// <item><term>Hidden</term><description>output is hidden</description></item>
/// <item><term>Strikethrough</term><description>message has a line through it</description></item>
/// </list>
/// While any of these attributes may be combined together not all combinations
/// work well together, for example setting both <i>Bright</i> and <i>Dim</i> attributes makes
/// no sense.
/// </para>
/// </remarks>
/// <author>Patrick Wagstrom</author>
/// <author>Nicko Cadell</author>
public class AnsiColorTerminalAppender : AppenderSkeleton
{
#region Colors Enum
/// <summary>
/// The enum of possible display attributes
/// </summary>
/// <remarks>
/// <para>
/// The following flags can be combined together to
/// form the ANSI color attributes.
/// </para>
/// </remarks>
/// <seealso cref="AnsiColorTerminalAppender" />
[Flags]
public enum AnsiAttributes : int
{
/// <summary>
/// text is bright
/// </summary>
Bright = 1,
/// <summary>
/// text is dim
/// </summary>
Dim = 2,
/// <summary>
/// text is underlined
/// </summary>
Underscore = 4,
/// <summary>
/// text is blinking
/// </summary>
/// <remarks>
/// Not all terminals support this attribute
/// </remarks>
Blink = 8,
/// <summary>
/// text and background colors are reversed
/// </summary>
Reverse = 16,
/// <summary>
/// text is hidden
/// </summary>
Hidden = 32,
/// <summary>
/// text is displayed with a strikethrough
/// </summary>
Strikethrough = 64
}
/// <summary>
/// The enum of possible foreground or background color values for
/// use with the color mapping method
/// </summary>
/// <remarks>
/// <para>
/// The output can be in one for the following ANSI colors.
/// </para>
/// </remarks>
/// <seealso cref="AnsiColorTerminalAppender" />
public enum AnsiColor : int
{
/// <summary>
/// color is black
/// </summary>
Black = 0,
/// <summary>
/// color is red
/// </summary>
Red = 1,
/// <summary>
/// color is green
/// </summary>
Green = 2,
/// <summary>
/// color is yellow
/// </summary>
Yellow = 3,
/// <summary>
/// color is blue
/// </summary>
Blue = 4,
/// <summary>
/// color is magenta
/// </summary>
Magenta = 5,
/// <summary>
/// color is cyan
/// </summary>
Cyan = 6,
/// <summary>
/// color is white
/// </summary>
White = 7
}
#endregion
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="AnsiColorTerminalAppender" /> class.
/// </summary>
/// <remarks>
/// The instance of the <see cref="AnsiColorTerminalAppender" /> class is set up to write
/// to the standard output stream.
/// </remarks>
public AnsiColorTerminalAppender()
{
}
#endregion Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Target is the value of the console output stream.
/// </summary>
/// <value>
/// Target is the value of the console output stream.
/// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>.
/// </value>
/// <remarks>
/// <para>
/// Target is the value of the console output stream.
/// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>.
/// </para>
/// </remarks>
virtual public string Target
{
get { return m_writeToErrorStream ? ConsoleError : ConsoleOut; }
set
{
string trimmedTargetName = value.Trim();
if (string.Compare(ConsoleError, trimmedTargetName, true, CultureInfo.InvariantCulture) == 0)
{
m_writeToErrorStream = true;
}
else
{
m_writeToErrorStream = false;
}
}
}
/// <summary>
/// Add a mapping of level to color
/// </summary>
/// <param name="mapping">The mapping to add</param>
/// <remarks>
/// <para>
/// Add a <see cref="LevelColors"/> mapping to this appender.
/// Each mapping defines the foreground and background colours
/// for a level.
/// </para>
/// </remarks>
public void AddMapping(LevelColors mapping)
{
m_levelMapping.Add(mapping);
}
#endregion Public Instance Properties
#region Override implementation of AppenderSkeleton
/// <summary>
/// This method is called by the <see cref="AppenderSkeleton.DoAppend(LoggingEvent)"/> method.
/// </summary>
/// <param name="loggingEvent">The event to log.</param>
/// <remarks>
/// <para>
/// Writes the event to the console.
/// </para>
/// <para>
/// The format of the output will depend on the appender's layout.
/// </para>
/// </remarks>
override protected void Append(log4net.Core.LoggingEvent loggingEvent)
{
string loggingMessage = RenderLoggingEvent(loggingEvent);
// see if there is a specified lookup.
LevelColors levelColors = m_levelMapping.Lookup(loggingEvent.Level) as LevelColors;
if (levelColors != null)
{
// Prepend the Ansi Color code
loggingMessage = levelColors.CombinedColor + loggingMessage;
}
// on most terminals there are weird effects if we don't clear the background color
// before the new line. This checks to see if it ends with a newline, and if
// so, inserts the clear codes before the newline, otherwise the clear codes
// are inserted afterwards.
if (loggingMessage.Length > 1)
{
if (loggingMessage.EndsWith("\r\n") || loggingMessage.EndsWith("\n\r"))
{
loggingMessage = loggingMessage.Insert(loggingMessage.Length - 2, PostEventCodes);
}
else if (loggingMessage.EndsWith("\n") || loggingMessage.EndsWith("\r"))
{
loggingMessage = loggingMessage.Insert(loggingMessage.Length - 1, PostEventCodes);
}
else
{
loggingMessage = loggingMessage + PostEventCodes;
}
}
else
{
if (loggingMessage[0] == '\n' || loggingMessage[0] == '\r')
{
loggingMessage = PostEventCodes + loggingMessage;
}
else
{
loggingMessage = loggingMessage + PostEventCodes;
}
}
#if NETCF
// Write to the output stream
Console.Write(loggingMessage);
#else
if (m_writeToErrorStream)
{
// Write to the error stream
Console.Error.Write(loggingMessage);
}
else
{
// Write to the output stream
Console.Write(loggingMessage);
}
#endif
}
/// <summary>
/// This appender requires a <see cref="Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="Layout"/> to be set.
/// </para>
/// </remarks>
override protected bool RequiresLayout
{
get { return true; }
}
/// <summary>
/// Initialize the options for this appender
/// </summary>
/// <remarks>
/// <para>
/// Initialize the level to color mappings set on this appender.
/// </para>
/// </remarks>
public override void ActivateOptions()
{
base.ActivateOptions();
m_levelMapping.ActivateOptions();
}
#endregion Override implementation of AppenderSkeleton
#region Public Static Fields
/// <summary>
/// The <see cref="AnsiColorTerminalAppender.Target"/> to use when writing to the Console
/// standard output stream.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="AnsiColorTerminalAppender.Target"/> to use when writing to the Console
/// standard output stream.
/// </para>
/// </remarks>
public const string ConsoleOut = "Console.Out";
/// <summary>
/// The <see cref="AnsiColorTerminalAppender.Target"/> to use when writing to the Console
/// standard error output stream.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="AnsiColorTerminalAppender.Target"/> to use when writing to the Console
/// standard error output stream.
/// </para>
/// </remarks>
public const string ConsoleError = "Console.Error";
#endregion Public Static Fields
#region Private Instances Fields
/// <summary>
/// Flag to write output to the error stream rather than the standard output stream
/// </summary>
private bool m_writeToErrorStream = false;
/// <summary>
/// Mapping from level object to color value
/// </summary>
private LevelMapping m_levelMapping = new LevelMapping();
/// <summary>
/// Ansi code to reset terminal
/// </summary>
private const string PostEventCodes = "\x1b[0m";
#endregion Private Instances Fields
#region LevelColors LevelMapping Entry
/// <summary>
/// A class to act as a mapping between the level that a logging call is made at and
/// the color it should be displayed as.
/// </summary>
/// <remarks>
/// <para>
/// Defines the mapping between a level and the color it should be displayed in.
/// </para>
/// </remarks>
public class LevelColors : LevelMappingEntry
{
private AnsiColor m_foreColor;
private AnsiColor m_backColor;
private AnsiAttributes m_attributes;
private string m_combinedColor = "";
/// <summary>
/// The mapped foreground color for the specified level
/// </summary>
/// <remarks>
/// <para>
/// Required property.
/// The mapped foreground color for the specified level
/// </para>
/// </remarks>
public AnsiColor ForeColor
{
get { return m_foreColor; }
set { m_foreColor = value; }
}
/// <summary>
/// The mapped background color for the specified level
/// </summary>
/// <remarks>
/// <para>
/// Required property.
/// The mapped background color for the specified level
/// </para>
/// </remarks>
public AnsiColor BackColor
{
get { return m_backColor; }
set { m_backColor = value; }
}
/// <summary>
/// The color attributes for the specified level
/// </summary>
/// <remarks>
/// <para>
/// Required property.
/// The color attributes for the specified level
/// </para>
/// </remarks>
public AnsiAttributes Attributes
{
get { return m_attributes; }
set { m_attributes = value; }
}
/// <summary>
/// Initialize the options for the object
/// </summary>
/// <remarks>
/// <para>
/// Combine the <see cref="ForeColor"/> and <see cref="BackColor"/> together
/// and append the attributes.
/// </para>
/// </remarks>
public override void ActivateOptions()
{
base.ActivateOptions();
StringBuilder buf = new StringBuilder();
// Reset any existing codes
buf.Append("\x1b[0;");
// set the foreground color
buf.Append(30 + (int)m_foreColor);
buf.Append(';');
// set the background color
buf.Append(40 + (int)m_backColor);
// set the attributes
if ((m_attributes & AnsiAttributes.Bright) > 0)
{
buf.Append(";1");
}
if ((m_attributes & AnsiAttributes.Dim) > 0)
{
buf.Append(";2");
}
if ((m_attributes & AnsiAttributes.Underscore) > 0)
{
buf.Append(";4");
}
if ((m_attributes & AnsiAttributes.Blink) > 0)
{
buf.Append(";5");
}
if ((m_attributes & AnsiAttributes.Reverse) > 0)
{
buf.Append(";7");
}
if ((m_attributes & AnsiAttributes.Hidden) > 0)
{
buf.Append(";8");
}
if ((m_attributes & AnsiAttributes.Strikethrough) > 0)
{
buf.Append(";9");
}
buf.Append('m');
m_combinedColor = buf.ToString();
}
/// <summary>
/// The combined <see cref="ForeColor"/>, <see cref="BackColor"/> and
/// <see cref="Attributes"/> suitable for setting the ansi terminal color.
/// </summary>
internal string CombinedColor
{
get { return m_combinedColor; }
}
}
#endregion // LevelColors LevelMapping Entry
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hangfire.Common;
using Hangfire.Logging;
using Hangfire.Mongo.Database;
using Hangfire.Mongo.Dto;
using Hangfire.States;
using Hangfire.Storage;
using MongoDB.Bson;
using MongoDB.Driver;
namespace Hangfire.Mongo
{
#pragma warning disable 1591
public class MongoWriteOnlyTransaction : JobStorageTransaction
{
protected MongoStorageOptions StorageOptions { get; }
protected static readonly ILog Logger = LogProvider.For<MongoWriteOnlyTransaction>();
public HangfireDbContext DbContext { get; }
private readonly IList<WriteModel<BsonDocument>> _writeModels = new List<WriteModel<BsonDocument>>();
protected HashSet<string> JobsAddedToQueue { get; }
public MongoWriteOnlyTransaction(HangfireDbContext dbContext, MongoStorageOptions storageOptions)
{
StorageOptions = storageOptions;
DbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
JobsAddedToQueue = new HashSet<string>();
}
public override void Dispose()
{
}
public override void ExpireJob(string jobId, TimeSpan expireIn)
{
var filter = CreateJobIdFilter(jobId);
var update = new BsonDocument("$set",
new BsonDocument(nameof(KeyJobDto.ExpireAt), DateTime.UtcNow.Add(expireIn)));
var writeModel = new UpdateOneModel<BsonDocument>(filter, update);
_writeModels.Add(writeModel);
}
public virtual string CreateExpiredJob(Job job, IDictionary<string, string> parameters, DateTime createdAt,
TimeSpan expireIn)
{
if (job == null)
throw new ArgumentNullException(nameof(job));
if (parameters == null)
throw new ArgumentNullException(nameof(parameters));
var invocationData = InvocationData.Serialize(job);
var jobDto = new JobDto
{
Id = ObjectId.GenerateNewId(),
InvocationData = JobHelper.ToJson(invocationData),
Arguments = invocationData.Arguments,
Parameters = parameters.ToDictionary(kv => kv.Key, kv => kv.Value),
CreatedAt = createdAt,
ExpireAt = createdAt.Add(expireIn)
};
var writeModel = new InsertOneModel<BsonDocument>(jobDto.ToBsonDocument());
_writeModels.Add(writeModel);
var jobId = jobDto.Id.ToString();
return jobId;
}
public override void PersistJob(string jobId)
{
var filter = CreateJobIdFilter(jobId);
var update = new BsonDocument("$set", new BsonDocument(nameof(KeyJobDto.ExpireAt), BsonNull.Value));
var writeModel = new UpdateOneModel<BsonDocument>(filter, update);
_writeModels.Add(writeModel);
}
public override void SetJobState(string jobId, IState state)
{
var filter = CreateJobIdFilter(jobId);
var stateDto = new StateDto
{
Name = state.Name,
Reason = state.Reason,
CreatedAt = DateTime.UtcNow,
Data = state.SerializeData()
}.ToBsonDocument();
var update = new BsonDocument
{
["$set"] = new BsonDocument(nameof(JobDto.StateName), state.Name),
["$push"] = new BsonDocument(nameof(JobDto.StateHistory), stateDto)
};
var writeModel = new UpdateOneModel<BsonDocument>(filter, update);
_writeModels.Add(writeModel);
}
public override void AddJobState(string jobId, IState state)
{
var filter = CreateJobIdFilter(jobId);
var stateDto = new StateDto
{
Name = state.Name,
Reason = state.Reason,
CreatedAt = DateTime.UtcNow,
Data = state.SerializeData()
}.ToBsonDocument();
var update = new BsonDocument("$push", new BsonDocument(nameof(JobDto.StateHistory), stateDto));
var writeModel = new UpdateOneModel<BsonDocument>(filter, update);
_writeModels.Add(writeModel);
}
public virtual void SetJobParameter(string id, string name, string value)
{
if (id == null)
{
throw new ArgumentNullException(nameof(id));
}
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
var filter = new BsonDocument("_id", ObjectId.Parse(id));
BsonValue bsonValue;
if (value == null)
{
bsonValue = BsonNull.Value;
}
else
{
bsonValue = value;
}
var update = new BsonDocument("$set", new BsonDocument($"{nameof(JobDto.Parameters)}.{name}", bsonValue));
var writeModel = new UpdateOneModel<BsonDocument>(filter, update);
_writeModels.Add(writeModel);
}
public override void AddToQueue(string queue, string jobId)
{
var jobQueueDto = new JobQueueDto
{
JobId = ObjectId.Parse(jobId),
Queue = queue,
Id = ObjectId.GenerateNewId(),
FetchedAt = null
}.ToBsonDocument();
JobsAddedToQueue.Add(queue);
var writeModel = new InsertOneModel<BsonDocument>(jobQueueDto);
_writeModels.Add(writeModel);
}
public override void IncrementCounter(string key)
{
SetCounter(key, 1, null);
}
public override void IncrementCounter(string key, TimeSpan expireIn)
{
SetCounter(key, 1, expireIn);
}
public override void DecrementCounter(string key)
{
SetCounter(key, -1, null);
}
public override void DecrementCounter(string key, TimeSpan expireIn)
{
SetCounter(key, -1, expireIn);
}
protected virtual void SetCounter(string key, long amount, TimeSpan? expireIn)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
var filter = new BsonDocument(nameof(CounterDto.Key), key);
BsonValue bsonDate = BsonNull.Value;
if (expireIn != null)
{
bsonDate = BsonValue.Create(DateTime.UtcNow.Add(expireIn.Value));
}
var update = new BsonDocument
{
["$inc"] = new BsonDocument(nameof(CounterDto.Value), amount),
["$set"] = new BsonDocument(nameof(KeyJobDto.ExpireAt), bsonDate),
["$setOnInsert"] = new BsonDocument
{
["_t"] = new BsonArray {nameof(BaseJobDto), nameof(ExpiringJobDto), nameof(KeyJobDto), nameof(CounterDto)},
}
};
var writeModel = new UpdateOneModel<BsonDocument>(filter, update){IsUpsert = true};
_writeModels.Add(writeModel);
}
public override void AddToSet(string key, string value)
{
AddToSet(key, value, 0.0);
}
public override void AddToSet(string key, string value, double score)
{
AddRangeToSet(key, new List<string> {value}, score);
}
public override void RemoveFromSet(string key, string value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
var filter = CreateSetFilter(key, value);
var writeModel = new DeleteOneModel<BsonDocument>(filter);
_writeModels.Add(writeModel);
}
public override void InsertToList(string key, string value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
var listDto = new ListDto
{
Id = ObjectId.GenerateNewId(),
Item = key,
Value = value
};
var writeModel = new InsertOneModel<BsonDocument>(listDto.ToBsonDocument());
_writeModels.Add(writeModel);
}
public override void RemoveFromList(string key, string value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
var filter = new BsonDocument("$and", new BsonArray
{
new BsonDocument(nameof(ListDto.Item), key),
new BsonDocument(nameof(ListDto.Value), value),
new BsonDocument("_t", nameof(ListDto))
});
var writeModel = new DeleteManyModel<BsonDocument>(filter);
_writeModels.Add(writeModel);
}
public override void TrimList(string key, int keepStartingFrom, int keepEndingAt)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
var start = keepStartingFrom + 1;
var end = keepEndingAt + 1;
// get all ids
var allIds = DbContext.JobGraph.OfType<ListDto>()
.Find(new BsonDocument())
.Project(doc => doc.Id)
.ToList();
// Add LisDto's scheduled for insertion writemodels collection, add it here.
allIds
.AddRange(_writeModels.OfType<InsertOneModel<BsonDocument>>()
.Where(model => ListDtoHasItem(key, model))
.Select(model => model.Document["_id"].AsObjectId));
var toTrim = allIds
.OrderByDescending(id => id.Timestamp)
.Select((id, i) => new {Index = i + 1, Id = id})
.Where(_ => (_.Index >= start && (_.Index <= end)) == false)
.Select(_ => _.Id)
.ToList();
var filter = new BsonDocument
{
["_id"] = new BsonDocument("$in", new BsonArray(toTrim)),
[nameof(ListDto.Item)] = key
};
var writeModel = new DeleteManyModel<BsonDocument>(filter);
_writeModels.Add(writeModel);
}
public override void SetRangeInHash(string key, IEnumerable<KeyValuePair<string, string>> keyValuePairs)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (keyValuePairs == null)
{
throw new ArgumentNullException(nameof(keyValuePairs));
}
var fields = new BsonDocument();
foreach (var pair in keyValuePairs)
{
var field = pair.Key;
var value = pair.Value;
fields[$"{nameof(HashDto.Fields)}.{field}"] = value;
}
var update = new BsonDocument
{
["$set"] = fields,
["$setOnInsert"] = new BsonDocument
{
["_t"] = new BsonArray {nameof(BaseJobDto), nameof(ExpiringJobDto), nameof(KeyJobDto), nameof(HashDto)},
[nameof(HashDto.ExpireAt)] = BsonNull.Value
}
};
var filter = new BsonDocument(nameof(HashDto.Key), key);
var writeModel = new UpdateOneModel<BsonDocument>(filter, update){IsUpsert = true};
_writeModels.Add(writeModel);
}
public override void RemoveHash(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
var filter = new BsonDocument(nameof(HashDto.Key), key);
var writeModel = new DeleteOneModel<BsonDocument>(filter);
_writeModels.Add(writeModel);
}
public override void Commit()
{
Log(_writeModels);
if (!_writeModels.Any())
{
return;
}
DbContext
.Database
.GetCollection<BsonDocument>(DbContext.JobGraph.CollectionNamespace.CollectionName)
.BulkWrite(_writeModels, new BulkWriteOptions
{
IsOrdered = true,
BypassDocumentValidation = false,
});
if (StorageOptions.UseNotificationsCollection)
{
SignalJobsAddedToQueues(JobsAddedToQueue);
}
}
public virtual void Log(IList<WriteModel<BsonDocument>> writeModels)
{
if (!Logger.IsTraceEnabled())
{
return;
}
var builder = new StringBuilder();
foreach (var writeModel in writeModels)
{
var serializedModel = SerializeWriteModel(writeModel);
builder.AppendLine($"{writeModel.ModelType}={serializedModel}");
}
Logger.Trace($"BulkWrite:\r\n{builder}" );
}
public virtual void SignalJobsAddedToQueues(ICollection<string> queues)
{
if (!queues.Any())
{
return;
}
var jobsEnqueued = queues.Select(NotificationDto.JobEnqueued);
DbContext.Notifications.InsertMany(jobsEnqueued, new InsertManyOptions
{
BypassDocumentValidation = false,
IsOrdered = true
});
}
public virtual string SerializeWriteModel(WriteModel<BsonDocument> writeModel)
{
string serializedDoc;
var serializer = DbContext
.Database
.GetCollection<BsonDocument>(DbContext.JobGraph.CollectionNamespace.CollectionName)
.DocumentSerializer;
var registry = DbContext.JobGraph.Settings.SerializerRegistry;
switch (writeModel.ModelType)
{
case WriteModelType.InsertOne:
serializedDoc = ((InsertOneModel<BsonDocument>) writeModel).Document.ToJson();
break;
case WriteModelType.DeleteOne:
serializedDoc = ((DeleteOneModel<BsonDocument>) writeModel).Filter.Render(serializer, registry)
.ToJson();
break;
case WriteModelType.DeleteMany:
serializedDoc = ((DeleteManyModel<BsonDocument>) writeModel).Filter.Render(serializer, registry)
.ToJson();
break;
case WriteModelType.ReplaceOne:
serializedDoc = new Dictionary<string, BsonDocument>
{
["Filter"] = ((ReplaceOneModel<BsonDocument>) writeModel).Filter.Render(serializer, registry),
["Replacement"] = ((ReplaceOneModel<BsonDocument>) writeModel).Replacement
}.ToJson();
break;
case WriteModelType.UpdateOne:
serializedDoc = new Dictionary<string, BsonDocument>
{
["Filter"] = ((UpdateOneModel<BsonDocument>) writeModel).Filter.Render(serializer, registry),
["Update"] = ((UpdateOneModel<BsonDocument>) writeModel).Update.Render(serializer, registry).AsBsonDocument
}.ToJson();
break;
case WriteModelType.UpdateMany:
serializedDoc = new Dictionary<string, BsonDocument>
{
["Filter"] = ((UpdateManyModel<BsonDocument>) writeModel).Filter.Render(serializer, registry),
["Update"] = ((UpdateManyModel<BsonDocument>) writeModel).Update.Render(serializer, registry).AsBsonDocument
}.ToJson();
break;
default:
throw new ArgumentOutOfRangeException();
}
return serializedDoc;
}
// New methods to support Hangfire pro feature - batches.
public override void ExpireSet(string key, TimeSpan expireIn)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
var filter = CreateSetFilter(key);
var update = new BsonDocument("$set",
new BsonDocument(nameof(SetDto.ExpireAt), DateTime.UtcNow.Add(expireIn)));
var writeModel = new UpdateManyModel<BsonDocument>(filter, update);
_writeModels.Add(writeModel);
}
public override void ExpireList(string key, TimeSpan expireIn)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
var filter = new BsonDocument("$and", new BsonArray
{
new BsonDocument(nameof(ListDto.Item), key),
new BsonDocument("_t", nameof(ListDto))
});
var update = new BsonDocument("$set",
new BsonDocument(nameof(ListDto.ExpireAt), DateTime.UtcNow.Add(expireIn)));
var writeModel = new UpdateManyModel<BsonDocument>(filter, update);
_writeModels.Add(writeModel);
}
public override void ExpireHash(string key, TimeSpan expireIn)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
var filter = new BsonDocument(nameof(KeyJobDto.Key), key);
var update = new BsonDocument("$set",
new BsonDocument(nameof(HashDto.ExpireAt), DateTime.UtcNow.Add(expireIn)));
var writeModel = new UpdateOneModel<BsonDocument>(filter, update);
_writeModels.Add(writeModel);
}
public override void PersistSet(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
var filter = CreateSetFilter(key);
var update = new BsonDocument("$set",
new BsonDocument(nameof(SetDto.ExpireAt), BsonNull.Value));
var writeModel = new UpdateManyModel<BsonDocument>(filter, update);
_writeModels.Add(writeModel);
}
public override void PersistList(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
var filter = new BsonDocument("$and", new BsonArray
{
new BsonDocument(nameof(ListDto.Item), key),
new BsonDocument("_t", nameof(ListDto))
});
var update = new BsonDocument("$set",
new BsonDocument(nameof(ListDto.ExpireAt), BsonNull.Value));
var writeModel = new UpdateManyModel<BsonDocument>(filter, update);
_writeModels.Add(writeModel);
}
public override void PersistHash(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
var filter = new BsonDocument(nameof(KeyJobDto.Key), key);
var update = new BsonDocument("$set",
new BsonDocument(nameof(HashDto.ExpireAt), BsonNull.Value));
var writeModel = new UpdateOneModel<BsonDocument>(filter, update);
_writeModels.Add(writeModel);
}
public override void AddRangeToSet(string key, IList<string> items)
{
AddRangeToSet(key, items, 0.0);
}
protected virtual void AddRangeToSet(string key, IList<string> items, double score)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (items == null)
{
throw new ArgumentNullException(nameof(items));
}
foreach (var item in items)
{
var filter = CreateSetFilter(key, item);
var update = CreateSetUpdate(key, item, score);
var writeModel = new UpdateOneModel<BsonDocument>(filter, update) {IsUpsert = true};
_writeModels.Add(writeModel);
}
}
public override void RemoveSet(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
var filter = CreateSetFilter(key);
var writeModel = new DeleteManyModel<BsonDocument>(filter);
_writeModels.Add(writeModel);
}
public virtual BsonDocument CreateJobIdFilter(string jobId)
{
return new BsonDocument("_id", ObjectId.Parse(jobId));
}
public virtual bool ListDtoHasItem(string key, InsertOneModel<BsonDocument> model)
{
return model.Document["_t"].AsBsonArray.Last().AsString == nameof(ListDto) &&
model.Document[nameof(ListDto.Item)].AsString == key;
}
public virtual BsonDocument CreateSetFilter(string key, string value)
{
var filter = new BsonDocument
{
[nameof(SetDto.Key)] = $"{key}<{value}>"
};
return filter;
}
public virtual BsonDocument CreateSetFilter(string key)
{
var filter = new BsonDocument
{
[nameof(SetDto.SetType)] = key,
["_t"] = nameof(SetDto)
};
return filter;
}
public virtual BsonDocument CreateSetUpdate(string key, string value, double score)
{
var update = new BsonDocument
{
["$set"] = new BsonDocument
{
[nameof(SetDto.Score)] = score,
},
["$setOnInsert"] = new BsonDocument
{
["_t"] = new BsonArray {nameof(BaseJobDto), nameof(ExpiringJobDto), nameof(KeyJobDto), nameof(SetDto)},
[nameof(SetDto.Value)] = value,
[nameof(SetDto.SetType)] = key,
[nameof(SetDto.ExpireAt)] = BsonNull.Value
}
};
return update;
}
}
#pragma warning restore 1591
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System;
using System.IO;
using System.Net.Mime;
using System.Runtime.Serialization;
using System.Runtime.Diagnostics;
using System.ServiceModel.Diagnostics;
using System.Runtime;
using System.Threading;
using System.ServiceModel.Diagnostics.Application;
public abstract class MessageEncoder
{
private string traceSourceString;
public abstract string ContentType { get; }
public abstract string MediaType { get; }
public abstract MessageVersion MessageVersion { get; }
public virtual T GetProperty<T>() where T : class
{
if (typeof(T) == typeof(FaultConverter))
{
return (T)(object)FaultConverter.GetDefaultFaultConverter(this.MessageVersion);
}
return null;
}
public Message ReadMessage(Stream stream, int maxSizeOfHeaders)
{
return ReadMessage(stream, maxSizeOfHeaders, null);
}
public abstract Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType);
public Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager)
{
Message message = ReadMessage(buffer, bufferManager, null);
return message;
}
public abstract Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType);
// used for buffered streaming
internal ArraySegment<byte> BufferMessageStream(Stream stream, BufferManager bufferManager, int maxBufferSize)
{
byte[] buffer = bufferManager.TakeBuffer(ConnectionOrientedTransportDefaults.ConnectionBufferSize);
int offset = 0;
int currentBufferSize = Math.Min(buffer.Length, maxBufferSize);
while (offset < currentBufferSize)
{
int count = stream.Read(buffer, offset, currentBufferSize - offset);
if (count == 0)
{
stream.Close();
break;
}
offset += count;
if (offset == currentBufferSize)
{
if (currentBufferSize >= maxBufferSize)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(MaxMessageSizeStream.CreateMaxReceivedMessageSizeExceededException(maxBufferSize));
}
currentBufferSize = Math.Min(currentBufferSize * 2, maxBufferSize);
byte[] temp = bufferManager.TakeBuffer(currentBufferSize);
Buffer.BlockCopy(buffer, 0, temp, 0, offset);
bufferManager.ReturnBuffer(buffer);
buffer = temp;
}
}
return new ArraySegment<byte>(buffer, 0, offset);
}
// used for buffered streaming
internal virtual Message ReadMessage(Stream stream, BufferManager bufferManager, int maxBufferSize, string contentType)
{
return ReadMessage(BufferMessageStream(stream, bufferManager, maxBufferSize), bufferManager, contentType);
}
public override string ToString()
{
return ContentType;
}
public abstract void WriteMessage(Message message, Stream stream);
public virtual IAsyncResult BeginWriteMessage(Message message, Stream stream, AsyncCallback callback, object state)
{
return new WriteMessageAsyncResult(message, stream, this, callback, state);
}
public virtual void EndWriteMessage(IAsyncResult result)
{
WriteMessageAsyncResult.End(result);
}
public ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager)
{
ArraySegment<byte> arraySegment = WriteMessage(message, maxMessageSize, bufferManager, 0);
return arraySegment;
}
public abstract ArraySegment<byte> WriteMessage(Message message, int maxMessageSize,
BufferManager bufferManager, int messageOffset);
public virtual bool IsContentTypeSupported(string contentType)
{
if (contentType == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("contentType"));
return IsContentTypeSupported(contentType, this.ContentType, this.MediaType);
}
internal bool IsContentTypeSupported(string contentType, string supportedContentType, string supportedMediaType)
{
if (supportedContentType == contentType)
return true;
if (contentType.Length > supportedContentType.Length &&
contentType.StartsWith(supportedContentType, StringComparison.Ordinal) &&
contentType[supportedContentType.Length] == ';')
return true;
// now check case-insensitively
if (contentType.StartsWith(supportedContentType, StringComparison.OrdinalIgnoreCase))
{
if (contentType.Length == supportedContentType.Length)
{
return true;
}
else if (contentType.Length > supportedContentType.Length)
{
char ch = contentType[supportedContentType.Length];
// Linear Whitespace is allowed to appear between the end of one property and the semicolon.
// LWS = [CRLF]? (SP | HT)+
if (ch == ';')
{
return true;
}
// Consume the [CRLF]?
int i = supportedContentType.Length;
if (ch == '\r' && contentType.Length > supportedContentType.Length + 1 && contentType[i + 1] == '\n')
{
i += 2;
ch = contentType[i];
}
// Look for a ';' or nothing after (SP | HT)+
if (ch == ' ' || ch == '\t')
{
i++;
while (i < contentType.Length)
{
ch = contentType[i];
if (ch != ' ' && ch != '\t')
break;
++i;
}
}
if (ch == ';' || i == contentType.Length)
return true;
}
}
// sometimes we get a contentType that has parameters, but our encoders
// merely expose the base content-type, so we will check a stripped version
try
{
ContentType parsedContentType = new ContentType(contentType);
if (supportedMediaType.Length > 0 && !supportedMediaType.Equals(parsedContentType.MediaType, StringComparison.OrdinalIgnoreCase))
return false;
if (!IsCharSetSupported(parsedContentType.CharSet))
return false;
}
catch (FormatException)
{
// bad content type, so we definitely don't support it!
return false;
}
return true;
}
internal virtual bool IsCharSetSupported(string charset)
{
return false;
}
internal void ThrowIfMismatchedMessageVersion(Message message)
{
if (message.Version != MessageVersion)
{
throw TraceUtility.ThrowHelperError(
new ProtocolException(SR.GetString(SR.EncoderMessageVersionMismatch, message.Version, MessageVersion)),
message);
}
}
internal string GetTraceSourceString()
{
if (this.traceSourceString == null)
{
this.traceSourceString = DiagnosticTraceBase.CreateDefaultSourceString(this);
}
return this.traceSourceString;
}
class WriteMessageAsyncResult : ScheduleActionItemAsyncResult
{
MessageEncoder encoder;
Message message;
Stream stream;
public WriteMessageAsyncResult(Message message, Stream stream, MessageEncoder encoder, AsyncCallback callback, object state)
: base(callback, state)
{
Fx.Assert(encoder != null, "encoder should never be null");
this.encoder = encoder;
this.message = message;
this.stream = stream;
Schedule();
}
protected override void OnDoWork()
{
this.encoder.WriteMessage(this.message, this.stream);
}
}
}
}
| |
//
// FilteredListSourceContents.cs
//
// Authors:
// Aaron Bockover <abockover@novell.com>
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2007-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Reflection;
using System.Collections.Generic;
using Gtk;
using Mono.Unix;
using Hyena;
using Hyena.Data;
using Hyena.Data.Gui;
using Hyena.Widgets;
using Banshee.Sources;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.Configuration;
using Banshee.Gui;
using Banshee.Collection.Gui;
using ScrolledWindow=Gtk.ScrolledWindow;
namespace Banshee.Sources.Gui
{
public abstract class FilteredListSourceContents : VBox, ISourceContents
{
private string name;
private object main_view;
private Gtk.ScrolledWindow main_scrolled_window;
private List<object> filter_views = new List<object> ();
protected List<ScrolledWindow> filter_scrolled_windows = new List<ScrolledWindow> ();
protected static readonly int DEFAULT_PANE_TOP_POSITION = 375;
protected static readonly int DEFAULT_PANE_LEFT_POSITION = 275;
private Dictionary<object, double> model_positions = new Dictionary<object, double> ();
private Paned container;
private Widget browser_container;
private InterfaceActionService action_service;
private ActionGroup browser_view_actions;
private readonly SchemaEntry<int> pane_top_position;
private readonly SchemaEntry<int> pane_left_position;
private static string menu_xml = @"
<ui>
<menubar name=""MainMenu"">
<menu name=""ViewMenu"" action=""ViewMenuAction"">
<placeholder name=""BrowserViews"">
<menuitem name=""BrowserVisible"" action=""BrowserVisibleAction"" />
<separator />
<menuitem name=""BrowserTop"" action=""BrowserTopAction"" />
<menuitem name=""BrowserLeft"" action=""BrowserLeftAction"" />
<separator />
</placeholder>
</menu>
</menubar>
</ui>
";
public FilteredListSourceContents (string name,
SchemaEntry<int> pane_top_position,
SchemaEntry<int> pane_left_position)
{
this.name = name;
this.pane_top_position = pane_top_position;
this.pane_left_position = pane_left_position;
InitializeViews ();
string position = Layout ();
if (ForcePosition != null) {
return;
}
if (ServiceManager.Contains ("InterfaceActionService")) {
action_service = ServiceManager.Get<InterfaceActionService> ();
if (action_service.FindActionGroup ("BrowserView") == null) {
browser_view_actions = new ActionGroup ("BrowserView");
browser_view_actions.Add (new RadioActionEntry [] {
new RadioActionEntry ("BrowserLeftAction", null,
Catalog.GetString ("Browser on Left"), null,
Catalog.GetString ("Show the artist/album browser to the left of the track list"), 0),
new RadioActionEntry ("BrowserTopAction", null,
Catalog.GetString ("Browser on Top"), null,
Catalog.GetString ("Show the artist/album browser above the track list"), 1),
}, position == "top" ? 1 : 0, null);
browser_view_actions.Add (new ToggleActionEntry [] {
new ToggleActionEntry ("BrowserVisibleAction", null,
Catalog.GetString ("Show Browser"), "<control>B",
Catalog.GetString ("Show or hide the artist/album browser"),
null, BrowserVisible.Get ())
});
action_service.AddActionGroup (browser_view_actions);
//action_merge_id = action_service.UIManager.NewMergeId ();
action_service.UIManager.AddUiFromString (menu_xml);
}
(action_service.FindAction("BrowserView.BrowserLeftAction") as RadioAction).Changed += OnViewModeChanged;
(action_service.FindAction("BrowserView.BrowserTopAction") as RadioAction).Changed += OnViewModeChanged;
action_service.FindAction("BrowserView.BrowserVisibleAction").Activated += OnToggleBrowser;
}
ServiceManager.SourceManager.ActiveSourceChanged += delegate {
ThreadAssist.ProxyToMain (delegate {
browser_container.Visible = ActiveSourceCanHasBrowser ? BrowserVisible.Get () : false;
});
};
NoShowAll = true;
}
protected abstract void InitializeViews ();
protected void SetupMainView<V> (V main_view) where V : Widget, IListView
{
this.main_view = main_view;
main_scrolled_window = SetupView (main_view);
}
protected void SetupFilterView<V> (V filter_view) where V : Widget, IListView
{
ScrolledWindow window = SetupView (filter_view);
filter_scrolled_windows.Add (window);
filter_view.HeaderVisible = false;
filter_view.SelectionProxy.Changed += OnBrowserViewSelectionChanged;
}
private ScrolledWindow SetupView (Widget view)
{
ScrolledWindow window = null;
//if (!Banshee.Base.ApplicationContext.CommandLine.Contains ("no-smooth-scroll")) {
if (ApplicationContext.CommandLine.Contains ("smooth-scroll")) {
window = new SmoothScrolledWindow ();
} else {
window = new ScrolledWindow ();
}
window.Add (view);
window.HscrollbarPolicy = PolicyType.Automatic;
window.VscrollbarPolicy = PolicyType.Automatic;
return window;
}
private void Reset ()
{
// Unparent the views' scrolled window parents so they can be re-packed in
// a new layout. The main container gets destroyed since it will be recreated.
foreach (ScrolledWindow window in filter_scrolled_windows) {
Paned filter_container = window.Parent as Paned;
if (filter_container != null) {
filter_container.Remove (window);
}
}
if (container != null && main_scrolled_window != null) {
container.Remove (main_scrolled_window);
}
if (container != null) {
Remove (container);
}
}
protected string Layout ()
{
string position = ForcePosition == null ? BrowserPosition.Get () : ForcePosition;
if (position == "top") {
LayoutTop ();
} else {
LayoutLeft ();
}
return position;
}
private void LayoutLeft ()
{
Layout (false);
}
private void LayoutTop ()
{
Layout (true);
}
private void Layout (bool top)
{
//Hyena.Log.Information ("ListBrowser LayoutLeft");
Reset ();
SchemaEntry<int> current_entry = top ? pane_top_position : pane_left_position;
container = GetPane (!top);
Paned filter_box = GetPane (top);
filter_box.PositionSet = true;
Paned current_pane = filter_box;
for (int i = 0; i < filter_scrolled_windows.Count; i++) {
ScrolledWindow window = filter_scrolled_windows[i];
bool last_even_filter = (i == filter_scrolled_windows.Count - 1 && filter_scrolled_windows.Count % 2 == 0);
if (i > 0 && !last_even_filter) {
Paned new_pane = GetPane (top);
current_pane.Pack2 (new_pane, true, false);
current_pane.Position = top ? 180 : 350;
PersistentPaneController.Control (current_pane, ControllerName (top, i));
current_pane = new_pane;
}
if (last_even_filter) {
current_pane.Pack2 (window, true, false);
current_pane.Position = top ? 180 : 350;
PersistentPaneController.Control (current_pane, ControllerName (top, i));
} else {
current_pane.Pack1 (window, false, false);
}
}
container.Pack1 (filter_box, false, false);
container.Pack2 (main_scrolled_window, true, false);
browser_container = filter_box;
if (current_entry.Equals (SchemaEntry<int>.Zero)) {
throw new InvalidOperationException (String.Format ("No SchemaEntry found for {0} position of {1}",
top ? "top" : "left", this.GetType ().FullName));
}
container.Position = current_entry.DefaultValue;
PersistentPaneController.Control (container, current_entry);
ShowPack ();
}
private string ControllerName (bool top, int filter)
{
if (filter < 0) {
throw new ArgumentException ("filter should be positive", "filter");
}
return String.Format ("{0}.browser.{1}.{2}", name, top ? "top" : "left", filter);
}
private Paned GetPane (bool hpane)
{
if (hpane)
return new HPaned ();
else
return new VPaned ();
}
private void ShowPack ()
{
PackStart (container, true, true, 0);
NoShowAll = false;
ShowAll ();
NoShowAll = true;
browser_container.Visible = ForcePosition != null || BrowserVisible.Get ();
}
private void OnViewModeChanged (object o, ChangedArgs args)
{
//Hyena.Log.InformationFormat ("ListBrowser mode toggled, val = {0}", args.Current.Value);
if (args.Current.Value == 0) {
LayoutLeft ();
BrowserPosition.Set ("left");
} else {
LayoutTop ();
BrowserPosition.Set ("top");
}
}
private void OnToggleBrowser (object o, EventArgs args)
{
ToggleAction action = (ToggleAction)o;
browser_container.Visible = action.Active && ActiveSourceCanHasBrowser;
BrowserVisible.Set (action.Active);
if (!browser_container.Visible) {
ClearFilterSelections ();
}
}
protected abstract void ClearFilterSelections ();
protected virtual void OnBrowserViewSelectionChanged (object o, EventArgs args)
{
// If the All item is now selected, scroll to the top
Hyena.Collections.Selection selection = (Hyena.Collections.Selection) o;
if (selection.AllSelected) {
// Find the view associated with this selection; a bit yuck; pass view in args?
foreach (IListView view in filter_views) {
if (view.Selection == selection) {
view.ScrollTo (0);
break;
}
}
}
}
protected void SetModel<T> (IListModel<T> model)
{
var view = FindListView <T> ();
if (view != null) {
SetModel (view, model);
} else {
Hyena.Log.DebugFormat ("Unable to find view for model {0}", model);
}
}
protected void SetModel<T> (IListView<T> view, IListModel<T> model)
{
if (view.Model != null) {
model_positions[view.Model] = view.Vadjustment != null ? view.Vadjustment.Value : 0;
}
if (model == null) {
view.SetModel (null);
return;
}
if (!model_positions.ContainsKey (model)) {
model_positions[model] = 0.0;
}
view.SetModel (model, model_positions[model]);
}
private IListView<T> FindListView<T> ()
{
if (main_view is IListView<T>)
return (IListView<T>) main_view;
foreach (object view in filter_views)
if (view is IListView<T>)
return (IListView<T>) view;
return null;
}
protected virtual string ForcePosition {
get { return null; }
}
protected abstract bool ActiveSourceCanHasBrowser { get; }
#region Implement ISourceContents
protected ISource source;
public abstract bool SetSource (ISource source);
public abstract void ResetSource ();
public ISource Source {
get { return source; }
}
public Widget Widget {
get { return this; }
}
#endregion
public static readonly SchemaEntry<bool> BrowserVisible = new SchemaEntry<bool> (
"browser", "visible",
true,
"Artist/Album Browser Visibility",
"Whether or not to show the Artist/Album browser"
);
public static readonly SchemaEntry<string> BrowserPosition = new SchemaEntry<string> (
"browser", "position",
"top",
"Artist/Album Browser Position",
"The position of the Artist/Album browser; either 'top' or 'left'"
);
}
}
| |
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Threading;
using FloodSensor.NrpeCheckers;
using FloodSensor.NrpeCheckers.Temperature;
using Microsoft.SPOT;
namespace FloodSensor.NrpeServer
{
public class TinyNrpeServer : IDisposable
{
private bool _disposed;
public static bool StopNrpeServer = false;
public AutoResetEvent TinyNrpeServerIsShuttingDown = new AutoResetEvent(false);
public const int DefaultNrpePort = 5666;
private const int PollTimeout = 1000;
/// <summary>
/// Did the server stop normally? (Or was there an exception?)
/// </summary>
public bool NrpeServerStoppedNormally = true;
/// <summary>
/// How many connections we'll queue up, evidently
/// </summary>
const int MaxLengthOfPendingConnectionsQueue = 1;
/// <summary>
/// Contains a reference to the socket
/// </summary>
private Socket _socket;
/// <summary>
/// NetworkStream rides on top of the socket. This provides us with the logical bytes, without the underlying packets.
/// </summary>
private NetworkStream _networkStream;
/// <summary>
/// Stores the TCP port connected to
/// </summary>
private readonly ushort _portNumber;
/// <summary>
/// Stores the hostname connected to
/// </summary>
private string _hostname;
private Socket _listenerSocket;
public TinyNrpeServer(ushort portNumber = DefaultNrpePort)
{
_portNumber = portNumber;
}
/// <summary>
/// Deletes an instance of the <see cref="TinyNrpeServer"/> class.
/// </summary>
~TinyNrpeServer()
{
Dispose(false);
}
/// <summary>
/// Releases resources used by this <see cref="TinyNrpeServer"/> object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the resources associated with the <see cref="DhtSensor"/> object.
/// </summary>
/// <param name="disposing">
/// <b>true</b> to release both managed and unmanaged resources;
/// <b>false</b> to release only unmanaged resources.
/// </param>
[MethodImpl(MethodImplOptions.Synchronized)]
protected void Dispose(bool disposing)
{
if (!_disposed)
{
try
{
this.CloseConnection();
this.CloseListeningSocket();
// Although it works, recovery after an exception in the TinyNrpeServer is currently a bit ragged.
// Note that actually *accomplishing* the Closing of the Listening Socket takes a minute or two, during which time we will repeatedly
// re-enter the RunServer(), and immediate get a SocketException in StartListening(). During this time we are waiting
// for the Socket to be released, and until it has we can't finish StartListening() without an exception. If there is a less
// brutal way to accomplish this I'd love to know about it.
}
catch (Exception e)
{
Debug.Print("Caught exception in TinyNrpeServer.Dispose(): " + e.Message);
}
finally
{
_disposed = true;
}
}
}
static readonly object RunServerLock = new object();
/// <summary>
/// Run the server
/// </summary>
public void RunServer()
{
EnsureNotDisposed();
lock (RunServerLock)
{
Debug.Print("Starting NRPE Server");
WatchpointDebugInfo();
using (var nrpeServer = new TinyNrpeServer())
{
NrpeServerStoppedNormally = true;
try
{
nrpeServer.StartListening();
WatchpointDebugInfo();
while (StopNrpeServer == false)
{
// Accept incoming connections
bool gotConnection = nrpeServer.AcceptConnection();
if (gotConnection)
{
WatchpointDebugInfo();
// Check in with Watchdog
Program.InactivityWatchdog.CheckIn();
// Flash the LED to indicate message processing activity
LedFlasher.FlashLed(1);
// Process each request as it arrives
NrpeMessage nrpeMessageQuery = nrpeServer.ReceiveNrpeMessage();
if (nrpeMessageQuery.IsLegalQuery)
{
NrpeMessage nrpeMessageReply = NrpeChecker.ProcessQuery(nrpeMessageQuery);
nrpeServer.SendNrpeMessage(nrpeMessageReply);
}
else
{
// There's not enough room in the Netduino for SSL, so this isn't possible:
// http://forums.netduino.com/index.php?/topic/2302-netduino-ssltls/
Debug.Print("Skipping unreadable incoming message (is SSL disabled for your check_nrpe request? This client can't handle SSL messages.");
}
nrpeServer.CloseConnection();
WatchpointDebugInfo();
}
}
}
catch (Exception e)
{
Debug.Print("Exception in NRPE server: " + e.Message);
if (e.GetType() == typeof (SocketException))
{
var socketException = (SocketException) e;
Debug.Print("Socket exception in NRPE Server. Error Code: " + socketException.ErrorCode);
}
nrpeServer.Dispose();
NrpeServerStoppedNormally = false;
// We have to suppress the exception
// throw;
}
}
}
WatchpointDebugInfo();
Debug.Print("Ending NRPE Server.");
// Indicate that the NRPE server thread is exiting, whether failing or not.
TinyNrpeServerIsShuttingDown.Set();
}
private void EnsureNotDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException();
}
}
private static void WatchpointDebugInfo()
{
var freeMemory = Debug.GC(false);
Debug.Print("Free memory: " + freeMemory);
}
private void StartListening()
{
_listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_listenerSocket.Bind(new IPEndPoint(IPAddress.Any, this._portNumber));
_listenerSocket.Listen(MaxLengthOfPendingConnectionsQueue);
Debug.Print("Listening on port " + _portNumber);
}
private bool AcceptConnection()
{
Debug.Print("Waiting for connection..");
// http://forums.netduino.com/index.php?/topic/10299-clean-way-to-interrupt-socketaccept/
// Poll, waiting for bytes to appear, and checking for the stop signal
while (!this._listenerSocket.Poll(PollTimeout, SelectMode.SelectRead))
{
if (StopNrpeServer)
{
return false;
}
}
// Bytes have appeared, accept the connection
this._socket = this._listenerSocket.Accept();
this._hostname = ((IPEndPoint)this._socket.RemoteEndPoint).Address.ToString();
Debug.Print("Accepted connection from " + this._hostname);
_networkStream = new NetworkStream(this._socket);
return true;
}
private void CloseConnection()
{
Debug.Print("Closing NetworkStream...");
if (_networkStream != null)
{
_networkStream.Dispose();
}
else
{
Debug.Print("Null _networkStream, skipping dispose...");
}
}
private void CloseListeningSocket()
{
if (_listenerSocket != null)
{
try
{
_listenerSocket.Close();
}
catch (Exception e)
{
Debug.Print("Suppressed exception during listenerSocket.Close(): " + e.Message);
}
}
else
{
Debug.Print("Null _listenerSocket, skipping close...");
}
}
public NrpeMessage ReceiveNrpeMessage()
{
EnsureNotDisposed();
Int16 packetVersion = Tools.ReadShort(this._networkStream);
Int16 packetType = Tools.ReadShort(this._networkStream);
UInt32 packetCrc = Tools.ReadUInt(this._networkStream);
Int16 packetResultCode = Tools.ReadShort(this._networkStream);
int bufferBytesRead;
var bufferBytes = ReceiveBinary(NrpeMessage.BufferLength, out bufferBytesRead);
int dummyBytesRead;
var dummyBytes = ReceiveBinary(NrpeMessage.DummyBytesLength, out dummyBytesRead);
return new NrpeMessage(packetVersion, packetType, packetCrc, packetResultCode, bufferBytes, dummyBytes);
}
/// <summary>
/// Receives binary data from the socket
/// </summary>
/// <param name="length">The amount of bytes to receive</param>
/// <param name="bytesRead">Count of bytes actually read</param>
/// <returns>The binary data</returns>
private byte[] ReceiveBinary(int length, out int bytesRead)
{
var binaryBytes = new byte[length];
bytesRead = this._networkStream.Read(binaryBytes, 0, length);
return binaryBytes;
}
private void SendNrpeMessage(NrpeMessage nrpeMessageReply)
{
Debug.Print("About to send reply message:");
nrpeMessageReply.PrintDebug();
uint crc;
var packetBytes = nrpeMessageReply.GetPacketBytes(out crc);
SendBinary(packetBytes);
Debug.Print("Reply message sent");
}
/// <summary>
/// Sends binary data on the socket
/// </summary>
/// <param name="binaryBytes"></param>
private void SendBinary(byte[] binaryBytes)
{
Debug.Print("Writing " + binaryBytes.Length + " bytes to network stream");
NrpeMessage.DebugPrintOutMessageInHex(binaryBytes.Length + " Bytes sent over the wire: ", binaryBytes);
this._networkStream.Write(binaryBytes, 0, binaryBytes.Length);
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 3/13/2009 1:51:04 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using GeoAPI.Geometries;
namespace DotSpatial.Data
{
/// <summary>
/// RasterBoundsEM
/// </summary>
public static class RasterBoundsExt
{
/// <summary>
/// Calculates the area of this envelope. Because the word Area,
/// like Volume, is dimension specific, this method only looks
/// at the X and Y ordinates, and requires at least 2 ordinates.
/// </summary>
/// <param name="self">The IEnvelope to use with this method</param>
/// <returns>The 2D area as a double value.</returns>
public static double Area(this IRasterBounds self)
{
if (self == null) return -1;
return self.Width * self.Height;
}
/// <summary>
/// Gets the minY, which is Y - Height.
/// </summary>
/// <param name="self">The <c>IRasterBounds</c> that this calculation is for.</param>
/// <returns></returns>
public static double Bottom(this IRasterBounds self)
{
return self.Y - self.Height;
}
/// <summary>
/// Uses the specified distance to expand the envelope by that amount in all dimensions.
/// </summary>
/// <param name="self">The <c>IRasterBounds</c> that this calculation is for.</param>
/// <param name="distance">The double distance to expand in all directions.</param>
public static void ExpandBy(this IRasterBounds self, double distance)
{
self.X -= distance;
self.Y += distance;
self.Width += distance * 2;
self.Height += distance * 2;
// the maximum is now the minimum etc.
}
/// <summary>
/// Gets the left value for this rectangle. This should be the
/// X coordinate, but is added for clarity.
/// </summary>
/// <param name="self">The <c>IRasterBounds</c> that this calculation is for.</param>
/// <returns></returns>
public static double Left(this IRasterBounds self)
{
return self.X;
}
/// <summary>
/// Gets the right value, which is X + Width.
/// </summary>
/// <param name="self">The <c>IRasterBounds</c> that this calculation is for.</param>
/// <returns></returns>
public static double Right(this IRasterBounds self)
{
return self.X + self.Width;
}
/// <summary>
/// Gets the maxY value, which should be Y.
/// </summary>
/// <param name="self">The <c>IRasterBounds</c> that this calculation is for.</param>
/// <returns>The double value representing the Max Y value of this rectangle</returns>
public static double Top(this IRasterBounds self)
{
return self.Y;
}
/// <summary>
/// Use the Open method instead of this extension. This only provides
/// a default behavior that can optionally be used by implementers
/// of the IRasterBounds interface.
/// </summary>
/// <param name="bounds">The bounds to open</param>
/// <param name="fileName">The *.wld or *.**w world file to open</param>
public static void OpenWorldFile(this IRasterBounds bounds, string fileName)
{
bounds.WorldFile = fileName;
double[] affine = new double[6];
StreamReader sr = new StreamReader(fileName);
string line = sr.ReadLine();
if (line != null)
{
affine[1] = double.Parse(line); // Dx
}
line = sr.ReadLine();
if (line != null)
{
affine[2] = double.Parse(line); // Skew X
}
line = sr.ReadLine();
if (line != null)
{
affine[4] = double.Parse(line); // Skew Y
}
line = sr.ReadLine();
if (line != null)
{
affine[5] = double.Parse(line); // Dy
}
line = sr.ReadLine();
if (line != null)
{
affine[0] = double.Parse(line); // Top Left X
}
line = sr.ReadLine();
if (line != null)
{
affine[3] = double.Parse(line); // Top Left Y
}
bounds.AffineCoefficients = affine;
sr.Close();
}
/// <summary>
/// Use the Save method instead of this extension. This only provides
/// a default behavior that can optionally be used by implementers
/// of the IRasterBounds interface.
/// </summary>
public static void SaveWorldFile(this IRasterBounds bounds)
{
using (var sw = new StreamWriter(bounds.WorldFile))
{
double[] affine = bounds.AffineCoefficients;
sw.WriteLine(affine[1]); // Dx
sw.WriteLine(affine[2]); // rotation X
sw.WriteLine(affine[4]); // rotation Y
sw.WriteLine(affine[5]); // Dy
sw.WriteLine(affine[0]); // Top Left X
sw.WriteLine(affine[3]); // Top Left Y
}
}
/// <summary>
/// Generates a new version of the affine transform that will
/// cover the same region, but using the specified number of
/// rows and columns instead.
/// </summary>
/// <param name="bounds">The raster bounds to resample</param>
/// <param name="numRows">The new number of rows </param>
/// <param name="numColumns">The new number of columns</param>
/// <returns>
/// X = [0] + [1] * Column + [2] * Row
/// Y = [3] + [4] * Column + [5] * Row
/// </returns>
public static IRasterBounds ResampleTransform(this IRasterBounds bounds, int numRows, int numColumns)
{
double[] affine = bounds.AffineCoefficients;
double[] result = new double[6];
double oldNumRows = bounds.NumRows;
double oldNumColumns = bounds.NumColumns;
result[0] = affine[0]; // Top Left X
result[3] = affine[3]; // Top Left Y
result[1] = affine[1] * oldNumColumns / numColumns; // dx
result[5] = affine[5] * oldNumRows / numRows; // dy
result[2] = affine[2] * oldNumRows / numRows; // skew x
result[4] = affine[4] * oldNumColumns / numColumns; // skew y
return new RasterBounds(numRows, numColumns, result);
}
/// <summary>
/// Attempts to save the affine coefficients to the specified worldfile file name
/// </summary>
/// <param name="bounds">The bounds to save</param>
/// <param name="fileName">The fileName to save this bounds to</param>
public static void SaveAs(this IRasterBounds bounds, string fileName)
{
bounds.WorldFile = fileName;
bounds.Save();
}
/// <summary>
/// Converts creates a float precisions drawing matrix from the double precision affine
/// coordinates. The Matrix can be manipulated and then set back. Some precision will
/// be lost, however, as only floats are supported.
/// </summary>
public static Matrix Get_AffineMatrix(this IRasterBounds bounds)
{
double[] affine = bounds.AffineCoefficients;
return new Matrix(
Convert.ToSingle(affine[0]), // XShift
Convert.ToSingle(affine[2]), // RotationX
Convert.ToSingle(affine[4]), // RotationY
Convert.ToSingle(affine[3]), // YShift
Convert.ToSingle(affine[1]), // CellWidth
Convert.ToSingle(affine[5])); // CellHeight
}
/// <summary>
/// Re-defines the double precision affine transform values based on the specified
/// system.Drawing.Matrix.
/// </summary>
/// <param name="bounds">The bounds to adjust based on the matrix</param>
/// <param name="matrix">The matrix to use as a guide for adjustments.</param>
public static void Set_AffineMatrix(this IRasterBounds bounds, Matrix matrix)
{
double[] affine = new double[6];
affine[0] = Convert.ToDouble(matrix.Elements[0]); // XShift
affine[2] = Convert.ToDouble(matrix.Elements[1]); // RotationX
affine[4] = Convert.ToDouble(matrix.Elements[2]); // RotationY
affine[3] = Convert.ToDouble(matrix.Elements[3]); // YShift
affine[1] = Convert.ToDouble(matrix.Elements[4]); // CellWidth
affine[5] = Convert.ToDouble(matrix.Elements[5]); // CellHeight
bounds.AffineCoefficients = affine;
}
/// <summary>
/// Images can be skewed, so this gets the point that actually defines the bottom left
/// corner of the data in geographic coordinates
/// </summary>
public static Coordinate BottomLeft(this IRasterBounds bounds)
{
double[] affine = bounds.AffineCoefficients;
int numRows = bounds.NumRows;
// X' = [0] + [1] * Column + [2] * Row
// Y' = [3] + [4] * Column + [5] * Row
double x = affine[0] + numRows * affine[2];
double y = affine[3] + numRows * affine[5];
return new Coordinate(x, y);
}
/// <summary>
/// Images can be skewed, so this gets the point that actually defines the bottom right
/// corner of the data in geographic coordinates
/// </summary>
public static Coordinate BottomRight(this IRasterBounds bounds)
{
double[] affine = bounds.AffineCoefficients;
double numRows = bounds.NumRows;
double numColumns = bounds.NumColumns;
// X' = [0] + [1] * Column + [2] * Row
// Y' = [3] + [4] * Column + [5] * Row
double x = affine[0] + numColumns * affine[1] + numRows * affine[2];
double y = affine[3] + numColumns * affine[4] + numRows * affine[5];
return new Coordinate(x, y);
}
/// <summary>
/// Images can be skewed, so this gets the point that actually defines the top left
/// corner of the data in geographic coordinates
/// </summary>
/// <param name="bounds">The IRasterBounds to obtain the top left of</param>
public static Coordinate TopLeft(this IRasterBounds bounds)
{
double[] affine = bounds.AffineCoefficients;
// X' = [0] + [1] * Column + [2] * Row
// Y' = [3] + [4] * Column + [5] * Row
double x = affine[0];
double y = affine[3];
return new Coordinate(x, y);
}
/// <summary>
/// Images can be skewed, so this gets the point that actually defines the top right
/// corner of the data in geographic coordinates
/// </summary>
public static Coordinate TopRight(this IRasterBounds bounds)
{
double[] affine = bounds.AffineCoefficients;
double numColumns = bounds.NumColumns;
// X' = [0] + [1] * Column + [2] * Row
// Y' = [3] + [4] * Column + [5] * Row
double x = affine[0] + numColumns * affine[1];
double y = affine[3] + numColumns * affine[4];
return new Coordinate(x, y);
}
#region projection Handling
/// <summary>
/// Given any input row or column, this returns the appropriate geographic location for the
/// position of the center of the cell.
/// </summary>
/// <param name="bounds">The raster bounds to perform the calculation on</param>
/// <param name="row">The integer row index from 0 to numRows - 1</param>
/// <param name="column">The integer column index from 0 to numColumns - 1</param>
/// <returns>The geographic position of the center of the specified cell</returns>
public static Coordinate CellCenter_ToProj(this IRasterBounds bounds, int row, int column)
{
return new AffineTransform(bounds.AffineCoefficients).CellCenter_ToProj(row, column);
}
/// <summary>
/// Given the row and column, this returns the geographic position of the top left corner of the cell
/// </summary>
/// <param name="bounds">The raster bounds to perform the calculation on</param>
/// <param name="row">The integer row index from 0 to numRows - 1</param>
/// <param name="column">The integer column index from 0 to numColumns - 1</param>
/// <returns>The geographic position of the top left corner of the specified cell</returns>
public static Coordinate CellTopLeft_ToProj(this IRasterBounds bounds, int row, int column)
{
return new AffineTransform(bounds.AffineCoefficients).CellTopLeft_ToProj(row, column);
}
/// <summary>
/// Given the row and column, this returns the geographic position of the top right corner of the cell
/// </summary>
/// <param name="bounds">The raster bounds to perform the calculation on</param>
/// <param name="row">The integer row index from 0 to numRows - 1</param>
/// <param name="column">The integer column index from 0 to numColumns - 1</param>
/// <returns>The geographic position of the top right corner of the specified cell</returns>
public static Coordinate CellTopRight_ToProj(this IRasterBounds bounds, int row, int column)
{
return new AffineTransform(bounds.AffineCoefficients).CellTopRight_ToProj(row, column);
}
/// <summary>
/// Given the row and column, this returns the geographic position of the bottom left corner of the cell
/// </summary>
/// <param name="bounds">The raster bounds to perform the calculation on</param>
/// <param name="row">The integer row index from 0 to numRows - 1</param>
/// <param name="column">The integer column index from 0 to numColumns - 1</param>
/// <returns>The geographic position of the bottom left corner of the specified cell</returns>
public static Coordinate CellBottomLeft_ToProj(this IRasterBounds bounds, int row, int column)
{
return new AffineTransform(bounds.AffineCoefficients).CellBottomLeft_ToProj(row, column);
}
/// <summary>
/// Given the row and column, this returns the geographic position of the bottom right corner of the cell
/// </summary>
/// <param name="bounds">The raster bounds to perform the calculation on</param>
/// <param name="row">The integer row index from 0 to numRows - 1</param>
/// <param name="column">The integer column index from 0 to numColumns - 1</param>
/// <returns>The geographic position of the bottom right corner of the specified cell</returns>
public static Coordinate CellBottomRight_ToProj(this IRasterBounds bounds, int row, int column)
{
return new AffineTransform(bounds.AffineCoefficients).CellBottomRight_ToProj(row, column);
}
/// <summary>
/// Returns the row col index
/// </summary>
/// <param name="bounds">The raster bounds to perform the calculation on</param>
/// <param name="location">Gets or sets the ICoordinate</param>
/// <returns>An RcIndex that shows the best row or column index for the specified coordinate.</returns>
public static RcIndex ProjToCell(this IRasterBounds bounds, Coordinate location)
{
var pc = new AffineTransform(bounds.AffineCoefficients).ProjToCell(location);
if (pc.Row < 0 || pc.Column < 0 || pc.Row >= bounds.NumRows || pc.Column >= bounds.NumColumns)
{
return RcIndex.Empty;
}
return pc;
}
/// <summary>
/// The affine transform can make figuring out what rows and columns are needed from the original image
/// in order to correctly fill a geographic extent challenging. This attempts to handle that back projection
/// problem. It returns a System.Drawing.Rectangle in pixel (cell) coordinates that is completely contains
/// the geographic extents, but is not larger than the bounds of the underlying image.
/// If geographic extent fully contains extent of IRasterBounds, than returns rectangle which contains full raster image.
/// If geographic extent partially contains extent of IRasterBounds, than returns rectangle which contains needed edges of full raster image.
/// It back projects all four corners of the extent and returns the bounding rectangle clipped by the image rectangle.
/// </summary>
/// <param name="self">Instance of <see cref="IRasterBounds"/></param>
/// <param name="extent">Extent to test.</param>
/// <returns>Rectangle in pixel (cell) coordinates.</returns>
public static Rectangle CellsContainingExtent(this IRasterBounds self, Extent extent)
{
var se = self.Extent;
var exMinX = Math.Max(extent.MinX, se.MinX);
var exMaxY = Math.Min(extent.MaxY, se.MaxY);
var exMaxX = Math.Min(extent.MaxX, se.MaxX);
var exMinY = Math.Max(extent.MinY, se.MinY);
var coords = new List<Coordinate>
{
new Coordinate(exMinX, exMaxY),
new Coordinate(exMaxX, exMaxY),
new Coordinate(exMinX, exMinY),
new Coordinate(exMaxX, exMinY)
};
int minX = self.NumColumns;
int minY = self.NumRows;
int maxX = 0;
int maxY = 0;
foreach (var c in coords)
{
var rowCol = self.ProjToCell(c);
if (rowCol.Row < minY) minY = rowCol.Row;
if (rowCol.Column < minX) minX = rowCol.Column;
if (rowCol.Row > maxY) maxY = rowCol.Row;
if (rowCol.Column > maxX) maxX = rowCol.Column;
}
if (minX < 0) minX = 0;
if (minY < 0) minY = 0;
if (maxX > self.NumColumns) maxX = self.NumColumns;
if (maxY > self.NumRows) maxY = self.NumRows;
return new Rectangle(minX, minY, maxX - minX, maxY - minY);
}
#endregion
}
}
| |
/*
The MIT License (MIT)
Copyright (c) 2016 Maksim Volkau
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 AddOrUpdateServiceFactory
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
namespace Marten.Util
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
/// <summary>Compiles expression to delegate by emitting the IL directly.
/// The emitter is ~20 times faster than Expression.Compile.</summary>
internal static partial class ExpressionCompiler
{
/// <summary>First tries to compile fast and if failed (null result), then falls back to Expression.Compile.</summary>
/// <typeparam name="T">Type of compiled delegate return result.</typeparam>
/// <param name="lambdaExpr">Expr to compile.</param>
/// <returns>Compiled delegate.</returns>
public static Func<T> Compile<T>(Expression<Func<T>> lambdaExpr)
{
return TryCompile<Func<T>>(lambdaExpr.Body, lambdaExpr.Parameters, _emptyTypes, typeof(T))
?? lambdaExpr.Compile();
}
/// <summary>Compiles lambda expression to <typeparamref name="TDelegate"/>.</summary>
/// <typeparam name="TDelegate">The compatible delegate type, otherwise case will throw.</typeparam>
/// <param name="lambdaExpr">Lambda expression to compile.</param>
/// <returns>Compiled delegate.</returns>
public static TDelegate Compile<TDelegate>(LambdaExpression lambdaExpr)
where TDelegate : class
{
return TryCompile<TDelegate>(lambdaExpr) ?? (TDelegate)(object)lambdaExpr.Compile();
}
/// <summary>Tries to compile lambda expression to <typeparamref name="TDelegate"/>.</summary>
/// <typeparam name="TDelegate">The compatible delegate type, otherwise case will throw.</typeparam>
/// <param name="lambdaExpr">Lambda expression to compile.</param>
/// <returns>Compiled delegate.</returns>
public static TDelegate TryCompile<TDelegate>(LambdaExpression lambdaExpr)
where TDelegate : class
{
var paramExprs = lambdaExpr.Parameters;
var paramTypes = GetParamExprTypes(paramExprs);
var expr = lambdaExpr.Body;
return TryCompile<TDelegate>(expr, paramExprs, paramTypes, expr.Type);
}
private static Type[] GetParamExprTypes(IList<ParameterExpression> paramExprs)
{
var paramsCount = paramExprs.Count;
if (paramsCount == 0)
return _emptyTypes;
if (paramsCount == 1)
return new[] { paramExprs[0].Type };
var paramTypes = new Type[paramsCount];
for (var i = 0; i < paramTypes.Length; i++)
paramTypes[i] = paramExprs[i].Type;
return paramTypes;
}
/// <summary>Compiles expression to delegate by emitting the IL.
/// If sub-expressions are not supported by emitter, then the method returns null.
/// The usage should be calling the method, if result is null then calling the Expression.Compile.</summary>
/// <param name="bodyExpr">Lambda body.</param>
/// <param name="paramExprs">Lambda parameter expressions.</param>
/// <param name="paramTypes">The types of parameters.</param>
/// <param name="returnType">The return type.</param>
/// <returns>Result delegate or null, if unable to compile.</returns>
public static TDelegate TryCompile<TDelegate>(
Expression bodyExpr,
IList<ParameterExpression> paramExprs,
Type[] paramTypes,
Type returnType) where TDelegate : class
{
ClosureInfo ignored = null;
return (TDelegate)TryCompile(ref ignored,
typeof(TDelegate), paramTypes, returnType, bodyExpr, paramExprs);
}
private static object TryCompile(ref ClosureInfo closureInfo,
Type delegateType, Type[] paramTypes, Type returnType,
Expression bodyExpr, IList<ParameterExpression> paramExprs)
{
if (!TryCollectBoundConstants(ref closureInfo, bodyExpr, paramExprs))
return null;
if (closureInfo != null)
closureInfo.ConstructClosure();
var method = GetDynamicMethod(paramTypes, returnType, closureInfo);
var il = method.GetILGenerator();
if (!EmittingVisitor.TryEmit(bodyExpr, paramExprs, il, closureInfo))
return null;
il.Emit(OpCodes.Ret); // emits return from generated method
// create open delegate with closure object
if (closureInfo == null)
return method.CreateDelegate(delegateType);
return method.CreateDelegate(delegateType, closureInfo.ClosureObject);
}
private static DynamicMethod GetDynamicMethod(Type[] paramTypes, Type returnType, ClosureInfo closureInfo)
{
if (closureInfo == null)
return new DynamicMethod(string.Empty, returnType, paramTypes,
typeof(ExpressionCompiler), skipVisibility: true);
var closureType = closureInfo.ClosureObject.GetType();
var closureAndParamTypes = GetClosureAndParamTypes(paramTypes, closureType);
return new DynamicMethod(string.Empty, returnType, closureAndParamTypes, closureType, skipVisibility: true);
}
private static Type[] GetClosureAndParamTypes(Type[] paramTypes, Type closureType)
{
var paramCount = paramTypes.Length;
if (paramCount == 0)
return new[] { closureType };
var closureAndParamTypes = new Type[paramCount + 1];
closureAndParamTypes[0] = closureType;
if (paramCount == 1)
closureAndParamTypes[1] = paramTypes[0];
else if (paramCount > 1)
Array.Copy(paramTypes, 0, closureAndParamTypes, 1, paramCount);
return closureAndParamTypes;
}
private sealed class ClosureInfo
{
public List<ConstantExpression> ConstantExpressions { get; private set; }
public List<ParameterExpression> UsedParamExpressions { get; private set; }
public List<NestedLambdaInfo> NestedLambdas { get; private set; }
public FieldInfo[] Fields { get; private set; }
public bool IsArray { get; private set; }
public object ClosureObject { get; private set; }
public int ConstantCount { get { return ConstantExpressions == null ? 0 : ConstantExpressions.Count; } }
public int UsedParamCount { get { return UsedParamExpressions == null ? 0 : UsedParamExpressions.Count; } }
public int NestedLambdaCount { get { return NestedLambdas == null ? 0 : NestedLambdas.Count; } }
public void Add(ConstantExpression expr)
{
if (ConstantExpressions == null)
ConstantExpressions = new List<ConstantExpression>();
ConstantExpressions.Add(expr);
}
public void Add(ParameterExpression expr)
{
if (UsedParamExpressions == null)
UsedParamExpressions = new List<ParameterExpression>();
UsedParamExpressions.Add(expr);
}
public void Add(NestedLambdaInfo nestedLambdaInfo)
{
if (NestedLambdas == null)
NestedLambdas = new List<NestedLambdaInfo>();
NestedLambdas.Add(nestedLambdaInfo);
}
public void ConstructClosure()
{
var constantCount = ConstantCount;
var constantPlusParamCount = constantCount + UsedParamCount;
var totalItemCount = constantPlusParamCount + NestedLambdaCount;
var items = new object[totalItemCount];
// Deciding to create typed or array based closure, based on number of closed constants
// Not null array of constant types means a typed closure can be created
var typedClosureCreateMethods = Closure.TypedClosureCreateMethods;
var constantTypes = totalItemCount <= typedClosureCreateMethods.Length ? new Type[totalItemCount] : null;
if (ConstantExpressions != null)
for (var i = 0; i < ConstantExpressions.Count; i++)
{
var constantExpr = ConstantExpressions[i];
items[i] = constantExpr.Value;
if (constantTypes != null)
constantTypes[i] = constantExpr.Type;
}
if (UsedParamExpressions != null)
for (var i = 0; i < UsedParamExpressions.Count; i++)
{
items[constantCount + i] = null;
if (constantTypes != null)
constantTypes[constantCount + i] = UsedParamExpressions[i].Type;
}
if (NestedLambdas != null)
for (var i = 0; i < NestedLambdas.Count; i++)
{
var lambda = NestedLambdas[i].Lambda;
items[constantPlusParamCount + i] = lambda;
if (constantTypes != null)
constantTypes[constantPlusParamCount + i] = lambda.GetType();
}
if (constantTypes != null)
{
var createClosureMethod = typedClosureCreateMethods[totalItemCount - 1];
var createClosure = createClosureMethod.MakeGenericMethod(constantTypes);
var closure = createClosure.Invoke(null, items);
var fields = closure.GetType().GetTypeInfo().DeclaredFields;
var fieldsArray = fields as FieldInfo[] ?? fields.ToArray();
ClosureObject = closure;
Fields = fieldsArray;
}
else
{
ClosureObject = new ArrayClosure(items);
IsArray = true;
}
}
}
#region Closures
internal static class Closure
{
public static readonly MethodInfo[] TypedClosureCreateMethods =
typeof(Closure).GetTypeInfo().DeclaredMethods.ToArray();
public static Closure<T1> CreateClosure<T1>(T1 v1)
{
return new Closure<T1>(v1);
}
public static Closure<T1, T2> CreateClosure<T1, T2>(T1 v1, T2 v2)
{
return new Closure<T1, T2>(v1, v2);
}
public static Closure<T1, T2, T3> CreateClosure<T1, T2, T3>(T1 v1, T2 v2, T3 v3)
{
return new Closure<T1, T2, T3>(v1, v2, v3);
}
public static Closure<T1, T2, T3, T4> CreateClosure<T1, T2, T3, T4>(T1 v1, T2 v2, T3 v3, T4 v4)
{
return new Closure<T1, T2, T3, T4>(v1, v2, v3, v4);
}
public static Closure<T1, T2, T3, T4, T5> CreateClosure<T1, T2, T3, T4, T5>(T1 v1, T2 v2, T3 v3, T4 v4,
T5 v5)
{
return new Closure<T1, T2, T3, T4, T5>(v1, v2, v3, v4, v5);
}
public static Closure<T1, T2, T3, T4, T5, T6> CreateClosure<T1, T2, T3, T4, T5, T6>(T1 v1, T2 v2, T3 v3,
T4 v4, T5 v5, T6 v6)
{
return new Closure<T1, T2, T3, T4, T5, T6>(v1, v2, v3, v4, v5, v6);
}
public static Closure<T1, T2, T3, T4, T5, T6, T7> CreateClosure<T1, T2, T3, T4, T5, T6, T7>(T1 v1, T2 v2,
T3 v3, T4 v4, T5 v5, T6 v6, T7 v7)
{
return new Closure<T1, T2, T3, T4, T5, T6, T7>(v1, v2, v3, v4, v5, v6, v7);
}
public static Closure<T1, T2, T3, T4, T5, T6, T7, T8> CreateClosure<T1, T2, T3, T4, T5, T6, T7, T8>(
T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8)
{
return new Closure<T1, T2, T3, T4, T5, T6, T7, T8>(v1, v2, v3, v4, v5, v6, v7, v8);
}
public static Closure<T1, T2, T3, T4, T5, T6, T7, T8, T9> CreateClosure<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9)
{
return new Closure<T1, T2, T3, T4, T5, T6, T7, T8, T9>(v1, v2, v3, v4, v5, v6, v7, v8, v9);
}
public static Closure<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> CreateClosure<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10)
{
return new Closure<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10);
}
}
internal sealed class Closure<T1>
{
public T1 V1;
public Closure(T1 v1)
{
V1 = v1;
}
}
internal sealed class Closure<T1, T2>
{
public T1 V1;
public T2 V2;
public Closure(T1 v1, T2 v2)
{
V1 = v1;
V2 = v2;
}
}
internal sealed class Closure<T1, T2, T3>
{
public T1 V1;
public T2 V2;
public T3 V3;
public Closure(T1 v1, T2 v2, T3 v3)
{
V1 = v1;
V2 = v2;
V3 = v3;
}
}
internal sealed class Closure<T1, T2, T3, T4>
{
public T1 V1;
public T2 V2;
public T3 V3;
public T4 V4;
public Closure(T1 v1, T2 v2, T3 v3, T4 v4)
{
V1 = v1;
V2 = v2;
V3 = v3;
V4 = v4;
}
}
internal sealed class Closure<T1, T2, T3, T4, T5>
{
public T1 V1;
public T2 V2;
public T3 V3;
public T4 V4;
public T5 V5;
public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5)
{
V1 = v1;
V2 = v2;
V3 = v3;
V4 = v4;
V5 = v5;
}
}
internal sealed class Closure<T1, T2, T3, T4, T5, T6>
{
public T1 V1;
public T2 V2;
public T3 V3;
public T4 V4;
public T5 V5;
public T6 V6;
public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6)
{
V1 = v1;
V2 = v2;
V3 = v3;
V4 = v4;
V5 = v5;
V6 = v6;
}
}
internal sealed class Closure<T1, T2, T3, T4, T5, T6, T7>
{
public T1 V1;
public T2 V2;
public T3 V3;
public T4 V4;
public T5 V5;
public T6 V6;
public T7 V7;
public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7)
{
V1 = v1;
V2 = v2;
V3 = v3;
V4 = v4;
V5 = v5;
V6 = v6;
V7 = v7;
}
}
internal sealed class Closure<T1, T2, T3, T4, T5, T6, T7, T8>
{
public T1 V1;
public T2 V2;
public T3 V3;
public T4 V4;
public T5 V5;
public T6 V6;
public T7 V7;
public T8 V8;
public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8)
{
V1 = v1;
V2 = v2;
V3 = v3;
V4 = v4;
V5 = v5;
V6 = v6;
V7 = v7;
V8 = v8;
}
}
internal sealed class Closure<T1, T2, T3, T4, T5, T6, T7, T8, T9>
{
public T1 V1;
public T2 V2;
public T3 V3;
public T4 V4;
public T5 V5;
public T6 V6;
public T7 V7;
public T8 V8;
public T9 V9;
public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9)
{
V1 = v1;
V2 = v2;
V3 = v3;
V4 = v4;
V5 = v5;
V6 = v6;
V7 = v7;
V8 = v8;
V9 = v9;
}
}
internal sealed class Closure<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>
{
public T1 V1;
public T2 V2;
public T3 V3;
public T4 V4;
public T5 V5;
public T6 V6;
public T7 V7;
public T8 V8;
public T9 V9;
public T10 V10;
public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10)
{
V1 = v1;
V2 = v2;
V3 = v3;
V4 = v4;
V5 = v5;
V6 = v6;
V7 = v7;
V8 = v8;
V9 = v9;
V10 = v10;
}
}
internal sealed class ArrayClosure
{
public readonly object[] Constants;
public static FieldInfo ArrayField = typeof(ArrayClosure).GetTypeInfo().DeclaredFields.First(f => !f.IsStatic);
public ArrayClosure(object[] constants)
{
Constants = constants;
}
}
#endregion Closures
#region Collect Bound Constants
private sealed class NestedLambdaInfo
{
public readonly object Lambda;
public readonly Expression LambdaExpr; // to find the lambda in bigger parent expression
public readonly ClosureInfo ClosureInfo;
public NestedLambdaInfo(object lambda, Expression lambdaExpr, ClosureInfo closureInfo)
{
Lambda = lambda;
LambdaExpr = lambdaExpr;
ClosureInfo = closureInfo;
}
}
private static bool IsBoundConstant(object value)
{
if (value == null)
return false;
var typeInfo = value.GetType().GetTypeInfo();
return !typeInfo.IsPrimitive
&& !(value is string)
&& !(value is Type)
&& !typeInfo.IsEnum;
}
private static readonly Type[] _emptyTypes = new Type[0];
// @paramExprs is required for nested lambda compilation
private static bool TryCollectBoundConstants(ref ClosureInfo closure, Expression expr, IList<ParameterExpression> paramExprs)
{
if (expr == null)
return false;
switch (expr.NodeType)
{
case ExpressionType.Constant:
var constantExpr = (ConstantExpression)expr;
var constantValue = constantExpr.Value;
if (constantValue is Delegate ||
IsBoundConstant(constantValue))
{
closure = closure ?? new ClosureInfo();
closure.Add(constantExpr);
}
break;
case ExpressionType.Parameter:
// if parameter is used But no passed (not in parameter expressions)
// it means parameter is provided by outer lambda and should be put in closure for current lambda
var paramExpr = (ParameterExpression)expr;
if (paramExprs.IndexOf(paramExpr) == -1)
{
closure = closure ?? new ClosureInfo();
closure.Add(paramExpr);
}
break;
case ExpressionType.Call:
var methodCallExpr = (MethodCallExpression)expr;
var methodOwnerExpr = methodCallExpr.Object;
return (methodOwnerExpr == null
|| TryCollectBoundConstants(ref closure, methodOwnerExpr, paramExprs))
&& TryCollectBoundConstants(ref closure, methodCallExpr.Arguments, paramExprs);
case ExpressionType.MemberAccess:
var memberExpr = ((MemberExpression)expr).Expression;
return memberExpr == null
|| TryCollectBoundConstants(ref closure, memberExpr, paramExprs);
case ExpressionType.New:
return TryCollectBoundConstants(ref closure, ((NewExpression)expr).Arguments, paramExprs);
case ExpressionType.NewArrayInit:
return TryCollectBoundConstants(ref closure, ((NewArrayExpression)expr).Expressions, paramExprs);
// property initializer
case ExpressionType.MemberInit:
var memberInitExpr = (MemberInitExpression)expr;
if (!TryCollectBoundConstants(ref closure, memberInitExpr.NewExpression, paramExprs))
return false;
var memberBindings = memberInitExpr.Bindings;
for (var i = 0; i < memberBindings.Count; ++i)
{
var memberBinding = memberBindings[i];
if (memberBinding.BindingType == MemberBindingType.Assignment &&
!TryCollectBoundConstants(ref closure, ((MemberAssignment)memberBinding).Expression, paramExprs))
return false;
}
break;
// nested lambda
case ExpressionType.Lambda:
// 1. Try to compile nested lambda in place
// 2. Check that parameters used in compiled lambda are passed or closed by outer lambda
// 3. Add the compiled lambda to closure of outer lambda for later invocation
var lambdaExpr = (LambdaExpression)expr;
var lambdaParamExprs = lambdaExpr.Parameters;
var paramTypes = GetParamExprTypes(lambdaParamExprs);
ClosureInfo nestedClosure = null;
var lambda = TryCompile(ref nestedClosure,
lambdaExpr.Type, paramTypes, lambdaExpr.Body.Type, lambdaExpr.Body, lambdaParamExprs);
if (lambda == null)
return false;
var lambdaInfo = new NestedLambdaInfo(lambda, lambdaExpr, nestedClosure);
closure = closure ?? new ClosureInfo();
closure.Add(lambdaInfo);
// if nested parameter is no matched with any outer parameter, that ensure it goes to outer closure
if (nestedClosure != null && nestedClosure.UsedParamExpressions != null)
{
var nestedClosedParams = nestedClosure.UsedParamExpressions;
for (var i = 0; i < nestedClosedParams.Count; i++)
{
var nestedClosedParamExpr = nestedClosedParams[i];
if (paramExprs.Count == 0 ||
paramExprs.IndexOf(nestedClosedParamExpr) == -1)
{
closure.Add(nestedClosedParamExpr);
}
}
}
break;
case ExpressionType.Invoke:
var invocationExpr = (InvocationExpression)expr;
return TryCollectBoundConstants(ref closure, invocationExpr.Expression, paramExprs)
&& TryCollectBoundConstants(ref closure, invocationExpr.Arguments, paramExprs);
case ExpressionType.Conditional:
var conditionalExpr = (ConditionalExpression)expr;
return TryCollectBoundConstants(ref closure, conditionalExpr.Test, paramExprs)
&& TryCollectBoundConstants(ref closure, conditionalExpr.IfTrue, paramExprs)
&& TryCollectBoundConstants(ref closure, conditionalExpr.IfFalse, paramExprs);
default:
var unaryExpr = expr as UnaryExpression;
if (unaryExpr != null)
return TryCollectBoundConstants(ref closure, unaryExpr.Operand, paramExprs);
var binaryExpr = expr as BinaryExpression;
if (binaryExpr != null)
return TryCollectBoundConstants(ref closure, binaryExpr.Left, paramExprs)
&& TryCollectBoundConstants(ref closure, binaryExpr.Right, paramExprs);
break;
}
return true;
}
private static bool TryCollectBoundConstants(ref ClosureInfo closure, IList<Expression> exprs, IList<ParameterExpression> paramExprs)
{
var count = exprs.Count;
for (var i = 0; i < count; i++)
if (!TryCollectBoundConstants(ref closure, exprs[i], paramExprs))
return false;
return true;
}
#endregion Collect Bound Constants
/// <summary>Supports emitting of selected expressions, e.g. lambdaExpr are not supported yet.
/// When emitter find not supported expression it will return false from <see cref="TryEmit"/>, so I could fallback
/// to normal and slow Expression.Compile.</summary>
private static class EmittingVisitor
{
private static readonly MethodInfo _getDelegateTargetProperty =
typeof(Delegate).GetTypeInfo().DeclaredMethods.First(p => p.Name == "get_Target");
public static bool TryEmit(Expression expr, IList<ParameterExpression> paramExprs, ILGenerator il, ClosureInfo closure)
{
switch (expr.NodeType)
{
case ExpressionType.Parameter:
return EmitParameter((ParameterExpression)expr, paramExprs, il, closure);
case ExpressionType.Convert:
return EmitConvert((UnaryExpression)expr, paramExprs, il, closure);
case ExpressionType.ArrayIndex:
return EmitArrayIndex((BinaryExpression)expr, paramExprs, il, closure);
case ExpressionType.Constant:
return EmitConstant((ConstantExpression)expr, il, closure);
case ExpressionType.New:
return EmitNew((NewExpression)expr, paramExprs, il, closure);
case ExpressionType.NewArrayInit:
return EmitNewArray((NewArrayExpression)expr, paramExprs, il, closure);
case ExpressionType.MemberInit:
return EmitMemberInit((MemberInitExpression)expr, paramExprs, il, closure);
case ExpressionType.Call:
return EmitMethodCall((MethodCallExpression)expr, paramExprs, il, closure);
case ExpressionType.MemberAccess:
return EmitMemberAccess((MemberExpression)expr, paramExprs, il, closure);
case ExpressionType.Lambda:
return EmitNestedLambda((LambdaExpression)expr, paramExprs, il, closure);
case ExpressionType.Invoke:
return EmitInvokeLambda((InvocationExpression)expr, paramExprs, il, closure);
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.Equal:
case ExpressionType.NotEqual:
return EmitComparison((BinaryExpression)expr, paramExprs, il, closure);
case ExpressionType.AndAlso:
case ExpressionType.OrElse:
return EmitLogicalOperator((BinaryExpression)expr, paramExprs, il, closure);
case ExpressionType.Conditional:
return EmitTernararyOperator((ConditionalExpression)expr, paramExprs, il, closure);
//case ExpressionType.Coalesce:
default:
return false;
}
}
private static bool EmitParameter(ParameterExpression p, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure)
{
var paramIndex = ps.IndexOf(p);
// if parameter is passed, then just load it on stack
if (paramIndex != -1)
{
if (closure != null)
paramIndex += 1; // shift parameter indices by one, because the first one will be closure
LoadParamArg(il, paramIndex);
return true;
}
// Otherwise (parameter isn't passed) then it is probably passed into outer lambda,
// so it should be loaded from closure
if (closure == null)
return false;
var usedParamIndex = closure.UsedParamExpressions.IndexOf(p);
if (usedParamIndex == -1)
return false; // what??? no chance
var closureItemIndex = usedParamIndex + closure.ConstantCount;
LoadClosureFieldOrItem(il, closure, closureItemIndex, p.Type);
return true;
}
private static void LoadParamArg(ILGenerator il, int paramIndex)
{
switch (paramIndex)
{
case 0:
il.Emit(OpCodes.Ldarg_0);
break;
case 1:
il.Emit(OpCodes.Ldarg_1);
break;
case 2:
il.Emit(OpCodes.Ldarg_2);
break;
case 3:
il.Emit(OpCodes.Ldarg_3);
break;
default:
if (paramIndex <= byte.MaxValue)
il.Emit(OpCodes.Ldarg_S, (byte)paramIndex);
else
il.Emit(OpCodes.Ldarg, paramIndex);
break;
}
}
private static bool EmitBinary(BinaryExpression e, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure)
{
return TryEmit(e.Left, ps, il, closure)
&& TryEmit(e.Right, ps, il, closure);
}
private static bool EmitMany(IList<Expression> es, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure)
{
for (int i = 0, n = es.Count; i < n; i++)
if (!TryEmit(es[i], ps, il, closure))
return false;
return true;
}
private static bool EmitConvert(UnaryExpression e, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure)
{
if (!TryEmit(e.Operand, ps, il, closure))
return false;
var targetType = e.Type;
if (targetType == typeof(object))
return false;
if (targetType == typeof(int))
il.Emit(OpCodes.Conv_I4);
else if (targetType == typeof(float))
il.Emit(OpCodes.Conv_R4);
else if (targetType == typeof(uint))
il.Emit(OpCodes.Conv_U4);
else if (targetType == typeof(sbyte))
il.Emit(OpCodes.Conv_I1);
else if (targetType == typeof(byte))
il.Emit(OpCodes.Conv_U1);
else if (targetType == typeof(short))
il.Emit(OpCodes.Conv_I2);
else if (targetType == typeof(ushort))
il.Emit(OpCodes.Conv_U2);
else if (targetType == typeof(long))
il.Emit(OpCodes.Conv_I8);
else if (targetType == typeof(ulong))
il.Emit(OpCodes.Conv_U8);
else if (targetType == typeof(double))
il.Emit(OpCodes.Conv_R8);
else
il.Emit(OpCodes.Castclass, targetType);
return true;
}
private static bool EmitConstant(ConstantExpression e, ILGenerator il, ClosureInfo closure)
{
var constant = e.Value;
if (constant == null)
{
il.Emit(OpCodes.Ldnull);
return true;
}
var constantActualType = constant.GetType();
if (constantActualType.GetTypeInfo().IsEnum)
constantActualType = Enum.GetUnderlyingType(constantActualType);
if (constantActualType == typeof(int))
{
EmitLoadConstantInt(il, (int)constant);
}
else if (constantActualType == typeof(char))
{
EmitLoadConstantInt(il, (char)constant);
}
else if (constantActualType == typeof(short))
{
EmitLoadConstantInt(il, (short)constant);
}
else if (constantActualType == typeof(byte))
{
EmitLoadConstantInt(il, (byte)constant);
}
else if (constantActualType == typeof(ushort))
{
EmitLoadConstantInt(il, (ushort)constant);
}
else if (constantActualType == typeof(sbyte))
{
EmitLoadConstantInt(il, (sbyte)constant);
}
else if (constantActualType == typeof(uint))
{
unchecked
{
EmitLoadConstantInt(il, (int)(uint)constant);
}
}
else if (constantActualType == typeof(long))
{
il.Emit(OpCodes.Ldc_I8, (long)constant);
}
else if (constantActualType == typeof(ulong))
{
unchecked
{
il.Emit(OpCodes.Ldc_I8, (long)(ulong)constant);
}
}
else if (constantActualType == typeof(float))
{
il.Emit(OpCodes.Ldc_R8, (float)constant);
}
else if (constantActualType == typeof(double))
{
il.Emit(OpCodes.Ldc_R8, (double)constant);
}
else if (constantActualType == typeof(bool))
{
il.Emit((bool)constant ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
}
else if (constant is string)
{
il.Emit(OpCodes.Ldstr, (string)constant);
}
else if (constant is Type)
{
il.Emit(OpCodes.Ldtoken, (Type)constant);
var getTypeFromHandle = typeof(Type).GetTypeInfo()
.DeclaredMethods.First(m => m.Name == "GetTypeFromHandle");
il.Emit(OpCodes.Call, getTypeFromHandle);
}
else if (closure != null)
{
var constantIndex = closure.ConstantExpressions.IndexOf(e);
if (constantIndex == -1)
return false;
LoadClosureFieldOrItem(il, closure, constantIndex, e.Type);
}
else
return false;
// boxing the value type, otherwise we can get a strange result when 0 is treated as Null.
if (e.Type == typeof(object) && constantActualType.GetTypeInfo().IsValueType)
il.Emit(OpCodes.Box, constant.GetType()); // using normal type for Enum instead of underlying type
return true;
}
private static void LoadClosureFieldOrItem(ILGenerator il, ClosureInfo closure, int constantIndex, Type constantType)
{
// load closure argument: Closure object or Closure array
il.Emit(OpCodes.Ldarg_0);
if (!closure.IsArray)
{
// load closure field
il.Emit(OpCodes.Ldfld, closure.Fields[constantIndex]);
return;
}
// load array field
il.Emit(OpCodes.Ldfld, ArrayClosure.ArrayField);
// load array item index
EmitLoadConstantInt(il, constantIndex);
// load item from index
il.Emit(OpCodes.Ldelem_Ref);
// Cast or unbox the object item depending if it is a class or value type
if (constantType != typeof(object))
{
if (constantType.GetTypeInfo().IsValueType)
il.Emit(OpCodes.Unbox_Any, constantType);
else
il.Emit(OpCodes.Castclass, constantType);
}
}
private static bool EmitNew(NewExpression e, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure)
{
if (!EmitMany(e.Arguments, ps, il, closure))
return false;
il.Emit(OpCodes.Newobj, e.Constructor);
return true;
}
private static bool EmitNewArray(NewArrayExpression e, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure)
{
var elems = e.Expressions;
var arrType = e.Type;
var elemType = arrType.GetElementType();
var isElemOfValueType = elemType.GetTypeInfo().IsValueType;
var arrVar = il.DeclareLocal(arrType);
EmitLoadConstantInt(il, elems.Count);
il.Emit(OpCodes.Newarr, elemType);
il.Emit(OpCodes.Stloc, arrVar);
for (int i = 0, n = elems.Count; i < n; i++)
{
il.Emit(OpCodes.Ldloc, arrVar);
EmitLoadConstantInt(il, i);
// loading element address for later copying of value into it.
if (isElemOfValueType)
il.Emit(OpCodes.Ldelema, elemType);
if (!TryEmit(elems[i], ps, il, closure))
return false;
if (isElemOfValueType)
il.Emit(OpCodes.Stobj, elemType); // store element of value type by array element address
else
il.Emit(OpCodes.Stelem_Ref);
}
il.Emit(OpCodes.Ldloc, arrVar);
return true;
}
private static bool EmitArrayIndex(BinaryExpression e, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure)
{
if (!EmitBinary(e, ps, il, closure))
return false;
il.Emit(OpCodes.Ldelem_Ref);
return true;
}
private static bool EmitMemberInit(MemberInitExpression mi, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure)
{
if (!EmitNew(mi.NewExpression, ps, il, closure))
return false;
var obj = il.DeclareLocal(mi.Type);
il.Emit(OpCodes.Stloc, obj);
var bindings = mi.Bindings;
for (int i = 0, n = bindings.Count; i < n; i++)
{
var binding = bindings[i];
if (binding.BindingType != MemberBindingType.Assignment)
return false;
il.Emit(OpCodes.Ldloc, obj);
if (!TryEmit(((MemberAssignment)binding).Expression, ps, il, closure))
return false;
var prop = binding.Member as PropertyInfo;
if (prop != null)
{
var propSetMethodName = "set_" + prop.Name;
var setMethod = prop.DeclaringType.GetTypeInfo()
.DeclaredMethods.FirstOrDefault(m => m.Name == propSetMethodName);
if (setMethod == null)
return false;
EmitMethodCall(setMethod, il);
}
else
{
var field = binding.Member as FieldInfo;
if (field == null)
return false;
il.Emit(OpCodes.Stfld, field);
}
}
il.Emit(OpCodes.Ldloc, obj);
return true;
}
private static bool EmitMethodCall(MethodCallExpression e, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure)
{
var methodOwnerExpr = e.Object;
if (methodOwnerExpr != null)
{
if (!TryEmit(methodOwnerExpr, ps, il, closure))
return false;
ForValueTypeStoreAndLoadValueAddress(il, methodOwnerExpr.Type);
}
if (e.Arguments.Count != 0 &&
!EmitMany(e.Arguments, ps, il, closure))
return false;
EmitMethodCall(e.Method, il);
return true;
}
private static void ForValueTypeStoreAndLoadValueAddress(ILGenerator il, Type ownerType)
{
if (ownerType.GetTypeInfo().IsValueType)
{
var valueVar = il.DeclareLocal(ownerType);
il.Emit(OpCodes.Stloc, valueVar);
il.Emit(OpCodes.Ldloca, valueVar);
}
}
private static bool EmitMemberAccess(MemberExpression e, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure)
{
var memberOwnerExpr = e.Expression;
if (memberOwnerExpr != null)
{
if (!TryEmit(memberOwnerExpr, ps, il, closure))
return false;
ForValueTypeStoreAndLoadValueAddress(il, memberOwnerExpr.Type);
}
var field = e.Member as FieldInfo;
if (field != null)
{
il.Emit(field.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, field);
return true;
}
var prop = e.Member as PropertyInfo;
if (prop != null)
{
var propGetMethodName = "get_" + prop.Name;
var getMethod = prop.DeclaringType.GetTypeInfo()
.DeclaredMethods.FirstOrDefault(_ => _.Name == propGetMethodName);
if (getMethod == null)
return false;
EmitMethodCall(getMethod, il);
}
return true;
}
private static bool EmitNestedLambda(LambdaExpression lambdaExpr, IList<ParameterExpression> paramExprs, ILGenerator il, ClosureInfo closure)
{
// First, find in closed compiled lambdas the one corresponding to the current lambda expression.
var nestedLambdas = closure.NestedLambdas;
var nestedLambdaIndex = nestedLambdas.Count - 1;
while (nestedLambdaIndex >= 0 && nestedLambdas[nestedLambdaIndex].LambdaExpr != lambdaExpr)
--nestedLambdaIndex;
// Situation with not found lambda is not possible/exceptional -
// means that we somehow skipped the lambda expression while collecting closure info.
if (nestedLambdaIndex == -1)
return false;
var nestedLambdaInfo = nestedLambdas[nestedLambdaIndex];
var nestedLambda = nestedLambdaInfo.Lambda;
var nestedLambdaType = nestedLambda.GetType();
// Next we are loading compiled lambda on stack
var closureItemIndex = nestedLambdaIndex + closure.ConstantCount + closure.UsedParamCount;
LoadClosureFieldOrItem(il, closure, closureItemIndex, nestedLambdaType);
// If lambda does not use any outer parameters to be set in closure, then we're done
var nestedLambdaClosure = nestedLambdaInfo.ClosureInfo;
if (nestedLambdaClosure == null ||
nestedLambdaClosure.UsedParamExpressions == null)
return true;
// Sets closure param placeholder fields to the param values
var nestedLambdaUsedParamExprs = nestedLambdaClosure.UsedParamExpressions;
for (var i = 0; i < nestedLambdaUsedParamExprs.Count; i++)
{
var nestedUsedParamExpr = nestedLambdaUsedParamExprs[i];
// copy lambda field on stack in order to set it Target.Param to param value
il.Emit(OpCodes.Dup);
// load lambda.Target property
EmitMethodCall(_getDelegateTargetProperty, il);
// params go after constants
var nestedUsedParamIndex = i + nestedLambdaClosure.ConstantCount;
if (nestedLambdaClosure.IsArray)
{
// load array field
il.Emit(OpCodes.Ldfld, ArrayClosure.ArrayField);
// load array item index
EmitLoadConstantInt(il, nestedUsedParamIndex);
}
var paramIndex = paramExprs.IndexOf(nestedUsedParamExpr);
if (paramIndex != -1) // load param from input params
{
// +1 is set cause of added first closure argument
LoadParamArg(il, paramIndex + 1);
}
else // load parameter from outer closure
{
if (closure.UsedParamExpressions == null)
return false; // impossible, better to throw?
var outerClosureParamIndex = closure.UsedParamExpressions.IndexOf(nestedUsedParamExpr);
if (outerClosureParamIndex == -1)
return false; // impossible, better to throw?
var outerClosureParamItemIndex = closure.ConstantCount + outerClosureParamIndex;
LoadClosureFieldOrItem(il, closure, outerClosureParamItemIndex, nestedUsedParamExpr.Type);
}
if (nestedLambdaClosure.IsArray)
{
// box value types before setting the object array item
if (nestedUsedParamExpr.Type.GetTypeInfo().IsValueType)
il.Emit(OpCodes.Box, nestedUsedParamExpr.Type);
// load item from index
il.Emit(OpCodes.Stelem_Ref);
}
else
{
var closedParamField = nestedLambdaClosure.Fields[nestedUsedParamIndex];
il.Emit(OpCodes.Stfld, closedParamField);
}
}
return true;
}
private static bool EmitInvokeLambda(InvocationExpression e, IList<ParameterExpression> paramExprs, ILGenerator il, ClosureInfo closure)
{
if (!TryEmit(e.Expression, paramExprs, il, closure) ||
!EmitMany(e.Arguments, paramExprs, il, closure))
return false;
var invokeMethod = e.Expression.Type.GetTypeInfo().DeclaredMethods.First(m => m.Name == "Invoke");
EmitMethodCall(invokeMethod, il);
return true;
}
private static bool EmitComparison(BinaryExpression e, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure)
{
if (!TryEmit(e.Left, ps, il, closure) ||
!TryEmit(e.Right, ps, il, closure))
return false;
switch (e.NodeType)
{
case ExpressionType.Equal:
il.Emit(OpCodes.Ceq);
break;
case ExpressionType.LessThan:
il.Emit(OpCodes.Clt);
break;
case ExpressionType.GreaterThan:
il.Emit(OpCodes.Cgt);
break;
case ExpressionType.NotEqual:
il.Emit(OpCodes.Ceq);
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Ceq);
break;
case ExpressionType.LessThanOrEqual:
il.Emit(OpCodes.Cgt);
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Ceq);
break;
case ExpressionType.GreaterThanOrEqual:
il.Emit(OpCodes.Clt);
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Ceq);
break;
}
return true;
}
private static bool EmitLogicalOperator(BinaryExpression e, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure)
{
if (!TryEmit(e.Left, ps, il, closure))
return false;
var labelSkipRight = il.DefineLabel();
var isAnd = e.NodeType == ExpressionType.AndAlso;
il.Emit(isAnd ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, labelSkipRight);
if (!TryEmit(e.Right, ps, il, closure))
return false;
var labelDone = il.DefineLabel();
il.Emit(OpCodes.Br, labelDone);
il.MarkLabel(labelSkipRight); // label the second branch
il.Emit(isAnd ? OpCodes.Ldc_I4_0 : OpCodes.Ldc_I4_1);
il.MarkLabel(labelDone);
return true;
}
private static bool EmitTernararyOperator(ConditionalExpression e, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure)
{
if (!TryEmit(e.Test, ps, il, closure))
return false;
var labelIfFalse = il.DefineLabel();
il.Emit(OpCodes.Brfalse_S, labelIfFalse);
if (!TryEmit(e.IfTrue, ps, il, closure))
return false;
var labelDone = il.DefineLabel();
il.Emit(OpCodes.Br, labelDone);
il.MarkLabel(labelIfFalse);
if (!TryEmit(e.IfFalse, ps, il, closure))
return false;
il.MarkLabel(labelDone);
return true;
}
private static void EmitMethodCall(MethodInfo method, ILGenerator il)
{
il.Emit(method.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, method);
}
private static void EmitLoadConstantInt(ILGenerator il, int i)
{
switch (i)
{
case -1:
il.Emit(OpCodes.Ldc_I4_M1);
break;
case 0:
il.Emit(OpCodes.Ldc_I4_0);
break;
case 1:
il.Emit(OpCodes.Ldc_I4_1);
break;
case 2:
il.Emit(OpCodes.Ldc_I4_2);
break;
case 3:
il.Emit(OpCodes.Ldc_I4_3);
break;
case 4:
il.Emit(OpCodes.Ldc_I4_4);
break;
case 5:
il.Emit(OpCodes.Ldc_I4_5);
break;
case 6:
il.Emit(OpCodes.Ldc_I4_6);
break;
case 7:
il.Emit(OpCodes.Ldc_I4_7);
break;
case 8:
il.Emit(OpCodes.Ldc_I4_8);
break;
default:
il.Emit(OpCodes.Ldc_I4, i);
break;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace WebApiBackend.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.