context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Xml;
using System.Reflection;
using NLog;
using NLog.Config;
using NUnit.Framework;
#if !NUNIT
using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute;
#endif
namespace NLog.UnitTests.LayoutRenderers
{
[TestFixture]
public class NDCTests : NLogTestBase
{
[Test]
public void NDCTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${ndc} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
NestedDiagnosticsContext.Clear();
LogManager.GetLogger("A").Debug("0");
AssertDebugLastMessage("debug", " 0");
using (NestedDiagnosticsContext.Push("ala"))
{
LogManager.GetLogger("A").Debug("a");
AssertDebugLastMessage("debug", "ala a");
using (NestedDiagnosticsContext.Push("ma"))
{
LogManager.GetLogger("A").Debug("b");
AssertDebugLastMessage("debug", "ala ma b");
using (NestedDiagnosticsContext.Push("kota"))
{
LogManager.GetLogger("A").Debug("c");
AssertDebugLastMessage("debug", "ala ma kota c");
using (NestedDiagnosticsContext.Push("kopytko"))
{
LogManager.GetLogger("A").Debug("d");
AssertDebugLastMessage("debug", "ala ma kota kopytko d");
}
LogManager.GetLogger("A").Debug("c");
AssertDebugLastMessage("debug", "ala ma kota c");
}
LogManager.GetLogger("A").Debug("b");
AssertDebugLastMessage("debug", "ala ma b");
}
LogManager.GetLogger("A").Debug("a");
AssertDebugLastMessage("debug", "ala a");
}
LogManager.GetLogger("A").Debug("0");
AssertDebugLastMessage("debug", " 0");
}
[Test]
public void NDCTopTestTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${ndc:topframes=2} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
NestedDiagnosticsContext.Clear();
LogManager.GetLogger("A").Debug("0");
AssertDebugLastMessage("debug", " 0");
using (NestedDiagnosticsContext.Push("ala"))
{
LogManager.GetLogger("A").Debug("a");
AssertDebugLastMessage("debug", "ala a");
using (NestedDiagnosticsContext.Push("ma"))
{
LogManager.GetLogger("A").Debug("b");
AssertDebugLastMessage("debug", "ala ma b");
using (NestedDiagnosticsContext.Push("kota"))
{
LogManager.GetLogger("A").Debug("c");
AssertDebugLastMessage("debug", "ma kota c");
using (NestedDiagnosticsContext.Push("kopytko"))
{
LogManager.GetLogger("A").Debug("d");
AssertDebugLastMessage("debug", "kota kopytko d");
}
LogManager.GetLogger("A").Debug("c");
AssertDebugLastMessage("debug", "ma kota c");
}
LogManager.GetLogger("A").Debug("b");
AssertDebugLastMessage("debug", "ala ma b");
}
LogManager.GetLogger("A").Debug("a");
AssertDebugLastMessage("debug", "ala a");
}
LogManager.GetLogger("A").Debug("0");
AssertDebugLastMessage("debug", " 0");
}
[Test]
public void NDCTop1TestTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${ndc:topframes=1} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
NestedDiagnosticsContext.Clear();
LogManager.GetLogger("A").Debug("0");
AssertDebugLastMessage("debug", " 0");
using (NestedDiagnosticsContext.Push("ala"))
{
LogManager.GetLogger("A").Debug("a");
AssertDebugLastMessage("debug", "ala a");
using (NestedDiagnosticsContext.Push("ma"))
{
LogManager.GetLogger("A").Debug("b");
AssertDebugLastMessage("debug", "ma b");
using (NestedDiagnosticsContext.Push("kota"))
{
LogManager.GetLogger("A").Debug("c");
AssertDebugLastMessage("debug", "kota c");
NestedDiagnosticsContext.Push("kopytko");
LogManager.GetLogger("A").Debug("d");
AssertDebugLastMessage("debug", "kopytko d");
Assert.AreEqual("kopytko", NestedDiagnosticsContext.Pop()); // manual pop
LogManager.GetLogger("A").Debug("c");
AssertDebugLastMessage("debug", "kota c");
}
LogManager.GetLogger("A").Debug("b");
AssertDebugLastMessage("debug", "ma b");
}
LogManager.GetLogger("A").Debug("a");
AssertDebugLastMessage("debug", "ala a");
}
LogManager.GetLogger("A").Debug("0");
AssertDebugLastMessage("debug", " 0");
Assert.AreEqual(string.Empty, NestedDiagnosticsContext.Pop());
Assert.AreEqual(string.Empty, NestedDiagnosticsContext.TopMessage);
NestedDiagnosticsContext.Push("zzz");
Assert.AreEqual("zzz", NestedDiagnosticsContext.TopMessage);
NestedDiagnosticsContext.Clear();
Assert.AreEqual(string.Empty, NestedDiagnosticsContext.Pop());
Assert.AreEqual(string.Empty, NestedDiagnosticsContext.TopMessage);
}
[Test]
public void NDCBottomTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${ndc:bottomframes=2} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
NestedDiagnosticsContext.Clear();
LogManager.GetLogger("A").Debug("0");
AssertDebugLastMessage("debug", " 0");
using (NestedDiagnosticsContext.Push("ala"))
{
LogManager.GetLogger("A").Debug("a");
AssertDebugLastMessage("debug", "ala a");
using (NestedDiagnosticsContext.Push("ma"))
{
LogManager.GetLogger("A").Debug("b");
AssertDebugLastMessage("debug", "ala ma b");
using (NestedDiagnosticsContext.Push("kota"))
{
LogManager.GetLogger("A").Debug("c");
AssertDebugLastMessage("debug", "ala ma c");
using (NestedDiagnosticsContext.Push("kopytko"))
{
LogManager.GetLogger("A").Debug("d");
AssertDebugLastMessage("debug", "ala ma d");
}
LogManager.GetLogger("A").Debug("c");
AssertDebugLastMessage("debug", "ala ma c");
}
LogManager.GetLogger("A").Debug("b");
AssertDebugLastMessage("debug", "ala ma b");
}
LogManager.GetLogger("A").Debug("a");
AssertDebugLastMessage("debug", "ala a");
}
LogManager.GetLogger("A").Debug("0");
AssertDebugLastMessage("debug", " 0");
}
[Test]
public void NDCSeparatorTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${ndc:separator=\:} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
NestedDiagnosticsContext.Clear();
LogManager.GetLogger("A").Debug("0");
AssertDebugLastMessage("debug", " 0");
using (NestedDiagnosticsContext.Push("ala"))
{
LogManager.GetLogger("A").Debug("a");
AssertDebugLastMessage("debug", "ala a");
using (NestedDiagnosticsContext.Push("ma"))
{
LogManager.GetLogger("A").Debug("b");
AssertDebugLastMessage("debug", "ala:ma b");
using (NestedDiagnosticsContext.Push("kota"))
{
LogManager.GetLogger("A").Debug("c");
AssertDebugLastMessage("debug", "ala:ma:kota c");
using (NestedDiagnosticsContext.Push("kopytko"))
{
LogManager.GetLogger("A").Debug("d");
AssertDebugLastMessage("debug", "ala:ma:kota:kopytko d");
}
LogManager.GetLogger("A").Debug("c");
AssertDebugLastMessage("debug", "ala:ma:kota c");
}
LogManager.GetLogger("A").Debug("b");
AssertDebugLastMessage("debug", "ala:ma b");
}
LogManager.GetLogger("A").Debug("a");
AssertDebugLastMessage("debug", "ala a");
}
LogManager.GetLogger("A").Debug("0");
AssertDebugLastMessage("debug", " 0");
}
}
}
| |
/*
* Copyright 2012-2015 Aerospike, Inc.
*
* Portions may be licensed to Aerospike, Inc. under one or more contributor
* license agreements.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using System;
using System.Collections.Generic;
using System.Threading;
using Aerospike.Client;
namespace Aerospike.Demo
{
abstract class BenchmarkThread
{
protected readonly Console console;
protected readonly BenchmarkArguments args;
protected readonly BenchmarkShared shared;
private readonly Example example;
private readonly RandomShift random;
private Thread thread;
public BenchmarkThread(Console console, BenchmarkArguments args, BenchmarkShared shared, Example example)
{
this.console = console;
this.args = args;
this.shared = shared;
this.example = example;
random = new RandomShift();
}
public void Start()
{
thread = new Thread(new ThreadStart(this.Run));
thread.Start();
}
public void Run()
{
try
{
if (args.recordsInit > 0)
{
InitRecords();
}
else
{
RunWorker();
}
}
catch (Exception ex)
{
console.Error(ex.Message);
}
}
public void Join()
{
thread.Join();
thread = null;
}
private void InitRecords()
{
while (example.valid)
{
int key = Interlocked.Increment(ref shared.currentKey);
if (key >= args.recordsInit)
{
if (key == args.recordsInit)
{
console.Info("write(tps={0} timeouts={1} errors={2} total={3}))",
shared.writeCount, shared.writeTimeoutCount, shared.writeErrorCount, args.recordsInit
);
}
break;
}
Write(key);
}
}
private void RunWorker()
{
while (example.valid)
{
// Choose key at random.
int key = random.Next(0, args.records);
// Roll a percentage die.
int die = random.Next(0, 100);
if (die < args.readPct)
{
Read(key);
}
else
{
Write(key);
}
}
}
private void Write(int userKey)
{
Key key = new Key(args.ns, args.set, userKey);
Bin bin = new Bin(args.binName, args.GetValue(random));
try
{
WriteRecord(args.writePolicy, key, bin);
}
catch (AerospikeException ae)
{
OnWriteFailure(key, bin, ae);
}
catch (Exception e)
{
OnWriteFailure(key, bin, e);
}
}
private void Read(int userKey)
{
Key key = new Key(args.ns, args.set, userKey);
try
{
ReadRecord(args.writePolicy, key, args.binName);
}
catch (AerospikeException ae)
{
OnReadFailure(key, ae);
}
catch (Exception e)
{
OnReadFailure(key, e);
}
}
protected void OnWriteSuccess()
{
Interlocked.Increment(ref shared.writeCount);
}
protected void OnWriteSuccess(double elapsed)
{
Interlocked.Increment(ref shared.writeCount);
shared.writeLatency.Add(elapsed);
}
protected void OnWriteFailure(Key key, Bin bin, AerospikeException ae)
{
if (ae.Result == ResultCode.TIMEOUT)
{
Interlocked.Increment(ref shared.writeTimeoutCount);
}
else
{
Interlocked.Increment(ref shared.writeErrorCount);
if (args.debug)
{
console.Error("Write error: ns={0} set={1} key={2} bin={3} exception={4}",
key.ns, key.setName, key.userKey, bin.name, ae.Message);
}
}
}
protected void OnWriteFailure(Key key, Bin bin, Exception e)
{
Interlocked.Increment(ref shared.writeErrorCount);
if (args.debug)
{
console.Error("Write error: ns={0} set={1} key={2} bin={3} exception={4}",
key.ns, key.setName, key.userKey, bin.name, e.Message);
}
}
protected void OnReadSuccess()
{
Interlocked.Increment(ref shared.readCount);
}
protected void OnReadSuccess(double elapsed)
{
Interlocked.Increment(ref shared.readCount);
shared.readLatency.Add(elapsed);
}
protected void OnReadFailure(Key key, AerospikeException ae)
{
if (ae.Result == ResultCode.TIMEOUT)
{
Interlocked.Increment(ref shared.readTimeoutCount);
}
else
{
Interlocked.Increment(ref shared.readErrorCount);
if (args.debug)
{
console.Error("Read error: ns={0} set={1} key={2} exception={3}",
key.ns, key.setName, key.userKey, ae.Message);
}
}
}
protected void OnReadFailure(Key key, Exception e)
{
Interlocked.Increment(ref shared.readErrorCount);
if (args.debug)
{
console.Error("Read error: ns={0} set={1} key={2} exception={3}",
key.ns, key.setName, key.userKey, e.Message);
}
}
protected abstract void WriteRecord(WritePolicy policy, Key key, Bin bin);
protected abstract void ReadRecord(Policy policy, Key key, string binName);
}
}
| |
using System;
using System.Collections;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using umbraco.BasePages;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.web;
using umbraco.editorControls.tinymce;
using umbraco.editorControls.tinyMCE3.webcontrol;
using umbraco.editorControls.wysiwyg;
using umbraco.interfaces;
using Umbraco.Core.IO;
using umbraco.presentation;
using umbraco.uicontrols;
namespace umbraco.editorControls.tinyMCE3
{
[Obsolete("IDataType and all other references to the legacy property editors are no longer used this will be removed from the codebase in future versions")]
public class TinyMCE : TinyMCEWebControl, IDataEditor, IMenuElement
{
private readonly string _activateButtons = "";
private readonly string _advancedUsers = "";
private readonly SortedList _buttons = new SortedList();
private readonly IData _data;
private readonly string _disableButtons = "help,visualaid,";
private readonly string _editorButtons = "";
private readonly bool _enableContextMenu;
private readonly bool _fullWidth;
private readonly int _height;
private readonly SortedList _mceButtons = new SortedList();
private readonly ArrayList _menuIcons = new ArrayList();
private readonly bool _showLabel;
private readonly ArrayList _stylesheets = new ArrayList();
private readonly int _width;
private readonly int m_maxImageWidth = 500;
private bool _isInitialized;
private string _plugins = "";
public TinyMCE(IData Data, string Configuration)
{
_data = Data;
try
{
string[] configSettings = Configuration.Split("|".ToCharArray());
if (configSettings.Length > 0)
{
_editorButtons = configSettings[0];
if (configSettings.Length > 1)
if (configSettings[1] == "1")
_enableContextMenu = true;
if (configSettings.Length > 2)
_advancedUsers = configSettings[2];
if (configSettings.Length > 3)
{
if (configSettings[3] == "1")
_fullWidth = true;
else if (configSettings[4].Split(',').Length > 1)
{
_width = int.Parse(configSettings[4].Split(',')[0]);
_height = int.Parse(configSettings[4].Split(',')[1]);
}
}
// default width/height
if (_width < 1)
_width = 500;
if (_height < 1)
_height = 400;
// add stylesheets
if (configSettings.Length > 4)
{
foreach (string s in configSettings[5].Split(",".ToCharArray()))
_stylesheets.Add(s);
}
if (configSettings.Length > 6 && configSettings[6] != "")
_showLabel = bool.Parse(configSettings[6]);
if (configSettings.Length > 7 && configSettings[7] != "")
m_maxImageWidth = int.Parse(configSettings[7]);
// sizing
if (!_fullWidth)
{
config.Add("width", _width.ToString());
config.Add("height", _height.ToString());
}
if (_enableContextMenu)
_plugins += ",contextmenu";
// If the editor is used in umbraco, use umbraco's own toolbar
bool onFront = false;
if (GlobalSettings.RequestIsInUmbracoApplication(HttpContext.Current))
{
config.Add("theme_umbraco_toolbar_location", "external");
config.Add("skin", "umbraco");
config.Add("inlinepopups_skin ", "umbraco");
}
else
{
onFront = true;
config.Add("theme_umbraco_toolbar_location", "top");
}
// load plugins
IDictionaryEnumerator pluginEnum = tinyMCEConfiguration.Plugins.GetEnumerator();
while (pluginEnum.MoveNext())
{
var plugin = (tinyMCEPlugin)pluginEnum.Value;
if (plugin.UseOnFrontend || (!onFront && !plugin.UseOnFrontend))
_plugins += "," + plugin.Name;
}
// add the umbraco overrides to the end
// NB: It is !!REALLY IMPORTANT!! that these plugins are added at the end
// as they make runtime modifications to default plugins, so require
// those plugins to be loaded first.
_plugins += ",umbracopaste,umbracolink,umbracocontextmenu";
if (_plugins.StartsWith(","))
_plugins = _plugins.Substring(1, _plugins.Length - 1);
if (_plugins.EndsWith(","))
_plugins = _plugins.Substring(0, _plugins.Length - 1);
config.Add("plugins", _plugins);
// Check advanced settings
if (UmbracoEnsuredPage.CurrentUser != null && ("," + _advancedUsers + ",").IndexOf("," + UmbracoEnsuredPage.CurrentUser.UserType.Id + ",") >
-1)
config.Add("umbraco_advancedMode", "true");
else
config.Add("umbraco_advancedMode", "false");
// Check maximum image width
config.Add("umbraco_maximumDefaultImageWidth", m_maxImageWidth.ToString());
// Styles
string cssFiles = String.Empty;
string styles = string.Empty;
foreach (string styleSheetId in _stylesheets)
{
if (styleSheetId.Trim() != "")
try
{
var s = StyleSheet.GetStyleSheet(int.Parse(styleSheetId), false, false);
if (s.nodeObjectType == StyleSheet.ModuleObjectType)
{
cssFiles += IOHelper.ResolveUrl(SystemDirectories.Css + "/" + s.Text + ".css");
foreach (StylesheetProperty p in s.Properties)
{
if (styles != string.Empty)
{
styles += ";";
}
if (p.Alias.StartsWith("."))
styles += p.Text + "=" + p.Alias;
else
styles += p.Text + "=" + p.Alias;
}
cssFiles += ",";
}
}
catch (Exception ee)
{
LogHelper.Error<TinyMCE>("Error adding stylesheet to tinymce Id:" + styleSheetId, ee);
}
}
// remove any ending comma (,)
if (!string.IsNullOrEmpty(cssFiles))
{
cssFiles = cssFiles.TrimEnd(',');
}
// language
string userLang = (UmbracoEnsuredPage.CurrentUser != null) ?
(User.GetCurrent().Language.Contains("-") ?
User.GetCurrent().Language.Substring(0, User.GetCurrent().Language.IndexOf("-")) : User.GetCurrent().Language)
: "en";
config.Add("language", userLang);
config.Add("content_css", cssFiles);
config.Add("theme_umbraco_styles", styles);
// Add buttons
IDictionaryEnumerator ide = tinyMCEConfiguration.Commands.GetEnumerator();
while (ide.MoveNext())
{
var cmd = (tinyMCECommand)ide.Value;
if (_editorButtons.IndexOf("," + cmd.Alias + ",") > -1)
_activateButtons += cmd.Alias + ",";
else
_disableButtons += cmd.Alias + ",";
}
if (_activateButtons.Length > 0)
_activateButtons = _activateButtons.Substring(0, _activateButtons.Length - 1);
if (_disableButtons.Length > 0)
_disableButtons = _disableButtons.Substring(0, _disableButtons.Length - 1);
// Add buttons
initButtons();
_activateButtons = "";
int separatorPriority = 0;
ide = _mceButtons.GetEnumerator();
while (ide.MoveNext())
{
string mceCommand = ide.Value.ToString();
var curPriority = (int)ide.Key;
// Check priority
if (separatorPriority > 0 &&
Math.Floor(decimal.Parse(curPriority.ToString()) / 10) >
Math.Floor(decimal.Parse(separatorPriority.ToString()) / 10))
_activateButtons += "separator,";
_activateButtons += mceCommand + ",";
separatorPriority = curPriority;
}
config.Add("theme_umbraco_buttons1", _activateButtons);
config.Add("theme_umbraco_buttons2", "");
config.Add("theme_umbraco_buttons3", "");
config.Add("theme_umbraco_toolbar_align", "left");
config.Add("theme_umbraco_disable", _disableButtons);
config.Add("theme_umbraco_path ", "true");
config.Add("extended_valid_elements", "div[*]");
config.Add("document_base_url", "/");
config.Add("relative_urls", "false");
config.Add("remove_script_host", "true");
config.Add("event_elements", "div");
config.Add("paste_auto_cleanup_on_paste", "true");
config.Add("valid_elements",
tinyMCEConfiguration.ValidElements.Substring(1,
tinyMCEConfiguration.ValidElements.Length -
2));
config.Add("invalid_elements", tinyMCEConfiguration.InvalidElements);
// custom commands
if (tinyMCEConfiguration.ConfigOptions.Count > 0)
{
ide = tinyMCEConfiguration.ConfigOptions.GetEnumerator();
while (ide.MoveNext())
{
config.Add(ide.Key.ToString(), ide.Value.ToString());
}
}
//if (HttpContext.Current.Request.Path.IndexOf(Umbraco.Core.IO.SystemDirectories.Umbraco) > -1)
// config.Add("language", User.GetUser(BasePage.GetUserId(BasePage.umbracoUserContextID)).Language);
//else
// config.Add("language", System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName);
if (_fullWidth)
{
config.Add("auto_resize", "true");
base.Columns = 30;
base.Rows = 30;
}
else
{
base.Columns = 0;
base.Rows = 0;
}
EnableViewState = false;
}
}
catch (Exception ex)
{
throw new ArgumentException("Incorrect TinyMCE configuration.", "Configuration", ex);
}
}
#region TreatAsRichTextEditor
public virtual bool TreatAsRichTextEditor
{
get { return false; }
}
#endregion
#region ShowLabel
public virtual bool ShowLabel
{
get { return _showLabel; }
}
#endregion
#region Editor
public Control Editor
{
get { return this; }
}
#endregion
#region Save()
public virtual void Save()
{
string parsedString = base.Text.Trim();
string parsedStringForTinyMce = parsedString;
if (parsedString != string.Empty)
{
parsedString = replaceMacroTags(parsedString).Trim();
// tidy html - refactored, see #30534
if (UmbracoConfig.For.UmbracoSettings().Content.TidyEditorContent)
{
// always wrap in a <div> - using <p> was a bad idea
parsedString = "<div>" + parsedString + "</div>";
string tidyTxt = library.Tidy(parsedString, false);
if (tidyTxt != "[error]")
{
parsedString = tidyTxt;
// remove pesky \r\n, and other empty chars
parsedString = parsedString.Trim(new char[] { '\r', '\n', '\t', ' ' });
// compensate for breaking macro tags by tidy (?)
parsedString = parsedString.Replace("/?>", "/>");
// remove the wrapping <div> - safer to check that it is still here
if (parsedString.StartsWith("<div>") && parsedString.EndsWith("</div>"))
parsedString = parsedString.Substring("<div>".Length, parsedString.Length - "<div></div>".Length);
}
}
// rescue umbraco tags
parsedString = parsedString.Replace("|||?", "<?").Replace("/|||", "/>").Replace("|*|", "\"");
// fix images
parsedString = tinyMCEImageHelper.cleanImages(parsedString);
// parse current domain and instances of slash before anchor (to fix anchor bug)
// NH 31-08-2007
if (HttpContext.Current.Request.ServerVariables != null)
{
parsedString = parsedString.Replace(helper.GetBaseUrl(HttpContext.Current) + "/#", "#");
parsedString = parsedString.Replace(helper.GetBaseUrl(HttpContext.Current), "");
}
// if a paragraph is empty, remove it
if (parsedString.ToLower() == "<p></p>")
parsedString = "";
// save string after all parsing is done, but before CDATA replacement - to put back into TinyMCE
parsedStringForTinyMce = parsedString;
//Allow CDATA nested into RTE without exceptions
// GE 2012-01-18
parsedString = parsedString.Replace("<![CDATA[", "<!--CDATAOPENTAG-->").Replace("]]>", "<!--CDATACLOSETAG-->");
}
_data.Value = parsedString;
// update internal webcontrol value with parsed result
base.Text = parsedStringForTinyMce;
}
#endregion
public virtual string Plugins
{
get { return _plugins; }
set { _plugins = value; }
}
public object[] MenuIcons
{
get
{
initButtons();
var tempIcons = new object[_menuIcons.Count];
for (int i = 0; i < _menuIcons.Count; i++)
tempIcons[i] = _menuIcons[i];
return tempIcons;
}
}
#region IMenuElement Members
public string ElementName
{
get { return "div"; }
}
public string ElementIdPreFix
{
get { return "umbTinymceMenu"; }
}
public string ElementClass
{
get { return "tinymceMenuBar"; }
}
public int ExtraMenuWidth
{
get
{
initButtons();
return _buttons.Count * 40 + 300;
}
}
#endregion
protected override void OnLoad(EventArgs e)
{
try
{
// add current page info
base.NodeId = ((cms.businesslogic.datatype.DefaultData)_data).NodeId;
if (NodeId != 0)
{
base.VersionId = ((cms.businesslogic.datatype.DefaultData)_data).Version;
config.Add("theme_umbraco_pageId", base.NodeId.ToString());
config.Add("theme_umbraco_versionId", base.VersionId.ToString());
// we'll need to make an extra check for the liveediting as that value is set after the constructor have initialized
config.Add("umbraco_toolbar_id",
ElementIdPreFix +
((cms.businesslogic.datatype.DefaultData)_data).PropertyId);
}
else
{
// this is for use when tinymce is used for non default Umbraco pages
config.Add("umbraco_toolbar_id",
ElementIdPreFix + "_" + this.ClientID);
}
}
catch
{
// Empty catch as this is caused by the document doesn't exists yet,
// like when using this on an autoform, partly replaced by the if/else check on nodeId above though
}
base.OnLoad(e);
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
//Allow CDATA nested into RTE without exceptions
// GE 2012-01-18
if (_data != null && _data.Value != null)
base.Text = _data.Value.ToString().Replace("<!--CDATAOPENTAG-->", "<![CDATA[").Replace("<!--CDATACLOSETAG-->", "]]>");
}
private string replaceMacroTags(string text)
{
while (findStartTag(text) > -1)
{
string result = text.Substring(findStartTag(text), findEndTag(text) - findStartTag(text));
text = text.Replace(result, generateMacroTag(result));
}
return text;
}
private string generateMacroTag(string macroContent)
{
string macroAttr = macroContent.Substring(5, macroContent.IndexOf(">") - 5);
string macroTag = "|||?UMBRACO_MACRO ";
Hashtable attributes = ReturnAttributes(macroAttr);
IDictionaryEnumerator ide = attributes.GetEnumerator();
while (ide.MoveNext())
{
if (ide.Key.ToString().IndexOf("umb_") != -1)
{
// Hack to compensate for Firefox adding all attributes as lowercase
string orgKey = ide.Key.ToString();
if (orgKey == "umb_macroalias")
orgKey = "umb_macroAlias";
macroTag += orgKey.Substring(4, orgKey.Length - 4) + "=|*|" +
ide.Value.ToString().Replace("\\r\\n", Environment.NewLine) + "|*| ";
}
}
macroTag += "/|||";
return macroTag;
}
[Obsolete("Has been superceded by Umbraco.Core.XmlHelper.GetAttributesFromElement")]
public static Hashtable ReturnAttributes(String tag)
{
var h = new Hashtable();
foreach (var i in Umbraco.Core.XmlHelper.GetAttributesFromElement(tag))
{
h.Add(i.Key, i.Value);
}
return h;
}
private int findStartTag(string text)
{
string temp = "";
text = text.ToLower();
if (text.IndexOf("ismacro=\"true\"") > -1)
{
temp = text.Substring(0, text.IndexOf("ismacro=\"true\""));
return temp.LastIndexOf("<");
}
return -1;
}
private int findEndTag(string text)
{
string find = "<!-- endumbmacro -->";
int endMacroIndex = text.ToLower().IndexOf(find);
string tempText = text.ToLower().Substring(endMacroIndex + find.Length,
text.Length - endMacroIndex - find.Length);
int finalEndPos = 0;
while (tempText.Length > 5)
if (tempText.Substring(finalEndPos, 6) == "</div>")
break;
else
finalEndPos++;
return endMacroIndex + find.Length + finalEndPos + 6;
}
private void initButtons()
{
if (!_isInitialized)
{
_isInitialized = true;
// Add icons for the editor control:
// Html
// Preview
// Style picker, showstyles
// Bold, italic, Text Gen
// Align: left, center, right
// Lists: Bullet, Ordered, indent, undo indent
// Link, Anchor
// Insert: Image, macro, table, formular
foreach (string button in _activateButtons.Split(','))
{
if (button.Trim() != "")
{
try
{
var cmd = (tinyMCECommand)tinyMCEConfiguration.Commands[button];
string appendValue = "";
if (cmd.Value != "")
appendValue = ", '" + cmd.Value + "'";
_mceButtons.Add(cmd.Priority, cmd.Command);
_buttons.Add(cmd.Priority,
new editorButton(cmd.Alias, ui.Text("buttons", cmd.Alias, null), cmd.Icon,
"tinyMCE.execInstanceCommand('" + ClientID + "', '" +
cmd.Command + "', " + cmd.UserInterface + appendValue + ")"));
}
catch (Exception ee)
{
LogHelper.Error<TinyMCE>(string.Format("TinyMCE: Error initializing button '{0}'", button), ee);
}
}
}
// add save icon
int separatorPriority = 0;
IDictionaryEnumerator ide = _buttons.GetEnumerator();
while (ide.MoveNext())
{
object buttonObj = ide.Value;
var curPriority = (int)ide.Key;
// Check priority
if (separatorPriority > 0 &&
Math.Floor(decimal.Parse(curPriority.ToString()) / 10) >
Math.Floor(decimal.Parse(separatorPriority.ToString()) / 10))
_menuIcons.Add("|");
try
{
var e = (editorButton)buttonObj;
MenuIconI menuItem = new MenuIconClass();
menuItem.OnClickCommand = e.onClickCommand;
menuItem.ImageURL = e.imageUrl;
menuItem.AltText = e.alttag;
menuItem.ID = e.id;
_menuIcons.Add(menuItem);
}
catch
{
}
separatorPriority = curPriority;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
namespace System.Net.Http
{
internal class WinHttpResponseStream : Stream
{
private volatile bool _disposed;
private readonly WinHttpRequestState _state;
// TODO (Issue 2505): temporary pinned buffer caches of 1 item. Will be replaced by PinnableBufferCache.
private GCHandle _cachedReceivePinnedBuffer = new GCHandle();
internal WinHttpResponseStream(WinHttpRequestState state)
{
_state = state;
}
public override bool CanRead
{
get
{
return !_disposed;
}
}
public override bool CanSeek
{
get
{
return false;
}
}
public override bool CanWrite
{
get
{
return false;
}
}
public override long Length
{
get
{
CheckDisposed();
throw new NotSupportedException();
}
}
public override long Position
{
get
{
CheckDisposed();
throw new NotSupportedException();
}
set
{
CheckDisposed();
throw new NotSupportedException();
}
}
public override void Flush()
{
// Nothing to do.
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken token)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if (count > buffer.Length - offset)
{
throw new ArgumentException("buffer");
}
if (token.IsCancellationRequested)
{
return Task.FromCanceled<int>(token);
}
CheckDisposed();
if (_state.TcsReadFromResponseStream != null && !_state.TcsReadFromResponseStream.Task.IsCompleted)
{
throw new InvalidOperationException(SR.net_http_no_concurrent_io_allowed);
}
// TODO (Issue 2505): replace with PinnableBufferCache.
if (!_cachedReceivePinnedBuffer.IsAllocated || _cachedReceivePinnedBuffer.Target != buffer)
{
if (_cachedReceivePinnedBuffer.IsAllocated)
{
_cachedReceivePinnedBuffer.Free();
}
_cachedReceivePinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);
}
_state.TcsReadFromResponseStream =
new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
_state.TcsQueryDataAvailable =
new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
_state.TcsQueryDataAvailable.Task.ContinueWith((previousTask) =>
{
if (previousTask.IsFaulted)
{
_state.TcsReadFromResponseStream.TrySetException(previousTask.Exception.InnerException);
}
else if (previousTask.IsCanceled || token.IsCancellationRequested)
{
_state.TcsReadFromResponseStream.TrySetCanceled(token);
}
else
{
int bytesToRead;
int bytesAvailable = previousTask.Result;
if (bytesAvailable > count)
{
bytesToRead = count;
}
else
{
bytesToRead = bytesAvailable;
}
lock (_state.Lock)
{
if (!Interop.WinHttp.WinHttpReadData(
_state.RequestHandle,
Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset),
(uint)bytesToRead,
IntPtr.Zero))
{
_state.TcsReadFromResponseStream.TrySetException(
new IOException(SR.net_http_io_read, WinHttpException.CreateExceptionUsingLastError()));
}
}
}
},
CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
// TODO: Issue #2165. Register callback on cancellation token to cancel WinHTTP operation.
lock (_state.Lock)
{
if (!Interop.WinHttp.WinHttpQueryDataAvailable(_state.RequestHandle, IntPtr.Zero))
{
_state.TcsReadFromResponseStream.TrySetException(
new IOException(SR.net_http_io_read, WinHttpException.CreateExceptionUsingLastError()));
}
}
return _state.TcsReadFromResponseStream.Task;
}
public override int Read(byte[] buffer, int offset, int count)
{
return ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
}
public override long Seek(long offset, SeekOrigin origin)
{
CheckDisposed();
throw new NotSupportedException();
}
public override void SetLength(long value)
{
CheckDisposed();
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
CheckDisposed();
throw new NotSupportedException();
}
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
if (disposing)
{
// TODO (Issue 2508): Pinned buffers must be released in the callback, when it is guaranteed no further
// operations will be made to the send/receive buffers.
if (_cachedReceivePinnedBuffer.IsAllocated)
{
_cachedReceivePinnedBuffer.Free();
}
if (_state.RequestHandle != null)
{
_state.RequestHandle.Dispose();
_state.RequestHandle = null;
}
}
}
base.Dispose(disposing);
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Rssdp.Infrastructure
{
/// <summary>
/// Provides the platform independent logic for publishing SSDP devices (notifications and search responses).
/// </summary>
public abstract class SsdpDevicePublisherBase : DisposableManagedObjectBase, ISsdpDevicePublisher
{
#region Fields & Constants
private ISsdpCommunicationsServer _CommsServer;
private string _OSName;
private string _OSVersion;
private ISsdpLogger _Log;
private bool _SupportPnpRootDevice;
private SsdpStandardsMode _StandardsMode;
private IList<SsdpRootDevice> _Devices;
private ReadOnlyEnumerable<SsdpRootDevice> _ReadOnlyDevices;
private System.Threading.Timer _RebroadcastAliveNotificationsTimer;
private TimeSpan _RebroadcastAliveNotificationsTimeSpan;
private DateTime _LastNotificationTime;
private IDictionary<string, SearchRequest> _RecentSearchRequests;
private IUpnpDeviceValidator _DeviceValidator;
private Random _Random;
private TimeSpan _MinCacheTime;
private TimeSpan _NotificationBroadcastInterval;
private const string ServerVersion = "1.0";
#endregion
#region Message Format Constants
private const string DeviceSearchResponseMessageFormat = @"HTTP/1.1 200 OK
EXT:
DATE: {7}
{0}
ST: {1}
SERVER: {4}/{5} UPnP/1.0 RSSDP/{6}
USN: {2}
LOCATION: {3}{8}
"; //Blank line at end important, do not remove.
private const string AliveNotificationMessageFormat = @"NOTIFY * HTTP/1.1
HOST: {8}:{9}
DATE: {7}
NT: {0}
NTS: ssdp:alive
SERVER: {4}/{5} UPnP/1.0 RSSDP/{6}
USN: {1}
LOCATION: {2}
{3}{10}
"; //Blank line at end important, do not remove.
private const string ByeByeNotificationMessageFormat = @"NOTIFY * HTTP/1.1
HOST: {6}:{7}
DATE: {5}
NT: {0}
NTS: ssdp:byebye
SERVER: {2}/{3} UPnP/1.0 RSSDP/{4}
USN: {1}
";
#endregion
#region Constructors
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="communicationsServer">The <see cref="ISsdpCommunicationsServer"/> implementation, used to send and receive SSDP network messages.</param>
/// <param name="osName">Then name of the operating system running the server.</param>
/// <param name="osVersion">The version of the operating system running the server.</param>
protected SsdpDevicePublisherBase(ISsdpCommunicationsServer communicationsServer, string osName, string osVersion) : this(communicationsServer, osName, osVersion, NullLogger.Instance)
{
}
/// <summary>
/// Full constructor.
/// </summary>
/// <param name="communicationsServer">The <see cref="ISsdpCommunicationsServer"/> implementation, used to send and receive SSDP network messages.</param>
/// <param name="osName">Then name of the operating system running the server.</param>
/// <param name="osVersion">The version of the operating system running the server.</param>
/// <param name="log">An implementation of <see cref="ISsdpLogger"/> to be used for logging activity. May be null, in which case no logging is performed.</param>
protected SsdpDevicePublisherBase(ISsdpCommunicationsServer communicationsServer, string osName, string osVersion, ISsdpLogger log)
{
if (communicationsServer == null) throw new ArgumentNullException("communicationsServer");
if (osName == null) throw new ArgumentNullException("osName");
if (osName.Length == 0) throw new ArgumentException("osName cannot be an empty string.", "osName");
if (osVersion == null) throw new ArgumentNullException("osVersion");
if (osVersion.Length == 0) throw new ArgumentException("osVersion cannot be an empty string.", "osName");
_Log = log ?? NullLogger.Instance;
_SupportPnpRootDevice = true;
_Devices = new List<SsdpRootDevice>();
_ReadOnlyDevices = new ReadOnlyEnumerable<SsdpRootDevice>(_Devices);
_RecentSearchRequests = new Dictionary<string, SearchRequest>(StringComparer.OrdinalIgnoreCase);
_Random = new Random();
_DeviceValidator = new Upnp10DeviceValidator(); //Should probably inject this later, but for now we only support 1.0.
_CommsServer = communicationsServer;
_CommsServer.RequestReceived += CommsServer_RequestReceived;
_OSName = osName;
_OSVersion = osVersion;
_Log.LogInfo("Publisher started.");
_CommsServer.BeginListeningForBroadcasts();
_Log.LogInfo("Publisher started listening for broadcasts.");
}
#endregion
#region Public Methods
/// <summary>
/// Adds a device (and it's children) to the list of devices being published by this server, making them discoverable to SSDP clients.
/// </summary>
/// <remarks>
/// <para>Adding a device causes "alive" notification messages to be sent immediately, or very soon after. Ensure your device/description service is running before adding the device object here.</para>
/// <para>Devices added here with a non-zero cache life time will also have notifications broadcast periodically.</para>
/// <para>This method ignores duplicate device adds (if the same device instance is added multiple times, the second and subsequent add calls do nothing).</para>
/// </remarks>
/// <param name="device">The <see cref="SsdpDevice"/> instance to add.</param>
/// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="device"/> argument is null.</exception>
/// <exception cref="System.InvalidOperationException">Thrown if the <paramref name="device"/> contains property values that are not acceptable to the UPnP 1.0 specification.</exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "t", Justification = "Capture task to local variable supresses compiler warning, but task is not really needed.")]
public void AddDevice(SsdpRootDevice device)
{
if (device == null) throw new ArgumentNullException("device");
ThrowIfDisposed();
_DeviceValidator.ThrowIfDeviceInvalid(device);
TimeSpan minCacheTime = TimeSpan.Zero;
bool wasAdded = false;
lock (_Devices)
{
if (!_Devices.Contains(device))
{
_Devices.Add(device);
wasAdded = true;
minCacheTime = GetMinimumNonZeroCacheLifetime();
}
}
if (wasAdded)
{
LogDeviceEvent("Device added", device);
_MinCacheTime = minCacheTime;
ConnectToDeviceEvents(device);
SetRebroadcastAliveNotificationsTimer(minCacheTime);
SendAliveNotifications(device, true);
}
else
LogDeviceEventWarning("AddDevice ignored (duplicate add)", device);
}
/// <summary>
/// Removes a device (and it's children) from the list of devices being published by this server, making them undiscoverable.
/// </summary>
/// <remarks>
/// <para>Removing a device causes "byebye" notification messages to be sent immediately, advising clients of the device/service becoming unavailable. We recommend removing the device from the published list before shutting down the actual device/service, if possible.</para>
/// <para>This method does nothing if the device was not found in the collection.</para>
/// </remarks>
/// <param name="device">The <see cref="SsdpDevice"/> instance to add.</param>
/// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="device"/> argument is null.</exception>
public void RemoveDevice(SsdpRootDevice device)
{
if (device == null) throw new ArgumentNullException("device");
ThrowIfDisposed();
bool wasRemoved = false;
TimeSpan minCacheTime = TimeSpan.Zero;
lock (_Devices)
{
if (_Devices.Contains(device))
{
_Devices.Remove(device);
wasRemoved = true;
minCacheTime = GetMinimumNonZeroCacheLifetime();
}
}
if (wasRemoved)
{
_MinCacheTime = minCacheTime;
DisconnectFromDeviceEvents(device);
LogDeviceEvent("Device Removed", device);
SendByeByeNotifications(device, true);
SetRebroadcastAliveNotificationsTimer(minCacheTime);
}
else
LogDeviceEventWarning("RemoveDevice ignored (device not in publisher)", device);
}
#endregion
#region Public Properties
/// <summary>
/// Returns a reference to the injected <see cref="ISsdpLogger"/> instance.
/// </summary>
/// <remarks>
/// <para>Should never return null. If null was injected a reference to an internal null logger should be returned.</para>
/// </remarks>
protected ISsdpLogger Log
{
get { return _Log; }
}
/// <summary>
/// Returns a read only list of devices being published by this instance.
/// </summary>
public IEnumerable<SsdpRootDevice> Devices
{
get
{
return _ReadOnlyDevices;
}
}
/// <summary>
/// If true (default) treats root devices as both upnp:rootdevice and pnp:rootdevice types.
/// </summary>
/// <remarks>
/// <para>Enabling this option will cause devices to show up in Microsoft Windows Explorer's network screens (if discovery is enabled etc.). Windows Explorer appears to search only for pnp:rootdeivce and not upnp:rootdevice.</para>
/// <para>If false, the system will only use upnp:rootdevice for notifiation broadcasts and and search responses, which is correct according to the UPnP/SSDP spec.</para>
/// </remarks>
[Obsolete("Set StandardsMode to SsdpStandardsMode.Relaxed instead.")]
public bool SupportPnpRootDevice
{
get { return _SupportPnpRootDevice; }
set
{
if (_SupportPnpRootDevice != value)
{
_SupportPnpRootDevice = value;
_Log.LogInfo("SupportPnpRootDevice set to " + value.ToString());
}
}
}
/// <summary>
/// Sets or returns a value from the <see cref="SsdpStandardsMode"/> controlling how strictly the publisher obeys the SSDP standard.
/// </summary>
/// <remarks>
/// <para>Using relaxed mode will process search requests even if the MX header is missing.</para>
/// </remarks>
public SsdpStandardsMode StandardsMode
{
get { return _StandardsMode; }
set
{
if (_StandardsMode != value)
{
_StandardsMode = value;
_Log.LogInfo("StandardsMode set to " + value.ToString());
}
}
}
/// <summary>
/// Sets or returns a fixed interval at which alive notifications for services exposed by this publisher instance are broadcast.
/// </summary>
/// <remarks>
/// <para>If this is set to <see cref="TimeSpan.Zero"/> then the system will follow the process recommended
/// by the SSDP spec and calculate a randomised interval based on the cache life times of the published services.
/// The default and recommended value is TimeSpan.Zero.
/// </para>
/// <para>While (zero and) any positive <see cref="TimeSpan"/> value are allowed, the SSDP specification says
/// notifications should not be broadcast more often than 15 minutes. If you wish to remain compatible with the SSDP
/// specification, do not set this property to a value greater than zero but less than 15 minutes.
/// </para>
/// </remarks>
public TimeSpan NotificationBroadcastInterval
{
get { return _NotificationBroadcastInterval; }
set
{
if (value.TotalSeconds < 0) throw new ArgumentException("Cannot be less than zero.", nameof(value));
if (_NotificationBroadcastInterval != value)
{
_NotificationBroadcastInterval = value;
_Log.LogInfo("NotificationBroadcastInterval set to " + value.ToString());
SetRebroadcastAliveNotificationsTimer(_MinCacheTime);
}
}
}
#endregion
#region Overrides
/// <summary>
/// Stops listening for requests, stops sending periodic broadcasts, disposes all internal resources.
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
_Log.LogInfo("Publisher disposed.");
DisposeRebroadcastTimer();
var commsServer = _CommsServer;
_CommsServer = null;
if (commsServer != null)
{
commsServer.RequestReceived -= this.CommsServer_RequestReceived;
if (!commsServer.IsShared)
commsServer.Dispose();
}
foreach (var device in this.Devices)
{
DisconnectFromDeviceEvents(device);
}
_RecentSearchRequests = null;
}
}
#endregion
#region Private Methods
#region Search Related Methods
private void ProcessSearchRequest(string mx, string searchTarget, UdpEndPoint endPoint)
{
if (String.IsNullOrEmpty(searchTarget))
{
_Log.LogWarning(String.Format("Invalid search request received From {0}, Target is null/empty.", endPoint.ToString()));
return;
}
_Log.LogInfo(String.Format("Search Request Received From {0}, Target = {1}", endPoint.ToString(), searchTarget));
if (IsDuplicateSearchRequest(searchTarget, endPoint))
{
Log.LogWarning("Search Request is Duplicate, ignoring.");
return;
}
//Wait on random interval up to MX, as per SSDP spec.
//Also, as per UPnP 1.1/SSDP spec ignore missing/bank MX header (strict mode only). If over 120, assume random value between 0 and 120.
//Using 16 as minimum as that's often the minimum system clock frequency anyway.
int maxWaitInterval = 0;
if (String.IsNullOrEmpty(mx))
{
//Windows Explorer is poorly behaved and doesn't supply an MX header value.
if (IsWindowsExplorerSupportEnabled)
mx = "1";
else
{
_Log.LogWarning("Search Request ignored due to missing MX header. Set StandardsMode to relaxed to respond to these requests.");
return;
}
}
if (!Int32.TryParse(mx, out maxWaitInterval) || maxWaitInterval <= 0) return;
if (maxWaitInterval > 120)
maxWaitInterval = _Random.Next(0, 120);
//Do not block synchronously as that may tie up a threadpool thread for several seconds.
TaskEx.Delay(_Random.Next(16, (maxWaitInterval * 1000))).ContinueWith((parentTask) =>
{
//Copying devices to local array here to avoid threading issues/enumerator exceptions.
IEnumerable<SsdpDevice> devices = null;
devices = GetDevicesMatchingSearchTarget(searchTarget, devices);
if (devices != null)
SendSearchResponses(searchTarget, endPoint, devices);
else
_Log.LogWarning("Sending search responses for 0 devices (no matching targets).");
});
}
private IEnumerable<SsdpDevice> GetDevicesMatchingSearchTarget(string searchTarget, IEnumerable<SsdpDevice> devices)
{
lock (_Devices)
{
if (String.Compare(SsdpConstants.SsdpDiscoverAllSTHeader, searchTarget, StringComparison.OrdinalIgnoreCase) == 0)
devices = GetAllDevicesAsFlatEnumerable().ToArray();
else if (String.Compare(SsdpConstants.UpnpDeviceTypeRootDevice, searchTarget, StringComparison.OrdinalIgnoreCase) == 0 || (IsWindowsExplorerSupportEnabled && String.Compare(SsdpConstants.PnpDeviceTypeRootDevice, searchTarget, StringComparison.OrdinalIgnoreCase) == 0))
devices = _Devices.ToArray();
else if (searchTarget.Trim().StartsWith("uuid:", StringComparison.OrdinalIgnoreCase))
{
devices = (
from device
in GetAllDevicesAsFlatEnumerable()
where String.Compare(device.Uuid, searchTarget.Substring(5), StringComparison.OrdinalIgnoreCase) == 0
select device
).ToArray();
}
else if (searchTarget.StartsWith("urn:", StringComparison.OrdinalIgnoreCase))
{
if (searchTarget.Contains(":service:"))
{
devices =
(
from device in GetAllDevicesAsFlatEnumerable()
where
(
from s in
device.Services
where String.Compare(s.FullServiceType, searchTarget, StringComparison.OrdinalIgnoreCase) == 0
select s
).Any()
select device
).ToArray();
}
else
{
devices =
(
from device
in GetAllDevicesAsFlatEnumerable()
where String.Compare(device.FullDeviceType, searchTarget, StringComparison.OrdinalIgnoreCase) == 0
select device
).ToArray();
}
}
}
return devices;
}
private bool IsWindowsExplorerSupportEnabled
{
get
{
#pragma warning disable CS0618 // Type or member is obsolete
return SupportPnpRootDevice || IsRelaxedStandardsMode;
#pragma warning restore CS0618 // Type or member is obsolete
}
}
private bool IsRelaxedStandardsMode
{
get
{
return this.StandardsMode != SsdpStandardsMode.Strict;
}
}
private IEnumerable<SsdpDevice> GetAllDevicesAsFlatEnumerable()
{
return _Devices.Union(_Devices.SelectManyRecursive<SsdpDevice>((d) => d.Devices));
}
private void SendSearchResponses(string searchTarget, UdpEndPoint endPoint, IEnumerable<SsdpDevice> devices)
{
_Log.LogInfo(String.Format("Sending search (target = {1}) responses for {0} devices", devices.Count(), searchTarget));
if (searchTarget.Contains(":service:"))
{
foreach (var device in devices)
{
SendServiceSearchResponses(device, searchTarget, endPoint);
}
}
else
{
foreach (var device in devices)
{
SendDeviceSearchResponses(device, searchTarget, endPoint);
}
}
}
private void SendDeviceSearchResponses(SsdpDevice device, string searchTarget, UdpEndPoint endPoint)
{
//http://www.upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.0-20080424.pdf - page 21
//For ssdp:all - Respond 3+2d+k times for a root device with d embedded devices and s embedded services but only k distinct service types
//Root devices - Respond once (special handling when in related/Win Explorer support mode)
//Udn (uuid) - Response once
//Device type - response once
//Service type - respond once per service type
bool isRootDevice = (device as SsdpRootDevice) != null;
bool sendAll = searchTarget == SsdpConstants.SsdpDiscoverAllSTHeader;
bool sendRootDevices = searchTarget == SsdpConstants.UpnpDeviceTypeRootDevice || searchTarget == SsdpConstants.PnpDeviceTypeRootDevice;
if (isRootDevice && (sendAll || sendRootDevices))
{
SendSearchResponse(SsdpConstants.UpnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), endPoint);
if (IsWindowsExplorerSupportEnabled)
SendSearchResponse(SsdpConstants.PnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.PnpDeviceTypeRootDevice), endPoint);
}
if (sendAll || searchTarget.StartsWith("uuid:", StringComparison.Ordinal))
SendSearchResponse(device.Udn, device, device.Udn, endPoint);
if (sendAll || searchTarget.Contains(":device:"))
SendSearchResponse(device.FullDeviceType, device, GetUsn(device.Udn, device.FullDeviceType), endPoint);
if (searchTarget == SsdpConstants.SsdpDiscoverAllSTHeader)
{
//Send 1 search response for each unique service type for all devices found
var serviceTypes =
(
from s
in device.Services
select s.FullServiceType
).Distinct().ToArray();
foreach (var st in serviceTypes)
{
SendServiceSearchResponses(device, st, endPoint);
}
}
}
private void SendServiceSearchResponses(SsdpDevice device, string searchTarget, UdpEndPoint endPoint)
{
//uuid:device-UUID::urn:domain-name:service:serviceType:ver
SendSearchResponse(searchTarget, device, device.Udn + "::" + searchTarget, endPoint);
}
private static string GetUsn(string udn, string fullDeviceType)
{
return String.Format("{0}::{1}", udn, fullDeviceType);
}
private void SendSearchResponse(string searchTarget, SsdpDevice device, string uniqueServiceName, UdpEndPoint endPoint)
{
var rootDevice = device.ToRootDevice();
var additionalheaders = FormatCustomHeadersForResponse(device);
var message = String.Format(DeviceSearchResponseMessageFormat,
CacheControlHeaderFromTimeSpan(rootDevice),
searchTarget,
uniqueServiceName,
rootDevice.Location,
_OSName,
_OSVersion,
ServerVersion,
DateTime.UtcNow.ToString("r"),
additionalheaders
);
_CommsServer.SendMessage(System.Text.UTF8Encoding.UTF8.GetBytes(message), endPoint);
LogDeviceEventVerbose(String.Format("Sent search response ({0}) to {1}", uniqueServiceName, endPoint.ToString()), device);
}
private bool IsDuplicateSearchRequest(string searchTarget, UdpEndPoint endPoint)
{
var isDuplicateRequest = false;
var newRequest = new SearchRequest() { EndPoint = endPoint, SearchTarget = searchTarget, Received = DateTime.UtcNow };
lock (_RecentSearchRequests)
{
if (_RecentSearchRequests.ContainsKey(newRequest.Key))
{
var lastRequest = _RecentSearchRequests[newRequest.Key];
if (lastRequest.IsOld())
_RecentSearchRequests[newRequest.Key] = newRequest;
else
isDuplicateRequest = true;
}
else
{
_RecentSearchRequests.Add(newRequest.Key, newRequest);
if (_RecentSearchRequests.Count > 10)
CleanUpRecentSearchRequestsAsync();
}
}
return isDuplicateRequest;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "t", Justification = "Capturing task to local variable avoids compiler warning, but value is otherwise not required.")]
private void CleanUpRecentSearchRequestsAsync()
{
var t = TaskEx.Run(() =>
{
lock (_RecentSearchRequests)
{
foreach (var requestKey in (from r in _RecentSearchRequests where r.Value.IsOld() select r.Key).ToArray())
{
_RecentSearchRequests.Remove(requestKey);
}
}
});
}
#endregion
#region Notification Related Methods
#region Alive
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void SendAllAliveNotifications(object state)
{
try
{
if (IsDisposed) return;
try
{
//Only dispose the timer so it gets re-created if we're following
//the SSDP Spec and randomising the broadcast interval.
//If we're using a fixed interval, no need to kill the timer as it's
//already set to go off on the correct interval.
if (_NotificationBroadcastInterval == TimeSpan.Zero)
DisposeRebroadcastTimer();
}
finally
{
// Must reset this here, otherwise if the next reset interval
// is calculated to be the same as the previous one we won't
// reset the timer.
// Reset it to _NotificationBroadcastInterval which is either TimeSpan.Zero
// which will cause the system to calculate a new random interval, or it's the
// current fixed interval which is fine.
_RebroadcastAliveNotificationsTimeSpan = _NotificationBroadcastInterval;
}
_Log.LogInfo("Sending Alive Notifications For All Devices");
_LastNotificationTime = DateTime.Now;
IEnumerable<SsdpRootDevice> devices;
lock (_Devices)
{
devices = _Devices.ToArray();
}
foreach (var device in devices)
{
if (IsDisposed) return;
SendAliveNotifications(device, true);
}
}
catch (Exception ex)
{
_Log.LogError("Publisher stopped, exception " + ex.Message);
Dispose();
}
finally
{
if (!this.IsDisposed)
SetRebroadcastAliveNotificationsTimer(_MinCacheTime);
}
}
private void SendAliveNotifications(SsdpDevice device, bool isRoot)
{
if (isRoot)
{
SendAliveNotification(device, SsdpConstants.UpnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice));
#pragma warning disable CS0618 // Type or member is obsolete
if (this.SupportPnpRootDevice)
#pragma warning restore CS0618 // Type or member is obsolete
SendAliveNotification(device, SsdpConstants.PnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.PnpDeviceTypeRootDevice));
}
SendAliveNotification(device, device.Udn, device.Udn);
SendAliveNotification(device, device.FullDeviceType, GetUsn(device.Udn, device.FullDeviceType));
foreach (var service in device.Services)
{
SendAliveNotification(device, service);
}
foreach (var childDevice in device.Devices)
{
SendAliveNotifications(childDevice, false);
}
}
private void SendAliveNotification(SsdpDevice device, string notificationType, string uniqueServiceName)
{
string multicastIpAddress = _CommsServer.DeviceNetworkType.GetMulticastIPAddress();
var multicastMessage = BuildAliveMessage(device, notificationType, uniqueServiceName, multicastIpAddress);
_CommsServer.SendMessage(multicastMessage, new UdpEndPoint
{
IPAddress = multicastIpAddress,
Port = SsdpConstants.MulticastPort
});
LogDeviceEvent(String.Format("Sent alive notification NT={0}, USN={1}", notificationType, uniqueServiceName), device);
}
private void SendAliveNotification(SsdpDevice device, SsdpService service)
{
SendAliveNotification(device, service.FullServiceType, device.Udn + "::" + service.FullServiceType);
}
private byte[] BuildAliveMessage(SsdpDevice device, string notificationType, string uniqueServiceName, string hostAddress)
{
var rootDevice = device.ToRootDevice();
var additionalheaders = FormatCustomHeadersForResponse(device);
return System.Text.UTF8Encoding.UTF8.GetBytes
(
String.Format
(
AliveNotificationMessageFormat,
notificationType,
uniqueServiceName,
rootDevice.Location,
CacheControlHeaderFromTimeSpan(rootDevice),
_OSName,
_OSVersion,
ServerVersion,
DateTime.UtcNow.ToString("r"),
hostAddress,
SsdpConstants.MulticastPort,
additionalheaders
)
);
}
#endregion
#region ByeBye
private void SendByeByeNotifications(SsdpDevice device, bool isRoot)
{
if (isRoot)
{
SendByeByeNotification(device, SsdpConstants.UpnpDeviceTypeRootDevice, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice));
#pragma warning disable CS0618 // Type or member is obsolete
if (this.SupportPnpRootDevice)
#pragma warning restore CS0618 // Type or member is obsolete
SendByeByeNotification(device, "pnp:rootdevice", GetUsn(device.Udn, "pnp:rootdevice"));
}
SendByeByeNotification(device, device.Udn, device.Udn);
SendByeByeNotification(device, String.Format("urn:{0}", device.FullDeviceType), GetUsn(device.Udn, device.FullDeviceType));
foreach (var service in device.Services)
{
SendByeByeNotification(device, service);
}
foreach (var childDevice in device.Devices)
{
SendByeByeNotifications(childDevice, false);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "byebye", Justification = "Correct value for this type of notification in SSDP.")]
private void SendByeByeNotification(SsdpDevice device, string notificationType, string uniqueServiceName)
{
string multicastIpAddress = _CommsServer.DeviceNetworkType.GetMulticastIPAddress();
var multicastMessage = BuildByeByeMessage(notificationType, uniqueServiceName, multicastIpAddress);
_CommsServer.SendMessage(multicastMessage, new UdpEndPoint
{
IPAddress = multicastIpAddress,
Port = SsdpConstants.MulticastPort
});
LogDeviceEvent(String.Format("Sent byebye notification, NT={0}, USN={1}", notificationType, uniqueServiceName), device);
}
private void SendByeByeNotification(SsdpDevice device, SsdpService service)
{
SendByeByeNotification(device, service.FullServiceType, device.Udn + "::" + service.FullServiceType);
}
private byte[] BuildByeByeMessage(string notificationType, string uniqueServiceName, string hostAddress)
{
var message = String.Format(ByeByeNotificationMessageFormat,
notificationType,
uniqueServiceName,
_OSName,
_OSVersion,
ServerVersion,
DateTime.UtcNow.ToString("r"),
hostAddress,
SsdpConstants.MulticastPort
);
return System.Text.UTF8Encoding.UTF8.GetBytes(message);
}
#endregion
#region Rebroadcast Timer
private void DisposeRebroadcastTimer()
{
var timer = _RebroadcastAliveNotificationsTimer;
_RebroadcastAliveNotificationsTimer = null;
if (timer != null)
timer.Dispose();
}
private void SetRebroadcastAliveNotificationsTimer(TimeSpan minCacheTime)
{
TimeSpan rebroadCastInterval = TimeSpan.Zero;
if (this.NotificationBroadcastInterval != TimeSpan.Zero)
{
if (_RebroadcastAliveNotificationsTimeSpan == this.NotificationBroadcastInterval) return;
rebroadCastInterval = this.NotificationBroadcastInterval;
}
else
{
if (minCacheTime == _RebroadcastAliveNotificationsTimeSpan) return;
if (minCacheTime == TimeSpan.Zero) return;
// According to UPnP/SSDP spec, we should randomise the interval at
// which we broadcast notifications, to help with network congestion.
// Specs also advise to choose a random interval up to *half* the cache time.
// Here we do that, but using the minimum non-zero cache time of any device we are publishing.
rebroadCastInterval = new TimeSpan(Convert.ToInt64((_Random.Next(1, 50) / 100D) * (minCacheTime.Ticks / 2)));
}
DisposeRebroadcastTimer();
// If we were already setup to rebroadcast sometime in the future,
// don't just blindly reset the next broadcast time to the new interval
// as repeatedly changing the interval might end up causing us to over
// delay in sending the next one.
var nextBroadcastInterval = rebroadCastInterval;
if (_LastNotificationTime != DateTime.MinValue)
{
nextBroadcastInterval = rebroadCastInterval.Subtract(DateTime.Now.Subtract(_LastNotificationTime));
if (nextBroadcastInterval.Ticks < 0)
nextBroadcastInterval = TimeSpan.Zero;
else if (nextBroadcastInterval > rebroadCastInterval)
nextBroadcastInterval = rebroadCastInterval;
}
_RebroadcastAliveNotificationsTimeSpan = rebroadCastInterval;
_RebroadcastAliveNotificationsTimer = new System.Threading.Timer(SendAllAliveNotifications, null, nextBroadcastInterval, rebroadCastInterval);
_Log.LogInfo(String.Format("Rebroadcast Interval = {0}, Next Broadcast At = {1}", rebroadCastInterval.ToString(), nextBroadcastInterval.ToString()));
}
private TimeSpan GetMinimumNonZeroCacheLifetime()
{
var nonzeroCacheLifetimesQuery = (from device
in _Devices
where device.CacheLifetime != TimeSpan.Zero
select device.CacheLifetime);
if (nonzeroCacheLifetimesQuery.Any())
return nonzeroCacheLifetimesQuery.Min();
else
return TimeSpan.Zero;
}
#endregion
#endregion
private static string GetFirstHeaderValue(System.Net.Http.Headers.HttpRequestHeaders httpRequestHeaders, string headerName)
{
string retVal = null;
IEnumerable<String> values = null;
if (httpRequestHeaders.TryGetValues(headerName, out values) && values != null)
retVal = values.FirstOrDefault();
return retVal;
}
private static string CacheControlHeaderFromTimeSpan(SsdpRootDevice device)
{
if (device.CacheLifetime == TimeSpan.Zero)
return "CACHE-CONTROL: no-cache";
else
return String.Format("CACHE-CONTROL: public, max-age={0}", device.CacheLifetime.TotalSeconds);
}
private void LogDeviceEvent(string text, SsdpDevice device)
{
_Log.LogInfo(GetDeviceEventLogMessage(text, device));
}
private void LogDeviceEventWarning(string text, SsdpDevice device)
{
_Log.LogWarning(GetDeviceEventLogMessage(text, device));
}
private void LogDeviceEventVerbose(string text, SsdpDevice device)
{
_Log.LogVerbose(GetDeviceEventLogMessage(text, device));
}
private static string GetDeviceEventLogMessage(string text, SsdpDevice device)
{
var rootDevice = device as SsdpRootDevice;
if (rootDevice != null)
return text + " " + device.DeviceType + " - " + device.Uuid + " - " + rootDevice.Location;
else
return text + " " + device.DeviceType + " - " + device.Uuid;
}
private void ConnectToDeviceEvents(SsdpDevice device)
{
device.DeviceAdded += device_DeviceAdded;
device.DeviceRemoved += device_DeviceRemoved;
device.ServiceAdded += device_ServiceAdded;
device.ServiceRemoved += device_ServiceRemoved;
foreach (var childDevice in device.Devices)
{
ConnectToDeviceEvents(childDevice);
}
}
private void DisconnectFromDeviceEvents(SsdpDevice device)
{
device.DeviceAdded -= device_DeviceAdded;
device.DeviceRemoved -= device_DeviceRemoved;
device.ServiceAdded -= device_ServiceAdded;
device.ServiceRemoved -= device_ServiceRemoved;
foreach (var childDevice in device.Devices)
{
DisconnectFromDeviceEvents(childDevice);
}
}
private static string FormatCustomHeadersForResponse(SsdpDevice device)
{
if (device.CustomResponseHeaders.Count == 0) return String.Empty;
StringBuilder returnValue = new StringBuilder();
foreach (var header in device.CustomResponseHeaders)
{
returnValue.Append("\r\n");
returnValue.Append(header.ToString());
}
return returnValue.ToString();
}
private static bool DeviceHasServiceOfType(SsdpDevice device, string fullServiceType)
{
int retries = 0;
while (retries < 5)
{
try
{
return (from s in device.Services where s.FullServiceType == fullServiceType select s).Any();
}
catch (InvalidOperationException) // Collection modified during enumeration
{
retries++;
}
}
return true;
}
#endregion
#region Event Handlers
private void device_DeviceAdded(object sender, DeviceEventArgs e)
{
SendAliveNotifications(e.Device, false);
ConnectToDeviceEvents(e.Device);
}
private void device_DeviceRemoved(object sender, DeviceEventArgs e)
{
SendByeByeNotifications(e.Device, false);
DisconnectFromDeviceEvents(e.Device);
}
private void device_ServiceAdded(object sender, ServiceEventArgs e)
{
//Technically we should only do this once per service type,
//but if we add services during runtime there is no way to
//notify anyone except by resending this notification.
_Log.LogInfo(String.Format("Service added: {0} ({1})", e.Service.ServiceId, e.Service.FullServiceType));
SendAliveNotification((SsdpDevice)sender, e.Service);
}
private void device_ServiceRemoved(object sender, ServiceEventArgs e)
{
_Log.LogInfo(String.Format("Service removed: {0} ({1})", e.Service.ServiceId, e.Service.FullServiceType));
var device = (SsdpDevice)sender;
//Only say this service type has disappeared if there are no
//services of this type left.
if (!DeviceHasServiceOfType(device, e.Service.FullServiceType))
SendByeByeNotification(device, e.Service);
}
private void CommsServer_RequestReceived(object sender, RequestReceivedEventArgs e)
{
if (this.IsDisposed) return;
if (e.Message.Method.Method == SsdpConstants.MSearchMethod)
{
//According to SSDP/UPnP spec, ignore message if missing these headers.
if (!e.Message.Headers.Contains("MX") && !IsRelaxedStandardsMode)
_Log.LogWarning("Ignoring search request - missing MX header. Set StandardsMode to relaxed to process these search requests.");
else if (!e.Message.Headers.Contains("MAN") && !IsRelaxedStandardsMode)
_Log.LogWarning("Ignoring search request - missing MAN header. Set StandardsMode to relaxed to process these search requests.");
else
ProcessSearchRequest(GetFirstHeaderValue(e.Message.Headers, "MX"), GetFirstHeaderValue(e.Message.Headers, "ST"), e.ReceivedFrom);
}
else if (String.Compare(e.Message.Method.Method, "NOTIFY", StringComparison.OrdinalIgnoreCase) != 0)
_Log.LogWarning(String.Format("Unknown request \"{0}\"received, ignoring.", e.Message.Method.Method));
}
#endregion
#region Private Classes
private class SearchRequest
{
public UdpEndPoint EndPoint { get; set; }
public DateTime Received { get; set; }
public string SearchTarget { get; set; }
public string Key
{
get { return this.SearchTarget + ":" + this.EndPoint.ToString(); }
}
public bool IsOld()
{
return DateTime.UtcNow.Subtract(this.Received).TotalMilliseconds > 500;
}
}
#endregion
}
}
| |
#region Namespaces
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using mshtml;
using System.Net;
#endregion //Namespaces
namespace Epi.Windows.Analysis.Dialogs
{
public partial class HelpDialog : CommandDesignDialog
{
#region Private Attributes
private bool showSaveOnly = false;
#endregion Private Attributes
#region Constructors
/// <summary>
/// Default Constructor
/// </summary>
[Obsolete("Use of default constructor not allowed", true)]
public HelpDialog()
{
InitializeComponent();
}
/// <summary>
/// Constructor for AssignDialog
/// </summary>
/// <param name="frm">The main form</param>
public HelpDialog(Epi.Windows.Analysis.Forms.AnalysisMainForm frm)
: base(frm)
{
InitializeComponent();
Construct();
}
/// <summary>
/// Constructor for AssignDialog. if showSave, enable the SaveOnly button
/// </summary>
/// <param name="frm">The main form</param>
/// <param name="showSave">True or False to show Save Only button</param>
public HelpDialog(Epi.Windows.Analysis.Forms.AnalysisMainForm frm, bool showSave)
: base(frm)
{
InitializeComponent();
if (showSave)
{
showSaveOnly = true;
this.btnSaveOnly.Click += new System.EventHandler(this.btnSaveOnly_Click);
Construct();
}
}
#endregion Constructors
#region Public Methods
/// <summary>
/// Checks if input is sufficient and Enables control buttons accordingly
/// </summary>
public override void CheckForInputSufficiency()
{
bool inputValid = ValidateInput();
btnOK.Enabled = inputValid;
btnSaveOnly.Enabled = inputValid;
}
#endregion Public Methods
#region Protected methods
/// <summary>
/// Validates user input
/// </summary>
/// <returns>true if ErrorMessages.Count is 0; otherwise false</returns>
protected override bool ValidateInput()
{
base.ValidateInput();
if (string.IsNullOrEmpty(this.txtFilename.Text))
{
ErrorMessages.Add(SharedStrings.NO_FILENAME);
}
return (ErrorMessages.Count == 0);
}
/// <summary>
/// Generates command text
/// </summary>
protected override void GenerateCommand()
{
StringBuilder command = new StringBuilder();
command.Append(CommandNames.HELP).Append(StringLiterals.SPACE);
command.Append(StringLiterals.SINGLEQUOTES).Append(txtFilename.Text.Trim()).Append(StringLiterals.SINGLEQUOTES);
command.Append(StringLiterals.SPACE);
command.Append(StringLiterals.DOUBLEQUOTES).Append(this.cmbAnchor.Text.Trim()).Append(StringLiterals.DOUBLEQUOTES);
CommandText = command.ToString();
}
#endregion Protected methods
#region Private Methods
/// <summary>
/// Repositions buttons on dialog
/// </summary>
private void RepositionButtons()
{
int x = this.btnClear.Left;
int y = btnClear.Top;
btnClear.Location = new Point(btnCancel.Left, y);
btnCancel.Location = new Point(btnOK.Left, y);
btnOK.Location = new Point(btnSaveOnly.Left, y);
btnSaveOnly.Location = new Point(x, y);
}
/// <summary>
/// Construct the dialog
/// </summary>
private void Construct()
{
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
}
/// <summary>
/// Loads the anchors for a specified html file
/// </summary>
/// <param name="fileName">The file name in which anchors are to be retrieved from</param>
private void LoadAnchors(string fileName)
{
WebClient client = new WebClient();
byte[] data = client.DownloadData(fileName);
mshtml.HTMLDocumentClass ms = new mshtml.HTMLDocumentClass();
string strHTML = Encoding.ASCII.GetString(data);
mshtml.IHTMLDocument2 mydoc = (mshtml.IHTMLDocument2)ms;
//mydoc.write(!--saved from url=(0014)about:internet -->);
mydoc.write(strHTML);
mshtml.IHTMLElementCollection ec = (mshtml.IHTMLElementCollection)mydoc.all.tags("a");
if (ec != null)
{
for (int i = 0; i < ec.length - 1; i++)
{
mshtml.HTMLAnchorElementClass anchor;
anchor = (mshtml.HTMLAnchorElementClass)ec.item(i, 0);
if (!string.IsNullOrEmpty(anchor.name))
{
cmbAnchor.Items.Add(anchor.name);
}
}
}
}
#endregion Private Methods
#region Event Handlers
/// <summary>
/// Loads the dialog
/// </summary>
/// <param name="sender">Object that fired the event</param>
/// <param name="e">.NET supplied event parameters</param>
private void HelpDialog_Load(object sender, EventArgs e)
{
btnSaveOnly.Visible = showSaveOnly;
if (showSaveOnly)
{
RepositionButtons();
}
}
/// <summary>
/// Handles the Text Changed event of the filename textbox
/// </summary>
/// <param name="sender">Object that fired the event</param>
/// <param name="e">.NET supplied event parameters</param>
private void txtFilename_TextChanged(object sender, EventArgs e)
{
CheckForInputSufficiency();
}
/// <summary>
/// Handles the Click event of the Browse button
/// </summary>
/// <param name="sender">Object that fired the event</param>
/// <param name="e">.NET supplied event parameters</param>
private void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "HTML files (*.htm)|*.htm*|CHM Help Files (*.chm)|*.chm";
if (dlg.ShowDialog(this) == DialogResult.OK)
{
this.txtFilename.Text = dlg.FileName;
LoadAnchors(this.txtFilename.Text);
}
dlg.Dispose();
}
#endregion Event Handlers
}
}
| |
/**************************************
* FILE: ConfigBase.cs
* DATE: 05.01.2010 10:12:25
* AUTHOR: Raphael B. Estrada
* AUTHOR URL: http://www.galaktor.net
* AUTHOR E-MAIL: galaktor@gmx.de
*
* The MIT License
*
* Copyright (c) 2010 Raphael B. Estrada
* Author URL: http://www.galaktor.net
* Author E-Mail: galaktor@gmx.de
*
* 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.IO;
using System.Xml;
using System.Xml.Serialization;
using NGin.Core.Exceptions;
using NGin.Core.Platform;
namespace NGin.Core.Configuration
{
public abstract class ConfigBase
{
protected Dictionary<string, Type> validConfigDataTypes = new Dictionary<string, Type>();
public void AddValidConfigDataType( Type validConfigDataType )
{
// must not be null
if ( validConfigDataType == null )
{
throw new ArgumentNullException();
}
// must have config datatype attribute
if ( validConfigDataType.GetCustomAttributes( typeof( ConfigDataTypeAttribute ), true ).Length == 0 )
{
throw new ArgumentException();
}
this.validConfigDataTypes[ validConfigDataType.FullName ] = validConfigDataType;
}
public ConfigBase()
{
// register fallback data types as valid
this.validConfigDataTypes.Add( typeof( XmlElement ).FullName, typeof( XmlElement ) );
this.validConfigDataTypes.Add( typeof( string ).FullName, typeof( string ) );
// register custom data types as valid
// TODO: move this code to a special class
Type[] types = null;
try
{
types = InputOutputManager.CoreAssembly.GetTypes();
}
catch ( System.Reflection.ReflectionTypeLoadException rtlEx )
{
foreach ( Exception ex in rtlEx.LoaderExceptions )
{
Console.WriteLine("LoaderException: " + ex.Message );
}
throw;
}
foreach ( Type assemblyType in types )
{
foreach ( object att in assemblyType.GetCustomAttributes( typeof( ConfigDataTypeAttribute ), true ) )
{
ConfigDataTypeAttribute cdt = att as ConfigDataTypeAttribute;
if ( cdt != null )
{
this.AddValidConfigDataType( cdt.ConfigDataType );
//this.validConfigDataTypes.Add( cdt.ConfigDataType.FullName, cdt.ConfigDataType );
}
}
}
}
internal T DeserializeXmlAs<T>( string rawXml )
{
return ( T ) this.DeserializeXmlAs( typeof( T ), rawXml );
}
internal object DeserializeXmlAs( string typeFullName, string rawXml )
{
byte[] rawXmlAsBytes = System.Text.Encoding.UTF8.GetBytes( rawXml );
return this.DeserializeXmlAs( typeFullName, rawXmlAsBytes );
}
internal object DeserializeXmlAs( Type type, string rawXml )
{
if ( type == null )
{
throw new ArgumentNullException( "type", "The given type must not be null." );
}
return this.DeserializeXmlAs( type.FullName, rawXml );
}
internal T DeserializeXmlAs<T>( byte[] rawXmlAsBytes )
{
return ( T ) this.DeserializeXmlAs( typeof( T ), rawXmlAsBytes );
}
internal object DeserializeXmlAs( Type type, byte[] rawXmlAsBytes )
{
if ( type == null )
{
throw new ArgumentNullException( "type", "The given type must not be null." );
}
return this.DeserializeXmlAs( type.FullName, rawXmlAsBytes );
}
internal object DeserializeXmlAs( string typeFullName, byte[] rawXmlAsBytes )
{
Type type = null;
if ( String.IsNullOrEmpty( typeFullName ) )
{
throw new ArgumentNullException( "The given type name must not be null or empty.", "typeFullName" );
}
if ( rawXmlAsBytes == null )
{
throw new ArgumentNullException( "The given xml as bytes must not be null.", "rawXmlAsBytes" );
}
if ( this.validConfigDataTypes.ContainsKey( typeFullName ) )
{
type = this.validConfigDataTypes[ typeFullName ];
}
else
{
// TODO: This exception should be thrown wherever the check for registerred types is performed, e. g. PlugInManager
throw new PluginNotFoundException( "The requested config data type '" + typeFullName + "' is not registerred." );
}
object result = null;
MemoryStream memStream = new MemoryStream( rawXmlAsBytes );
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
settings.CloseInput = true;
XmlReader reader = null;
try
{
reader = XmlReader.Create( memStream, settings );
}
catch ( InvalidOperationException ivoEx )
{
throw new CoreConfigException( "An error occurred while processing the byte stream as xml.", ivoEx );
}
finally
{
if ( reader == null )
{
memStream.Close();
memStream.Dispose();
}
}
XmlSerializer serializer = new XmlSerializer( type );
try
{
result = serializer.Deserialize( reader );
}
catch ( InvalidOperationException ivoEx )
{
throw new CoreConfigException( "An error occurred during deserialization to type '" + type.FullName + "'.", ivoEx );
}
catch ( System.Text.DecoderFallbackException dfbEx )
{
throw new CoreConfigException( "The text encoding caused an error during deserialization of type '" + type.FullName + "'", dfbEx );
}
finally
{
reader.Close();
}
return result;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.Kusto;
using Microsoft.Azure.Management.Kusto.Models;
using Microsoft.Azure.Test.HttpRecorder;
using Microsoft.Rest.Azure;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Kusto.Tests.Utils;
using Xunit;
namespace Kusto.Tests.ScenarioTests
{
public class KustoOperationsTests : TestBase
{
[Fact]
public void OperationsTest()
{
string executingAssemblyPath = typeof(KustoOperationsTests).GetTypeInfo().Assembly.Location;
HttpMockServer.RecordsDirectory = Path.Combine(Path.GetDirectoryName(executingAssemblyPath), "SessionRecords");
using (var context = MockContext.Start(this.GetType()))
{
var testBase = new KustoTestBase(context);
var numOfOperations = 54;
try
{
//Create a test capacity
var resultOperationsList = testBase.client.Operations.List();
// validate the operations result
Assert.Equal(numOfOperations, resultOperationsList.Count());
var operationsPageLink =
"https://management.azure.com/providers/Microsoft.Kusto/operations?api-version=2018-09-07-preview";
var resultOperationsNextPage = testBase.client.Operations.ListNext(operationsPageLink);
// validate the operations result
Assert.Equal(numOfOperations, resultOperationsNextPage.Count());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
throw;
}
}
}
[Fact]
public void KustoClusterTests()
{
string runningState = "Running";
string stoppedState = "Stopped";
using (MockContext context = MockContext.Start(this.GetType()))
{
var testBase = new KustoTestBase(context);
//create cluster
var createdcluster = testBase.client.Clusters.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.cluster);
VerifyCluster(createdcluster, testBase.clusterName, testBase.sku1, trustedExternalTenants: testBase.trustedExternalTenants, state: runningState);
// get cluster
var cluster = testBase.client.Clusters.Get(testBase.rgName, testBase.clusterName);
VerifyCluster(cluster, testBase.clusterName, testBase.sku1, trustedExternalTenants: testBase.trustedExternalTenants, state: runningState);
//update cluster
testBase.cluster.Sku = testBase.sku2;
var updatedcluster = testBase.client.Clusters.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.cluster);
VerifyCluster(updatedcluster, testBase.clusterName, testBase.sku2, trustedExternalTenants: testBase.trustedExternalTenants, state: runningState);
//suspend cluster
testBase.client.Clusters.Stop(testBase.rgName, testBase.clusterName);
var stoppedCluster = testBase.client.Clusters.Get(testBase.rgName, testBase.clusterName);
VerifyCluster(stoppedCluster, testBase.clusterName, testBase.sku2, trustedExternalTenants: testBase.trustedExternalTenants, state: stoppedState);
//suspend cluster
testBase.client.Clusters.Start(testBase.rgName, testBase.clusterName);
var runningCluster = testBase.client.Clusters.Get(testBase.rgName, testBase.clusterName);
VerifyCluster(runningCluster, testBase.clusterName, testBase.sku2, trustedExternalTenants: testBase.trustedExternalTenants, state: runningState);
//delete cluster
testBase.client.Clusters.Delete(testBase.rgName, testBase.clusterName);
Assert.Throws<CloudException>(() =>
{
testBase.client.Clusters.Get(
resourceGroupName: testBase.rgName,
clusterName: testBase.clusterName);
});
}
}
[Fact]
public void KustoDatabaseTests()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
var testBase = new KustoTestBase(context);
//create cluster
var createdcluster = testBase.client.Clusters.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.cluster);
//create database
var createdDb = testBase.client.Databases.CreateOrUpdate(testBase.rgName, createdcluster.Name, testBase.databaseName, testBase.database) as ReadWriteDatabase;
VerifyReadWriteDatabase(createdDb, testBase.databaseName, testBase.softDeletePeriod1, testBase.hotCachePeriod1, createdcluster.Name);
// get database
var database = testBase.client.Databases.Get(testBase.rgName, createdcluster.Name, testBase.databaseName) as ReadWriteDatabase;
VerifyReadWriteDatabase(database, testBase.databaseName, testBase.softDeletePeriod1, testBase.hotCachePeriod1, createdcluster.Name);
//update database
testBase.database.HotCachePeriod = testBase.hotCachePeriod2;
testBase.database.SoftDeletePeriod = testBase.softDeletePeriod2;
var updatedDb = testBase.client.Databases.CreateOrUpdate(testBase.rgName, createdcluster.Name, testBase.databaseName, testBase.database) as ReadWriteDatabase;
VerifyReadWriteDatabase(updatedDb, testBase.databaseName, testBase.softDeletePeriod2, testBase.hotCachePeriod2, createdcluster.Name);
//delete database
testBase.client.Databases.Delete(testBase.rgName, createdcluster.Name, testBase.databaseName);
Assert.Throws<CloudException>(() =>
{
testBase.client.Databases.Get(
resourceGroupName: testBase.rgName,
clusterName: createdcluster.Name,
databaseName: testBase.databaseName);
});
//delete cluster
testBase.client.Clusters.Delete(testBase.rgName, testBase.clusterName);
}
}
[Fact]
public void KustoEventHubTests()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
var testBase = new KustoTestBase(context);
//create cluster
var createdCluster = testBase.client.Clusters.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.cluster);
//create database
var createdDb = testBase.client.Databases.CreateOrUpdate(testBase.rgName, createdCluster.Name, testBase.databaseName, testBase.database);
//create event hub connection
var createdEventHubConnection = testBase.client.DataConnections.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.databaseName, testBase.eventHubConnectionName, testBase.eventhubConnection);
VerifyEventHub(createdEventHubConnection as EventHubDataConnection,
testBase.eventHubConnectionName,
testBase.eventHubResourceId,
testBase.consumerGroupName,
testBase.clusterName,
testBase.databaseName,
string.Empty);
// get event hub connection
var eventHubConnection = testBase.client.DataConnections.Get(testBase.rgName, testBase.clusterName, testBase.databaseName, testBase.eventHubConnectionName);
VerifyEventHub(eventHubConnection as EventHubDataConnection,
testBase.eventHubConnectionName,
testBase.eventHubResourceId,
testBase.consumerGroupName,
testBase.clusterName,
testBase.databaseName,
string.Empty);
//update event hub connection
testBase.eventhubConnection.DataFormat = testBase.dataFormat;
var updatedEventHubConnection = testBase.client.DataConnections.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.databaseName, testBase.eventHubConnectionName, testBase.eventhubConnection);
VerifyEventHub(updatedEventHubConnection as EventHubDataConnection,
testBase.eventHubConnectionName,
testBase.eventHubResourceId,
testBase.consumerGroupName,
testBase.clusterName,
testBase.databaseName,
testBase.dataFormat);
//delete event hub
testBase.client.DataConnections.Delete(testBase.rgName, testBase.clusterName, testBase.databaseName, testBase.eventHubConnectionName);
Assert.Throws<CloudException>(() =>
{
testBase.client.DataConnections.Get(
resourceGroupName: testBase.rgName,
clusterName: createdCluster.Name,
databaseName: createdDb.Name,
dataConnectionName: testBase.eventHubConnectionName);
});
//delete database
testBase.client.Databases.Delete(testBase.rgName, testBase.clusterName, testBase.databaseName);
//delete cluster
testBase.client.Clusters.Delete(testBase.rgName, testBase.clusterName);
}
}
[Fact]
public void KustoIotHubTests()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
var testBase = new KustoTestBase(context);
//create cluster
var createdCluster = testBase.client.Clusters.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.cluster);
//create database
var createdDb = testBase.client.Databases.CreateOrUpdate(testBase.rgName, createdCluster.Name, testBase.databaseName, testBase.database);
//create iot hub connection
var createdIotHubConnection = testBase.client.DataConnections.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.databaseName, testBase.iotHubConnectionName, testBase.iotHubDataConnection);
VerifyIotHub(createdIotHubConnection as IotHubDataConnection,
testBase.iotHubConnectionName,
testBase.iotHubResourceId,
testBase.consumerGroupName,
testBase.clusterName,
testBase.databaseName,
string.Empty);
// get Iot hub connection
var iotHubConnection = testBase.client.DataConnections.Get(testBase.rgName, testBase.clusterName, testBase.databaseName, testBase.iotHubConnectionName);
VerifyIotHub(iotHubConnection as IotHubDataConnection,
testBase.iotHubConnectionName,
testBase.iotHubResourceId,
testBase.consumerGroupName,
testBase.clusterName,
testBase.databaseName,
string.Empty);
//update Iot hub connection
testBase.iotHubDataConnection.DataFormat = testBase.dataFormat;
var updatedIotHubConnection = testBase.client.DataConnections.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.databaseName, testBase.iotHubConnectionName, testBase.iotHubDataConnection);
VerifyIotHub(updatedIotHubConnection as IotHubDataConnection,
testBase.iotHubConnectionName,
testBase.iotHubResourceId,
testBase.consumerGroupName,
testBase.clusterName,
testBase.databaseName,
testBase.dataFormat);
//delete Iot hub
testBase.client.DataConnections.Delete(testBase.rgName, testBase.clusterName, testBase.databaseName, testBase.iotHubConnectionName);
Assert.Throws<CloudException>(() =>
{
testBase.client.DataConnections.Get(
resourceGroupName: testBase.rgName,
clusterName: testBase.clusterName,
databaseName: testBase.databaseName,
dataConnectionName: testBase.iotHubConnectionName);
});
//delete database
testBase.client.Databases.Delete(testBase.rgName, testBase.clusterName, testBase.databaseName);
//delete cluster
testBase.client.Clusters.Delete(testBase.rgName, testBase.clusterName);
}
}
[Fact]
public void KustoEventGridTests()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
var testBase = new KustoTestBase(context);
//create event grid connection
var createdEventGridConnection = testBase.client.DataConnections.CreateOrUpdate(testBase.resourceGroupForTest, testBase.clusterForEventGridTest, testBase.databaseForEventGridTest, testBase.eventGridConnectinoName, testBase.eventGridDataConnection);
VerifyEventGrid(createdEventGridConnection as EventGridDataConnection,
testBase.eventGridConnectinoName,
testBase.eventHubResourceId,
testBase.consumerGroupName,
testBase.clusterForEventGridTest,
testBase.databaseForEventGridTest,
testBase.dataFormat,
testBase.storageAccountForEventGridResourceId,
testBase.tableName);
// get event grid connection
var eventGridConnection = testBase.client.DataConnections.Get(testBase.resourceGroupForTest, testBase.clusterForEventGridTest, testBase.databaseForEventGridTest, testBase.eventGridConnectinoName);
VerifyEventGrid(eventGridConnection as EventGridDataConnection,
testBase.eventGridConnectinoName,
testBase.eventHubResourceId,
testBase.consumerGroupName,
testBase.clusterForEventGridTest,
testBase.databaseForEventGridTest,
testBase.dataFormat,
testBase.storageAccountForEventGridResourceId,
testBase.tableName);
//update event grid connection
testBase.eventhubConnection.DataFormat = testBase.dataFormat;
var updatedEventGridConnection = testBase.client.DataConnections.CreateOrUpdate(testBase.resourceGroupForTest, testBase.clusterForEventGridTest, testBase.databaseForEventGridTest, testBase.eventGridConnectinoName, testBase.eventGridDataConnection);
VerifyEventGrid(updatedEventGridConnection as EventGridDataConnection,
testBase.eventGridConnectinoName,
testBase.eventHubResourceId,
testBase.consumerGroupName,
testBase.clusterForEventGridTest,
testBase.databaseForEventGridTest,
testBase.dataFormat,
testBase.storageAccountForEventGridResourceId,
testBase.tableName);
//delete event grid
testBase.client.DataConnections.Delete(testBase.resourceGroupForTest, testBase.clusterForEventGridTest, testBase.databaseForEventGridTest, testBase.eventGridConnectinoName);
Assert.Throws<CloudException>(() =>
{
testBase.client.DataConnections.Get(
resourceGroupName: testBase.resourceGroupForTest,
clusterName: testBase.clusterForEventGridTest,
databaseName: testBase.databaseForEventGridTest,
dataConnectionName: testBase.eventGridConnectinoName);
});
}
}
[Fact]
public void KustoOptimizedAutoscaleTests()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
var testBase = new KustoTestBase(context);
// Create cluster with optimized autoscale
var enabledOptimizedAutoscale = new OptimizedAutoscale(1, true, 2, 100);
testBase.cluster.OptimizedAutoscale = enabledOptimizedAutoscale;
var createdCluster = testBase.client.Clusters.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.cluster);
ValidateOptimizedAutoscale(createdCluster, enabledOptimizedAutoscale);
// Update cluster with optimized autoscale
enabledOptimizedAutoscale = new OptimizedAutoscale(1, true, 2, 101);
testBase.cluster.OptimizedAutoscale = enabledOptimizedAutoscale;
var updatedCluster = testBase.client.Clusters.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.cluster);
ValidateOptimizedAutoscale(updatedCluster, enabledOptimizedAutoscale);
var optimizedAutoscaleThatShouldNotBeAllowed = new OptimizedAutoscale(1, true, 0, 100);
testBase.cluster.OptimizedAutoscale = optimizedAutoscaleThatShouldNotBeAllowed;
Assert.Throws<CloudException>(() =>
{
testBase.client.Clusters.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.cluster);
});
// Delete cluster
testBase.client.Clusters.Delete(testBase.rgName, testBase.clusterName);
}
}
[Fact]
public void KustoStreamingIngestTests()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
var testBase = new KustoTestBase(context);
// Create cluster with streaming ingest true
testBase.cluster.EnableStreamingIngest = true;
var createdCluster = testBase.client.Clusters.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.cluster);
Assert.True(createdCluster.EnableStreamingIngest);
// Update cluster with streaming ingest false
testBase.cluster.EnableStreamingIngest = false;
var updatedCluster = testBase.client.Clusters.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.cluster);
Assert.False(updatedCluster.EnableStreamingIngest);
// Delete cluster
testBase.client.Clusters.Delete(testBase.rgName, testBase.clusterName);
}
}
[Fact]
public void KustoEnableDiskEncryptionTests()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
var testBase = new KustoTestBase(context);
// Create cluster with Enable Disk Encryption true
testBase.cluster.EnableDiskEncryption = true;
var createdCluster = testBase.client.Clusters.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.cluster);
Assert.True(createdCluster.EnableDiskEncryption);
// Update cluster with Enable Disk Encryption false
testBase.cluster.EnableDiskEncryption = false;
var updatedCluster = testBase.client.Clusters.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.cluster);
Assert.False(updatedCluster.EnableDiskEncryption);
//Delete cluster
testBase.client.Clusters.Delete(testBase.rgName, testBase.clusterName);
}
}
[Fact]
public void KustoDatabasePrincipalsTests()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
var testBase = new KustoTestBase(context);
//create cluster
var createdCluster = testBase.client.Clusters.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.cluster);
//create database
var createdDb = testBase.client.Databases.CreateOrUpdate(testBase.rgName, createdCluster.Name, testBase.databaseName, testBase.database);
//create principals list
var databasePrincipalListRequest = new DatabasePrincipalListRequest(testBase.databasePrincipals);
var principalsResult = testBase.client.Databases.AddPrincipals(testBase.rgName, testBase.clusterName, testBase.databaseName, databasePrincipalListRequest);
VerifyPrincipalsExists(principalsResult.Value, testBase.databasePrincipal);
// get principals list
var principalsList = testBase.client.Databases.ListPrincipals(testBase.rgName, testBase.clusterName, testBase.databaseName);
VerifyPrincipalsExists(principalsList, testBase.databasePrincipal);
//delete principals
principalsResult = testBase.client.Databases.RemovePrincipals(testBase.rgName, testBase.clusterName, testBase.databaseName, databasePrincipalListRequest);
VerifyPrincipalsDontExist(principalsResult.Value, testBase.databasePrincipal);
//delete database
testBase.client.Databases.Delete(testBase.rgName, testBase.clusterName, testBase.databaseName);
//delete cluster
testBase.client.Clusters.Delete(testBase.rgName, testBase.clusterName);
}
}
[Fact]
public void KustoPrincipalAssignmentsTests()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
var testBase = new KustoTestBase(context);
//create cluster
var createdCluster = testBase.client.Clusters.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.cluster);
var principalName = "principal1";
//create cluster principal assignment
var clusterPrincipalAssignment = new ClusterPrincipalAssignment(testBase.clientIdForPrincipal, "AllDatabasesAdmin", "App");
testBase.client.ClusterPrincipalAssignments.CreateOrUpdate(testBase.rgName, testBase.clusterName, principalName, clusterPrincipalAssignment);
testBase.client.ClusterPrincipalAssignments.Get(testBase.rgName, testBase.clusterName, principalName);
testBase.client.ClusterPrincipalAssignments.Delete(testBase.rgName, testBase.clusterName, principalName);
Assert.Throws<CloudException>(() =>
{
testBase.client.ClusterPrincipalAssignments.Get(testBase.rgName, testBase.clusterName, principalName);
});
//create database
var createdDb = testBase.client.Databases.CreateOrUpdate(testBase.rgName, createdCluster.Name, testBase.databaseName, testBase.database);
//create database principal assignment
var databasePrincipalAssignment = new DatabasePrincipalAssignment(testBase.clientIdForPrincipal, "Viewer", "App");
testBase.client.DatabasePrincipalAssignments.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.databaseName, principalName, databasePrincipalAssignment);
testBase.client.DatabasePrincipalAssignments.Get(testBase.rgName, testBase.clusterName, testBase.databaseName, principalName);
testBase.client.DatabasePrincipalAssignments.Delete(testBase.rgName, testBase.clusterName, testBase.databaseName, principalName);
Assert.Throws<CloudException>(() =>
{
testBase.client.DatabasePrincipalAssignments.Get(testBase.rgName, testBase.clusterName, testBase.databaseName, principalName);
});
//delete database
testBase.client.Databases.Delete(testBase.rgName, testBase.clusterName, testBase.databaseName);
//delete cluster
testBase.client.Clusters.Delete(testBase.rgName, testBase.clusterName);
}
}
[Fact]
public void KustoAttachedDatabaseConfigurationTests()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
var testBase = new KustoTestBase(context);
//create cluster
var createdCluster = testBase.client.Clusters.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.cluster);
// create a follower cluster
var createdFollowerCluster = testBase.client.Clusters.CreateOrUpdate(testBase.rgName, testBase.followerClusterName, testBase.cluster);
//create database
var createdDb = testBase.client.Databases.CreateOrUpdate(testBase.rgName, createdCluster.Name, testBase.databaseName, testBase.database);
//create attached database configuration
var createdAttachedDatabaseConfiguration = testBase.client.AttachedDatabaseConfigurations.CreateOrUpdate(
testBase.rgName,
testBase.followerClusterName,
testBase.attachedDatabaseConfigurationName,
testBase.attachedDatabaseConfiguration);
VerifyAttachedDatabaseConfiguration(createdAttachedDatabaseConfiguration,
testBase.attachedDatabaseConfigurationName,
testBase.followerClusterName, testBase.databaseName,
createdCluster.Id,
testBase.defaultPrincipalsModificationKind);
// get attached database configuration
var attachedDatabaseConfiguration = testBase.client.AttachedDatabaseConfigurations.Get(testBase.rgName, createdFollowerCluster.Name, testBase.attachedDatabaseConfigurationName);
VerifyAttachedDatabaseConfiguration(attachedDatabaseConfiguration,
testBase.attachedDatabaseConfigurationName,
testBase.followerClusterName, testBase.databaseName,
createdCluster.Id,
testBase.defaultPrincipalsModificationKind);
// testing the created read-only following database
TestReadonlyFollowingDatabase(testBase);
// delete the attached database configuration
testBase.client.AttachedDatabaseConfigurations.Delete(testBase.rgName, createdFollowerCluster.Name, testBase.attachedDatabaseConfigurationName);
Assert.Throws<CloudException>(() =>
{
testBase.client.AttachedDatabaseConfigurations.Get(
resourceGroupName: testBase.rgName,
clusterName: createdFollowerCluster.Name,
attachedDatabaseConfigurationName: testBase.attachedDatabaseConfigurationName);
});
// delete cluster
testBase.client.Clusters.Delete(testBase.rgName, testBase.clusterName);
// delete follower cluster
testBase.client.Clusters.Delete(testBase.rgName, testBase.followerClusterName);
}
}
[Fact]
public void KustoFollowerDatabaseActionsTests()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
var testBase = new KustoTestBase(context);
//create cluster
var createdCluster = testBase.client.Clusters.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.cluster);
// create a follower cluster
var createdFollowerCluster = testBase.client.Clusters.CreateOrUpdate(testBase.rgName, testBase.followerClusterName, testBase.cluster);
//create database
var createdDb = testBase.client.Databases.CreateOrUpdate(testBase.rgName, createdCluster.Name, testBase.databaseName, testBase.database);
//create attached database configuration
var createdAttachedDatabaseConfiguration = testBase.client.AttachedDatabaseConfigurations.CreateOrUpdate(
testBase.rgName,
testBase.followerClusterName,
testBase.attachedDatabaseConfigurationName,
testBase.attachedDatabaseConfiguration);
var followerDatabasesList = testBase.client.Clusters.ListFollowerDatabases(testBase.rgName, testBase.clusterName);
var followerDatabase = followerDatabasesList.FirstOrDefault(f => f.AttachedDatabaseConfigurationName.Equals(testBase.attachedDatabaseConfigurationName, StringComparison.OrdinalIgnoreCase));
VerifyFollowerDatabase(followerDatabase, testBase.attachedDatabaseConfigurationName, testBase.databaseName, createdFollowerCluster.Id);
// detach the follower database
testBase.client.Clusters.DetachFollowerDatabases(testBase.rgName, testBase.clusterName, followerDatabase);
followerDatabasesList = testBase.client.Clusters.ListFollowerDatabases(testBase.rgName, testBase.clusterName);
VerifyFollowerDatabaseDontExist(followerDatabasesList, testBase.attachedDatabaseConfigurationName);
// delete cluster
testBase.client.Clusters.Delete(testBase.rgName, testBase.clusterName);
// delete follower cluster
testBase.client.Clusters.Delete(testBase.rgName, testBase.followerClusterName);
}
}
[Fact]
public void KustoIdentityTests()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
var testBase = new KustoTestBase(context);
// Create cluster with an identity
testBase.cluster.Identity = new Identity(IdentityType.SystemAssigned);
var createdCluster = testBase.client.Clusters.CreateOrUpdate(testBase.rgName, testBase.clusterName, testBase.cluster);
Assert.Equal(IdentityType.SystemAssigned, createdCluster.Identity.Type);
// Delete cluster
testBase.client.Clusters.Delete(testBase.rgName, testBase.clusterName);
}
}
[Fact]
public void KustoKeyVaultPropertiesTests()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
var testBase = new KustoTestBase(context);
// Update the cluster with key vault properties
var cluster = testBase.client.Clusters.Update(testBase.resourceGroupForTest, testBase.clusterForKeyVaultPropertiesTest, new ClusterUpdate(keyVaultProperties: testBase.keyVaultProperties));
VerifyKeyVaultProperties(cluster.KeyVaultProperties,
testBase.KeyNameForKeyVaultPropertiesTest,
testBase.KeyVersionForKeyVaultPropertiesTest,
testBase.KeyVaultUriForKeyVaultPropertiesTest);
}
}
private void TestReadonlyFollowingDatabase(KustoTestBase testBase)
{
var readonlyFollowingDb = testBase.client.Databases.Get(testBase.rgName, testBase.followerClusterName, testBase.databaseName) as ReadOnlyFollowingDatabase;
VerifyReadOnlyFollowingDatabase(readonlyFollowingDb, testBase.databaseName, testBase.softDeletePeriod1, testBase.hotCachePeriod1, testBase.defaultPrincipalsModificationKind, testBase.followerClusterName);
readonlyFollowingDb.HotCachePeriod = testBase.hotCachePeriod2;
readonlyFollowingDb = testBase.client.Databases.CreateOrUpdate(testBase.rgName, testBase.followerClusterName, testBase.databaseName, readonlyFollowingDb) as ReadOnlyFollowingDatabase;
VerifyReadOnlyFollowingDatabase(readonlyFollowingDb, testBase.databaseName, testBase.softDeletePeriod1, testBase.hotCachePeriod2, testBase.defaultPrincipalsModificationKind, testBase.followerClusterName);
}
private void VerifyFollowerDatabase(FollowerDatabaseDefinition followerDatabaseDefinition, string attachedDatabaseConfigurationName, string databaseName, string clusterResourceId)
{
Assert.NotNull(followerDatabaseDefinition);
Assert.Equal(followerDatabaseDefinition.AttachedDatabaseConfigurationName, attachedDatabaseConfigurationName);
Assert.Equal(followerDatabaseDefinition.DatabaseName, databaseName);
Assert.Equal(followerDatabaseDefinition.ClusterResourceId, clusterResourceId);
}
private void VerifyKeyVaultProperties(KeyVaultProperties keyVaultProperties, string keyName, string keyVersion, string keyVaultUri)
{
Assert.NotNull(keyVaultProperties);
Assert.Equal(keyVaultProperties.KeyName, keyName);
Assert.Equal(keyVaultProperties.KeyVersion, keyVersion);
Assert.Equal(keyVaultProperties.KeyVaultUri, keyVaultUri);
}
private void VerifyFollowerDatabaseDontExist(IEnumerable<FollowerDatabaseDefinition> followerDatabasesList, string attachedDatabaseConfigurationName)
{
Assert.Null(followerDatabasesList.FirstOrDefault(f => f.AttachedDatabaseConfigurationName.Equals(attachedDatabaseConfigurationName, StringComparison.OrdinalIgnoreCase)));
}
private void VerifyPrincipalsExists(IEnumerable<DatabasePrincipal> principals, DatabasePrincipal databasePrincipal)
{
Assert.NotNull(principals.First(principal => principal.Email == databasePrincipal.Email));
}
private void VerifyPrincipalsDontExist(IEnumerable<DatabasePrincipal> principals, DatabasePrincipal databasePrincipal)
{
Assert.Null(principals.FirstOrDefault(principal => principal.Email == databasePrincipal.Email));
}
private void VerifyAttachedDatabaseConfiguration(AttachedDatabaseConfiguration createdAttachedDatabaseConfiguration, string attachedDatabaseConfigurationName, string clusterName, string databaseName, string clusterResourceId, string defaultPrincipalsModificationKind)
{
var attahcedDatabaseConfigurationFullName = ResourcesNamesUtils.GetAttachedDatabaseConfigurationName(clusterName, attachedDatabaseConfigurationName);
Assert.Equal(createdAttachedDatabaseConfiguration.Name, attahcedDatabaseConfigurationFullName);
Assert.Equal(createdAttachedDatabaseConfiguration.DatabaseName, databaseName);
Assert.Equal(createdAttachedDatabaseConfiguration.ClusterResourceId, clusterResourceId);
Assert.Equal(createdAttachedDatabaseConfiguration.DefaultPrincipalsModificationKind, defaultPrincipalsModificationKind);
}
private void VerifyEventHub(EventHubDataConnection createdDataConnection, string eventHubConnectionName, string eventHubResourceId, string consumerGroupName, string clusterName, string databaseName, string dataFormat)
{
var eventHubFullName = ResourcesNamesUtils.GetDataConnectionFullName(clusterName, databaseName, eventHubConnectionName);
Assert.Equal(createdDataConnection.Name, eventHubFullName);
Assert.Equal(createdDataConnection.EventHubResourceId, eventHubResourceId);
Assert.Equal(createdDataConnection.ConsumerGroup, consumerGroupName);
Assert.Equal(createdDataConnection.DataFormat, dataFormat);
}
private void VerifyIotHub(IotHubDataConnection createdDataConnection, string iotHubConnectionName, string iotHubResourceId, string consumerGroupName, string clusterName, string databaseName, string dataFormat)
{
var iotHubFullName = ResourcesNamesUtils.GetDataConnectionFullName(clusterName, databaseName, iotHubConnectionName);
Assert.Equal(createdDataConnection.Name, iotHubFullName);
Assert.Equal(createdDataConnection.IotHubResourceId, iotHubResourceId);
Assert.Equal(createdDataConnection.ConsumerGroup, consumerGroupName);
Assert.Equal(createdDataConnection.DataFormat, dataFormat);
}
private void VerifyEventGrid(EventGridDataConnection createdDataConnection, string eventGridConnectinoName, string eventHubResourceId, string consumerGroupName, string clusterName, string databaseName, string dataFormat, string storageAccountResourceId, string tableName)
{
var eventGridFullName = ResourcesNamesUtils.GetDataConnectionFullName(clusterName, databaseName, eventGridConnectinoName);
Assert.Equal(createdDataConnection.Name, eventGridFullName);
Assert.Equal(createdDataConnection.EventHubResourceId, eventHubResourceId);
Assert.Equal(createdDataConnection.ConsumerGroup, consumerGroupName);
Assert.Equal(createdDataConnection.DataFormat, dataFormat);
Assert.Equal(createdDataConnection.StorageAccountResourceId, storageAccountResourceId);
Assert.Equal(createdDataConnection.TableName, tableName);
}
private void VerifyReadOnlyFollowingDatabase(ReadOnlyFollowingDatabase database, string databaseName, TimeSpan? softDeletePeriod, TimeSpan? hotCachePeriod, string principalsModificationKind, string clusterName)
{
var databaseFullName = ResourcesNamesUtils.GetFullDatabaseName(clusterName, databaseName);
Assert.NotNull(database);
Assert.Equal(database.Name, databaseFullName);
Assert.Equal(softDeletePeriod, database.SoftDeletePeriod);
Assert.Equal(hotCachePeriod, database.HotCachePeriod);
Assert.Equal(principalsModificationKind, database.PrincipalsModificationKind);
}
private void VerifyReadWriteDatabase(ReadWriteDatabase database, string databaseName, TimeSpan? softDeletePeriod, TimeSpan? hotCachePeriod, string clusterName)
{
var databaseFullName = ResourcesNamesUtils.GetFullDatabaseName(clusterName, databaseName);
Assert.NotNull(database);
Assert.Equal(database.Name, databaseFullName);
Assert.Equal(database.SoftDeletePeriod, softDeletePeriod);
Assert.Equal(database.HotCachePeriod, hotCachePeriod);
}
private void VerifyCluster(Cluster cluster, string name, AzureSku sku, IList<TrustedExternalTenant> trustedExternalTenants, string state)
{
Assert.Equal(cluster.Name, name);
AssetEqualtsSku(cluster.Sku, sku);
Assert.Equal(state, cluster.State);
AssetEqualtsExtrnalTenants(cluster.TrustedExternalTenants, trustedExternalTenants);
}
private void ValidateOptimizedAutoscale(Cluster createdCluster, OptimizedAutoscale expectedOptimizedAutoscale)
{
var clusterOptimizedAutoscale = createdCluster.OptimizedAutoscale;
if (clusterOptimizedAutoscale == null)
{
Assert.Null(expectedOptimizedAutoscale);
return;
}
Assert.Equal(clusterOptimizedAutoscale.Version, expectedOptimizedAutoscale.Version);
Assert.Equal(clusterOptimizedAutoscale.Minimum, expectedOptimizedAutoscale.Minimum);
Assert.Equal(clusterOptimizedAutoscale.Maximum, expectedOptimizedAutoscale.Maximum);
Assert.Equal(clusterOptimizedAutoscale.IsEnabled, expectedOptimizedAutoscale.IsEnabled);
}
private void AssetEqualtsSku(AzureSku sku1, AzureSku sku2)
{
Assert.Equal(sku1.Capacity, sku2.Capacity);
Assert.Equal(sku1.Name, sku2.Name);
}
private void AssetEqualtsExtrnalTenants(IList<TrustedExternalTenant> trustedExternalTenants, IList<TrustedExternalTenant> other)
{
Assert.Equal(trustedExternalTenants.Count, other.Count);
foreach (var otherExtrenalTenants in other)
{
var equalExternalTenants = trustedExternalTenants.Where((extrenalTenant) =>
{
return otherExtrenalTenants.Value == extrenalTenant.Value;
});
Assert.Single(equalExternalTenants);
}
}
}
}
| |
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text.Json;
namespace Ganss.Excel
{
/// <summary>
/// Describes the mapping of a property to a cell in an Excel sheet.
/// </summary>
public class ColumnInfo
{
/// <summary>
/// Gets or sets the mapping directions.
/// </summary>
public MappingDirections Directions { get; internal set; } = MappingDirections.Both;
private PropertyInfo property;
private bool isSubType;
/// <summary>
/// Sets the property type.
/// </summary>
/// <param name="propertyType">The property type.</param>
internal void SetPropertyType(Type propertyType)
{
var underlyingType = Nullable.GetUnderlyingType(propertyType);
IsNullable = underlyingType != null;
PropertyType = underlyingType ?? propertyType;
isSubType = PropertyType != null
&& !PropertyType.IsPrimitive
&& PropertyType != typeof(decimal)
&& PropertyType != typeof(string)
&& PropertyType != typeof(DateTime)
&& PropertyType != typeof(Guid);
}
/// <summary>
/// Gets or sets the property name.
/// </summary>
public string Name { get; protected set; }
/// <summary>
/// Gets or sets the property.
/// </summary>
/// <value>
/// The property.
/// </value>
public PropertyInfo Property
{
get { return property; }
set
{
property = value;
if (property != null)
{
SetPropertyType(property.PropertyType);
Name = property.Name;
}
else
{
PropertyType = null;
IsNullable = false;
}
}
}
/// <summary>
/// Gets a value indicating whether the mapped property has a nested type.
/// </summary>
public bool IsSubType
{
get
{
return isSubType && !Json
&& SetProp == null;
}
}
/// <summary>
/// Gets a value indicating whether the property is nullable.
/// </summary>
/// <value>
/// <c>true</c> if the property is nullable; otherwise, <c>false</c>.
/// </value>
public bool IsNullable { get; protected set; }
/// <summary>
/// Gets the type of the property.
/// </summary>
/// <value>
/// The type of the property.
/// </value>
public Type PropertyType { get; protected set; }
/// <summary>
/// Gets or sets the cell setter.
/// </summary>
/// <value>
/// The cell setter.
/// </value>
public Action<ICell, object> SetCell { get; set; }
/// <summary>
/// Gets or sets the property setter.
/// </summary>
/// <value>
/// The property setter.
/// </value>
public Func<object, object, ICell, object> SetProp { get; set; }
/// <summary>
/// Gets or sets the builtin format.
/// </summary>
/// <value>
/// The builtin format.
/// </value>
public short BuiltinFormat { get; set; }
/// <summary>
/// Gets or sets the custom format.
/// </summary>
/// <value>
/// The custom format.
/// </value>
public string CustomFormat { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to map the formula result.
/// </summary>
/// <value>
/// <c>true</c> if the formula result will be mapped; otherwise, <c>false</c>.
/// </value>
public bool FormulaResult { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to serialize as JSON.
/// </summary>
/// <value>
/// <c>true</c> if the property will be serialized as JSON; otherwise, <c>false</c>.
/// </value>
public bool Json { get; set; }
static readonly HashSet<Type> NumericTypes = new()
{
typeof(decimal),
typeof(byte), typeof(sbyte),
typeof(short), typeof(ushort),
typeof(int), typeof(uint),
typeof(long), typeof(ulong),
typeof(float), typeof(double)
};
/// <summary>
/// Generates the cell setter.
/// </summary>
/// <returns>The cell setter.</returns>
protected Action<ICell, object> GenerateCellSetter()
{
if (PropertyType == typeof(DateTime))
{
return (c, o) =>
{
if (o == null)
c.SetCellValue((string)null);
else
c.SetCellValue((DateTime)o);
};
}
else if (PropertyType == typeof(bool))
{
if (IsNullable)
return (c, o) =>
{
if (o == null)
c.SetCellValue((string)null);
else
c.SetCellValue((bool)o);
};
else
return (c, o) => c.SetCellValue((bool)o);
}
else if (NumericTypes.Contains(PropertyType))
{
if (IsNullable)
return (c, o) =>
{
if (o == null)
c.SetCellValue((string)null);
else
c.SetCellValue(Convert.ToDouble(o));
};
else
return (c, o) => c.SetCellValue(Convert.ToDouble(o));
}
else
{
return (c, o) =>
{
if (o == null)
c.SetCellValue((string)null);
else if (!Json)
c.SetCellValue(o.ToString());
else
c.SetCellValue(JsonSerializer.Serialize(o));
};
}
}
/// <summary>Sets the column style.</summary>
/// <param name="sheet">The sheet.</param>
/// <param name="columnIndex">Index of the column.</param>
public void SetColumnStyle(ISheet sheet, int columnIndex)
{
if (BuiltinFormat != 0 || CustomFormat != null)
{
var wb = sheet.Workbook;
var cs = wb.CreateCellStyle();
if (CustomFormat != null)
cs.DataFormat = wb.CreateDataFormat().GetFormat(CustomFormat);
else
cs.DataFormat = BuiltinFormat;
sheet.SetDefaultColumnStyle(columnIndex, cs);
}
}
/// <summary>Sets the cell style.</summary>
/// <param name="c">The cell.</param>
public void SetCellStyle(ICell c)
{
if (BuiltinFormat != 0 || CustomFormat != null)
c.CellStyle = c.Sheet.GetColumnStyle(c.ColumnIndex);
}
/// <summary>
/// Computes value that can be assigned to property from cell value.
/// </summary>
/// <param name="o">The object which contains the property.</param>
/// <param name="val">The value.</param>
/// <param name="cell">The cell where the value originates from.</param>
/// <returns>Value that can be assigned to property.</returns>
public virtual object GetPropertyValue(object o, object val, ICell cell)
{
object v;
if (SetProp != null)
v = SetProp(o, val, cell);
else if (IsNullable && (val == null || (val is string s && s.Length == 0)))
v = null;
else if (val is string g && PropertyType == typeof(Guid))
v = Guid.Parse(g);
else
v = Convert.ChangeType(val, PropertyType, CultureInfo.InvariantCulture);
return v;
}
/// <summary>
/// Sets the property of the specified object to the specified value.
/// </summary>
/// <param name="o">The object whose property to set.</param>
/// <param name="val">The value.</param>
/// <param name="cell">The cell where the value originates from.</param>
public virtual void SetProperty(object o, object val, ICell cell)
{
var v = GetPropertyValue(o, val, cell);
Property.SetValue(o, v, null);
}
/// <summary>
/// Gets the property value of the specified object.
/// </summary>
/// <param name="o">The object from which to get the property value.</param>
/// <returns>The property value.</returns>
public virtual object GetProperty(object o)
{
return Property.GetValue(o, null);
}
/// <summary>Specifies a method to use when setting the cell value from an object.</summary>
/// <param name="setCell">The method to use when setting the cell value from an object.</param>
/// <returns>The <see cref="ColumnInfo"/> object.</returns>
public ColumnInfo SetCellUsing(Action<ICell, object> setCell)
{
SetCell = setCell;
return this;
}
/// <summary>Specifies a method to use when setting the cell value from an object.</summary>
/// <param name="setCell">The method to use when setting the cell value from an object.</param>
/// <returns>The <see cref="ColumnInfo"/> object.</returns>
public ColumnInfo SetCellUsing<T>(Action<ICell, T> setCell)
{
SetCell = (c, o) => setCell(c, (T)o);
return this;
}
/// <summary>Specifies a method to use when setting the property value from the cell value.</summary>
/// <param name="setProp">The method to use when setting the property value from the cell value.</param>
/// <returns>The <see cref="ColumnInfo"/> object.</returns>
public ColumnInfo SetPropertyUsing(Func<object, object> setProp)
{
SetProp = (o, v, c) => setProp(v);
return this;
}
/// <summary>Specifies a method to use when setting the property value from the cell value.</summary>
/// <param name="setProp">The method to use when setting the property value from the cell value.</param>
/// <returns>The <see cref="ColumnInfo"/> object.</returns>
public ColumnInfo SetPropertyUsing(Func<object, ICell, object> setProp)
{
SetProp = (o, v, c) => setProp(v, c);
return this;
}
/// <summary>Specifies a method to use when setting the property value from the cell value.</summary>
/// <param name="setProp">The method to use when setting the property value from the cell value.</param>
/// <returns>The <see cref="ColumnInfo"/> object.</returns>
public ColumnInfo SetPropertyUsing(Func<object, object, ICell, object> setProp)
{
SetProp = setProp;
return this;
}
/// <summary>Specifies a method to use when setting the property value from the cell value.</summary>
/// <param name="setProp">The method to use when setting the property value from the cell value.</param>
/// <returns>The <see cref="ColumnInfo"/> object.</returns>
public ColumnInfo SetPropertyUsing<T>(Func<T, object, object> setProp)
{
SetProp = (o, v, c) => setProp((T)o, v);
return this;
}
/// <summary>Specifies a method to use when setting the property value from the cell value.</summary>
/// <param name="setProp">The method to use when setting the property value from the cell value.</param>
/// <returns>The <see cref="ColumnInfo"/> object.</returns>
public ColumnInfo SetPropertyUsing<T>(Func<T, object, ICell, object> setProp)
{
SetProp = (o, v, c) => setProp((T)o, v, c);
return this;
}
/// <summary>Selects formula results to be mapped instead of the formula itself.</summary>
/// <returns>The <see cref="ColumnInfo"/> object.</returns>
public ColumnInfo AsFormulaResult()
{
FormulaResult = true;
return this;
}
/// <summary>Selects the property to be serialized as JSON.</summary>
/// <returns>The <see cref="ColumnInfo"/> object.</returns>
public ColumnInfo AsJson()
{
Json = true;
return this;
}
/// <summary>
/// Initializes a new instance of the <see cref="ColumnInfo"/> class.
/// </summary>
/// <param name="propertyInfo">The property information.</param>
/// <param name="direction">Data direction</param>
public ColumnInfo(PropertyInfo propertyInfo, MappingDirections direction = MappingDirections.Both)
{
Property = propertyInfo;
Directions = direction;
SetCell = GenerateCellSetter();
if (PropertyType == typeof(DateTime))
BuiltinFormat = 0x16; // "m/d/yy h:mm"
}
/// <summary>
/// Initializes a new instance of the <see cref="ColumnInfo"/> class.
/// </summary>
protected ColumnInfo() { }
/// <summary>Selects the property to be unidirectional from Excel to Object.</summary>
/// <returns>The <see cref="ColumnInfo"/> object.</returns>
public ColumnInfo FromExcelOnly()
{
Directions = MappingDirections.ExcelToObject;
return this;
}
/// <summary>Selects the property to be unidirectional from Excel to Object.</summary>
/// <returns>The <see cref="ColumnInfo"/> object.</returns>
public ColumnInfo ToExcelOnly()
{
Directions = MappingDirections.ObjectToExcel;
return this;
}
internal void ChangeSetterType(Type newType)
{
SetPropertyType(newType);
SetCell = GenerateCellSetter();
}
}
/// <summary>
/// Describes the mapping of an <see cref="ExpandoObject"/>'s property to a cell.
/// </summary>
public class DynamicColumnInfo : ColumnInfo
{
/// <summary>
/// Gets or sets the column index.
/// </summary>
public int Index { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="DynamicColumnInfo"/> class.
/// </summary>
/// <param name="index">The column index.</param>
/// <param name="name">The column name.</param>
public DynamicColumnInfo(int index, string name)
{
Index = index;
Name = name;
FormulaResult = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="DynamicColumnInfo"/> class.
/// </summary>
/// <param name="name">The column name.</param>
/// <param name="t">The type of the column.</param>
public DynamicColumnInfo(string name, Type t)
{
Name = name;
SetPropertyType(t);
SetCell = GenerateCellSetter();
if (PropertyType == typeof(DateTime))
BuiltinFormat = 0x16; // "m/d/yy h:mm"
}
/// <summary>
/// Sets the property of the specified object to the specified value.
/// </summary>
/// <param name="o">The object whose property to set.</param>
/// <param name="val">The value.</param>
/// <param name="cell">The cell where the value originates from.</param>
public override void SetProperty(object o, object val, ICell cell)
{
var expando = (IDictionary<string, object>)o;
if (!string.IsNullOrEmpty(Name))
expando.Add(Name, val);
}
/// <summary>
/// Gets the property value of the specified object.
/// </summary>
/// <param name="o">The o.</param>
/// <returns>The property value.</returns>
public override object GetProperty(object o)
{
return ((IDictionary<string, object>)o)[Name];
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
namespace ModestTree
{
public static class LinqExtensions
{
public static IEnumerable<T> Append<T>(this IEnumerable<T> first, T item)
{
foreach (T t in first)
{
yield return t;
}
yield return item;
}
public static IEnumerable<T> Prepend<T>(this IEnumerable<T> first, T item)
{
yield return item;
foreach (T t in first)
{
yield return t;
}
}
// Return the first item when the list is of length one and otherwise returns default
public static TSource OnlyOrDefault<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
var results = source.Take(2).ToArray();
return results.Length == 1 ? results[0] : default(TSource);
}
public static IEnumerable<T> Prepend<T>(this IEnumerable<T> first, IEnumerable<T> second)
{
foreach (T t in second)
{
yield return t;
}
foreach (T t in first)
{
yield return t;
}
}
// These are more efficient than Count() in cases where the size of the collection is not known
public static bool HasAtLeast<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.Take(amount).Count() == amount;
}
public static bool HasMoreThan<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.HasAtLeast(amount+1);
}
public static bool HasLessThan<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.HasAtMost(amount-1);
}
public static bool HasAtMost<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.Take(amount + 1).Count() <= amount;
}
public static bool IsEmpty<T>(this IEnumerable<T> enumerable)
{
return !enumerable.Any();
}
public static IEnumerable<T> GetDuplicates<T>(this IEnumerable<T> list)
{
return list.GroupBy(x => x).Where(x => x.Skip(1).Any()).Select(x => x.Key);
}
public static IEnumerable<T> ReplaceOrAppend<T>(
this IEnumerable<T> enumerable, Predicate<T> match, T replacement)
{
bool replaced = false;
foreach (T t in enumerable)
{
if (match(t))
{
replaced = true;
yield return replacement;
}
else
{
yield return t;
}
}
if (!replaced)
{
yield return replacement;
}
}
public static IEnumerable<T> ToEnumerable<T>(this IEnumerator enumerator)
{
while (enumerator.MoveNext())
{
yield return (T)enumerator.Current;
}
}
public static IEnumerable<T> ToEnumerable<T>(this IEnumerator<T> enumerator)
{
while (enumerator.MoveNext())
{
yield return enumerator.Current;
}
}
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> enumerable)
{
return new HashSet<T>(enumerable);
}
// This is more efficient than just Count() < x because it will end early
// rather than iterating over the entire collection
public static bool IsLength<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.Take(amount + 1).Count() == amount;
}
public static T GetSingle<T>(this object[] objectArray, bool required)
{
if (required)
{
return objectArray.Where(x => x is T).Cast<T>().Single();
}
else
{
return objectArray.Where(x => x is T).Cast<T>().SingleOrDefault();
}
}
public static IEnumerable<T> OfType<T>(this IEnumerable<T> source, Type type)
{
Assert.That(type.DerivesFromOrEqual<T>());
return source.Where(x => x.GetType() == type);
}
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
return source.DistinctBy(keySelector, null);
}
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
if (source == null)
throw new ArgumentNullException("source");
if (keySelector == null)
throw new ArgumentNullException("keySelector");
return DistinctByImpl(source, keySelector, comparer);
}
static IEnumerable<TSource> DistinctByImpl<TSource, TKey>(IEnumerable<TSource> source,
Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
var knownKeys = new HashSet<TKey>(comparer);
foreach (var element in source)
{
if (knownKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
public static T Second<T>(this IEnumerable<T> list)
{
return list.Skip(1).First();
}
public static T SecondOrDefault<T>(this IEnumerable<T> list)
{
return list.Skip(1).FirstOrDefault();
}
public static int RemoveAll<T>(this LinkedList<T> list, Func<T, bool> predicate)
{
int numRemoved = 0;
var currentNode = list.First;
while (currentNode != null)
{
if (predicate(currentNode.Value))
{
var toRemove = currentNode;
currentNode = currentNode.Next;
list.Remove(toRemove);
numRemoved++;
}
else
{
currentNode = currentNode.Next;
}
}
return numRemoved;
}
}
}
| |
// 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.Buffers.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Thrift.Protocol.Entities;
using Thrift.Transport;
namespace Thrift.Protocol
{
// ReSharper disable once InconsistentNaming
public class TBinaryProtocol : TProtocol
{
protected const uint VersionMask = 0xffff0000;
protected const uint Version1 = 0x80010000;
protected bool StrictRead;
protected bool StrictWrite;
// minimize memory allocations by means of an preallocated bytes buffer
// The value of 128 is arbitrarily chosen, the required minimum size must be sizeof(long)
private byte[] PreAllocatedBuffer = new byte[128];
private static readonly TStruct AnonymousStruct = new TStruct(string.Empty);
private static readonly TField StopField = new TField() { Type = TType.Stop };
public TBinaryProtocol(TTransport trans)
: this(trans, false, true)
{
}
public TBinaryProtocol(TTransport trans, bool strictRead, bool strictWrite)
: base(trans)
{
StrictRead = strictRead;
StrictWrite = strictWrite;
}
public override async Task WriteMessageBeginAsync(TMessage message, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
if (StrictWrite)
{
var version = Version1 | (uint) message.Type;
await WriteI32Async((int) version, cancellationToken);
await WriteStringAsync(message.Name, cancellationToken);
await WriteI32Async(message.SeqID, cancellationToken);
}
else
{
await WriteStringAsync(message.Name, cancellationToken);
await WriteByteAsync((sbyte) message.Type, cancellationToken);
await WriteI32Async(message.SeqID, cancellationToken);
}
}
public override async Task WriteMessageEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async Task WriteStructBeginAsync(TStruct @struct, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async Task WriteStructEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async Task WriteFieldBeginAsync(TField field, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
await WriteByteAsync((sbyte) field.Type, cancellationToken);
await WriteI16Async(field.ID, cancellationToken);
}
public override async Task WriteFieldEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async Task WriteFieldStopAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
await WriteByteAsync((sbyte) TType.Stop, cancellationToken);
}
public override async Task WriteMapBeginAsync(TMap map, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
PreAllocatedBuffer[0] = (byte)map.KeyType;
PreAllocatedBuffer[1] = (byte)map.ValueType;
await Trans.WriteAsync(PreAllocatedBuffer, 0, 2, cancellationToken);
await WriteI32Async(map.Count, cancellationToken);
}
public override async Task WriteMapEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async Task WriteListBeginAsync(TList list, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
await WriteByteAsync((sbyte) list.ElementType, cancellationToken);
await WriteI32Async(list.Count, cancellationToken);
}
public override async Task WriteListEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async Task WriteSetBeginAsync(TSet set, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
await WriteByteAsync((sbyte) set.ElementType, cancellationToken);
await WriteI32Async(set.Count, cancellationToken);
}
public override async Task WriteSetEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async Task WriteBoolAsync(bool b, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
await WriteByteAsync(b ? (sbyte) 1 : (sbyte) 0, cancellationToken);
}
public override async Task WriteByteAsync(sbyte b, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
PreAllocatedBuffer[0] = (byte)b;
await Trans.WriteAsync(PreAllocatedBuffer, 0, 1, cancellationToken);
}
public override async Task WriteI16Async(short i16, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
BinaryPrimitives.WriteInt16BigEndian(PreAllocatedBuffer, i16);
await Trans.WriteAsync(PreAllocatedBuffer, 0, 2, cancellationToken);
}
public override async Task WriteI32Async(int i32, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
BinaryPrimitives.WriteInt32BigEndian(PreAllocatedBuffer, i32);
await Trans.WriteAsync(PreAllocatedBuffer, 0, 4, cancellationToken);
}
public override async Task WriteI64Async(long i64, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
BinaryPrimitives.WriteInt64BigEndian(PreAllocatedBuffer, i64);
await Trans.WriteAsync(PreAllocatedBuffer, 0, 8, cancellationToken);
}
public override async Task WriteDoubleAsync(double d, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
await WriteI64Async(BitConverter.DoubleToInt64Bits(d), cancellationToken);
}
public override async Task WriteBinaryAsync(byte[] bytes, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
await WriteI32Async(bytes.Length, cancellationToken);
await Trans.WriteAsync(bytes, 0, bytes.Length, cancellationToken);
}
public override async ValueTask<TMessage> ReadMessageBeginAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<TMessage>(cancellationToken);
}
var message = new TMessage();
var size = await ReadI32Async(cancellationToken);
if (size < 0)
{
var version = (uint) size & VersionMask;
if (version != Version1)
{
throw new TProtocolException(TProtocolException.BAD_VERSION,
$"Bad version in ReadMessageBegin: {version}");
}
message.Type = (TMessageType) (size & 0x000000ff);
message.Name = await ReadStringAsync(cancellationToken);
message.SeqID = await ReadI32Async(cancellationToken);
}
else
{
if (StrictRead)
{
throw new TProtocolException(TProtocolException.BAD_VERSION,
"Missing version in ReadMessageBegin, old client?");
}
message.Name = (size > 0) ? await ReadStringBodyAsync(size, cancellationToken) : string.Empty;
message.Type = (TMessageType) await ReadByteAsync(cancellationToken);
message.SeqID = await ReadI32Async(cancellationToken);
}
return message;
}
public override async Task ReadMessageEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async ValueTask<TStruct> ReadStructBeginAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
return AnonymousStruct;
}
public override async Task ReadStructEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async ValueTask<TField> ReadFieldBeginAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<TField>(cancellationToken);
}
var type = (TType)await ReadByteAsync(cancellationToken);
if (type == TType.Stop)
{
return StopField;
}
return new TField {
Type = type,
ID = await ReadI16Async(cancellationToken)
};
}
public override async Task ReadFieldEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async ValueTask<TMap> ReadMapBeginAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<TMap>(cancellationToken);
}
var map = new TMap
{
KeyType = (TType) await ReadByteAsync(cancellationToken),
ValueType = (TType) await ReadByteAsync(cancellationToken),
Count = await ReadI32Async(cancellationToken)
};
CheckReadBytesAvailable(map);
return map;
}
public override async Task ReadMapEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async ValueTask<TList> ReadListBeginAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<TList>(cancellationToken);
}
var list = new TList
{
ElementType = (TType) await ReadByteAsync(cancellationToken),
Count = await ReadI32Async(cancellationToken)
};
CheckReadBytesAvailable(list);
return list;
}
public override async Task ReadListEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async ValueTask<TSet> ReadSetBeginAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<TSet>(cancellationToken);
}
var set = new TSet
{
ElementType = (TType) await ReadByteAsync(cancellationToken),
Count = await ReadI32Async(cancellationToken)
};
CheckReadBytesAvailable(set);
return set;
}
public override async Task ReadSetEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async ValueTask<bool> ReadBoolAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<bool>(cancellationToken);
}
return await ReadByteAsync(cancellationToken) == 1;
}
public override async ValueTask<sbyte> ReadByteAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<sbyte>(cancellationToken);
}
await Trans.ReadAllAsync(PreAllocatedBuffer, 0, 1, cancellationToken);
return (sbyte)PreAllocatedBuffer[0];
}
public override async ValueTask<short> ReadI16Async(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<short>(cancellationToken);
}
await Trans.ReadAllAsync(PreAllocatedBuffer, 0, 2, cancellationToken);
var result = BinaryPrimitives.ReadInt16BigEndian(PreAllocatedBuffer);
return result;
}
public override async ValueTask<int> ReadI32Async(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<int>(cancellationToken);
}
await Trans.ReadAllAsync(PreAllocatedBuffer, 0, 4, cancellationToken);
var result = BinaryPrimitives.ReadInt32BigEndian(PreAllocatedBuffer);
return result;
}
public override async ValueTask<long> ReadI64Async(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<long>(cancellationToken);
}
await Trans.ReadAllAsync(PreAllocatedBuffer, 0, 8, cancellationToken);
return BinaryPrimitives.ReadInt64BigEndian(PreAllocatedBuffer);
}
public override async ValueTask<double> ReadDoubleAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<double>(cancellationToken);
}
var d = await ReadI64Async(cancellationToken);
return BitConverter.Int64BitsToDouble(d);
}
public override async ValueTask<byte[]> ReadBinaryAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<byte[]>(cancellationToken);
}
var size = await ReadI32Async(cancellationToken);
Transport.CheckReadBytesAvailable(size);
var buf = new byte[size];
await Trans.ReadAllAsync(buf, 0, size, cancellationToken);
return buf;
}
public override async ValueTask<string> ReadStringAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<string>(cancellationToken);
}
var size = await ReadI32Async(cancellationToken);
return size > 0 ? await ReadStringBodyAsync(size, cancellationToken) : string.Empty;
}
private async ValueTask<string> ReadStringBodyAsync(int size, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled<string>(cancellationToken);
}
if (size <= PreAllocatedBuffer.Length)
{
await Trans.ReadAllAsync(PreAllocatedBuffer, 0, size, cancellationToken);
return Encoding.UTF8.GetString(PreAllocatedBuffer, 0, size);
}
Transport.CheckReadBytesAvailable(size);
var buf = new byte[size];
await Trans.ReadAllAsync(buf, 0, size, cancellationToken);
return Encoding.UTF8.GetString(buf, 0, buf.Length);
}
// Return the minimum number of bytes a type will consume on the wire
public override int GetMinSerializedSize(TType type)
{
switch (type)
{
case TType.Stop: return 0;
case TType.Void: return 0;
case TType.Bool: return sizeof(byte);
case TType.Byte: return sizeof(byte);
case TType.Double: return sizeof(double);
case TType.I16: return sizeof(short);
case TType.I32: return sizeof(int);
case TType.I64: return sizeof(long);
case TType.String: return sizeof(int); // string length
case TType.Struct: return 0; // empty struct
case TType.Map: return sizeof(int); // element count
case TType.Set: return sizeof(int); // element count
case TType.List: return sizeof(int); // element count
default: throw new TTransportException(TTransportException.ExceptionType.Unknown, "unrecognized type code");
}
}
public class Factory : TProtocolFactory
{
protected bool StrictRead;
protected bool StrictWrite;
public Factory()
: this(false, true)
{
}
public Factory(bool strictRead, bool strictWrite)
{
StrictRead = strictRead;
StrictWrite = strictWrite;
}
public override TProtocol GetProtocol(TTransport trans)
{
return new TBinaryProtocol(trans, StrictRead, StrictWrite);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Routing;
using System.Xml;
using System.Xml.Linq;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
namespace Umbraco.Core.Configuration
{
//NOTE: Do not expose this class ever until we cleanup all configuration including removal of static classes, etc...
// we have this two tasks logged:
// http://issues.umbraco.org/issue/U4-58
// http://issues.umbraco.org/issue/U4-115
//TODO: Replace checking for if the app settings exist and returning an empty string, instead return the defaults!
/// <summary>
/// The GlobalSettings Class contains general settings information for the entire Umbraco instance based on information from web.config appsettings
/// </summary>
internal class GlobalSettings
{
#region Private static fields
private static Version _version;
private static readonly object Locker = new object();
//make this volatile so that we can ensure thread safety with a double check lock
private static volatile string _reservedUrlsCache;
private static string _reservedPathsCache;
private static StartsWithContainer _reservedList = new StartsWithContainer();
private static string _reservedPaths;
private static string _reservedUrls;
//ensure the built on (non-changeable) reserved paths are there at all times
private const string StaticReservedPaths = "~/app_plugins/,~/install/,";
private const string StaticReservedUrls = "~/config/splashes/booting.aspx,~/install/default.aspx,~/config/splashes/noNodes.aspx,~/VSEnterpriseHelper.axd,";
#endregion
/// <summary>
/// Used in unit testing to reset all config items that were set with property setters (i.e. did not come from config)
/// </summary>
private static void ResetInternal()
{
_reservedUrlsCache = null;
_reservedPaths = null;
_reservedUrls = null;
}
/// <summary>
/// Resets settings that were set programmatically, to their initial values.
/// </summary>
/// <remarks>To be used in unit tests.</remarks>
internal static void Reset()
{
ResetInternal();
}
/// <summary>
/// Gets the reserved urls from web.config.
/// </summary>
/// <value>The reserved urls.</value>
public static string ReservedUrls
{
get
{
if (_reservedUrls == null)
{
var urls = ConfigurationManager.AppSettings.ContainsKey("umbracoReservedUrls")
? ConfigurationManager.AppSettings["umbracoReservedUrls"]
: string.Empty;
//ensure the built on (non-changeable) reserved paths are there at all times
_reservedUrls = StaticReservedUrls + urls;
}
return _reservedUrls;
}
internal set { _reservedUrls = value; }
}
/// <summary>
/// Gets the reserved paths from web.config
/// </summary>
/// <value>The reserved paths.</value>
public static string ReservedPaths
{
get
{
if (_reservedPaths == null)
{
var reservedPaths = StaticReservedPaths;
//always add the umbraco path to the list
if (ConfigurationManager.AppSettings.ContainsKey("umbracoPath")
&& !ConfigurationManager.AppSettings["umbracoPath"].IsNullOrWhiteSpace())
{
reservedPaths += ConfigurationManager.AppSettings["umbracoPath"].EnsureEndsWith(',');
}
var allPaths = ConfigurationManager.AppSettings.ContainsKey("umbracoReservedPaths")
? ConfigurationManager.AppSettings["umbracoReservedPaths"]
: string.Empty;
_reservedPaths = reservedPaths + allPaths;
}
return _reservedPaths;
}
internal set { _reservedPaths = value; }
}
/// <summary>
/// Gets the name of the content XML file.
/// </summary>
/// <value>The content XML.</value>
public static string ContentXmlFile
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoContentXML")
? ConfigurationManager.AppSettings["umbracoContentXML"]
: string.Empty;
}
}
/// <summary>
/// Gets the path to the storage directory (/data by default).
/// </summary>
/// <value>The storage directory.</value>
public static string StorageDirectory
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoStorageDirectory")
? ConfigurationManager.AppSettings["umbracoStorageDirectory"]
: string.Empty;
}
}
/// <summary>
/// Gets the path to umbraco's root directory (/umbraco by default).
/// </summary>
/// <value>The path.</value>
public static string Path
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoPath")
? IOHelper.ResolveUrl(ConfigurationManager.AppSettings["umbracoPath"])
: string.Empty;
}
}
/// <summary>
/// This returns the string of the MVC Area route.
/// </summary>
/// <remarks>
/// THIS IS TEMPORARY AND SHOULD BE REMOVED WHEN WE MIGRATE/UPDATE THE CONFIG SETTINGS TO BE A REAL CONFIG SECTION
/// AND SHOULD PROBABLY BE HANDLED IN A MORE ROBUST WAY.
///
/// This will return the MVC area that we will route all custom routes through like surface controllers, etc...
/// We will use the 'Path' (default ~/umbraco) to create it but since it cannot contain '/' and people may specify a path of ~/asdf/asdf/admin
/// we will convert the '/' to '-' and use that as the path. its a bit lame but will work.
///
/// We also make sure that the virtual directory (SystemDirectories.Root) is stripped off first, otherwise we'd end up with something
/// like "MyVirtualDirectory-Umbraco" instead of just "Umbraco".
/// </remarks>
internal static string UmbracoMvcArea
{
get
{
if (Path.IsNullOrWhiteSpace())
{
throw new InvalidOperationException("Cannot create an MVC Area path without the umbracoPath specified");
}
return Path.TrimStart(SystemDirectories.Root).TrimStart('~').TrimStart('/').Replace('/', '-').Trim().ToLower();
}
}
/// <summary>
/// Gets the path to umbraco's client directory (/umbraco_client by default).
/// This is a relative path to the Umbraco Path as it always must exist beside the 'umbraco'
/// folder since the CSS paths to images depend on it.
/// </summary>
/// <value>The path.</value>
public static string ClientPath
{
get
{
return Path + "/../umbraco_client";
}
}
/// <summary>
/// Gets the database connection string
/// </summary>
/// <value>The database connection string.</value>
[Obsolete("Use System.Configuration.ConfigurationManager.ConnectionStrings[\"umbracoDbDSN\"] instead")]
public static string DbDsn
{
get
{
var settings = ConfigurationManager.ConnectionStrings[UmbracoConnectionName];
var connectionString = string.Empty;
if (settings != null)
{
connectionString = settings.ConnectionString;
// The SqlCe connectionString is formatted slightly differently, so we need to update it
if (settings.ProviderName.Contains("SqlServerCe"))
connectionString = string.Format("datalayer=SQLCE4Umbraco.SqlCEHelper,SQLCE4Umbraco;{0}", connectionString);
}
return connectionString;
}
set
{
if (DbDsn != value)
{
if (value.ToLower().Contains("SQLCE4Umbraco.SqlCEHelper".ToLower()))
{
ApplicationContext.Current.DatabaseContext.ConfigureEmbeddedDatabaseConnection();
}
else
{
ApplicationContext.Current.DatabaseContext.ConfigureDatabaseConnection(value);
}
}
}
}
public const string UmbracoConnectionName = "umbracoDbDSN";
public const string UmbracoMigrationName = "Umbraco";
/// <summary>
/// Gets or sets the configuration status. This will return the version number of the currently installed umbraco instance.
/// </summary>
/// <value>The configuration status.</value>
public static string ConfigurationStatus
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoConfigurationStatus")
? ConfigurationManager.AppSettings["umbracoConfigurationStatus"]
: string.Empty;
}
set
{
SaveSetting("umbracoConfigurationStatus", value);
}
}
/// <summary>
/// Saves a setting into the configuration file.
/// </summary>
/// <param name="key">Key of the setting to be saved.</param>
/// <param name="value">Value of the setting to be saved.</param>
internal static void SaveSetting(string key, string value)
{
var fileName = GetFullWebConfigFileName();
var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace);
var appSettings = xml.Root.Descendants("appSettings").Single();
// Update appSetting if it exists, or else create a new appSetting for the given key and value
var setting = appSettings.Descendants("add").FirstOrDefault(s => s.Attribute("key").Value == key);
if (setting == null)
appSettings.Add(new XElement("add", new XAttribute("key", key), new XAttribute("value", value)));
else
setting.Attribute("value").Value = value;
xml.Save(fileName, SaveOptions.DisableFormatting);
ConfigurationManager.RefreshSection("appSettings");
}
/// <summary>
/// Removes a setting from the configuration file.
/// </summary>
/// <param name="key">Key of the setting to be removed.</param>
internal static void RemoveSetting(string key)
{
var fileName = GetFullWebConfigFileName();
var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace);
var appSettings = xml.Root.Descendants("appSettings").Single();
var setting = appSettings.Descendants("add").FirstOrDefault(s => s.Attribute("key").Value == key);
if (setting != null)
{
setting.Remove();
xml.Save(fileName, SaveOptions.DisableFormatting);
ConfigurationManager.RefreshSection("appSettings");
}
}
private static string GetFullWebConfigFileName()
{
var webConfig = new WebConfigurationFileMap();
var vDir = FullpathToRoot;
foreach (VirtualDirectoryMapping v in webConfig.VirtualDirectories)
{
if (v.IsAppRoot)
vDir = v.PhysicalDirectory;
}
var fileName = System.IO.Path.Combine(vDir, "web.config");
return fileName;
}
/// <summary>
/// Gets the full path to root.
/// </summary>
/// <value>The fullpath to root.</value>
public static string FullpathToRoot
{
get { return IOHelper.GetRootDirectorySafe(); }
}
/// <summary>
/// Gets a value indicating whether umbraco is running in [debug mode].
/// </summary>
/// <value><c>true</c> if [debug mode]; otherwise, <c>false</c>.</value>
public static bool DebugMode
{
get
{
try
{
return bool.Parse(ConfigurationManager.AppSettings["umbracoDebugMode"]);
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets a value indicating whether the current version of umbraco is configured.
/// </summary>
/// <value><c>true</c> if configured; otherwise, <c>false</c>.</value>
public static bool Configured
{
get
{
try
{
string configStatus = ConfigurationStatus;
string currentVersion = UmbracoVersion.Current.ToString(3);
if (currentVersion != configStatus)
{
LogHelper.Debug<GlobalSettings>("CurrentVersion different from configStatus: '" + currentVersion + "','" + configStatus + "'");
}
return (configStatus == currentVersion);
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets the time out in minutes.
/// </summary>
/// <value>The time out in minutes.</value>
public static int TimeOutInMinutes
{
get
{
try
{
return int.Parse(ConfigurationManager.AppSettings["umbracoTimeOutInMinutes"]);
}
catch
{
return 20;
}
}
}
/// <summary>
/// Gets a value indicating whether umbraco uses directory urls.
/// </summary>
/// <value><c>true</c> if umbraco uses directory urls; otherwise, <c>false</c>.</value>
public static bool UseDirectoryUrls
{
get
{
try
{
return bool.Parse(ConfigurationManager.AppSettings["umbracoUseDirectoryUrls"]);
}
catch
{
return false;
}
}
}
/// <summary>
/// Returns a string value to determine if umbraco should skip version-checking.
/// </summary>
/// <value>The version check period in days (0 = never).</value>
public static int VersionCheckPeriod
{
get
{
try
{
return int.Parse(ConfigurationManager.AppSettings["umbracoVersionCheckPeriod"]);
}
catch
{
return 7;
}
}
}
/// <summary>
/// Returns a string value to determine if umbraco should disbable xslt extensions
/// </summary>
/// <value><c>"true"</c> if version xslt extensions are disabled, otherwise, <c>"false"</c></value>
public static string DisableXsltExtensions
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoDisableXsltExtensions")
? ConfigurationManager.AppSettings["umbracoDisableXsltExtensions"]
: string.Empty;
}
}
/// <summary>
/// Returns a string value to determine if umbraco should use Xhtml editing mode in the wysiwyg editor
/// </summary>
/// <value><c>"true"</c> if Xhtml mode is enable, otherwise, <c>"false"</c></value>
public static string EditXhtmlMode
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoEditXhtmlMode")
? ConfigurationManager.AppSettings["umbracoEditXhtmlMode"]
: string.Empty;
}
}
/// <summary>
/// Gets the default UI language.
/// </summary>
/// <value>The default UI language.</value>
public static string DefaultUILanguage
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoDefaultUILanguage")
? ConfigurationManager.AppSettings["umbracoDefaultUILanguage"]
: string.Empty;
}
}
/// <summary>
/// Gets the profile URL.
/// </summary>
/// <value>The profile URL.</value>
public static string ProfileUrl
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoProfileUrl")
? ConfigurationManager.AppSettings["umbracoProfileUrl"]
: string.Empty;
}
}
/// <summary>
/// Gets a value indicating whether umbraco should hide top level nodes from generated urls.
/// </summary>
/// <value>
/// <c>true</c> if umbraco hides top level nodes from urls; otherwise, <c>false</c>.
/// </value>
public static bool HideTopLevelNodeFromPath
{
get
{
try
{
return bool.Parse(ConfigurationManager.AppSettings["umbracoHideTopLevelNodeFromPath"]);
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets the current version.
/// </summary>
/// <value>The current version.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static string CurrentVersion
{
get
{
return UmbracoVersion.Current.ToString(3);
}
}
/// <summary>
/// Gets the major version number.
/// </summary>
/// <value>The major version number.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static int VersionMajor
{
get
{
return UmbracoVersion.Current.Major;
}
}
/// <summary>
/// Gets the minor version number.
/// </summary>
/// <value>The minor version number.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static int VersionMinor
{
get
{
return UmbracoVersion.Current.Minor;
}
}
/// <summary>
/// Gets the patch version number.
/// </summary>
/// <value>The patch version number.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static int VersionPatch
{
get
{
return UmbracoVersion.Current.Build;
}
}
/// <summary>
/// Gets the version comment (like beta or RC).
/// </summary>
/// <value>The version comment.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static string VersionComment
{
get
{
return Umbraco.Core.Configuration.UmbracoVersion.CurrentComment;
}
}
/// <summary>
/// Requests the is in umbraco application directory structure.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
public static bool RequestIsInUmbracoApplication(HttpContext context)
{
return context.Request.Path.ToLower().IndexOf(IOHelper.ResolveUrl(SystemDirectories.Umbraco).ToLower()) > -1;
}
public static bool RequestIsLiveEditRedirector(HttpContext context)
{
return context.Request.Path.ToLower().IndexOf(SystemDirectories.Umbraco.ToLower() + "/liveediting.aspx") > -1;
}
public static bool RequestIsInUmbracoApplication(HttpContextBase context)
{
return context.Request.Path.ToLower().IndexOf(IOHelper.ResolveUrl(SystemDirectories.Umbraco).ToLower()) > -1;
}
public static bool RequestIsLiveEditRedirector(HttpContextBase context)
{
return context.Request.Path.ToLower().IndexOf(SystemDirectories.Umbraco.ToLower() + "/liveediting.aspx") > -1;
}
/// <summary>
/// Gets a value indicating whether umbraco should force a secure (https) connection to the backoffice.
/// </summary>
/// <value><c>true</c> if [use SSL]; otherwise, <c>false</c>.</value>
public static bool UseSSL
{
get
{
try
{
return bool.Parse(ConfigurationManager.AppSettings["umbracoUseSSL"]);
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets the umbraco license.
/// </summary>
/// <value>The license.</value>
public static string License
{
get
{
string license =
"<A href=\"http://umbraco.org/redir/license\" target=\"_blank\">the open source license MIT</A>. The umbraco UI is freeware licensed under the umbraco license.";
var versionDoc = new XmlDocument();
var versionReader = new XmlTextReader(IOHelper.MapPath(SystemDirectories.Umbraco + "/version.xml"));
versionDoc.Load(versionReader);
versionReader.Close();
// check for license
try
{
string licenseUrl =
versionDoc.SelectSingleNode("/version/licensing/licenseUrl").FirstChild.Value;
string licenseValidation =
versionDoc.SelectSingleNode("/version/licensing/licenseValidation").FirstChild.Value;
string licensedTo =
versionDoc.SelectSingleNode("/version/licensing/licensedTo").FirstChild.Value;
if (licensedTo != "" && licenseUrl != "")
{
license = "umbraco Commercial License<br/><b>Registered to:</b><br/>" +
licensedTo.Replace("\n", "<br/>") + "<br/><b>For use with domain:</b><br/>" +
licenseUrl;
}
}
catch
{
}
return license;
}
}
/// <summary>
/// Determines whether the current request is reserved based on the route table and
/// whether the specified URL is reserved or is inside a reserved path.
/// </summary>
/// <param name="url"></param>
/// <param name="httpContext"></param>
/// <param name="routes">The route collection to lookup the request in</param>
/// <returns></returns>
public static bool IsReservedPathOrUrl(string url, HttpContextBase httpContext, RouteCollection routes)
{
if (httpContext == null) throw new ArgumentNullException("httpContext");
if (routes == null) throw new ArgumentNullException("routes");
//check if the current request matches a route, if so then it is reserved.
var route = routes.GetRouteData(httpContext);
if (route != null)
return true;
//continue with the standard ignore routine
return IsReservedPathOrUrl(url);
}
/// <summary>
/// Determines whether the specified URL is reserved or is inside a reserved path.
/// </summary>
/// <param name="url">The URL to check.</param>
/// <returns>
/// <c>true</c> if the specified URL is reserved; otherwise, <c>false</c>.
/// </returns>
public static bool IsReservedPathOrUrl(string url)
{
if (_reservedUrlsCache == null)
{
lock (Locker)
{
if (_reservedUrlsCache == null)
{
// store references to strings to determine changes
_reservedPathsCache = GlobalSettings.ReservedPaths;
_reservedUrlsCache = GlobalSettings.ReservedUrls;
string _root = SystemDirectories.Root.Trim().ToLower();
// add URLs and paths to a new list
StartsWithContainer _newReservedList = new StartsWithContainer();
foreach (string reservedUrl in _reservedUrlsCache.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries))
{
//resolves the url to support tilde chars
string reservedUrlTrimmed = IOHelper.ResolveUrl(reservedUrl).Trim().ToLower();
if (reservedUrlTrimmed.Length > 0)
_newReservedList.Add(reservedUrlTrimmed);
}
foreach (string reservedPath in _reservedPathsCache.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries))
{
bool trimEnd = !reservedPath.EndsWith("/");
//resolves the url to support tilde chars
string reservedPathTrimmed = IOHelper.ResolveUrl(reservedPath).Trim().ToLower();
if (reservedPathTrimmed.Length > 0)
_newReservedList.Add(reservedPathTrimmed + (reservedPathTrimmed.EndsWith("/") ? "" : "/"));
}
// use the new list from now on
_reservedList = _newReservedList;
}
}
}
//The url should be cleaned up before checking:
// * If it doesn't contain an '.' in the path then we assume it is a path based URL, if that is the case we should add an trailing '/' because all of our reservedPaths use a trailing '/'
// * We shouldn't be comparing the query at all
var pathPart = url.Split('?')[0];
if (!pathPart.Contains(".") && !pathPart.EndsWith("/"))
{
pathPart += "/";
}
// return true if url starts with an element of the reserved list
return _reservedList.StartsWith(pathPart.ToLowerInvariant());
}
/// <summary>
/// Structure that checks in logarithmic time
/// if a given string starts with one of the added keys.
/// </summary>
private class StartsWithContainer
{
/// <summary>Internal sorted list of keys.</summary>
public SortedList<string, string> _list
= new SortedList<string, string>(StartsWithComparator.Instance);
/// <summary>
/// Adds the specified new key.
/// </summary>
/// <param name="newKey">The new key.</param>
public void Add(string newKey)
{
// if the list already contains an element that begins with newKey, return
if (String.IsNullOrEmpty(newKey) || StartsWith(newKey))
return;
// create a new collection, so the old one can still be accessed
SortedList<string, string> newList
= new SortedList<string, string>(_list.Count + 1, StartsWithComparator.Instance);
// add only keys that don't already start with newKey, others are unnecessary
foreach (string key in _list.Keys)
if (!key.StartsWith(newKey))
newList.Add(key, null);
// add the new key
newList.Add(newKey, null);
// update the list (thread safe, _list was never in incomplete state)
_list = newList;
}
/// <summary>
/// Checks if the given string starts with any of the added keys.
/// </summary>
/// <param name="target">The target.</param>
/// <returns>true if a key is found that matches the start of target</returns>
/// <remarks>
/// Runs in O(s*log(n)), with n the number of keys and s the length of target.
/// </remarks>
public bool StartsWith(string target)
{
return _list.ContainsKey(target);
}
/// <summary>Comparator that tests if a string starts with another.</summary>
/// <remarks>Not a real comparator, since it is not reflexive. (x==y does not imply y==x)</remarks>
private sealed class StartsWithComparator : IComparer<string>
{
/// <summary>Default string comparer.</summary>
private readonly static Comparer<string> _stringComparer = Comparer<string>.Default;
/// <summary>Gets an instance of the StartsWithComparator.</summary>
public static readonly StartsWithComparator Instance = new StartsWithComparator();
/// <summary>
/// Tests if whole begins with all characters of part.
/// </summary>
/// <param name="part">The part.</param>
/// <param name="whole">The whole.</param>
/// <returns>
/// Returns 0 if whole starts with part, otherwise performs standard string comparison.
/// </returns>
public int Compare(string part, string whole)
{
// let the default string comparer deal with null or when part is not smaller then whole
if (part == null || whole == null || part.Length >= whole.Length)
return _stringComparer.Compare(part, whole);
////ensure both have a / on the end
//part = part.EndsWith("/") ? part : part + "/";
//whole = whole.EndsWith("/") ? whole : whole + "/";
//if (part.Length >= whole.Length)
// return _stringComparer.Compare(part, whole);
// loop through all characters that part and whole have in common
int pos = 0;
bool match;
do
{
match = (part[pos] == whole[pos]);
} while (match && ++pos < part.Length);
// return result of last comparison
return match ? 0 : (part[pos] < whole[pos] ? -1 : 1);
}
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) Under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for Additional information regarding copyright ownership.
* The ASF licenses this file to You Under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed Under the License is distributed on an "AS Is" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations Under the License.
*/
namespace NPOI.SS.Formula.Functions
{
using System;
using NPOI.SS.Formula.Eval;
using System.Text;
/**
* Implementation for Excel function OFFSet()<p/>
*
* OFFSet returns an area reference that Is a specified number of rows and columns from a
* reference cell or area.<p/>
*
* <b>Syntax</b>:<br/>
* <b>OFFSet</b>(<b>reference</b>, <b>rows</b>, <b>cols</b>, height, width)<p/>
* <b>reference</b> Is the base reference.<br/>
* <b>rows</b> Is the number of rows up or down from the base reference.<br/>
* <b>cols</b> Is the number of columns left or right from the base reference.<br/>
* <b>height</b> (default same height as base reference) Is the row Count for the returned area reference.<br/>
* <b>width</b> (default same width as base reference) Is the column Count for the returned area reference.<br/>
*
* @author Josh Micich
*/
public class Offset : Function
{
// These values are specific to BIFF8
private const int LAST_VALID_ROW_INDEX = 0xFFFF;
private const int LAST_VALID_COLUMN_INDEX = 0xFF;
/**
* Exceptions are used within this class to help simplify flow control when error conditions
* are enCountered
*/
[Serializable]
private class EvalEx : Exception
{
private ErrorEval _error;
public EvalEx(ErrorEval error)
{
_error = error;
}
public ErrorEval GetError()
{
return _error;
}
}
/**
* A one dimensional base + offset. Represents either a row range or a column range.
* Two instances of this class toGether specify an area range.
*/
/* package */
public class LinearOffsetRange
{
private int _offset;
private int _Length;
public LinearOffsetRange(int offset, int length)
{
if (length == 0)
{
// handled that condition much earlier
throw new ArgumentException("Length may not be zero");
}
_offset = offset;
_Length = length;
}
public short FirstIndex
{
get
{
return (short)_offset;
}
}
public short LastIndex
{
get
{
return (short)(_offset + _Length - 1);
}
}
/**
* Moves the range by the specified translation amount.<p/>
*
* This method also 'normalises' the range: Excel specifies that the width and height
* parameters (Length field here) cannot be negative. However, OFFSet() does produce
* sensible results in these cases. That behavior Is replicated here. <p/>
*
* @param translationAmount may be zero negative or positive
*
* @return the equivalent <c>LinearOffsetRange</c> with a positive Length, moved by the
* specified translationAmount.
*/
public LinearOffsetRange NormaliseAndTranslate(int translationAmount)
{
if (_Length > 0)
{
if (translationAmount == 0)
{
return this;
}
return new LinearOffsetRange(translationAmount + _offset, _Length);
}
return new LinearOffsetRange(translationAmount + _offset + _Length + 1, -_Length);
}
public bool IsOutOfBounds(int lowValidIx, int highValidIx)
{
if (_offset < lowValidIx)
{
return true;
}
if (LastIndex > highValidIx)
{
return true;
}
return false;
}
public override String ToString()
{
StringBuilder sb = new StringBuilder(64);
sb.Append(GetType().Name).Append(" [");
sb.Append(_offset).Append("...").Append(LastIndex);
sb.Append("]");
return sb.ToString();
}
}
/**
* Encapsulates either an area or cell reference which may be 2d or 3d.
*/
private class BaseRef
{
private const int INVALID_SHEET_INDEX = -1;
private int _firstRowIndex;
private int _firstColumnIndex;
private int _width;
private int _height;
private RefEval _refEval;
private AreaEval _areaEval;
public BaseRef(RefEval re)
{
_refEval = re;
_areaEval = null;
_firstRowIndex = re.Row;
_firstColumnIndex = re.Column;
_height = 1;
_width = 1;
}
public BaseRef(AreaEval ae)
{
_refEval = null;
_areaEval = ae;
_firstRowIndex = ae.FirstRow;
_firstColumnIndex = ae.FirstColumn;
_height = ae.LastRow - ae.FirstRow + 1;
_width = ae.LastColumn - ae.FirstColumn + 1;
}
public int Width
{
get
{
return _width;
}
}
public int Height
{
get
{
return _height;
}
}
public int FirstRowIndex
{
get
{
return _firstRowIndex;
}
}
public int FirstColumnIndex
{
get
{
return _firstColumnIndex;
}
}
public AreaEval Offset(int relFirstRowIx, int relLastRowIx,int relFirstColIx, int relLastColIx)
{
if (_refEval == null)
{
return _areaEval.Offset(relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx);
}
return _refEval.Offset(relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx);
}
}
public ValueEval Evaluate(ValueEval[] args, int srcCellRow, int srcCellCol)
{
if (args.Length < 3 || args.Length > 5)
{
return ErrorEval.VALUE_INVALID;
}
try
{
BaseRef baseRef = EvaluateBaseRef(args[0]);
int rowOffset = EvaluateIntArg(args[1], srcCellRow, srcCellCol);
int columnOffset = EvaluateIntArg(args[2], srcCellRow, srcCellCol);
int height = baseRef.Height;
int width = baseRef.Width;
switch (args.Length)
{
case 5:
width = EvaluateIntArg(args[4], srcCellRow, srcCellCol);
break;
case 4:
height = EvaluateIntArg(args[3], srcCellRow, srcCellCol);
break;
}
// Zero height or width raises #REF! error
if (height == 0 || width == 0)
{
return ErrorEval.REF_INVALID;
}
LinearOffsetRange rowOffsetRange = new LinearOffsetRange(rowOffset, height);
LinearOffsetRange colOffsetRange = new LinearOffsetRange(columnOffset, width);
return CreateOffset(baseRef, rowOffsetRange, colOffsetRange);
}
catch (EvaluationException e)
{
return e.GetErrorEval();
}
}
private static AreaEval CreateOffset(BaseRef baseRef,
LinearOffsetRange orRow, LinearOffsetRange orCol)
{
LinearOffsetRange absRows = orRow.NormaliseAndTranslate(baseRef.FirstRowIndex);
LinearOffsetRange absCols = orCol.NormaliseAndTranslate(baseRef.FirstColumnIndex);
if (absRows.IsOutOfBounds(0, LAST_VALID_ROW_INDEX))
{
throw new EvaluationException(ErrorEval.REF_INVALID);
}
if (absCols.IsOutOfBounds(0, LAST_VALID_COLUMN_INDEX))
{
throw new EvaluationException(ErrorEval.REF_INVALID);
}
return baseRef.Offset(orRow.FirstIndex, orRow.LastIndex, orCol.FirstIndex, orCol.LastIndex);
}
private static BaseRef EvaluateBaseRef(ValueEval eval)
{
if (eval is RefEval)
{
return new BaseRef((RefEval)eval);
}
if (eval is AreaEval)
{
return new BaseRef((AreaEval)eval);
}
if (eval is ErrorEval)
{
throw new EvalEx((ErrorEval)eval);
}
throw new EvalEx(ErrorEval.VALUE_INVALID);
}
/**
* OFFSet's numeric arguments (2..5) have similar Processing rules
*/
public static int EvaluateIntArg(ValueEval eval, int srcCellRow, int srcCellCol)
{
double d = EvaluateDoubleArg(eval, srcCellRow, srcCellCol);
return ConvertDoubleToInt(d);
}
/**
* Fractional values are silently truncated by Excel.
* Truncation Is toward negative infinity.
*/
/* package */
public static int ConvertDoubleToInt(double d)
{
// Note - the standard java type conversion from double to int truncates toward zero.
// but Math.floor() truncates toward negative infinity
return (int)Math.Floor(d);
}
private static double EvaluateDoubleArg(ValueEval eval, int srcCellRow, int srcCellCol)
{
ValueEval ve = OperandResolver.GetSingleValue(eval, srcCellRow, srcCellCol);
if (ve is NumericValueEval)
{
return ((NumericValueEval)ve).NumberValue;
}
if (ve is StringEval)
{
StringEval se = (StringEval)ve;
double d = OperandResolver.ParseDouble(se.StringValue);
if (double.IsNaN(d))
{
throw new EvalEx(ErrorEval.VALUE_INVALID);
}
return d;
}
if (ve is BoolEval)
{
// in the context of OFFSet, bools resolve to 0 and 1.
if (((BoolEval)ve).BooleanValue)
{
return 1;
}
return 0;
}
throw new Exception("Unexpected eval type (" + ve.GetType().Name + ")");
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Automation
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// AutomationAccountOperations operations.
/// </summary>
internal partial class AutomationAccountOperations : IServiceOperations<AutomationClient>, IAutomationAccountOperations
{
/// <summary>
/// Initializes a new instance of the AutomationAccountOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal AutomationAccountOperations(AutomationClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutomationClient
/// </summary>
public AutomationClient Client { get; private set; }
/// <summary>
/// Update an automation account.
/// <see href="http://aka.ms/azureautomationsdk/automationaccountoperations" />
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// Automation account name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the update automation account.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<AutomationAccount>> UpdateWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, AutomationAccountUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (automationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-10-31";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccountName", automationAccountName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<AutomationAccount>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AutomationAccount>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Create or update automation account.
/// <see href="http://aka.ms/azureautomationsdk/automationaccountoperations" />
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// Parameters supplied to the create or update automation account.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update automation account.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<AutomationAccount>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, AutomationAccountCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (automationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-10-31";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccountName", automationAccountName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201 && (int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<AutomationAccount>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AutomationAccount>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AutomationAccount>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Delete an automation account.
/// <see href="http://aka.ms/azureautomationsdk/automationaccountoperations" />
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// Automation account name.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (automationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-10-31";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccountName", automationAccountName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get information about an Automation Account.
/// <see href="http://aka.ms/azureautomationsdk/automationaccountoperations" />
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='automationAccountName'>
/// The automation account name.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<AutomationAccount>> GetWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (automationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-10-31";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccountName", automationAccountName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<AutomationAccount>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AutomationAccount>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Retrieve a list of accounts within a given resource group.
/// <see href="http://aka.ms/azureautomationsdk/automationaccountoperations" />
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<AutomationAccount>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$");
}
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-10-31";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroup", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<AutomationAccount>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<AutomationAccount>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists the Automation Accounts within an Azure subscription.
/// </summary>
/// <remarks>
/// Retrieve a list of accounts within a given subscription.
/// </remarks>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<AutomationAccount>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2015-10-31";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Automation/automationAccounts").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<AutomationAccount>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<AutomationAccount>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Retrieve a list of accounts within a given resource group.
/// <see href="http://aka.ms/azureautomationsdk/automationaccountoperations" />
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<AutomationAccount>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroupNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<AutomationAccount>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<AutomationAccount>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists the Automation Accounts within an Azure subscription.
/// </summary>
/// <remarks>
/// Retrieve a list of accounts within a given subscription.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<AutomationAccount>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<AutomationAccount>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<AutomationAccount>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System.IO;
using NUnit.Framework;
namespace FileHelpers.Tests.CommonTests
{
[TestFixture]
public class TransformEngine
{
private readonly string fileOut = TestCommon.GetTempFile("transformout.txt");
[Test]
public void CsvToFixedLength()
{
var link = new FileTransformEngine<FromClass, ToClass>();
link.TransformFile(FileTest.Good.Transform1.Path, fileOut);
var engine = new FileHelperEngine<ToClass>();
ToClass[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(6, res.Length);
}
#if !NETCOREAPP
[Test]
public void CsvToFixedLengthCommon()
{
CommonEngine.TransformFile<FromClass, ToClass>(FileTest.Good.Transform1.Path, fileOut);
var engine = new FileHelperEngine<ToClass>();
ToClass[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(6, res.Length);
}
[Test]
public void CsvToFixedLengthCommonAsync()
{
CommonEngine.TransformFileFast<FromClass, ToClass>(FileTest.Good.Transform1.Path, fileOut);
var engine = new FileHelperEngine<ToClass>();
ToClass[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(6, res.Length);
}
#endif
[Test]
public void CsvToFixedLength2()
{
var link = new FileTransformEngine<FromClass, ToClass>();
link.TransformFile(FileTest.Good.Transform2.Path, fileOut);
var engine = new FileHelperEngine<ToClass>();
ToClass[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(@"c:\Prueba1\anda ? ", res[0].CompanyName);
Assert.AreEqual("\"D:\\Glossaries\\O12\" ", res[1].CompanyName);
Assert.AreEqual(@"\\s\\ ", res[2].CompanyName);
}
[Test]
public void TransformRecords()
{
var engine = new FileTransformEngine<FromClass, ToClass>();
ToClass[] res = engine.ReadAndTransformRecords(FileTest.Good.Transform2.Path);
Assert.AreEqual(@"c:\Prueba1\anda ?", res[0].CompanyName);
Assert.AreEqual("\"D:\\Glossaries\\O12\"", res[1].CompanyName);
Assert.AreEqual(@"\\s\\", res[2].CompanyName);
}
[Test]
public void CsvToDelimited()
{
var link = new FileTransformEngine<FromClass, ToClass2>();
link.TransformFile(FileTest.Good.Transform1.Path, fileOut);
var engine = new FileHelperEngine<ToClass2>();
ToClass2[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(6, res.Length);
}
#if !NETCOREAPP
[Test]
public void CsvToDelimitedCommon()
{
CommonEngine.TransformFile<FromClass, ToClass2>(FileTest.Good.Transform1.Path, fileOut);
var engine = new FileHelperEngine<ToClass2>();
ToClass2[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(6, res.Length);
}
[Test]
public void CsvToDelimitedCommonAsync()
{
CommonEngine.TransformFileFast<FromClass, ToClass2>(FileTest.Good.Transform1.Path, fileOut);
var engine = new FileHelperEngine<ToClass2>();
ToClass2[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(6, res.Length);
}
#endif
[Test]
public void CsvToDelimited2()
{
var link = new FileTransformEngine<FromClass, ToClass2>();
link.TransformFile(FileTest.Good.Transform2.Path, fileOut);
var engine = new FileHelperEngine<ToClass2>();
ToClass2[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(@"c:\Prueba1\anda ?", res[0].CompanyName);
Assert.AreEqual("\"D:\\Glossaries\\O12\"", res[1].CompanyName);
Assert.AreEqual(@"\\s\\", res[2].CompanyName);
}
[Test]
public void AsyncCsvToFixedLength()
{
var link = new FileTransformEngine<FromClass, ToClass>();
link.TransformFileFast(FileTest.Good.Transform1.Path, fileOut);
var engine = new FileHelperEngine<ToClass>();
ToClass[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(6, res.Length);
}
[Test]
public void AsyncCsvToFixedLength2()
{
var link = new FileTransformEngine<FromClass, ToClass>();
link.TransformFileFast(FileTest.Good.Transform2.Path, fileOut);
var engine = new FileHelperEngine<ToClass>();
ToClass[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(@"c:\Prueba1\anda ? ", res[0].CompanyName);
Assert.AreEqual("\"D:\\Glossaries\\O12\" ", res[1].CompanyName);
Assert.AreEqual(@"\\s\\ ", res[2].CompanyName);
}
[Test]
public void AsyncCsvToDelimited()
{
var link = new FileTransformEngine<FromClass, ToClass2>();
link.TransformFileFast(FileTest.Good.Transform1.Path, fileOut);
var engine = new FileHelperEngine<ToClass2>();
ToClass2[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(6, res.Length);
}
[Test]
public void AsyncCsvToDelimited2()
{
var link = new FileTransformEngine<FromClass, ToClass2>();
link.TransformFileFast(FileTest.Good.Transform2.Path, fileOut);
var engine = new FileHelperEngine<ToClass2>();
ToClass2[] res = engine.ReadFile(fileOut);
if (File.Exists(fileOut))
File.Delete(fileOut);
Assert.AreEqual(@"c:\Prueba1\anda ?", res[0].CompanyName);
Assert.AreEqual("\"D:\\Glossaries\\O12\"", res[1].CompanyName);
Assert.AreEqual(@"\\s\\", res[2].CompanyName);
}
[DelimitedRecord(",")]
private class FromClass
: ITransformable<ToClass>,
ITransformable<ToClass2>
{
public string CustomerId;
public string CompanyName;
public string CustomerName;
ToClass ITransformable<ToClass>.TransformTo()
{
var res = new ToClass();
res.CustomerId = CustomerId;
res.CompanyName = CompanyName;
res.CustomerName = CustomerName;
return res;
}
ToClass2 ITransformable<ToClass2>.TransformTo()
{
var res = new ToClass2();
res.CustomerId = CustomerId;
res.CompanyName = CompanyName;
res.CustomerName = CustomerName;
return res;
}
}
[DelimitedRecord("|")]
private class ToClass2
{
public string CustomerId;
public string CompanyName;
public string CustomerName;
}
[FixedLengthRecord]
private class ToClass
{
[FieldFixedLength(10)]
public string CustomerId;
[FieldFixedLength(50)]
public string CompanyName;
[FieldFixedLength(60)]
public string CustomerName;
}
}
}
| |
namespace XenAdmin.Dialogs.OptionsPages
{
partial class PluginOptionsPage
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PluginOptionsPage));
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
this.m_gridFeatures = new System.Windows.Forms.DataGridView();
this.col1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.col2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.label2 = new System.Windows.Forms.Label();
this.labelIntro = new System.Windows.Forms.Label();
this.linkLabel1 = new System.Windows.Forms.LinkLabel();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.refreshButton = new System.Windows.Forms.Button();
this.m_tlpScanning = new System.Windows.Forms.TableLayoutPanel();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.label4 = new System.Windows.Forms.Label();
this.labelNoPlugins = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.m_gridPlugins = new System.Windows.Forms.DataGridView();
this.colEnabled = new System.Windows.Forms.DataGridViewCheckBoxColumn();
this.colName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colVendor = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colDesc = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn3 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn4 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn5 = new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.m_gridFeatures)).BeginInit();
this.tableLayoutPanel2.SuspendLayout();
this.m_tlpScanning.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.m_gridPlugins)).BeginInit();
this.SuspendLayout();
//
// m_gridFeatures
//
this.m_gridFeatures.AllowUserToAddRows = false;
this.m_gridFeatures.AllowUserToDeleteRows = false;
this.m_gridFeatures.AllowUserToResizeRows = false;
this.m_gridFeatures.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
this.m_gridFeatures.BackgroundColor = System.Drawing.SystemColors.Window;
this.m_gridFeatures.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.m_gridFeatures.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None;
this.m_gridFeatures.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.m_gridFeatures.ColumnHeadersVisible = false;
this.m_gridFeatures.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.col1,
this.col2});
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Window;
dataGridViewCellStyle1.Font = new System.Drawing.Font("Segoe UI", 9F);
dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Window;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.m_gridFeatures.DefaultCellStyle = dataGridViewCellStyle1;
resources.ApplyResources(this.m_gridFeatures, "m_gridFeatures");
this.m_gridFeatures.Name = "m_gridFeatures";
this.m_gridFeatures.ReadOnly = true;
dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle2.Font = new System.Drawing.Font("Segoe UI", 9F);
dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.m_gridFeatures.RowHeadersDefaultCellStyle = dataGridViewCellStyle2;
this.m_gridFeatures.RowHeadersVisible = false;
this.m_gridFeatures.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.m_gridFeatures.RowStateChanged += new System.Windows.Forms.DataGridViewRowStateChangedEventHandler(this.m_gridFeatures_RowStateChanged);
this.m_gridFeatures.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.m_gridFeatures_CellContentClick);
//
// col1
//
resources.ApplyResources(this.col1, "col1");
this.col1.Name = "col1";
this.col1.ReadOnly = true;
//
// col2
//
resources.ApplyResources(this.col2, "col2");
this.col2.Name = "col2";
this.col2.ReadOnly = true;
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// labelIntro
//
resources.ApplyResources(this.labelIntro, "labelIntro");
this.labelIntro.Name = "labelIntro";
//
// linkLabel1
//
resources.ApplyResources(this.linkLabel1, "linkLabel1");
this.linkLabel1.Name = "linkLabel1";
this.linkLabel1.TabStop = true;
this.linkLabel1.VisitedLinkColor = System.Drawing.Color.Blue;
this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
//
// tableLayoutPanel2
//
resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2");
this.tableLayoutPanel2.Controls.Add(this.labelIntro, 0, 0);
this.tableLayoutPanel2.Controls.Add(this.refreshButton, 0, 1);
this.tableLayoutPanel2.Controls.Add(this.m_tlpScanning, 0, 2);
this.tableLayoutPanel2.Controls.Add(this.labelNoPlugins, 0, 3);
this.tableLayoutPanel2.Controls.Add(this.label2, 0, 4);
this.tableLayoutPanel2.Controls.Add(this.m_gridFeatures, 0, 7);
this.tableLayoutPanel2.Controls.Add(this.label3, 0, 6);
this.tableLayoutPanel2.Controls.Add(this.m_gridPlugins, 0, 5);
this.tableLayoutPanel2.Controls.Add(this.linkLabel1, 0, 8);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
//
// refreshButton
//
resources.ApplyResources(this.refreshButton, "refreshButton");
this.refreshButton.Name = "refreshButton";
this.refreshButton.UseVisualStyleBackColor = true;
this.refreshButton.Click += new System.EventHandler(this.refreshButton_Click);
//
// m_tlpScanning
//
resources.ApplyResources(this.m_tlpScanning, "m_tlpScanning");
this.m_tlpScanning.Controls.Add(this.pictureBox1, 0, 0);
this.m_tlpScanning.Controls.Add(this.label4, 1, 0);
this.m_tlpScanning.Name = "m_tlpScanning";
//
// pictureBox1
//
this.pictureBox1.Image = global::XenAdmin.Properties.Resources.ajax_loader;
resources.ApplyResources(this.pictureBox1, "pictureBox1");
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.TabStop = false;
//
// label4
//
resources.ApplyResources(this.label4, "label4");
this.label4.Name = "label4";
//
// labelNoPlugins
//
resources.ApplyResources(this.labelNoPlugins, "labelNoPlugins");
this.labelNoPlugins.Name = "labelNoPlugins";
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// m_gridPlugins
//
this.m_gridPlugins.AllowUserToAddRows = false;
this.m_gridPlugins.AllowUserToDeleteRows = false;
this.m_gridPlugins.AllowUserToResizeRows = false;
this.m_gridPlugins.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
this.m_gridPlugins.BackgroundColor = System.Drawing.SystemColors.Window;
this.m_gridPlugins.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.m_gridPlugins.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None;
this.m_gridPlugins.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
this.m_gridPlugins.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.colEnabled,
this.colName,
this.colVendor,
this.colDesc});
resources.ApplyResources(this.m_gridPlugins, "m_gridPlugins");
this.m_gridPlugins.MultiSelect = false;
this.m_gridPlugins.Name = "m_gridPlugins";
dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle3.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle3.Font = new System.Drawing.Font("Segoe UI", 9F);
dataGridViewCellStyle3.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.m_gridPlugins.RowHeadersDefaultCellStyle = dataGridViewCellStyle3;
this.m_gridPlugins.RowHeadersVisible = false;
this.m_gridPlugins.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing;
this.m_gridPlugins.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.m_gridPlugins.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.m_gridPlugins_CellFormatting);
this.m_gridPlugins.SelectionChanged += new System.EventHandler(this.m_gridPlugins_SelectionChanged);
this.m_gridPlugins.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.m_gridPlugins_CellClick);
//
// colEnabled
//
resources.ApplyResources(this.colEnabled, "colEnabled");
this.colEnabled.Name = "colEnabled";
this.colEnabled.ReadOnly = true;
this.colEnabled.Resizable = System.Windows.Forms.DataGridViewTriState.False;
//
// colName
//
resources.ApplyResources(this.colName, "colName");
this.colName.Name = "colName";
this.colName.ReadOnly = true;
//
// colVendor
//
resources.ApplyResources(this.colVendor, "colVendor");
this.colVendor.Name = "colVendor";
this.colVendor.ReadOnly = true;
//
// colDesc
//
this.colDesc.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
resources.ApplyResources(this.colDesc, "colDesc");
this.colDesc.Name = "colDesc";
this.colDesc.ReadOnly = true;
//
// dataGridViewTextBoxColumn1
//
resources.ApplyResources(this.dataGridViewTextBoxColumn1, "dataGridViewTextBoxColumn1");
this.dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1";
this.dataGridViewTextBoxColumn1.ReadOnly = true;
//
// dataGridViewTextBoxColumn2
//
resources.ApplyResources(this.dataGridViewTextBoxColumn2, "dataGridViewTextBoxColumn2");
this.dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2";
this.dataGridViewTextBoxColumn2.ReadOnly = true;
//
// dataGridViewTextBoxColumn3
//
this.dataGridViewTextBoxColumn3.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
resources.ApplyResources(this.dataGridViewTextBoxColumn3, "dataGridViewTextBoxColumn3");
this.dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3";
this.dataGridViewTextBoxColumn3.ReadOnly = true;
//
// dataGridViewTextBoxColumn4
//
resources.ApplyResources(this.dataGridViewTextBoxColumn4, "dataGridViewTextBoxColumn4");
this.dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4";
this.dataGridViewTextBoxColumn4.ReadOnly = true;
//
// dataGridViewTextBoxColumn5
//
this.dataGridViewTextBoxColumn5.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
resources.ApplyResources(this.dataGridViewTextBoxColumn5, "dataGridViewTextBoxColumn5");
this.dataGridViewTextBoxColumn5.Name = "dataGridViewTextBoxColumn5";
this.dataGridViewTextBoxColumn5.ReadOnly = true;
//
// PluginOptionsPage
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.Controls.Add(this.tableLayoutPanel2);
this.Name = "PluginOptionsPage";
((System.ComponentModel.ISupportInitialize)(this.m_gridFeatures)).EndInit();
this.tableLayoutPanel2.ResumeLayout(false);
this.tableLayoutPanel2.PerformLayout();
this.m_tlpScanning.ResumeLayout(false);
this.m_tlpScanning.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.m_gridPlugins)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label labelIntro;
private System.Windows.Forms.LinkLabel linkLabel1;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
private System.Windows.Forms.Button refreshButton;
private System.Windows.Forms.DataGridView m_gridPlugins;
private System.Windows.Forms.DataGridView m_gridFeatures;
private System.Windows.Forms.DataGridViewTextBoxColumn col1;
private System.Windows.Forms.DataGridViewTextBoxColumn col2;
private System.Windows.Forms.DataGridViewCheckBoxColumn colEnabled;
private System.Windows.Forms.DataGridViewTextBoxColumn colName;
private System.Windows.Forms.DataGridViewTextBoxColumn colVendor;
private System.Windows.Forms.DataGridViewTextBoxColumn colDesc;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn5;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TableLayoutPanel m_tlpScanning;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label labelNoPlugins;
}
}
| |
///---------------------------------------------------------------------------------------------------------------------
/// <copyright company="Microsoft">
/// Copyright (c) Microsoft Corporation. All rights reserved.
/// </copyright>
///---------------------------------------------------------------------------------------------------------------------
namespace ExpressionBuilder
{
using System;
using System.Collections.Generic;
using System.Numerics;
using Windows.UI;
using Windows.UI.Composition;
internal enum ExpressionNodeType
{
ConstantValue,
ConstantParameter,
CurrentValueProperty,
Reference,
ReferenceProperty,
StartingValueProperty,
TargetReference,
Conditional,
Swizzle,
Add,
And,
Divide,
Equals,
GreaterThan,
GreaterThanEquals,
LessThan,
LessThanEquals,
Multiply,
Not,
NotEquals,
Or,
Subtract,
Absolute,
Acos,
Asin,
Atan,
Cos,
Ceil,
Clamp,
ColorHsl,
ColorRgb,
ColorLerp,
ColorLerpHsl,
ColorLerpRgb,
Concatenate,
Distance,
DistanceSquared,
Floor,
Inverse,
Length,
LengthSquared,
Lerp,
Ln,
Log10,
Max,
Matrix3x2FromRotation,
Matrix3x2FromScale,
Matrix3x2FromSkew,
Matrix3x2FromTranslation,
Matrix3x2,
Matrix4x4FromAxisAngle,
Matrix4x4FromScale,
Matrix4x4FromTranslation,
Matrix4x4,
Min,
Modulus,
Negate,
Normalize,
Pow,
QuaternionFromAxisAngle,
Quaternion,
Round,
Scale,
Sin,
Slerp,
Sqrt,
Square,
Tan,
ToDegrees,
ToRadians,
Transform,
Vector2,
Vector3,
Vector4,
Count
}
internal enum ValueKeywordKind
{
CurrentValue,
StartingValue,
}
///---------------------------------------------------------------------------------------------------------------------
///
/// class ExpressionNode
/// ToDo: Add description after docs written
///
///---------------------------------------------------------------------------------------------------------------------
public abstract class ExpressionNode
{
internal ExpressionNode() { }
/// <summary> Resolve a named reference parameter to the CompositionObject it will refer to. </summary>
/// <param name="parameterName">The string name of the parameter to be resolved.</param>
/// <param name="compObj">The composition object that the parameter should resolve to.</param>
public void SetReferenceParameter(string parameterName, CompositionObject compObj)
{
// Make sure we have our reference list populated
EnsureReferenceInfo();
for (int i = 0; i < _objRefList.Count; i++)
{
if (string.Compare(_objRefList[i].ParameterName, parameterName, true /*ignoreCase*/) == 0)
{
var item = _objRefList[i];
item.CompObject = compObj;
_objRefList[i] = item;
}
}
}
/// <summary> Resolve a named parameter to the boolean value it will use. </summary>
/// <param name="parameterName">The string name of the parameter to be resolved.</param>
/// <param name="value">The value that the parameter should resolve to.</param>
public void SetBooleanParameter(string parameterName, bool value) { _constParamMap[parameterName] = value; }
/// <summary> Resolve a named parameter to the float value it will use. </summary>
/// <param name="parameterName">The string name of the parameter to be resolved.</param>
/// <param name="value">The value that the parameter should resolve to.</param>
public void SetScalarParameter(string parameterName, float value) { _constParamMap[parameterName] = value; }
/// <summary> Resolve a named parameter to the Vector2 value it will use. </summary>
/// <param name="parameterName">The string name of the parameter to be resolved.</param>
/// <param name="value">The value that the parameter should resolve to.</param>
public void SetVector2Parameter(string parameterName, Vector2 value) { _constParamMap[parameterName] = value; }
/// <summary> Resolve a named parameter to the Vector3 value it will use. </summary>
/// <param name="parameterName">The string name of the parameter to be resolved.</param>
/// <param name="value">The value that the parameter should resolve to.</param>
public void SetVector3Parameter(string parameterName, Vector3 value) { _constParamMap[parameterName] = value; }
/// <summary> Resolve a named parameter to the Vector4 value it will use. </summary>
/// <param name="parameterName">The string name of the parameter to be resolved.</param>
/// <param name="value">The value that the parameter should resolve to.</param>
public void SetVector4Parameter(string parameterName, Vector4 value) { _constParamMap[parameterName] = value; }
/// <summary> Resolve a named parameter to the Color value it will use. </summary>
/// <param name="parameterName">The string name of the parameter to be resolved.</param>
/// <param name="value">The value that the parameter should resolve to.</param>
public void SetColorParameter(string parameterName, Color value) { _constParamMap[parameterName] = value; }
/// <summary> Resolve a named parameter to the Quaternion value it will use. </summary>
/// <param name="parameterName">The string name of the parameter to be resolved.</param>
/// <param name="value">The value that the parameter should resolve to.</param>
public void SetQuaternionParameter(string parameterName, Quaternion value) { _constParamMap[parameterName] = value; }
/// <summary> Resolve a named parameter to the Matrix3x2 value it will use. </summary>
/// <param name="parameterName">The string name of the parameter to be resolved.</param>
/// <param name="value">The value that the parameter should resolve to.</param>
public void SetMatrix3x2Parameter(string parameterName, Matrix3x2 value) { _constParamMap[parameterName] = value; }
/// <summary> Resolve a named parameter to the Matrix4x4 value it will use. </summary>
/// <param name="parameterName">The string name of the parameter to be resolved.</param>
/// <param name="value">The value that the parameter should resolve to.</param>
public void SetMatrix4x4Parameter(string parameterName, Matrix4x4 value) { _constParamMap[parameterName] = value; }
/// <summary> Releases all resources used by this ExpressionNode. </summary>
public void Dispose()
{
_objRefList = null;
_compObjToParamNameMap = null;
_constParamMap = null;
_subchannels = null;
_propertyName = null;
_nodeType = ExpressionNodeType.Count;
// Note: we don't recursively dispose all child nodes, as those nodes could be in use by a different Expression
_children = null;
if (_expressionAnimation != null)
{
_expressionAnimation.Dispose();
_expressionAnimation = null;
}
}
//
// Helper functions
//
internal static T CreateExpressionNode<T>() where T : class
{
T newNode;
if (typeof(T) == typeof(BooleanNode))
{
newNode = new BooleanNode() as T;
}
else if (typeof(T) == typeof(ScalarNode))
{
newNode = new ScalarNode() as T;
}
else if (typeof(T) == typeof(Vector2Node))
{
newNode = new Vector2Node() as T;
}
else if (typeof(T) == typeof(Vector3Node))
{
newNode = new Vector3Node() as T;
}
else if (typeof(T) == typeof(Vector4Node))
{
newNode = new Vector4Node() as T;
}
else if (typeof(T) == typeof(ColorNode))
{
newNode = new ColorNode() as T;
}
else if (typeof(T) == typeof(QuaternionNode))
{
newNode = new QuaternionNode() as T;
}
else if (typeof(T) == typeof(Matrix3x2Node))
{
newNode = new Matrix3x2Node() as T;
}
else if (typeof(T) == typeof(Matrix4x4Node))
{
newNode = new Matrix4x4Node() as T;
}
else
{
throw new Exception("unexpected type");
}
return newNode;
}
internal string ToExpressionString()
{
if (_objRefList == null)
{
EnsureReferenceInfo();
}
return ToExpressionStringInternal();
}
internal void EnsureReferenceInfo()
{
if (_objRefList == null)
{
// Get all ReferenceNodes in this expression
HashSet<ReferenceNode> referenceNodes = new HashSet<ReferenceNode>();
PopulateParameterNodes(ref _constParamMap, ref referenceNodes);
// Find all CompositionObjects across all referenceNodes that need a paramName to be created
HashSet<CompositionObject> compObjects = new HashSet<CompositionObject>();
foreach (var refNode in referenceNodes)
{
if ((refNode.Reference != null) && (refNode.GetReferenceParamString() == null))
{
compObjects.Add(refNode.Reference);
}
}
// Create a map to store the generated paramNames for each CompObj
uint id = 0;
_compObjToParamNameMap = new Dictionary<CompositionObject, string>();
foreach (var compObj in compObjects)
{
// compObj.ToString() will return something like "Windows.UI.Composition.SpriteVisual"
// Make it look like "SpriteVisual_1"
string paramName = compObj.ToString();
paramName = $"{paramName.Substring(paramName.LastIndexOf('.') + 1)}_{++id}"; // make sure the created param name doesn't overwrite a custom name
_compObjToParamNameMap.Add(compObj, paramName);
}
// Go through all reference nodes again to create our full list of referenceInfo. This time, if
// the param name is null, look it up from our new map and store it.
_objRefList = new List<ReferenceInfo>();
foreach (var refNode in referenceNodes)
{
string paramName = refNode.GetReferenceParamString();
if ((refNode.Reference == null) && (paramName == null))
{
// This can't happen - if the ref is null it must be because it's a named param
throw new Exception("Reference and paramName can't both be null");
}
if (paramName == null)
{
paramName = _compObjToParamNameMap[refNode.Reference];
}
_objRefList.Add(new ReferenceInfo(paramName, refNode.Reference));
refNode._paramName = paramName;
}
}
}
internal void SetAllParameters(CompositionAnimation anim)
{
// Make sure the list is populated
EnsureReferenceInfo();
foreach (var refInfo in _objRefList)
{
anim.SetReferenceParameter(refInfo.ParameterName, refInfo.CompObject);
}
foreach (var constParam in _constParamMap)
{
if (constParam.Value.GetType() == typeof(bool))
{
anim.SetBooleanParameter(constParam.Key, (bool)constParam.Value);
}
else if (constParam.Value.GetType() == typeof(float))
{
anim.SetScalarParameter(constParam.Key, (float)constParam.Value);
}
else if (constParam.Value.GetType() == typeof(Vector2))
{
anim.SetVector2Parameter(constParam.Key, (Vector2)constParam.Value);
}
else if (constParam.Value.GetType() == typeof(Vector3))
{
anim.SetVector3Parameter(constParam.Key, (Vector3)constParam.Value);
}
else if (constParam.Value.GetType() == typeof(Vector4))
{
anim.SetVector4Parameter(constParam.Key, (Vector4)constParam.Value);
}
else if (constParam.Value.GetType() == typeof(Color))
{
anim.SetColorParameter(constParam.Key, (Color)constParam.Value);
}
else if (constParam.Value.GetType() == typeof(Quaternion))
{
anim.SetQuaternionParameter(constParam.Key, (Quaternion)constParam.Value);
}
else if (constParam.Value.GetType() == typeof(Matrix3x2))
{
anim.SetMatrix3x2Parameter(constParam.Key, (Matrix3x2)constParam.Value);
}
else if (constParam.Value.GetType() == typeof(Matrix4x4))
{
anim.SetMatrix4x4Parameter(constParam.Key, (Matrix4x4)constParam.Value);
}
else
{
throw new Exception($"Unexpected constant parameter datatype ({constParam.Value.GetType()})");
}
}
}
internal static T CreateValueKeyword<T>(ValueKeywordKind keywordKind) where T : class
{
T node = CreateExpressionNode<T>();
(node as ExpressionNode)._paramName = null;
switch (keywordKind)
{
case ValueKeywordKind.CurrentValue:
(node as ExpressionNode)._nodeType = ExpressionNodeType.CurrentValueProperty;
break;
case ValueKeywordKind.StartingValue:
(node as ExpressionNode)._nodeType = ExpressionNodeType.StartingValueProperty;
break;
default:
throw new Exception("Invalid ValueKeywordKind");
}
return node;
}
internal protected abstract string GetValue();
internal protected T SubchannelsInternal<T>(params string[] subchannels) where T : class
{
ExpressionNodeType swizzleNodeType = ExpressionNodeType.Swizzle;
T newNode;
switch (subchannels.GetLength(0))
{
case 1:
newNode = ExpressionFunctions.Function<ScalarNode>(swizzleNodeType, this) as T;
break;
case 2:
newNode = ExpressionFunctions.Function<Vector2Node>(swizzleNodeType, this) as T;
break;
case 3:
newNode = ExpressionFunctions.Function<Vector3Node>(swizzleNodeType, this) as T;
break;
case 4:
newNode = ExpressionFunctions.Function<Vector4Node>(swizzleNodeType, this) as T;
break;
case 6:
newNode = ExpressionFunctions.Function<Matrix3x2Node>(swizzleNodeType, this) as T;
break;
case 16:
newNode = ExpressionFunctions.Function<Matrix4x4Node>(swizzleNodeType, this) as T;
break;
default:
throw new Exception($"Invalid subchannel count ({subchannels.GetLength(0)})");
}
(newNode as ExpressionNode)._subchannels = subchannels;
return newNode;
}
internal protected void PopulateParameterNodes(ref Dictionary<string, object> constParamMap, ref HashSet<ReferenceNode> referenceNodes)
{
var refNode = (this as ReferenceNode);
if ((refNode != null) && (refNode._nodeType != ExpressionNodeType.TargetReference))
{
referenceNodes.Add(refNode);
}
if ((_constParamMap != null) && (_constParamMap != constParamMap))
{
foreach (var entry in _constParamMap)
{
// If this parameter hasn't already been set on the root, use this node's parameter info
if (!constParamMap.ContainsKey(entry.Key))
{
constParamMap[entry.Key] = entry.Value;
}
}
}
foreach (var child in _children)
{
child.PopulateParameterNodes(ref constParamMap, ref referenceNodes);
}
}
private OperationType GetOperationKind() { return ExpressionFunctions.GetNodeInfoFromType(_nodeType).NodeOperationKind; }
private string GetOperationString() { return ExpressionFunctions.GetNodeInfoFromType(_nodeType).OperationString; }
private string ToExpressionStringInternal()
{
string ret = "";
// Do a recursive depth-first traversal of the node tree to print out the full expression string
switch (GetOperationKind())
{
case OperationType.Function:
if (_children.Count == 0)
{
throw new Exception("Can't have an expression function with no params");
}
ret = $"{GetOperationString()}({_children[0].ToExpressionStringInternal()}";
for (int i = 1; i < _children.Count; i++)
{
ret += "," + _children[i].ToExpressionStringInternal();
}
ret += ")";
break;
case OperationType.Operator:
if (_children.Count != 2)
{
throw new Exception("Can't have an operator that doesn't have 2 exactly params");
}
ret = $"({_children[0].ToExpressionStringInternal()} {GetOperationString()} {_children[1].ToExpressionStringInternal()})";
break;
case OperationType.Constant:
if (_children.Count == 0)
{
// If a parameterName was specified, use it. Otherwise write the value.
ret = _paramName ?? GetValue();
}
else
{
throw new Exception("Constants must have 0 children");
}
break;
case OperationType.Swizzle:
if (_children.Count != 1)
{
throw new Exception("Swizzles should have exactly 1 child");
}
string swizzleString = "";
foreach (var sub in _subchannels)
{
swizzleString += sub;
}
ret = $"{_children[0].ToExpressionStringInternal()}.{swizzleString}";
break;
case OperationType.Reference:
if ((_nodeType == ExpressionNodeType.Reference) ||
(_nodeType == ExpressionNodeType.TargetReference))
{
// This is the reference node itself
if (_children.Count != 0)
{
throw new Exception("References cannot have children");
}
ret = (this as ReferenceNode).GetReferenceParamString();
}
else if (_nodeType == ExpressionNodeType.ReferenceProperty)
{
// This is the property node of the reference
if (_children.Count != 1)
{
throw new Exception("Reference properties must have exactly one child");
}
if (_propertyName == null)
{
throw new Exception("Reference properties must have a property name");
}
ret = $"{_children[0].ToExpressionStringInternal()}.{_propertyName}";
}
else if (_nodeType == ExpressionNodeType.StartingValueProperty)
{
// This is a "this.StartingValue" node
if (_children.Count != 0)
{
throw new Exception("StartingValue references Cannot have children");
}
ret = "this.StartingValue";
}
else if (_nodeType == ExpressionNodeType.CurrentValueProperty)
{
// This is a "this.CurrentValue" node
if (_children.Count != 0)
{
throw new Exception("CurrentValue references Cannot have children");
}
ret = "this.CurrentValue";
}
else
{
throw new Exception("Unexpected NodeType for OperationType.Reference");
}
break;
case OperationType.Conditional:
if (_children.Count != 3)
{
throw new Exception("Conditionals must have exactly 3 children");
}
ret = $"(({_children[0].ToExpressionStringInternal()}) ? ({_children[1].ToExpressionStringInternal()}) : ({_children[2].ToExpressionStringInternal()}))";
break;
default:
throw new Exception($"Unexpected operation type ({GetOperationKind()}), nodeType = {_nodeType}");
}
return ret;
}
//
// Structs
//
internal struct ReferenceInfo
{
public ReferenceInfo(string paramName, CompositionObject compObj)
{
ParameterName = paramName;
CompObject = compObj;
}
public string ParameterName;
public CompositionObject CompObject;
}
//
// Data
//
private List<ReferenceInfo> _objRefList = null;
private Dictionary<CompositionObject, string> _compObjToParamNameMap = null;
private Dictionary<string, object> _constParamMap = new Dictionary<string, object>(StringComparer.CurrentCultureIgnoreCase);
internal protected string[] _subchannels = null;
internal string _propertyName = null;
internal ExpressionNodeType _nodeType;
internal List<ExpressionNode> _children = new List<ExpressionNode>();
internal string _paramName = null;
internal ExpressionAnimation _expressionAnimation = null;
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Student Merit Behaviour Details Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class STMBDataSet : EduHubDataSet<STMB>
{
/// <inheritdoc />
public override string Name { get { return "STMB"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal STMBDataSet(EduHubContext Context)
: base(Context)
{
Index_AWARD = new Lazy<NullDictionary<string, IReadOnlyList<STMB>>>(() => this.ToGroupedNullDictionary(i => i.AWARD));
Index_B_CODE = new Lazy<NullDictionary<string, IReadOnlyList<STMB>>>(() => this.ToGroupedNullDictionary(i => i.B_CODE));
Index_SKEY = new Lazy<Dictionary<string, IReadOnlyList<STMB>>>(() => this.ToGroupedDictionary(i => i.SKEY));
Index_TID = new Lazy<Dictionary<int, STMB>>(() => this.ToDictionary(i => i.TID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="STMB" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="STMB" /> fields for each CSV column header</returns>
internal override Action<STMB, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<STMB, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TID":
mapper[i] = (e, v) => e.TID = int.Parse(v);
break;
case "SKEY":
mapper[i] = (e, v) => e.SKEY = v;
break;
case "B_CODE":
mapper[i] = (e, v) => e.B_CODE = v;
break;
case "DETAIL":
mapper[i] = (e, v) => e.DETAIL = v;
break;
case "START_DATE":
mapper[i] = (e, v) => e.START_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "END_DATE":
mapper[i] = (e, v) => e.END_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "RECOMMEND_TYPE":
mapper[i] = (e, v) => e.RECOMMEND_TYPE = v;
break;
case "RECOMMEND_KEY":
mapper[i] = (e, v) => e.RECOMMEND_KEY = v;
break;
case "RECOMMEND_DFAB":
mapper[i] = (e, v) => e.RECOMMEND_DFAB = v;
break;
case "RECOMMEND_OTHER":
mapper[i] = (e, v) => e.RECOMMEND_OTHER = v;
break;
case "AWARD":
mapper[i] = (e, v) => e.AWARD = v;
break;
case "STMB_COMMENT":
mapper[i] = (e, v) => e.STMB_COMMENT = v;
break;
case "CREATOR":
mapper[i] = (e, v) => e.CREATOR = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="STMB" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="STMB" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="STMB" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{STMB}"/> of entities</returns>
internal override IEnumerable<STMB> ApplyDeltaEntities(IEnumerable<STMB> Entities, List<STMB> DeltaEntities)
{
HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.SKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TID.Remove(entity.TID);
if (entity.SKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<NullDictionary<string, IReadOnlyList<STMB>>> Index_AWARD;
private Lazy<NullDictionary<string, IReadOnlyList<STMB>>> Index_B_CODE;
private Lazy<Dictionary<string, IReadOnlyList<STMB>>> Index_SKEY;
private Lazy<Dictionary<int, STMB>> Index_TID;
#endregion
#region Index Methods
/// <summary>
/// Find STMB by AWARD field
/// </summary>
/// <param name="AWARD">AWARD value used to find STMB</param>
/// <returns>List of related STMB entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STMB> FindByAWARD(string AWARD)
{
return Index_AWARD.Value[AWARD];
}
/// <summary>
/// Attempt to find STMB by AWARD field
/// </summary>
/// <param name="AWARD">AWARD value used to find STMB</param>
/// <param name="Value">List of related STMB entities</param>
/// <returns>True if the list of related STMB entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByAWARD(string AWARD, out IReadOnlyList<STMB> Value)
{
return Index_AWARD.Value.TryGetValue(AWARD, out Value);
}
/// <summary>
/// Attempt to find STMB by AWARD field
/// </summary>
/// <param name="AWARD">AWARD value used to find STMB</param>
/// <returns>List of related STMB entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STMB> TryFindByAWARD(string AWARD)
{
IReadOnlyList<STMB> value;
if (Index_AWARD.Value.TryGetValue(AWARD, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find STMB by B_CODE field
/// </summary>
/// <param name="B_CODE">B_CODE value used to find STMB</param>
/// <returns>List of related STMB entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STMB> FindByB_CODE(string B_CODE)
{
return Index_B_CODE.Value[B_CODE];
}
/// <summary>
/// Attempt to find STMB by B_CODE field
/// </summary>
/// <param name="B_CODE">B_CODE value used to find STMB</param>
/// <param name="Value">List of related STMB entities</param>
/// <returns>True if the list of related STMB entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByB_CODE(string B_CODE, out IReadOnlyList<STMB> Value)
{
return Index_B_CODE.Value.TryGetValue(B_CODE, out Value);
}
/// <summary>
/// Attempt to find STMB by B_CODE field
/// </summary>
/// <param name="B_CODE">B_CODE value used to find STMB</param>
/// <returns>List of related STMB entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STMB> TryFindByB_CODE(string B_CODE)
{
IReadOnlyList<STMB> value;
if (Index_B_CODE.Value.TryGetValue(B_CODE, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find STMB by SKEY field
/// </summary>
/// <param name="SKEY">SKEY value used to find STMB</param>
/// <returns>List of related STMB entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STMB> FindBySKEY(string SKEY)
{
return Index_SKEY.Value[SKEY];
}
/// <summary>
/// Attempt to find STMB by SKEY field
/// </summary>
/// <param name="SKEY">SKEY value used to find STMB</param>
/// <param name="Value">List of related STMB entities</param>
/// <returns>True if the list of related STMB entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindBySKEY(string SKEY, out IReadOnlyList<STMB> Value)
{
return Index_SKEY.Value.TryGetValue(SKEY, out Value);
}
/// <summary>
/// Attempt to find STMB by SKEY field
/// </summary>
/// <param name="SKEY">SKEY value used to find STMB</param>
/// <returns>List of related STMB entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STMB> TryFindBySKEY(string SKEY)
{
IReadOnlyList<STMB> value;
if (Index_SKEY.Value.TryGetValue(SKEY, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find STMB by TID field
/// </summary>
/// <param name="TID">TID value used to find STMB</param>
/// <returns>Related STMB entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public STMB FindByTID(int TID)
{
return Index_TID.Value[TID];
}
/// <summary>
/// Attempt to find STMB by TID field
/// </summary>
/// <param name="TID">TID value used to find STMB</param>
/// <param name="Value">Related STMB entity</param>
/// <returns>True if the related STMB entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTID(int TID, out STMB Value)
{
return Index_TID.Value.TryGetValue(TID, out Value);
}
/// <summary>
/// Attempt to find STMB by TID field
/// </summary>
/// <param name="TID">TID value used to find STMB</param>
/// <returns>Related STMB entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public STMB TryFindByTID(int TID)
{
STMB value;
if (Index_TID.Value.TryGetValue(TID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a STMB table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[STMB]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[STMB](
[TID] int IDENTITY NOT NULL,
[SKEY] varchar(10) NOT NULL,
[B_CODE] varchar(10) NULL,
[DETAIL] varchar(MAX) NULL,
[START_DATE] datetime NULL,
[END_DATE] datetime NULL,
[RECOMMEND_TYPE] varchar(2) NULL,
[RECOMMEND_KEY] varchar(10) NULL,
[RECOMMEND_DFAB] varchar(1) NULL,
[RECOMMEND_OTHER] varchar(MAX) NULL,
[AWARD] varchar(10) NULL,
[STMB_COMMENT] varchar(MAX) NULL,
[CREATOR] varchar(128) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [STMB_Index_TID] PRIMARY KEY NONCLUSTERED (
[TID] ASC
)
);
CREATE NONCLUSTERED INDEX [STMB_Index_AWARD] ON [dbo].[STMB]
(
[AWARD] ASC
);
CREATE NONCLUSTERED INDEX [STMB_Index_B_CODE] ON [dbo].[STMB]
(
[B_CODE] ASC
);
CREATE CLUSTERED INDEX [STMB_Index_SKEY] ON [dbo].[STMB]
(
[SKEY] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STMB]') AND name = N'STMB_Index_AWARD')
ALTER INDEX [STMB_Index_AWARD] ON [dbo].[STMB] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STMB]') AND name = N'STMB_Index_B_CODE')
ALTER INDEX [STMB_Index_B_CODE] ON [dbo].[STMB] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STMB]') AND name = N'STMB_Index_TID')
ALTER INDEX [STMB_Index_TID] ON [dbo].[STMB] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STMB]') AND name = N'STMB_Index_AWARD')
ALTER INDEX [STMB_Index_AWARD] ON [dbo].[STMB] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STMB]') AND name = N'STMB_Index_B_CODE')
ALTER INDEX [STMB_Index_B_CODE] ON [dbo].[STMB] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STMB]') AND name = N'STMB_Index_TID')
ALTER INDEX [STMB_Index_TID] ON [dbo].[STMB] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="STMB"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="STMB"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<STMB> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_TID = new List<int>();
foreach (var entity in Entities)
{
Index_TID.Add(entity.TID);
}
builder.AppendLine("DELETE [dbo].[STMB] WHERE");
// Index_TID
builder.Append("[TID] IN (");
for (int index = 0; index < Index_TID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TID
var parameterTID = $"@p{parameterIndex++}";
builder.Append(parameterTID);
command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the STMB data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the STMB data set</returns>
public override EduHubDataSetDataReader<STMB> GetDataSetDataReader()
{
return new STMBDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the STMB data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the STMB data set</returns>
public override EduHubDataSetDataReader<STMB> GetDataSetDataReader(List<STMB> Entities)
{
return new STMBDataReader(new EduHubDataSetLoadedReader<STMB>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class STMBDataReader : EduHubDataSetDataReader<STMB>
{
public STMBDataReader(IEduHubDataSetReader<STMB> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 16; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TID
return Current.TID;
case 1: // SKEY
return Current.SKEY;
case 2: // B_CODE
return Current.B_CODE;
case 3: // DETAIL
return Current.DETAIL;
case 4: // START_DATE
return Current.START_DATE;
case 5: // END_DATE
return Current.END_DATE;
case 6: // RECOMMEND_TYPE
return Current.RECOMMEND_TYPE;
case 7: // RECOMMEND_KEY
return Current.RECOMMEND_KEY;
case 8: // RECOMMEND_DFAB
return Current.RECOMMEND_DFAB;
case 9: // RECOMMEND_OTHER
return Current.RECOMMEND_OTHER;
case 10: // AWARD
return Current.AWARD;
case 11: // STMB_COMMENT
return Current.STMB_COMMENT;
case 12: // CREATOR
return Current.CREATOR;
case 13: // LW_DATE
return Current.LW_DATE;
case 14: // LW_TIME
return Current.LW_TIME;
case 15: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 2: // B_CODE
return Current.B_CODE == null;
case 3: // DETAIL
return Current.DETAIL == null;
case 4: // START_DATE
return Current.START_DATE == null;
case 5: // END_DATE
return Current.END_DATE == null;
case 6: // RECOMMEND_TYPE
return Current.RECOMMEND_TYPE == null;
case 7: // RECOMMEND_KEY
return Current.RECOMMEND_KEY == null;
case 8: // RECOMMEND_DFAB
return Current.RECOMMEND_DFAB == null;
case 9: // RECOMMEND_OTHER
return Current.RECOMMEND_OTHER == null;
case 10: // AWARD
return Current.AWARD == null;
case 11: // STMB_COMMENT
return Current.STMB_COMMENT == null;
case 12: // CREATOR
return Current.CREATOR == null;
case 13: // LW_DATE
return Current.LW_DATE == null;
case 14: // LW_TIME
return Current.LW_TIME == null;
case 15: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TID
return "TID";
case 1: // SKEY
return "SKEY";
case 2: // B_CODE
return "B_CODE";
case 3: // DETAIL
return "DETAIL";
case 4: // START_DATE
return "START_DATE";
case 5: // END_DATE
return "END_DATE";
case 6: // RECOMMEND_TYPE
return "RECOMMEND_TYPE";
case 7: // RECOMMEND_KEY
return "RECOMMEND_KEY";
case 8: // RECOMMEND_DFAB
return "RECOMMEND_DFAB";
case 9: // RECOMMEND_OTHER
return "RECOMMEND_OTHER";
case 10: // AWARD
return "AWARD";
case 11: // STMB_COMMENT
return "STMB_COMMENT";
case 12: // CREATOR
return "CREATOR";
case 13: // LW_DATE
return "LW_DATE";
case 14: // LW_TIME
return "LW_TIME";
case 15: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TID":
return 0;
case "SKEY":
return 1;
case "B_CODE":
return 2;
case "DETAIL":
return 3;
case "START_DATE":
return 4;
case "END_DATE":
return 5;
case "RECOMMEND_TYPE":
return 6;
case "RECOMMEND_KEY":
return 7;
case "RECOMMEND_DFAB":
return 8;
case "RECOMMEND_OTHER":
return 9;
case "AWARD":
return 10;
case "STMB_COMMENT":
return 11;
case "CREATOR":
return 12;
case "LW_DATE":
return 13;
case "LW_TIME":
return 14;
case "LW_USER":
return 15;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Zlib;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
namespace IronPython.Modules {
/// <summary>
/// Implementes a resource-based meta_path importer as described in PEP 302.
/// </summary>
[PythonType]
public class ResourceMetaPathImporter {
private readonly PackedResourceLoader _loader;
private readonly IDictionary<string, PackedResourceInfo> _unpackedLibrary;
private readonly IDictionary<string, PackedResourceInfo[]> _unpackedModules;
private readonly string _unpackingError;
private static readonly Dictionary<string, ModuleCodeType> SearchOrder;
[Flags]
private enum ModuleCodeType {
Source = 0,
//ByteCode,
Package,
}
static ResourceMetaPathImporter() {
// we currently don't support bytecode, so just include the source versions.
SearchOrder = new Dictionary<string, ModuleCodeType> {
{
Path.DirectorySeparatorChar + "__init__.py",
ModuleCodeType.Package |
ModuleCodeType.Source
},
{".py", ModuleCodeType.Source},
};
}
/// <summary>
/// Instantiates a new meta_path importer using an embedded ZIP resource file.
/// </summary>
/// <param name="fromAssembly"></param>
/// <param name="resourceName"></param>
public ResourceMetaPathImporter(Assembly fromAssembly, string resourceName) {
_loader = new PackedResourceLoader(fromAssembly, resourceName);
if (_loader.LoadZipDirectory(out _unpackedLibrary, out _unpackedModules,
out _unpackingError))
return;
_unpackedLibrary = new Dictionary<string, PackedResourceInfo>();
_unpackedModules = new Dictionary<string, PackedResourceInfo[]>();
if (!String.IsNullOrEmpty(_unpackingError))
throw MakeError("meta_path importer initialization error: {0}", _unpackingError);
}
[Documentation(
@"find_module(fullname, path=None) -> self or None.
Search for a module specified by 'fullname'. 'fullname' must be the
fully qualified (dotted) module name. It returns the importer
instance itself if the module was found, or None if it wasn't.
The optional 'path' argument is ignored -- it's there for compatibility
with the importer protocol."
)]
public object find_module(CodeContext /*!*/ context, string fullname, params object[] args) {
var packedName = MakeFilename(fullname);
foreach (var entry in SearchOrder) {
var temp = packedName + entry.Key;
if (_unpackedLibrary.ContainsKey(temp))
return this;
}
return null;
}
[Documentation(
@"load_module(fullname) -> module.
Load the module specified by 'fullname'. 'fullname' must be the
fully qualified (dotted) module name. It returns the imported
module, or raises ResourceImportError if it wasn't found."
)]
public object load_module(CodeContext /*!*/ context, string fullname) {
var modules = context.LanguageContext.SystemStateModules;
if (modules.ContainsKey(fullname))
return modules[fullname];
bool ispackage;
string modpath;
var code = GetModuleCode(context, fullname, out ispackage, out modpath);
if (code == null)
return null;
var pythonContext = context.LanguageContext;
ScriptCode script;
var mod = pythonContext.CompileModule(modpath, fullname,
new SourceUnit(pythonContext,
new MemoryStreamContentProvider(pythonContext, code, modpath),
modpath, SourceCodeKind.File),
ModuleOptions.None, out script);
var dict = mod.__dict__;
// we do these here because we don't want CompileModule to initialize the module until we've set
// up some additional stuff
dict.Add("__name__", fullname);
dict.Add("__loader__", this);
// ReSharper disable AssignNullToNotNullAttribute
dict.Add("__package__", null);
// ReSharper restore AssignNullToNotNullAttribute
dict.Add("__file__", "<resource>");
if (ispackage) {
//// add __path__ to the module *before* the code
//// gets executed
//var subname = GetSubName(fullname);
//var fullpath = string.Format("{0}{1}",
// Path.DirectorySeparatorChar,
// subname);
//var pkgpath = PythonOps.MakeList(fullpath);
var pkgpath = new PythonList();
dict.Add("__path__", pkgpath);
}
modules.Add(fullname, mod);
try {
script.Run(mod.Scope);
}
catch (Exception) {
modules.Remove(fullname);
throw;
}
return mod;
}
private byte[] GetModuleCode(CodeContext /*!*/ context, string fullname, out bool ispackage,
out string modpath) {
var path = MakeFilename(fullname);
ispackage = false;
modpath = string.Empty;
if (String.IsNullOrEmpty(path))
return null;
foreach (var entry in SearchOrder) {
var temp = path + entry.Key;
if (!_unpackedLibrary.ContainsKey(temp))
continue;
var tocEntry = _unpackedLibrary[temp];
ispackage = (entry.Value & ModuleCodeType.Package) == ModuleCodeType.Package;
// we currently don't support bytecode modules, so we don't check
// the time of the bytecode file vs. the time of the source file.
byte[] code = GetCodeFromData(context, false, tocEntry);
if (code == null) {
continue;
}
modpath = tocEntry.FullName;
return code;
}
throw MakeError("can't find module '{0}'", fullname);
}
private byte[] GetCodeFromData(CodeContext /*!*/ context, bool isbytecode, PackedResourceInfo tocEntry) {
byte[] data = GetData(tocEntry);
byte[] code = null;
if (data != null) {
if (isbytecode) {
// would put in code to unmarshal the bytecode here...
}
else {
code = data;
}
}
return code;
}
private byte[] GetData(PackedResourceInfo tocEntry) {
string unpackingError;
byte[] result;
if (!_loader.GetData(tocEntry, out result, out unpackingError))
throw MakeError(unpackingError);
return result;
}
private static Exception MakeError(params object[] args) {
return IronPython.Runtime.Operations.PythonOps.CreateThrowable(PythonExceptions.ImportError, args);
}
private static string MakeFilename(string name) {
return name.Replace('.', Path.DirectorySeparatorChar);
}
private struct PackedResourceInfo {
private int _fileSize;
public string FullName;
public int Compress;
public int DataSize;
public int FileOffset;
public static PackedResourceInfo Create(string fullName, int compress,
int dataSize, int fileSize, int fileOffset) {
PackedResourceInfo result;
result.FullName = fullName;
result.Compress = compress;
result.DataSize = dataSize;
result._fileSize = fileSize;
result.FileOffset = fileOffset;
return result;
}
#if DEBUG
public override string ToString() {
var sizeDesc = String.Format("{0} bytes", _fileSize);
if (Convert.ToDouble(_fileSize)/1024.0 > 1.0)
sizeDesc = String.Format("{0} KB", Math.Round(Convert.ToDouble(_fileSize)/1024.0, 1));
return String.Format("{0} ({1})", FullName, sizeDesc);
}
#endif
}
private class PackedResourceLoader {
private readonly Assembly _fromAssembly;
private readonly string _resourceNameBase;
private const int MaxPathLen = 256;
public PackedResourceLoader(Assembly fromAssembly, string resourceName) {
_fromAssembly = fromAssembly;
_resourceNameBase = resourceName;
}
public bool LoadZipDirectory(
out IDictionary<string, PackedResourceInfo> files,
out IDictionary<string, PackedResourceInfo[]> modules,
out string unpackingError) {
if (!ReadZipDirectory(out files, out unpackingError)) {
modules = null;
return false;
}
try {
var parsedSources =
from entry in files.Values
let isPyFile = entry.FullName.EndsWith(".py", StringComparison.OrdinalIgnoreCase)
where isPyFile
let name = entry.FullName.Substring(0, entry.FullName.Length - 3)
let dottedName = name.Replace('\\', '.').Replace('/', '.')
let lineage = dottedName.Split('.')
let fileName = lineage.Last()
let path = lineage.Take(lineage.Length - 1).ToArray()
orderby fileName
select new {
name = fileName,
path,
dottedPath = String.Join(".", path),
entry
};
var moduleContents =
from source in parsedSources
orderby source.dottedPath
group source by source.dottedPath
into moduleGroup
select new {
moduleGroup.Key,
Items = moduleGroup.Select(item => item.entry).ToArray()
};
modules = moduleContents.ToDictionary(
moduleGroup => moduleGroup.Key,
moduleGroup => moduleGroup.Items);
return true;
}
catch (Exception exception) {
files = null;
modules = null;
unpackingError = String.Format("{0}: {1}", exception.GetType().Name, exception.Message);
return false;
}
}
private Stream GetZipArchive() {
var fullResourceName = _fromAssembly.GetManifestResourceNames().Where(name => name.EndsWith(_resourceNameBase, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
return string.IsNullOrEmpty(fullResourceName) ? null : _fromAssembly.GetManifestResourceStream(fullResourceName);
}
private bool ReadZipDirectory(out IDictionary<string, PackedResourceInfo> result,
out string unpackingError) {
unpackingError = null;
result = null;
try {
var stream = GetZipArchive();
if (stream == null) {
unpackingError = "Resource not found.";
return false;
}
using (var reader = new BinaryReader(stream)) {
if (reader.BaseStream.Length < 2) {
unpackingError = "Can't read ZIP resource: Empty Resource.";
return false;
}
var endofCentralDir = new byte[22];
reader.BaseStream.Seek(-22, SeekOrigin.End);
var headerPosition = (int) reader.BaseStream.Position;
if (reader.Read(endofCentralDir, 0, 22) != 22) {
unpackingError = "Can't read ZIP resource: Invalid ZIP Directory.";
return false;
}
if (BitConverter.ToUInt32(endofCentralDir, 0) != 0x06054B50) {
// Bad: End of Central Dir signature
unpackingError = "Can't read ZIP resource: Not a ZIP file.";
return false;
}
var headerSize = BitConverter.ToInt32(endofCentralDir, 12);
var headerOffset = BitConverter.ToInt32(endofCentralDir, 16);
var arcOffset = headerPosition - headerOffset - headerSize;
headerOffset += arcOffset;
var directoryEntries = ReadZipDirectory(reader, headerOffset, arcOffset);
result = directoryEntries
.OrderBy(entry => entry.FullName)
.ToDictionary(entry => entry.FullName);
return true;
}
}
catch (Exception exception) {
unpackingError = String.Format("{0}: {1}", exception.GetType().Name, exception.Message);
return false;
}
}
private static IEnumerable<PackedResourceInfo> ReadZipDirectory(BinaryReader reader, int headerOffset,
int arcoffset) {
while (true) {
var name = string.Empty;
reader.BaseStream.Seek(headerOffset, SeekOrigin.Begin); // Start of file header
int l = reader.ReadInt32();
if (l != 0x02014B50) {
break; // Bad: Central Dir File Header
}
reader.BaseStream.Seek(headerOffset + 10, SeekOrigin.Begin);
var compress = reader.ReadInt16();
/*var time =*/
reader.ReadInt16();
/*var date =*/
reader.ReadInt16();
/*var crc =*/
reader.ReadInt32();
var dataSize = reader.ReadInt32();
var fileSize = reader.ReadInt32();
var nameSize = reader.ReadInt16();
var headerSize = 46 + nameSize +
reader.ReadInt16() +
reader.ReadInt16();
reader.BaseStream.Seek(headerOffset + 42, SeekOrigin.Begin);
var fileOffset = reader.ReadInt32() + arcoffset;
if (nameSize > MaxPathLen)
nameSize = MaxPathLen;
for (int i = 0; i < nameSize; i++) {
char c = reader.ReadChar();
if (c == '/')
c = Path.DirectorySeparatorChar;
name += c;
}
headerOffset += headerSize;
yield return
PackedResourceInfo.Create(name, compress, dataSize, fileSize, fileOffset);
}
}
public bool GetData(PackedResourceInfo tocEntry, out byte[] result, out string unpackingError) {
unpackingError = null;
result = null;
var fileOffset = tocEntry.FileOffset;
var dataSize = tocEntry.DataSize;
var compress = tocEntry.Compress;
try {
var stream = GetZipArchive();
if (stream == null) {
unpackingError = "Resource not found.";
return false;
}
using (var reader = new BinaryReader(stream)) {
// Check to make sure the local file header is correct
reader.BaseStream.Seek(fileOffset, SeekOrigin.Begin);
var l = reader.ReadInt32();
if (l != 0x04034B50) {
// Bad: Local File Header
unpackingError = "Bad local file header in ZIP resource.";
return false;
}
reader.BaseStream.Seek(fileOffset + 26, SeekOrigin.Begin);
l = 30 + reader.ReadInt16() + reader.ReadInt16(); // local header size
fileOffset += l; // start of file data
reader.BaseStream.Seek(fileOffset, SeekOrigin.Begin);
byte[] rawData;
try {
rawData = reader.ReadBytes(compress == 0 ? dataSize : dataSize + 1);
}
catch {
unpackingError = "Can't read data";
return false;
}
if (compress != 0) {
rawData[dataSize] = (byte) 'Z';
}
result = compress == 0 ? rawData : ZlibModule.Decompress(rawData, -15);
return true;
}
}
catch (Exception exception) {
unpackingError = String.Format("{0}: {1}", exception.GetType().Name, exception.Message);
return false;
}
}
}
}
}
| |
//
// This code was created by Jeff Molofee '99
//
// If you've found this code useful, please let me know.
//
// Visit me at www.demonews.com/hosted/nehe
//
//=====================================================================
// Converted to C# and MonoMac by Kenneth J. Pouncey
// http://www.cocoa-mono.org
//
// Copyright (c) 2011 Kenneth J. Pouncey
//
//
// 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.Drawing;
using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.CoreVideo;
using MonoMac.OpenGL;
namespace NeHeLesson13
{
public partial class MyOpenGLView : MonoMac.AppKit.NSView
{
NSOpenGLContext openGLContext;
NSOpenGLPixelFormat pixelFormat;
MainWindowController controller;
CVDisplayLink displayLink;
NSObject notificationProxy;
[Export("initWithFrame:")]
public MyOpenGLView (RectangleF frame) : this(frame, null)
{
}
public MyOpenGLView (RectangleF frame,NSOpenGLContext context) : base(frame)
{
var attribs = new object [] {
NSOpenGLPixelFormatAttribute.Accelerated,
NSOpenGLPixelFormatAttribute.NoRecovery,
NSOpenGLPixelFormatAttribute.DoubleBuffer,
NSOpenGLPixelFormatAttribute.ColorSize, 24,
NSOpenGLPixelFormatAttribute.DepthSize, 16 };
pixelFormat = new NSOpenGLPixelFormat (attribs);
if (pixelFormat == null)
Console.WriteLine ("No OpenGL pixel format");
// NSOpenGLView does not handle context sharing, so we draw to a custom NSView instead
openGLContext = new NSOpenGLContext (pixelFormat, context);
openGLContext.MakeCurrentContext ();
// Synchronize buffer swaps with vertical refresh rate
openGLContext.SwapInterval = true;
// Initialize our newly created view.
InitGL ();
SetupDisplayLink ();
// Look for changes in view size
// Note, -reshape will not be called automatically on size changes because NSView does not export it to override
notificationProxy = NSNotificationCenter.DefaultCenter.AddObserver (NSView.GlobalFrameChangedNotification, HandleReshape);
}
public override void DrawRect (RectangleF dirtyRect)
{
// Ignore if the display link is still running
if (!displayLink.IsRunning && controller != null)
DrawView ();
}
public override bool AcceptsFirstResponder ()
{
// We want this view to be able to receive key events
return true;
}
public override void LockFocus ()
{
base.LockFocus ();
if (openGLContext.View != this)
openGLContext.View = this;
}
public override void KeyDown (NSEvent theEvent)
{
controller.KeyDown (theEvent);
}
public override void MouseDown (NSEvent theEvent)
{
controller.MouseDown (theEvent);
}
// All Setup For OpenGL Goes Here
public bool InitGL ()
{
// Enables Smooth Shading
GL.ShadeModel (ShadingModel.Smooth);
// Set background color to black
GL.ClearColor (Color.Black);
// Setup Depth Testing
// Depth Buffer setup
GL.ClearDepth (1.0);
// Enables Depth testing
GL.Enable (EnableCap.DepthTest);
// The type of depth testing to do
GL.DepthFunc (DepthFunction.Lequal);
// Really Nice Perspective Calculations
GL.Hint (HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);
return true;
}
private void DrawView ()
{
var previous = NSApplication.CheckForIllegalCrossThreadCalls;
NSApplication.CheckForIllegalCrossThreadCalls = false;
// This method will be called on both the main thread (through -drawRect:) and a secondary thread (through the display link rendering loop)
// Also, when resizing the view, -reshape is called on the main thread, but we may be drawing on a secondary thread
// Add a mutex around to avoid the threads accessing the context simultaneously
openGLContext.CGLContext.Lock ();
// Make sure we draw to the right context
openGLContext.MakeCurrentContext ();
// Delegate to the scene object for rendering
controller.Scene.DrawGLScene ();
openGLContext.FlushBuffer ();
openGLContext.CGLContext.Unlock ();
NSApplication.CheckForIllegalCrossThreadCalls = previous;
}
private void SetupDisplayLink ()
{
// Create a display link capable of being used with all active displays
displayLink = new CVDisplayLink ();
// Set the renderer output callback function
displayLink.SetOutputCallback (MyDisplayLinkOutputCallback);
// Set the display link for the current renderer
CGLContext cglContext = openGLContext.CGLContext;
CGLPixelFormat cglPixelFormat = PixelFormat.CGLPixelFormat;
displayLink.SetCurrentDisplay (cglContext, cglPixelFormat);
}
public CVReturn MyDisplayLinkOutputCallback (CVDisplayLink displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut)
{
CVReturn result = GetFrameForTime (inOutputTime);
return result;
}
private CVReturn GetFrameForTime (CVTimeStamp outputTime)
{
// There is no autorelease pool when this method is called because it will be called from a background thread
// It's important to create one or you will leak objects
using (NSAutoreleasePool pool = new NSAutoreleasePool ()) {
// Update the animation
DrawView ();
}
return CVReturn.Success;
}
public NSOpenGLContext OpenGLContext {
get { return openGLContext; }
}
public NSOpenGLPixelFormat PixelFormat {
get { return pixelFormat; }
}
public MainWindowController MainController {
set { controller = value; }
}
public void UpdateView ()
{
// This method will be called on the main thread when resizing, but we may be drawing on a secondary thread through the display link
// Add a mutex around to avoid the threads accessing the context simultaneously
openGLContext.CGLContext.Lock ();
// Delegate to the scene object to update for a change in the view size
controller.Scene.ResizeGLScene (Bounds);
openGLContext.Update ();
openGLContext.CGLContext.Unlock ();
}
private void HandleReshape (NSNotification note)
{
UpdateView ();
}
public void StartAnimation ()
{
if (displayLink != null && !displayLink.IsRunning)
displayLink.Start ();
}
public void StopAnimation ()
{
if (displayLink != null && displayLink.IsRunning)
displayLink.Stop ();
}
// Clean up the notifications
public void DeAllocate ()
{
displayLink.Stop ();
displayLink.SetOutputCallback (null);
NSNotificationCenter.DefaultCenter.RemoveObserver (notificationProxy);
}
[Export("toggleFullScreen:")]
public void toggleFullScreen (NSObject sender)
{
controller.toggleFullScreen (sender);
}
}
}
| |
// 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.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using AutoRest.Core.Model;
using AutoRest.Core.Utilities;
using AutoRest.NodeJS.Templates;
using Newtonsoft.Json;
using static AutoRest.Core.Utilities.DependencyInjection;
namespace AutoRest.NodeJS.Model
{
public class MethodJs : Method
{
public MethodJs()
{
// methods that have no group name get the client name as their name
Group.OnGet += groupName =>
{
return groupName.IsNullOrEmpty() ? CodeModel?.Name.Value : groupName;
};
OptionsParameterTemplateModel = (ParameterJs)New<Parameter>(new
{
Name = "options",
SerializedName = "options",
IsRequired = false,
Documentation = "Optional Parameters.",
Location = ParameterLocation.None,
ModelType = New<CompositeType>(new
{
Name = "options",
SerializedName = "options",
Documentation = "Optional Parameters."
})
});
OptionsParameterModelType.Add(New<Core.Model.Property>(new
{
IsReadOnly = false,
Name = "customHeaders",
IsRequired = false,
Documentation = "Headers that will be added to the request",
ModelType = New<PrimaryType>(KnownPrimaryType.Object),
SerializedName = "customHeaders"
}));
}
public override void Remove(Parameter item)
{
base.Remove(item);
// find a Property in OptionsParameterModelType with the same name and remove it.
OptionsParameterModelType.Remove(prop => prop.Name == item.Name);
}
public enum MethodFlavor
{
Callback,
Promise,
HttpOperationResponse
}
public enum Language
{
JavaScript,
TypeScript
}
public override Parameter Add(Parameter item)
{
var parameter = base.Add(item) as ParameterJs;
if (parameter.IsLocal && !parameter.IsRequired)
{
OptionsParameterModelType.Add(New<Core.Model.Property>(new
{
IsReadOnly = false,
Name = parameter.Name,
IsRequired = parameter.IsRequired,
DefaultValue = parameter.DefaultValue,
Documentation = parameter.Documentation,
ModelType = parameter.ModelType,
SerializedName = parameter.SerializedName,
Constraints = parameter.Constraints,
// optionalProperty.Constraints.AddRange(parameter.Constraints);
Extensions = parameter.Extensions // optionalProperty.Extensions.AddRange(parameter.Extensions);
}));
}
return parameter;
}
[JsonIgnore]
private CompositeType OptionsParameterModelType => ((CompositeType)OptionsParameterTemplateModel.ModelType);
[JsonIgnore]
public IEnumerable<ParameterJs> ParameterTemplateModels => Parameters.Cast<ParameterJs>();
[JsonIgnore]
public ParameterJs OptionsParameterTemplateModel { get; }
/// <summary>
/// Get the predicate to determine of the http operation status code indicates success
/// </summary>
public string FailureStatusCodePredicate
{
get
{
if (Responses.Any())
{
List<string> predicates = new List<string>();
foreach (var responseStatus in Responses.Keys)
{
predicates.Add(string.Format(CultureInfo.InvariantCulture,
"statusCode !== {0}", GetStatusCodeReference(responseStatus)));
}
return string.Join(" && ", predicates);
}
return "statusCode < 200 || statusCode >= 300";
}
}
/// <summary>
/// Generate the method parameter declarations for a method
/// </summary>
public string MethodParameterDeclaration
{
get
{
List<string> declarations = new List<string>();
foreach (var parameter in LocalParametersWithOptions)
{
declarations.Add(parameter.Name);
}
var declaration = string.Join(", ", declarations);
return declaration;
}
}
/// <summary>
/// Generate the method parameter declarations for a method, using TypeScript declaration syntax
/// <param name="includeOptions">whether the ServiceClientOptions parameter should be included</param>
/// <param name="isOptionsOptional">whether the ServiceClientOptions parameter should be optional</param>
/// </summary>
public string MethodParameterDeclarationTS(bool includeOptions, bool isOptionsOptional = true)
{
StringBuilder declarations = new StringBuilder();
bool first = true;
IEnumerable<ParameterJs> requiredParameters = LocalParameters.Where(p => p.IsRequired);
foreach (var parameter in requiredParameters)
{
if (!first)
declarations.Append(", ");
declarations.Append(parameter.Name);
declarations.Append(": ");
// For date/datetime parameters, use a union type to reflect that they can be passed as a JS Date or a string.
var type = parameter.ModelType;
if (type.IsPrimaryType(KnownPrimaryType.Date) || type.IsPrimaryType(KnownPrimaryType.DateTime))
declarations.Append("Date|string");
else declarations.Append(type.TSType(false));
first = false;
}
if (includeOptions)
{
if (!first)
declarations.Append(", ");
if (isOptionsOptional)
{
declarations.Append("options?: { ");
}
else
{
declarations.Append("options: { ");
}
var optionalParameters = ((CompositeType)OptionsParameterTemplateModel.ModelType).Properties.OrderBy(each => each.Name == "customHeaders" ? 1 : 0).ToArray();
for (int i = 0; i < optionalParameters.Length; i++)
{
if (i != 0)
{
declarations.Append(", ");
}
declarations.Append(optionalParameters[i].Name);
declarations.Append("? : ");
if (optionalParameters[i].Name.EqualsIgnoreCase("customHeaders"))
{
declarations.Append("{ [headerName: string]: string; }");
}
else
{
declarations.Append(optionalParameters[i].ModelType.TSType(false));
}
}
declarations.Append(" }");
}
return declarations.ToString();
}
/// <summary>
/// Generate the method parameter declarations with callback or optionalCallback for a method
/// <param name="isCallbackOptional">If true, the method signature has an optional callback, otherwise the callback is required.</param>
/// </summary>
public string MethodParameterDeclarationWithCallback(bool isCallbackOptional = false)
{
var parameters = MethodParameterDeclaration;
if (isCallbackOptional)
{
parameters += ", optionalCallback";
}
else
{
parameters += ", callback";
}
return parameters;
}
/// <summary>
/// Generate the method parameter declarations with callback for a method, using TypeScript method syntax
/// <param name="includeOptions">whether the ServiceClientOptions parameter should be included</param>
/// <param name="includeCallback">If true, the method signature will have a callback, otherwise the callback will not be present.</param>
/// </summary>
public string MethodParameterDeclarationWithCallbackTS(bool includeOptions, bool includeCallback = true)
{
//var parameters = MethodParameterDeclarationTS(includeOptions);
StringBuilder parameters = new StringBuilder();
if (!includeCallback)
{
//Promise scenario no callback and options is optional
parameters.Append(MethodParameterDeclarationTS(includeOptions));
}
else
{
//callback scenario
if (includeOptions)
{
//with options as required parameter
parameters.Append(MethodParameterDeclarationTS(includeOptions, isOptionsOptional: false));
}
else
{
//with options as optional parameter
parameters.Append(MethodParameterDeclarationTS(includeOptions: false));
}
}
if (includeCallback)
{
if (parameters.Length > 0)
{
parameters.Append(", ");
}
parameters.Append("callback: ServiceCallback<" + ReturnTypeTSString + ">");
}
return parameters.ToString();
}
/// <summary>
/// Get the parameters that are actually method parameters in the order they appear in the method signature
/// exclude global parameters and constants.
/// </summary>
internal IEnumerable<ParameterJs> LocalParameters
{
get
{
return ParameterTemplateModels.Where(
p => p != null && !p.IsClientProperty && !string.IsNullOrWhiteSpace(p.Name) && !p.IsConstant)
.OrderBy(item => !item.IsRequired);
}
}
/// <summary>
/// Get the parameters that are actually method parameters in the order they appear in the method signature
/// exclude global parameters. All the optional parameters are pushed into the second last "options" parameter.
/// </summary>
[JsonIgnore]
public IEnumerable<ParameterJs> LocalParametersWithOptions
{
get
{
List<ParameterJs> requiredParamsWithOptionsList = LocalParameters.Where(p => p.IsRequired).ToList();
requiredParamsWithOptionsList.Add(OptionsParameterTemplateModel);
return requiredParamsWithOptionsList as IEnumerable<ParameterJs>;
}
}
/// <summary>
/// Returns list of parameters and their properties in (alphabetical order) that needs to be documented over a method.
/// This property does simple tree traversal using stack and hashtable for already visited complex types.
/// </summary>
[JsonIgnore]
public IEnumerable<ParameterJs> DocumentationParameters
{
get
{
var traversalStack = new Stack<ParameterJs>();
var visitedHash = new HashSet<string>();
var retValue = new Stack<ParameterJs>();
foreach (var param in LocalParametersWithOptions)
{
traversalStack.Push(param);
}
while (traversalStack.Count() != 0)
{
var param = traversalStack.Pop();
if (!(param.ModelType is CompositeType))
{
retValue.Push(param);
}
if (param.ModelType is CompositeType)
{
if (!visitedHash.Contains(param.ModelType.Name))
{
traversalStack.Push(param);
foreach (var property in param.ComposedProperties.OrderBy(each => each.Name == "customHeaders" ? 1 : 0)) //.OrderBy( each => each.Name.Else("")))
{
if (property.IsReadOnly || property.IsConstant)
{
continue;
}
var propertyParameter = New<Parameter>() as ParameterJs;
propertyParameter.ModelType = property.ModelType;
propertyParameter.IsRequired = property.IsRequired;
propertyParameter.Name.FixedValue = param.Name + "." + property.Name;
string documentationString = string.Join(" ", (new[] { property.Summary, property.Documentation }).Where(s => !string.IsNullOrEmpty(s)));
propertyParameter.Documentation = documentationString;
traversalStack.Push(propertyParameter);
}
visitedHash.Add(param.ModelType.Name);
}
else
{
retValue.Push(param);
}
}
}
return retValue.ToList();
}
}
public static string ConstructParameterDocumentation(string documentation)
{
var builder = new IndentedStringBuilder(" ");
return builder.AppendLine(documentation)
.AppendLine(" * ").ToString();
}
/// <summary>
/// Get the type name for the method's return type
/// </summary>
[JsonIgnore]
public string ReturnTypeString
{
get
{
if (ReturnType.Body != null)
{
return ReturnType.Body.Name;
}
else
{
return "null";
}
}
}
/// <summary>
/// Get the type name for the method's return type for TS
/// </summary>
[JsonIgnore]
public string ReturnTypeTSString
{
get
{
if (ReturnType.Body != null)
{
return ReturnType.Body.TSType(false);
}
else
{
return "void";
}
}
}
/// <summary>
/// The Deserialization Error handling code block that provides a useful Error
/// message when exceptions occur in deserialization along with the request
/// and response object
/// </summary>
[JsonIgnore]
public string DeserializationError
{
get
{
var builder = new IndentedStringBuilder(" ");
var errorVariable = this.GetUniqueName("deserializationError");
return builder.AppendLine("let {0} = new Error(`Error ${{error}} occurred in " +
"deserializing the responseBody - ${{responseBody}}`);", errorVariable)
.AppendLine("{0}.request = msRest.stripRequest(httpRequest);", errorVariable)
.AppendLine("{0}.response = msRest.stripResponse(response);", errorVariable)
.AppendLine("return callback({0});", errorVariable).ToString();
}
}
public string PopulateErrorCodeAndMessage()
{
var builder = new IndentedStringBuilder(" ");
if (DefaultResponse.Body != null && DefaultResponse.Body.Name.RawValue.EqualsIgnoreCase("CloudError"))
{
builder.AppendLine("if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;")
.AppendLine("if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;")
.AppendLine("if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;");
}
else
{
builder.AppendLine("let internalError = null;")
.AppendLine("if (parsedErrorResponse.error) internalError = parsedErrorResponse.error;")
.AppendLine("error.code = internalError ? internalError.code : parsedErrorResponse.code;")
.AppendLine("error.message = internalError ? internalError.message : parsedErrorResponse.message;");
}
return builder.ToString();
}
/// <summary>
/// Provides the parameter name in the correct jsdoc notation depending on
/// whether it is required or optional
/// </summary>
/// <param name="parameter">Parameter to be documented</param>
/// <returns>Parameter name in the correct jsdoc notation</returns>
public static string GetParameterDocumentationName(Parameter parameter)
{
if (parameter == null)
{
throw new ArgumentNullException(nameof(parameter));
}
if (parameter.IsRequired)
{
return parameter.Name;
}
else
{
return string.Format(CultureInfo.InvariantCulture, "[{0}]", parameter.Name);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")]
public static string GetParameterDocumentationType(Parameter parameter)
{
if (parameter == null)
{
throw new ArgumentNullException(nameof(parameter));
}
string typeName = "object";
if (parameter.ModelType is PrimaryTypeJs)
{
typeName = parameter.ModelType.Name;
}
else if (parameter.ModelType is Core.Model.SequenceType)
{
typeName = "array";
}
else if (parameter.ModelType is EnumType)
{
typeName = "string";
}
return typeName.ToLowerInvariant();
}
public string GetDeserializationString(IModelType type, string valueReference = "result", string responseVariable = "parsedResponse")
{
var builder = new IndentedStringBuilder(" ");
if (type is CompositeType)
{
builder.AppendLine("let resultMapper = new client.models['{0}']().mapper();", type.Name);
}
else
{
builder.AppendLine("let resultMapper = {{{0}}};", type.ConstructMapper(responseVariable, null, false, false));
}
builder.AppendLine("{1} = client.deserialize(resultMapper, {0}, '{1}');", responseVariable, valueReference);
return builder.ToString();
}
[JsonIgnore]
public string ValidationString
{
get
{
var builder = new IndentedStringBuilder(" ");
foreach (var parameter in ParameterTemplateModels.Where(p => !p.IsConstant))
{
if ((HttpMethod == HttpMethod.Patch && parameter.ModelType is CompositeType))
{
if (parameter.IsRequired)
{
builder.AppendLine("if ({0} === null || {0} === undefined) {{", parameter.Name)
.Indent()
.AppendLine("throw new Error('{0} cannot be null or undefined.');", parameter.Name)
.Outdent()
.AppendLine("}");
}
}
else
{
builder.AppendLine(parameter.ModelType.ValidateType(this, parameter.Name, parameter.IsRequired));
if (parameter.Constraints != null && parameter.Constraints.Count > 0 && parameter.Location != ParameterLocation.Body)
{
builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", parameter.Name).Indent();
builder = parameter.ModelType.AppendConstraintValidations(parameter.Name, parameter.Constraints, builder);
builder.Outdent().AppendLine("}");
}
}
}
return builder.ToString();
}
}
public string DeserializeResponse(IModelType type, string valueReference = "result", string responseVariable = "parsedResponse")
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
var builder = new IndentedStringBuilder(" ");
builder.AppendLine("let {0} = null;", responseVariable)
.AppendLine("try {")
.Indent()
.AppendLine("{0} = JSON.parse(responseBody);", responseVariable)
.AppendLine("{0} = JSON.parse(responseBody);", valueReference);
var deserializeBody = GetDeserializationString(type, valueReference, responseVariable);
if (!string.IsNullOrWhiteSpace(deserializeBody))
{
builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", responseVariable)
.Indent()
.AppendLine(deserializeBody)
.Outdent()
.AppendLine("}");
}
builder.Outdent()
.AppendLine("} catch (error) {")
.Indent()
.AppendLine(DeserializationError)
.Outdent()
.AppendLine("}");
return builder.ToString();
}
/// <summary>
/// Get the method's request body (or null if there is no request body)
/// </summary>
public ParameterJs RequestBody => Body as ParameterJs;
/// <summary>
/// Generate a reference to the ServiceClient
/// </summary>
[JsonIgnore]
public string ClientReference => MethodGroup.IsCodeModelMethodGroup ? "this" : "this.client";
public static string GetStatusCodeReference(HttpStatusCode code)
{
return string.Format(CultureInfo.InvariantCulture, "{0}", (int)code);
}
/// <summary>
/// Generate code to build the URL from a url expression and method parameters
/// </summary>
/// <param name="variableName">The variable to store the url in.</param>
/// <returns></returns>
public virtual string BuildUrl(string variableName)
{
var builder = new IndentedStringBuilder(" ");
BuildPathParameters(variableName, builder);
if (HasQueryParameters())
{
BuildQueryParameterArray(builder);
AddQueryParametersToUrl(variableName, builder);
}
return builder.ToString();
}
/// <summary>
/// Generate code to construct the query string from an array of query parameter strings containing 'key=value'
/// </summary>
/// <param name="variableName">The variable reference for the url</param>
/// <param name="builder">The string builder for url construction</param>
private void AddQueryParametersToUrl(string variableName, IndentedStringBuilder builder)
{
builder.AppendLine("if (queryParameters.length > 0) {")
.Indent();
if (this.Extensions.ContainsKey("nextLinkMethod") && (bool)this.Extensions["nextLinkMethod"])
{
builder.AppendLine("{0} += ({0}.indexOf('?') !== -1 ? '&' : '?') + queryParameters.join('&');", variableName);
}
else
{
builder.AppendLine("{0} += '?' + queryParameters.join('&');", variableName);
}
builder.Outdent().AppendLine("}");
}
/// <summary>
/// Detremines whether the Uri will have any query string
/// </summary>
/// <returns>True if a query string is possible given the method parameters, otherwise false</returns>
protected virtual bool HasQueryParameters()
{
return LogicalParameters.Any(p => p.Location == ParameterLocation.Query);
}
/// <summary>
/// Genrate code to build an array of query parameter strings in a variable named 'queryParameters'. The
/// array should contain one string element for each query parameter of the form 'key=value'
/// </summary>
/// <param name="builder">The stringbuilder for url construction</param>
protected virtual void BuildQueryParameterArray(IndentedStringBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
builder.AppendLine("let queryParameters = [];");
foreach (var queryParameter in LogicalParameters
.Where(p => p.Location == ParameterLocation.Query))
{
var queryAddFormat = "queryParameters.push('{0}=' + encodeURIComponent({1}));";
if (queryParameter.SkipUrlEncoding())
{
queryAddFormat = "queryParameters.push('{0}=' + {1});";
}
if (!queryParameter.IsRequired)
{
builder.AppendLine("if ({0} !== null && {0} !== undefined) {{", queryParameter.Name)
.Indent()
.AppendLine(queryAddFormat,
queryParameter.SerializedName, queryParameter.GetFormattedReferenceValue()).Outdent()
.AppendLine("}");
}
else
{
builder.AppendLine(queryAddFormat,
queryParameter.SerializedName, queryParameter.GetFormattedReferenceValue());
}
}
}
/// <summary>
/// Generate code to replace path parameters in the url template with the appropriate values
/// </summary>
/// <param name="variableName">The variable name for the url to be constructed</param>
/// <param name="builder">The string builder for url construction</param>
protected virtual void BuildPathParameters(string variableName, IndentedStringBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
foreach (var pathParameter in LogicalParameters.Where(p => p.Location == ParameterLocation.Path))
{
var pathReplaceFormat = "{0} = {0}.replace('{{{1}}}', encodeURIComponent({2}));";
if (pathParameter.SkipUrlEncoding())
{
pathReplaceFormat = "{0} = {0}.replace('{{{1}}}', {2});";
}
builder.AppendLine(pathReplaceFormat, variableName, pathParameter.SerializedName,
pathParameter.ModelType.ToString(pathParameter.Name));
}
}
/// <summary>
/// Gets the expression for default header setting.
/// </summary>
public virtual string SetDefaultHeaders
{
get
{
return string.Empty;
}
}
[JsonIgnore]
public string ConstructRequestBodyMapper
{
get
{
var builder = new IndentedStringBuilder(" ");
if (RequestBody.ModelType is CompositeType)
{
builder.AppendLine("let requestModelMapper = new client.models['{0}']().mapper();", RequestBody.ModelType.Name);
}
else
{
builder.AppendLine("let requestModelMapper = {{{0}}};",
RequestBody.ModelType.ConstructMapper(RequestBody.SerializedName, RequestBody, false, false));
}
return builder.ToString();
}
}
[JsonIgnore]
public virtual string InitializeResult
{
get
{
return string.Empty;
}
}
[JsonIgnore]
public string ReturnTypeInfo
{
get
{
string result = null;
if (ReturnType.Body is EnumType)
{
var returnBodyType = ReturnType.Body as EnumType;
if (!returnBodyType.ModelAsString)
{
string enumValues = "";
for (var i = 0; i < returnBodyType.Values.Count; i++)
{
if (i == returnBodyType.Values.Count - 1)
{
enumValues += returnBodyType.Values[i].SerializedName;
}
else
{
enumValues += returnBodyType.Values[i].SerializedName + ", ";
}
}
result = string.Format(CultureInfo.InvariantCulture,
"Possible values for result are - {0}.", enumValues);
}
}
else if (ReturnType.Body is CompositeType)
{
result = string.Format(CultureInfo.InvariantCulture,
"See {{@link {0}}} for more information.", ReturnTypeString);
}
return result;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")]
[JsonIgnore]
public string DocumentReturnTypeString
{
get
{
string typeName = "object";
IModelType returnBodyType = ReturnType.Body;
if (returnBodyType == null)
{
typeName = "null";
}
else if (returnBodyType is PrimaryTypeJs)
{
typeName = returnBodyType.Name;
}
else if (returnBodyType is Core.Model.SequenceType)
{
typeName = "array";
}
else if (returnBodyType is EnumType)
{
typeName = "string";
}
return typeName.ToLowerInvariant();
}
}
/// <summary>
/// Generates input mapping code block.
/// </summary>
/// <returns></returns>
public virtual string BuildInputMappings()
{
var builder = new IndentedStringBuilder(" ");
if (InputParameterTransformation.Count > 0)
{
if (AreWeFlatteningParameters())
{
return BuildFlattenParameterMappings();
}
else
{
return BuildGroupedParameterMappings();
}
}
return builder.ToString();
}
public virtual bool AreWeFlatteningParameters()
{
bool result = true;
foreach (var transformation in InputParameterTransformation)
{
var compositeOutputParameter = transformation.OutputParameter.ModelType as CompositeType;
if (compositeOutputParameter == null)
{
result = false;
break;
}
else
{
foreach (var poperty in compositeOutputParameter.ComposedProperties.Select(p => p.Name))
{
if (!transformation.ParameterMappings.Select(m => m.InputParameter.Name).Contains(poperty))
{
result = false;
break;
}
}
if (!result) break;
}
}
return result;
}
public virtual string BuildFlattenParameterMappings()
{
var builder = new IndentedStringBuilder(" ");
foreach (var transformation in InputParameterTransformation)
{
builder.AppendLine("let {0};",
transformation.OutputParameter.Name);
builder.AppendLine("if ({0}) {{", BuildNullCheckExpression(transformation))
.Indent();
if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) &&
transformation.OutputParameter.ModelType is CompositeType)
{
builder.AppendLine("{0} = new client.models['{1}']();",
transformation.OutputParameter.Name,
transformation.OutputParameter.ModelType.Name);
}
foreach (var mapping in transformation.ParameterMappings)
{
builder.AppendLine("{0};", mapping.CreateCode(transformation.OutputParameter));
}
builder.Outdent()
.AppendLine("}");
}
return builder.ToString();
}
public virtual string BuildGroupedParameterMappings()
{
var builder = new IndentedStringBuilder(" ");
if (InputParameterTransformation.Count > 0)
{
// Declare all the output paramaters outside the try block
foreach (var transformation in InputParameterTransformation)
{
if (transformation.OutputParameter.ModelType is CompositeType &&
transformation.OutputParameter.IsRequired)
{
builder.AppendLine("let {0} = new client.models['{1}']();",
transformation.OutputParameter.Name,
transformation.OutputParameter.ModelType.Name);
}
else
{
builder.AppendLine("let {0};", transformation.OutputParameter.Name);
}
}
builder.AppendLine("try {").Indent();
foreach (var transformation in InputParameterTransformation)
{
builder.AppendLine("if ({0})", BuildNullCheckExpression(transformation))
.AppendLine("{").Indent();
var outputParameter = transformation.OutputParameter;
bool noCompositeTypeInitialized = true;
if (transformation.ParameterMappings.Any(m => !string.IsNullOrEmpty(m.OutputParameterProperty)) &&
transformation.OutputParameter.ModelType is CompositeType)
{
//required outputParameter is initialized at the time of declaration
if (!transformation.OutputParameter.IsRequired)
{
builder.AppendLine("{0} = new client.models['{1}']();",
transformation.OutputParameter.Name,
transformation.OutputParameter.ModelType.Name);
}
noCompositeTypeInitialized = false;
}
foreach (var mapping in transformation.ParameterMappings)
{
builder.AppendLine("{0};", mapping.CreateCode(transformation.OutputParameter));
if (noCompositeTypeInitialized)
{
// If composite type is initialized based on the above logic then it should not be validated.
builder.AppendLine(outputParameter.ModelType.ValidateType(this, outputParameter.Name, outputParameter.IsRequired));
}
}
builder.Outdent()
.AppendLine("}");
}
builder.Outdent()
.AppendLine("} catch (error) {")
.Indent()
.AppendLine("return callback(error);")
.Outdent()
.AppendLine("}");
}
return builder.ToString();
}
private static string BuildNullCheckExpression(ParameterTransformation transformation)
{
if (transformation == null)
{
throw new ArgumentNullException(nameof(transformation));
}
if (transformation.ParameterMappings.Count == 1)
{
return string.Format(CultureInfo.InvariantCulture,
"{0} !== null && {0} !== undefined",
transformation.ParameterMappings[0].InputParameter.Name);
}
else
{
return string.Join(" || ",
transformation.ParameterMappings.Select(m =>
string.Format(CultureInfo.InvariantCulture,
"({0} !== null && {0} !== undefined)", m.InputParameter.Name)));
}
}
public string BuildOptionalMappings()
{
IEnumerable<Core.Model.Property> optionalParameters =
((CompositeType)OptionsParameterTemplateModel.ModelType)
.Properties.Where(p => p.Name != "customHeaders");
var builder = new IndentedStringBuilder(" ");
foreach (var optionalParam in optionalParameters)
{
string defaultValue = "undefined";
if (!string.IsNullOrWhiteSpace(optionalParam.DefaultValue))
{
defaultValue = optionalParam.DefaultValue;
}
builder.AppendLine("let {0} = ({1} && {1}.{2} !== undefined) ? {1}.{2} : {3};",
optionalParam.Name, OptionsParameterTemplateModel.Name, optionalParam.Name, defaultValue);
}
return builder.ToString();
}
/// <summary>
/// Generates documentation for every method on the client.
/// </summary>
/// <param name="flavor">Describes the flavor of the method (Callback based, promise based,
/// raw httpOperationResponse based) to be documented.</param>
/// <param name = "language" > Describes the language in which the method needs to be documented (Javascript (default), TypeScript).</param>
/// <returns></returns>
public string GenerateMethodDocumentation(MethodFlavor flavor, Language language = Language.JavaScript)
{
var template = new NodeJSTemplate<Object>();
var builder = new IndentedStringBuilder(" ");
builder.AppendLine("/**");
if (!String.IsNullOrEmpty(Summary))
{
builder.AppendLine(template.WrapComment(" * ", "@summary " + Summary)).AppendLine(" *");
}
if (!String.IsNullOrEmpty(Description))
{
builder.AppendLine(template.WrapComment(" * ", Description)).AppendLine(" *");
}
foreach (var parameter in DocumentationParameters)
{
var paramDoc = $"@param {{{GetParameterDocumentationType(parameter)}}} {GetParameterDocumentationName(parameter)} {parameter.Documentation}";
builder.AppendLine(ConstructParameterDocumentation(template.WrapComment(" * ", paramDoc)));
}
if (flavor == MethodFlavor.HttpOperationResponse)
{
var errorType = (language == Language.JavaScript) ? "Error" : "Error|ServiceError";
builder.AppendLine(" * @returns {Promise} A promise is returned").AppendLine(" *")
.AppendLine(" * @resolve {{HttpOperationResponse<{0}>}} - The deserialized result object.", ReturnTypeString).AppendLine(" *")
.AppendLine(" * @reject {{{0}}} - The error object.", errorType);
}
else
{
if (language == Language.JavaScript)
{
if (flavor == MethodFlavor.Callback)
{
builder.AppendLine(template.WrapComment(" * ", " @param {function} callback - The callback.")).AppendLine(" *")
.AppendLine(template.WrapComment(" * ", " @returns {function} callback(err, result, request, response)")).AppendLine(" *");
}
else if (flavor == MethodFlavor.Promise)
{
builder.AppendLine(template.WrapComment(" * ", " @param {function} [optionalCallback] - The optional callback.")).AppendLine(" *")
.AppendLine(template.WrapComment(" * ", " @returns {function|Promise} If a callback was passed as the last parameter " +
"then it returns the callback else returns a Promise.")).AppendLine(" *")
.AppendLine(" * {Promise} A promise is returned").AppendLine(" *")
.AppendLine(" * @resolve {{{0}}} - The deserialized result object.", ReturnTypeString).AppendLine(" *")
.AppendLine(" * @reject {Error} - The error object.").AppendLine(" *")
.AppendLine(template.WrapComment(" * ", "{function} optionalCallback(err, result, request, response)")).AppendLine(" *");
}
builder.AppendLine(" * {Error} err - The Error object if an error occurred, null otherwise.").AppendLine(" *")
.AppendLine(" * {{{0}}} [result] - The deserialized result object if an error did not occur.", DocumentReturnTypeString)
.AppendLine(template.WrapComment(" * ", ReturnTypeInfo)).AppendLine(" *")
.AppendLine(" * {object} [request] - The HTTP Request object if an error did not occur.").AppendLine(" *")
.AppendLine(" * {stream} [response] - The HTTP Response stream if an error did not occur.");
}
else
{
if (flavor == MethodFlavor.Callback)
{
builder.AppendLine(template.WrapComment(" * ", " @param {ServiceCallback} callback - The callback.")).AppendLine(" *")
.AppendLine(template.WrapComment(" * ", " @returns {ServiceCallback} callback(err, result, request, response)")).AppendLine(" *");
}
else if (flavor == MethodFlavor.Promise)
{
builder.AppendLine(template.WrapComment(" * ", " @param {ServiceCallback} [optionalCallback] - The optional callback.")).AppendLine(" *")
.AppendLine(template.WrapComment(" * ", " @returns {ServiceCallback|Promise} If a callback was passed as the last parameter " +
"then it returns the callback else returns a Promise.")).AppendLine(" *")
.AppendLine(" * {Promise} A promise is returned.").AppendLine(" *")
.AppendLine(" * @resolve {{{0}}} - The deserialized result object.", ReturnTypeString).AppendLine(" *")
.AppendLine(" * @reject {Error|ServiceError} - The error object.").AppendLine(" *")
.AppendLine(template.WrapComment(" * ", "{ServiceCallback} optionalCallback(err, result, request, response)")).AppendLine(" *");
}
builder.AppendLine(" * {Error|ServiceError} err - The Error object if an error occurred, null otherwise.").AppendLine(" *")
.AppendLine(" * {{{0}}} [result] - The deserialized result object if an error did not occur.", ReturnTypeString)
.AppendLine(template.WrapComment(" * ", ReturnTypeInfo)).AppendLine(" *")
.AppendLine(" * {WebResource} [request] - The HTTP Request object if an error did not occur.").AppendLine(" *")
.AppendLine(" * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.");
}
}
builder.AppendLine(" */");
return builder.ToString();
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// The implementation for the reduced product of intervals and symbolic weak upper bounds
// This has got the official name of "Pentagons"
using System;
using System.Text;
using System.Diagnostics;
using Microsoft.Research.AbstractDomains.Expressions;
using Microsoft.Research.DataStructures;
using Microsoft.Research.CodeAnalysis;
namespace Microsoft.Research.AbstractDomains.Numerical
{
using System.Collections.Generic;
public class StripeWithIntervals<Variable, Expression, MetaDataDecoder>
: ReducedCartesianAbstractDomain<IntervalEnvironment<Variable, Expression>, StripeWithIntervals<Variable, Expression, MetaDataDecoder>>,
INumericalAbstractDomain<Variable, Expression>
where Expression : class
{
#region Protected status
protected readonly IExpressionDecoder<Variable, Expression>/*!*/ decoder;
#endregion
#region Constructor
public StripeWithIntervals(IntervalEnvironment<Variable, Expression>/*!*/ left, StripeWithIntervals<Variable, Expression, MetaDataDecoder>/*!*/ right, IExpressionDecoder<Variable, Expression> decoder, Logger Log)
: base(left, right, Log)
{
this.decoder = decoder;
}
protected IExpressionDecoder<Variable, Expression> Decoder
{
get
{
return this.decoder;
}
}
#endregion
#region Implementation of the abstract methods
override protected ReducedCartesianAbstractDomain<IntervalEnvironment<Variable, Expression>, StripeWithIntervals<Variable, Expression, MetaDataDecoder>>
Factory(IntervalEnvironment<Variable, Expression> left, StripeWithIntervals<Variable, Expression, MetaDataDecoder> right)
{
return new StripeWithIntervals<Variable, Expression, MetaDataDecoder>(left, right, this.decoder, this.Log);
}
public override ReducedCartesianAbstractDomain<IntervalEnvironment<Variable, Expression>, StripeWithIntervals<Variable, Expression, MetaDataDecoder>>
Reduce(IntervalEnvironment<Variable, Expression>left, StripeWithIntervals<Variable, Expression, MetaDataDecoder> right)
{
return this.Factory(left, right);
}
/// <summary>
/// The pairwise widening
/// </summary>
public override IAbstractDomain Widening(IAbstractDomain prev)
{
if (this.IsBottom)
return prev;
if (prev.IsBottom)
return this;
Debug.Assert(prev is StripeWithIntervals<Variable, Expression, MetaDataDecoder>, "Wrong type of the domain for the widening...");
StripeWithIntervals<Variable, Expression, MetaDataDecoder> asIntWSUB = (StripeWithIntervals<Variable, Expression, MetaDataDecoder>)prev;
var widenLeft = (IntervalEnvironment<Variable, Expression>) this.Left.Widening(asIntWSUB.Left);
StripeWithIntervals<Variable, Expression, MetaDataDecoder> widenRight = (StripeWithIntervals<Variable, Expression, MetaDataDecoder>)this.Right.Widening(asIntWSUB.Right);
StripeWithIntervals<Variable, Expression, MetaDataDecoder> result = (StripeWithIntervals<Variable, Expression, MetaDataDecoder>)this.Factory(widenLeft, widenRight);
return result;
}
#endregion
new IntervalEnvironment<Variable, Expression> Left
{
get
{
return base.Left;
}
}
new StripeWithIntervals<Variable, Expression, MetaDataDecoder> Right
{
get
{
return base.Right;
}
}
#region INumericalAbstractDomain<Variable, Expression>Members
public virtual void AssignInParallel(Dictionary<Variable, FList<Variable>> sourcesToTargets, Converter<Variable, Expression> convert)
{
this.Right.AssignInParallel(sourcesToTargets, convert);
this.Left.AssignInParallel(sourcesToTargets, convert);
}
public Interval BoundsFor(Expression v)
{
return this.Left.BoundsFor(v);
}
public Interval BoundsFor(Variable v)
{
return this.Left.BoundsFor(v);
}
public Dictionary<Variable, Int32> IntConstants
{
get
{
return new Dictionary<Variable, Int32>();
}
}
public Set<Expression> LowerBoundsFor(Expression v, bool strict)
{
return new Set<Expression>(); //not implemented
}
public Set<Expression> UpperBoundsFor(Expression v, bool strict)
{
return new Set<Expression>(); //not implemented
}
public Set<Expression> LowerBoundsFor(Variable v, bool strict)
{
return new Set<Expression>(); //not implemented
}
public Set<Expression> UpperBoundsFor(Variable v, bool strict)
{
return new Set<Expression>(); //not implemented
}
#endregion
#region IPureExpressionAssignmentsWithForward<Expression> Members
public void Assign(Expression x, Expression exp)
{
// this.Left.Assign(x, exp);
// this.Right.Assign(x, exp);
this.Assign(x, exp, TopNumericalDomain<Variable, Expression>.Singleton);
}
public void Assign(Expression/*!*/ x, Expression/*!*/ exp, INumericalAbstractDomainQuery<Variable, Expression> preState)
{
this.Left.Assign(x, exp, preState);
this.Right.Assign(x, exp, preState);
}
public void AssignInterval(Variable x, Interval value)
{
this.Left.AssignInterval(x, value);
this.Right.AssignInterval(x, value);
}
#endregion
#region IPureExpressionAssignments<Expression> Members
public Set<Variable> Variables
{
get
{
var varInLeft = this.Left.Variables;
var varInRight = this.Right.Variables;
var retVal = new Set<Variable>(varInLeft);
retVal.AddRange(varInRight);
return retVal;
}
}
public void AddVariable(Variable var)
{
this.Left.AddVariable(var);
this.Right.AddVariable(var);
}
public void ProjectVariable(Variable var)
{
this.Left.ProjectVariable(var);
this.Right.ProjectVariable(var);
}
public void RemoveVariable(Variable var)
{
this.Left.RemoveVariable(var);
this.Right.RemoveVariable(var);
}
public void RenameVariable(Variable OldName, Variable NewName)
{
this.Left.RenameVariable(OldName, NewName);
this.Right.RenameVariable(OldName, NewName);
}
#endregion
#region IPureExpressionTest<Expression> Members
public INumericalAbstractDomain<Variable, Expression> TestTrueGeqZero(Expression/*!*/ exp)
{
IntervalEnvironment<Variable, Expression> resultLeft = this.Left.TestTrueGeqZero(exp);
StripeWithIntervals<Variable, Expression, MetaDataDecoder> resultRight = (StripeWithIntervals<Variable, Expression, MetaDataDecoder>)this.Right.TestTrueGeqZero(exp);
return (INumericalAbstractDomain<Variable, Expression>)Factory(resultLeft, resultRight);
}
public INumericalAbstractDomain<Variable, Expression>TestTrueLessThan(Expression/*!*/ exp1, Expression/*!*/ exp2)
{
IntervalEnvironment<Variable, Expression> resultLeft = this.Left.TestTrueLessThan(exp1, exp2);
StripeWithIntervals<Variable, Expression, MetaDataDecoder> resultRight = (StripeWithIntervals<Variable, Expression, MetaDataDecoder>)this.Right.TestTrueLessThan(exp1, exp2);
return (INumericalAbstractDomain<Variable, Expression>)Factory(resultLeft, resultRight);
}
public INumericalAbstractDomain<Variable, Expression>TestTrueLessEqualThan(Expression/*!*/ exp1, Expression/*!*/ exp2)
{
IntervalEnvironment<Variable, Expression> resultLeft = this.Left.TestTrueLessEqualThan(exp1, exp2);
StripeWithIntervals<Variable, Expression, MetaDataDecoder> resultRight = (StripeWithIntervals<Variable, Expression, MetaDataDecoder>)this.Right.TestTrueLessEqualThan(exp1, exp2);
return (INumericalAbstractDomain<Variable, Expression>)Factory(resultLeft, resultRight);
}
public INumericalAbstractDomain<Variable, Expression> TestTrueEqual(Expression/*!*/ exp1, Expression/*!*/ exp2)
{
IntervalEnvironment<Variable, Expression> resultLeft = this.Left.TestTrueEqual(exp1, exp2);
StripeWithIntervals<Variable, Expression, MetaDataDecoder> resultRight = (StripeWithIntervals<Variable, Expression, MetaDataDecoder>) this.Right.TestTrueEqual(exp1, exp2);
return (INumericalAbstractDomain<Variable, Expression>)Factory(resultLeft, resultRight);
}
public virtual IAbstractDomainForEnvironments<Variable, Expression> TestTrue(Expression guard)
{
IntervalEnvironment<Variable, Expression> resultLeft = this.Left.TestTrue(guard);
StripeWithIntervals<Variable, Expression, MetaDataDecoder> resultRight = (StripeWithIntervals<Variable, Expression, MetaDataDecoder>)this.Right.TestTrue(guard);
return (IAbstractDomainForEnvironments<Variable, Expression>)Factory(resultLeft, resultRight);
}
public virtual IAbstractDomainForEnvironments<Variable, Expression> TestFalse(Expression guard)
{
IntervalEnvironment<Variable, Expression> resultLeft = this.Left.TestFalse(guard);
StripeWithIntervals<Variable, Expression, MetaDataDecoder> resultRight = (StripeWithIntervals<Variable, Expression, MetaDataDecoder>)this.Right.TestFalse(guard);
return (IAbstractDomainForEnvironments<Variable, Expression>)Factory(resultLeft, resultRight);
}
public INumericalAbstractDomain<Variable, Expression> RemoveRedundanciesWith(INumericalAbstractDomain<Variable, Expression> oracle)
{
IntervalEnvironment<Variable, Expression> resultLeft = (IntervalEnvironment<Variable, Expression>) this.Left.RemoveRedundanciesWith(oracle);
StripeWithIntervals<Variable, Expression, MetaDataDecoder> resultRight = (StripeWithIntervals<Variable, Expression, MetaDataDecoder>)this.Right.RemoveRedundanciesWith(oracle);
return (INumericalAbstractDomain<Variable, Expression>)Factory(resultLeft, resultRight);
}
public FlatAbstractDomain<bool> CheckIfHolds(Expression exp)
{
FlatAbstractDomain<bool> checkLeft = this.Left.CheckIfHolds(exp);
FlatAbstractDomain<bool> checkRight = this.Right.CheckIfHolds(exp/*, this.Left*/);
FlatAbstractDomain<bool> result = checkLeft.Meet(checkRight);
if (result.Equals(result.Top))
{ //If we do not arrive to check the condition, we try to refine the information in the stripe domain with the state of Interval domain and also internally
StripeWithIntervals<Variable, Expression, MetaDataDecoder> refined = this.Right/*.Refine(this.Left).RefineInternally()*/;
checkRight = refined.CheckIfHolds(exp/*, this.Left*/);
result = checkLeft.Meet(checkRight);
}
return result;
}
public FlatAbstractDomain<bool>/*!*/ CheckIfGreaterEqualThanZero(Expression/*!*/ exp)
{
FlatAbstractDomain<bool>/*!*/ checkLeft = this.Left.CheckIfGreaterEqualThanZero(exp);
FlatAbstractDomain<bool>/*!*/ checkRight = this.Right.CheckIfGreaterEqualThanZero(exp);
FlatAbstractDomain<bool> result = checkLeft.Meet(checkRight);
if (result.Equals(result.Top))
{ //If we do not arrive to check the condition, we try to refine the information in the stripe domain with the state of Interval domain and also internally
StripeWithIntervals<Variable, Expression, MetaDataDecoder> refined = this.Right/*.Refine(this.Left).RefineInternally()*/;
checkRight = refined.CheckIfGreaterEqualThanZero(exp);
result = checkLeft.Meet(checkRight);
}
return result;
}
public FlatAbstractDomain<bool>/*!*/ CheckIfLessThan(Expression/*!*/ e1, Expression/*!*/ e2)
{
FlatAbstractDomain<bool>/*!*/ checkLeft = this.Left.CheckIfLessThan(e1, e2);
FlatAbstractDomain<bool>/*!*/ checkRight = this.Right.CheckIfLessThan(e1, e2/*, this.Left*/);
FlatAbstractDomain<bool> result = checkLeft.Meet(checkRight);
if (result.Equals(result.Top))
{ //If we do not arrive to check the condition, we try to refine the information in the stripe domain with the state of Interval domain and also internally
StripeWithIntervals<Variable, Expression, MetaDataDecoder> refined = this.Right/*.Refine(this.Left).RefineInternally()*/;
checkRight = refined.CheckIfLessThan(e1, e2/*, this.Left*/);
result = checkLeft.Meet(checkRight);
}
return result;
}
public FlatAbstractDomain<bool>/*!*/ CheckIfLessThan(Variable/*!*/ v1, Variable/*!*/ v2)
{
return CheckOutcome.Top;
}
public FlatAbstractDomain<bool>/*!*/ CheckIfNonZero(Expression/*!*/ e)
{
var checkLeft = this.Left.CheckIfNonZero(e);
var checkRight = this.Right.CheckIfNonZero(e);
return checkLeft.Meet(checkRight);
}
public FlatAbstractDomain<bool>/*!*/ CheckIfLessEqualThan(Expression/*!*/ e1, Expression/*!*/ e2)
{
return AbstractDomainsHelper.HelperForCheckLessEqualThan(this, e1, e2);
}
public FlatAbstractDomain<bool> CheckIfEqual(Expression e1, Expression e2)
{
var c1 = CheckIfLessEqualThan(e1, e2);
var c2 = CheckIfLessEqualThan(e2, e1);
if (c1.IsNormal() && c2.IsNormal())
{
return new FlatAbstractDomain<bool>(c1.BoxedElement && c2.BoxedElement);
}
return CheckOutcome.Top;
}
public FlatAbstractDomain<bool>/*!*/ CheckIfLessEqualThan(Variable/*!*/ v1, Variable/*!*/ v2)
{
return CheckOutcome.Top;
}
#endregion
#region ToString
public string ToString(Expression exp)
{
if (this.decoder != null)
{
return ExpressionPrinter.ToString(exp, this.decoder);
}
else
{
return "< missing expression decoder >";
}
}
#endregion
#region Floating point types
public void SetFloatType(Variable v, Floats f)
{
// does nothing
}
public FlatAbstractDomain<Floats> GetFloatType(Variable v)
{
return FloatTypes<Variable, Expression>.Unknown;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Utilities.Editor;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using UnityEditor;
using UnityEditor.Build.Reporting;
using UnityEngine;
using Debug = UnityEngine.Debug;
namespace Microsoft.MixedReality.Toolkit.Build.Editor
{
/// <summary>
/// Cross platform player build tools
/// </summary>
public static class UnityPlayerBuildTools
{
// Build configurations. Exactly one of these should be defined for any given build.
public const string BuildSymbolDebug = "debug";
public const string BuildSymbolRelease = "release";
public const string BuildSymbolMaster = "master";
/// <summary>
/// Starts the build process
/// </summary>
/// <returns>The <see href="https://docs.unity3d.com/ScriptReference/Build.Reporting.BuildReport.html">BuildReport</see> from Unity's <see href="https://docs.unity3d.com/ScriptReference/BuildPipeline.html">BuildPipeline</see></returns>
public static BuildReport BuildUnityPlayer(IBuildInfo buildInfo)
{
EditorUtility.DisplayProgressBar("Build Pipeline", "Gathering Build Data...", 0.25f);
// Call the pre-build action, if any
buildInfo.PreBuildAction?.Invoke(buildInfo);
BuildTargetGroup buildTargetGroup = buildInfo.BuildTarget.GetGroup();
string playerBuildSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTargetGroup);
if (!string.IsNullOrEmpty(playerBuildSymbols))
{
if (buildInfo.HasConfigurationSymbol())
{
buildInfo.AppendWithoutConfigurationSymbols(playerBuildSymbols);
}
else
{
buildInfo.AppendSymbols(playerBuildSymbols.Split(';'));
}
}
if (!string.IsNullOrEmpty(buildInfo.BuildSymbols))
{
PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTargetGroup, buildInfo.BuildSymbols);
}
if ((buildInfo.BuildOptions & BuildOptions.Development) == BuildOptions.Development &&
!buildInfo.HasConfigurationSymbol())
{
buildInfo.AppendSymbols(BuildSymbolDebug);
}
if (buildInfo.HasAnySymbols(BuildSymbolDebug))
{
buildInfo.BuildOptions |= BuildOptions.Development | BuildOptions.AllowDebugging;
}
if (buildInfo.HasAnySymbols(BuildSymbolRelease))
{
// Unity automatically adds the DEBUG symbol if the BuildOptions.Development flag is
// specified. In order to have debug symbols and the RELEASE symbols we have to
// inject the symbol Unity relies on to enable the /debug+ flag of csc.exe which is "DEVELOPMENT_BUILD"
buildInfo.AppendSymbols("DEVELOPMENT_BUILD");
}
var oldColorSpace = PlayerSettings.colorSpace;
if (buildInfo.ColorSpace.HasValue)
{
PlayerSettings.colorSpace = buildInfo.ColorSpace.Value;
}
if (buildInfo.ScriptingBackend.HasValue)
{
PlayerSettings.SetScriptingBackend(buildTargetGroup, buildInfo.ScriptingBackend.Value);
}
BuildTarget oldBuildTarget = EditorUserBuildSettings.activeBuildTarget;
BuildTargetGroup oldBuildTargetGroup = oldBuildTarget.GetGroup();
if (EditorUserBuildSettings.activeBuildTarget != buildInfo.BuildTarget)
{
EditorUserBuildSettings.SwitchActiveBuildTarget(buildTargetGroup, buildInfo.BuildTarget);
}
switch (buildInfo.BuildTarget)
{
case BuildTarget.Android:
buildInfo.OutputDirectory = $"{buildInfo.OutputDirectory}/{PlayerSettings.productName}.apk";
break;
case BuildTarget.StandaloneWindows:
case BuildTarget.StandaloneWindows64:
buildInfo.OutputDirectory = $"{buildInfo.OutputDirectory}/{PlayerSettings.productName}.exe";
break;
}
BuildReport buildReport = default;
try
{
buildReport = BuildPipeline.BuildPlayer(
buildInfo.Scenes.ToArray(),
buildInfo.OutputDirectory,
buildInfo.BuildTarget,
buildInfo.BuildOptions);
}
catch (Exception e)
{
Debug.LogError($"{e.Message}\n{e.StackTrace}");
}
PlayerSettings.colorSpace = oldColorSpace;
if (EditorUserBuildSettings.activeBuildTarget != oldBuildTarget)
{
EditorUserBuildSettings.SwitchActiveBuildTarget(oldBuildTargetGroup, oldBuildTarget);
}
// Call the post-build action, if any
buildInfo.PostBuildAction?.Invoke(buildInfo, buildReport);
return buildReport;
}
/// <summary>
/// Force Unity To Write Project Files
/// </summary>
public static void SyncSolution()
{
var syncVs = Type.GetType("UnityEditor.SyncVS,UnityEditor");
var syncSolution = syncVs.GetMethod("SyncSolution", BindingFlags.Public | BindingFlags.Static);
syncSolution.Invoke(null, null);
}
/// <summary>
/// Start a build using Unity's command line.
/// </summary>
public static async void StartCommandLineBuild()
{
var success = await BuildUnityPlayerSimplified();
Debug.Log($"Exiting build...");
EditorApplication.Exit(success ? 0 : 1);
}
public static async Task<bool> BuildUnityPlayerSimplified()
{
// We don't need stack traces on all our logs. Makes things a lot easier to read.
Application.SetStackTraceLogType(LogType.Log, StackTraceLogType.None);
Debug.Log($"Starting command line build for {EditorUserBuildSettings.activeBuildTarget}...");
EditorAssemblyReloadManager.LockReloadAssemblies = true;
bool success;
try
{
SyncSolution();
switch (EditorUserBuildSettings.activeBuildTarget)
{
case BuildTarget.WSAPlayer:
success = await UwpPlayerBuildTools.BuildPlayer(new UwpBuildInfo(true));
break;
default:
var buildInfo = new BuildInfo(true) as IBuildInfo;
ParseBuildCommandLine(ref buildInfo);
var buildResult = BuildUnityPlayer(buildInfo);
success = buildResult.summary.result == BuildResult.Succeeded;
break;
}
}
catch (Exception e)
{
Debug.LogError($"Build Failed!\n{e.Message}\n{e.StackTrace}");
success = false;
}
Debug.Log($"Finished build... Build success? {success}");
return success;
}
internal static bool CheckBuildScenes()
{
if (EditorBuildSettings.scenes.Length == 0)
{
return EditorUtility.DisplayDialog("Attention!",
"No scenes are present in the build settings.\n" +
"The current scene will be the one built.\n\n" +
"Do you want to cancel and add one?",
"Continue Anyway", "Cancel Build");
}
return true;
}
/// <summary>
/// Get the Unity Project Root Path.
/// </summary>
/// <returns>The full path to the project's root.</returns>
public static string GetProjectPath()
{
return Path.GetDirectoryName(Path.GetFullPath(Application.dataPath));
}
public static void ParseBuildCommandLine(ref IBuildInfo buildInfo)
{
string[] arguments = Environment.GetCommandLineArgs();
for (int i = 0; i < arguments.Length; ++i)
{
switch (arguments[i])
{
case "-autoIncrement":
buildInfo.AutoIncrement = true;
break;
case "-sceneList":
buildInfo.Scenes = buildInfo.Scenes.Union(SplitSceneList(arguments[++i]));
break;
case "-sceneListFile":
string path = arguments[++i];
if (File.Exists(path))
{
buildInfo.Scenes = buildInfo.Scenes.Union(SplitSceneList(File.ReadAllText(path)));
}
else
{
Debug.LogWarning($"Scene list file at '{path}' does not exist.");
}
break;
case "-buildOutput":
buildInfo.OutputDirectory = arguments[++i];
break;
case "-colorSpace":
buildInfo.ColorSpace = (ColorSpace)Enum.Parse(typeof(ColorSpace), arguments[++i]);
break;
case "-scriptingBackend":
buildInfo.ScriptingBackend = (ScriptingImplementation)Enum.Parse(typeof(ScriptingImplementation), arguments[++i]);
break;
case "-x86":
case "-x64":
case "-arm":
case "-arm64":
buildInfo.BuildPlatform = arguments[i].Substring(1);
break;
case "-debug":
case "-master":
case "-release":
buildInfo.Configuration = arguments[i].Substring(1).ToLower();
break;
case "-logDirectory":
buildInfo.LogDirectory = arguments[++i];
break;
}
}
}
private static IEnumerable<string> SplitSceneList(string sceneList)
{
return from scene in sceneList.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
select scene.Trim();
}
/// <summary>
/// Restores any nuget packages at the path specified.
/// </summary>
/// <returns>True, if the nuget packages were successfully restored.</returns>
public static async Task<bool> RestoreNugetPackagesAsync(string nugetPath, string storePath)
{
Debug.Assert(File.Exists(nugetPath));
Debug.Assert(Directory.Exists(storePath));
string projectJSONPath = Path.Combine(storePath, "project.json");
string projectJSONLockPath = Path.Combine(storePath, "project.lock.json");
await new Process().StartProcessAsync(nugetPath, $"restore \"{projectJSONPath}\"");
return File.Exists(projectJSONLockPath);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsPaging
{
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// PagingOperations operations.
/// </summary>
public partial interface IPagingOperations
{
/// <summary>
/// A paging operation that finishes on the first call without a
/// nextlink
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetSinglePagesWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesWithHttpMessagesAsync(string clientRequestId = default(string), PagingGetMultiplePagesOptionsInner pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptionsInner), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink in odata format that
/// has 10 pages
/// </summary>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetOdataMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetOdataMultiplePagesWithHttpMessagesAsync(string clientRequestId = default(string), PagingGetOdataMultiplePagesOptionsInner pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptionsInner), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='pagingGetMultiplePagesWithOffsetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesWithOffsetWithHttpMessagesAsync(PagingGetMultiplePagesWithOffsetOptionsInner pagingGetMultiplePagesWithOffsetOptions, string clientRequestId = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that fails on the first call with 500 and then
/// retries and then get a response including a nextLink that has 10
/// pages
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesRetryFirstWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of
/// which the 2nd call fails first with 500. The client should retry
/// and finish all 10 pages eventually.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesRetrySecondWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetSinglePagesFailureWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesFailureWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesFailureUriWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that finishes on the first call without a
/// nextlink
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetSinglePagesNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesNextWithHttpMessagesAsync(string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesOptionsInner pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptionsInner), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink in odata format that
/// has 10 pages
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetOdataMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetOdataMultiplePagesNextWithHttpMessagesAsync(string nextPageLink, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptionsInner pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptionsInner), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesWithOffsetNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesWithOffsetNextWithHttpMessagesAsync(string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesWithOffsetNextOptionsInner pagingGetMultiplePagesWithOffsetNextOptions = default(PagingGetMultiplePagesWithOffsetNextOptionsInner), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that fails on the first call with 500 and then
/// retries and then get a response including a nextLink that has 10
/// pages
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesRetryFirstNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of
/// which the 2nd call fails first with 500. The client should retry
/// and finish all 10 pages eventually.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesRetrySecondNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetSinglePagesFailureNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesFailureNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesFailureUriNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="FontConverter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
*/
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Scope="type", Target="System.Drawing.FontConverter")]
namespace System.Drawing {
using System.Runtime.Serialization.Formatters;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Win32;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.Reflection;
using System.Collections.Generic;
using System.Runtime.Versioning;
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter"]/*' />
/// <devdoc>
/// FontConverter is a class that can be used to convert
/// fonts from one data type to another. Access this
/// class through the TypeDescriptor.
/// </devdoc>
public class FontConverter : TypeConverter {
private FontNameConverter fontNameConverter;
private const string styleHdr = "style=";
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.~FontConverter"]/*' />
/// <devdoc>
/// Destructor
/// </devdoc>
~FontConverter() {
if (fontNameConverter != null) {
((IDisposable)fontNameConverter).Dispose();
}
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.CanConvertFrom"]/*' />
/// <devdoc>
/// Determines if this converter can convert an object in the given source
/// type to the native type of the converter.
/// </devdoc>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
if (sourceType == typeof(string)) {
return true;
}
return base.CanConvertFrom(context, sourceType);
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.CanConvertTo"]/*' />
/// <devdoc>
/// <para>Gets a value indicating whether this converter can
/// convert an object to the given destination type using the context.</para>
/// </devdoc>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
if (destinationType == typeof(InstanceDescriptor)) {
return true;
}
return base.CanConvertTo(context, destinationType);
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.ConvertFrom"]/*' />
/// <devdoc>
/// Converts the given object to the converter's native type.
/// </devdoc>
[SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")]
[SuppressMessage("Microsoft.Security", "CA2102:CatchNonClsCompliantExceptionsInGeneralHandlers")]
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
string strValue = value as string;
if (strValue != null) {
string text = strValue.Trim();
// Expected string format: "name[, size[, units[, style=style1[, style2[...]]]]]"
// Example using 'vi-VN' culture: "Microsoft Sans Serif, 8,25pt, style=Italic, Bold"
if (text.Length == 0) {
return null;
}
else {
if (culture == null) {
culture = CultureInfo.CurrentCulture;
}
char sep = culture.TextInfo.ListSeparator[0]; // For vi-VN: ','
string name = text; // start with the assumption that only the font name was provided.
string styleStr = null;
string sizeStr = null;
float size = 8.25f;
FontStyle style = FontStyle.Regular;
GraphicsUnit units = GraphicsUnit.Point;
// Get the index of the first separator (would indicate the end of the name in the string).
int nameIndex = text.IndexOf(sep);
if( nameIndex > 0 ){ // some parameters provided in addtion to name.
name = text.Substring(0, nameIndex);
if( nameIndex < text.Length - 1 ){ // other parameters provided.
// Get the style index (if any). The size is a bit problematic because it can be formatted differently
// depending on the culture, we'll parse it last.
int styleIndex = text.IndexOf(styleHdr);
if (styleIndex != -1) { // style found.
styleStr = text.Substring(styleIndex, text.Length - styleIndex);
// Expected style format ~ "style=Italic, Bold"
if (!styleStr.StartsWith(styleHdr)){
throw GetFormatException(text, sep);
}
// Get the mid-substring containing the size information.
sizeStr = text.Substring(nameIndex + 1, styleIndex - nameIndex - 1);
}
else { // no style.
sizeStr = text.Substring(nameIndex + 1, text.Length - nameIndex - 1);
}
// Parse size.
string[] unitTokens = ParseSizeTokens(sizeStr, sep);
if (unitTokens[0] != null) {
try{
size = (float)TypeDescriptor.GetConverter(typeof(float)).ConvertFromString(context, culture, unitTokens[0]);
}
catch{ // Exception from converter is too generic.
throw GetFormatException(text, sep);
}
}
if (unitTokens[1] != null) {
// ParseGraphicsUnits throws an ArgumentException if format is invalid.
units = ParseGraphicsUnits(unitTokens[1]);
}
if (styleStr != null) {
int eqIndex = styleStr.IndexOf("=");
styleStr = styleStr.Substring(eqIndex + 1, styleStr.Length - styleHdr.Length);
string[] styleTokens = styleStr.Split(sep);
for (int tokenCount = 0; tokenCount < styleTokens.Length; tokenCount++) {
string styleText = styleTokens[tokenCount];
styleText = styleText.Trim();
// Note: Enum.Parse will throw InvalidEnumArgumentException if the styleText is not valid but could
// throw other exceptions depending on the string passed.
try{
style |= (FontStyle)Enum.Parse(typeof(FontStyle), styleText, true);
}
catch(Exception ex ){
if( ex is InvalidEnumArgumentException ){
throw;
}
throw GetFormatException(text, sep);
}
// Enum.IsDefined doesn't do what we want on flags enums...
FontStyle validBits = FontStyle.Regular | FontStyle.Bold | FontStyle.Italic | FontStyle.Underline | FontStyle.Strikeout;
if ((style | validBits) != validBits){
throw new InvalidEnumArgumentException("style", (int)style, typeof(FontStyle));
}
}
}
}
}
if (fontNameConverter == null) {
fontNameConverter = new FontNameConverter();
}
// should get cached version from TypeDescriptor
name = (string)(fontNameConverter.ConvertFrom(context, culture, name));
// Name is the only parameter not validated, if it is invalid a default Font will be created.
return new Font(name, size, style, units);
}
}
return base.ConvertFrom(context, culture, value);
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.ConvertTo"]/*' />
/// <devdoc>
/// Converts the given object to another type. The most common types to convert
/// are to and from a string object. The default implementation will make a call
/// to ToString on the object if the object is valid and if the destination
/// type is string. If this cannot convert to the desitnation type, this will
/// throw a NotSupportedException.
/// </devdoc>
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
if (destinationType == null) {
throw new ArgumentNullException("destinationType");
}
if (destinationType == typeof(string)) {
// Convert to a string following: "name[, size[, units[, style=<style1[, style2[...]]>]]]"
// Example using 'vi-VN' culture: "Microsoft Sans Serif, 8,25pt, style=Italic"
Font font = value as Font;
if (font == null) {
return SR.GetString(SR.toStringNone);
}
else {
if (culture == null) {
culture = CultureInfo.CurrentCulture;
}
string sep = culture.TextInfo.ListSeparator + " "; // For vi-VN: ','
int argCount = 2;
if (font.Style != FontStyle.Regular){
argCount++;
}
string[] args = new string[argCount];
int nArg = 0;
// should go through type converters here -- we already need
// converts for Name, Size and Units.
// Add name.
args[nArg++] = font.Name;
// Add size and units.
// Note: ConvertToString will raise exception if value cannot be converted.
args[nArg++] = TypeDescriptor.GetConverter(font.Size).ConvertToString(context, culture, font.Size) + GetGraphicsUnitText(font.Unit);
if (font.Style != FontStyle.Regular){
// Add style.
args[nArg++] = styleHdr + font.Style.ToString("G");
}
return string.Join(sep, args);
}
}
if (destinationType == typeof(InstanceDescriptor) && value is Font) {
Font font = (Font)value;
// Custom font, not derived from any stock font
//
int argCount = 2;
if (font.GdiVerticalFont) {
argCount = 6;
}
else if (font.GdiCharSet != SafeNativeMethods.DEFAULT_CHARSET) {
argCount = 5;
}
else if (font.Unit != GraphicsUnit.Point) {
argCount = 4;
}
else if (font.Style != FontStyle.Regular) {
argCount++;
}
object[] args = new object[argCount];
Type[] types = new Type[argCount];
// Always specifying the eight parameter constructor is nastily confusing.
// Use as simple a constructor as possible.
//
args[0] = font.Name; types[0] = typeof(string);
args[1] = font.Size; types[1] = typeof(float);
if (argCount > 2) {
args[2] = font.Style; types[2] = typeof(FontStyle);
}
if (argCount > 3) {
args[3] = font.Unit; types[3] = typeof(GraphicsUnit);
}
if (argCount > 4) {
args[4] = font.GdiCharSet; types[4] = typeof(byte);
}
if (argCount > 5) {
args[5] = font.GdiVerticalFont; types[5] = typeof(bool);
}
MemberInfo ctor = typeof(Font).GetConstructor(types);
if (ctor != null) {
return new InstanceDescriptor(ctor, args);
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.CreateInstance"]/*' />
/// <devdoc>
/// Creates an instance of this type given a set of property values
/// for the object. This is useful for objects that are immutable, but still
/// want to provide changable properties.
/// </devdoc>
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) {
if( propertyValues == null ){
throw new ArgumentNullException("propertyValues");
}
object name = propertyValues["Name"];
object size = propertyValues["Size"];
object units = propertyValues["Unit"];
object bold = propertyValues["Bold"];
object italic = propertyValues["Italic"];
object strikeout = propertyValues["Strikeout"];
object underline = propertyValues["Underline"];
object gdiCharSet = propertyValues["GdiCharSet"];
object gdiVerticalFont = propertyValues["GdiVerticalFont"];
// If any of these properties are null, it may indicate a change in font that
// was not propgated to FontConverter.
//
Debug.Assert(name != null && size != null && units != null &&
bold != null && italic != null && strikeout != null && gdiCharSet != null &&
underline != null, "Missing font properties. Did Font change without FontConverter getting updated?");
// Check for null param values and in that case set param to default value.
if (name == null){
name = "Tahoma";
}
if (size == null){
size = 8.0f;
}
if (units == null){
units = GraphicsUnit.Point;
}
if( bold == null ) {
bold = false;
}
if( italic == null ) {
italic = false;
}
if( strikeout == null ) {
strikeout = false;
}
if( underline == null ) {
underline = false;
}
if (gdiCharSet == null) {
gdiCharSet = (byte)0;
}
if (gdiVerticalFont == null){
gdiVerticalFont = false;
}
// now test param types.
if( !( name is string &&
size is float &&
gdiCharSet is byte &&
units is GraphicsUnit &&
bold is bool &&
italic is bool &&
strikeout is bool &&
underline is bool &&
gdiVerticalFont is bool )) {
throw new ArgumentException( SR.GetString( SR.PropertyValueInvalidEntry ) );
}
FontStyle style = 0;
if( bold != null && ( (bool) bold ) ) {
style |= FontStyle.Bold;
}
if( italic != null && ( (bool) italic ) ) {
style |= FontStyle.Italic;
}
if( strikeout != null && ( (bool) strikeout ) ) {
style |= FontStyle.Strikeout;
}
if( underline != null && ( (bool) underline ) ) {
style |= FontStyle.Underline;
}
return new Font( (string) name,
(float) size,
style,
(GraphicsUnit) units,
(byte) gdiCharSet,
(bool) gdiVerticalFont );
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.GetCreateInstanceSupported"]/*' />
/// <devdoc>
/// Determines if changing a value on this object should require a call to
/// CreateInstance to create a new value.
/// </devdoc>
public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) {
return true;
}
private ArgumentException GetFormatException(string text, char separator){
string fonstStringFormat = string.Format(CultureInfo.CurrentCulture, "name{0} size[units[{0} style=style1[{0} style2{0} ...]]]", separator);
return new ArgumentException(SR.GetString(SR.TextParseFailedFormat, text, fonstStringFormat));
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.GetGraphicsUnitText"]/*' />
/// <devdoc>
/// Returns a text description for the font units
/// </devdoc>
private string GetGraphicsUnitText(GraphicsUnit units) {
string unitStr = "";
for (int i = 0; i < UnitName.names.Length; i++) {
if (UnitName.names[i].unit == units) {
unitStr = UnitName.names[i].name;
break;
}
}
return unitStr;
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.GetProperties"]/*' />
/// <devdoc>
/// Retrieves the set of properties for this type. By default, a type has
/// does not return any properties. An easy implementation of this method
/// can just call TypeDescriptor.GetProperties for the correct data type.
/// </devdoc>
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) {
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(Font), attributes);
return props.Sort(new string[] {"Name", "Size", "Unit", "Weight"});
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.GetPropertiesSupported"]/*' />
/// <devdoc>
/// Determines if this object supports properties. By default, this
/// is false.
/// </devdoc>
public override bool GetPropertiesSupported(ITypeDescriptorContext context) {
return true;
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.ParseSizeTokens"]/*' />
/// <devdoc>
/// Takes a string of the format ####.##CC and parses it into two strings.
/// </devdoc>
private string[] ParseSizeTokens(string text, char separator) {
string size = null;
string units = null;
text = text.Trim();
int length = text.Length;
int splitPoint;
if( length > 0){
// text is expected to have a format like " 8,25pt, ". Leading and trailing spaces (trimmed above),
// last comma, unit and decimal value may not appear. We need to make it ####.##CC
for (splitPoint = 0; splitPoint < length; splitPoint++) {
if (Char.IsLetter(text[splitPoint])) {
break;
}
}
char[] trimChars = new char[] { separator, ' ' };
if (splitPoint > 0) {
size = text.Substring(0, splitPoint);
size = size.Trim(trimChars);
}
if (splitPoint < length) {
units = text.Substring(splitPoint);
units = units.TrimEnd(trimChars);
}
}
return new string[] {size, units};
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.ParseGraphicsUnits"]/*' />
/// <devdoc>
/// Parses the font units from the given text.
/// </devdoc>
private GraphicsUnit ParseGraphicsUnits(string units) {
UnitName unitName = null;
for (int i = 0; i < UnitName.names.Length; i++) {
if (String.Equals(UnitName.names[i].name, units, StringComparison.OrdinalIgnoreCase)) {
unitName = UnitName.names[i];
break;
}
}
if (unitName == null) {
throw new ArgumentException(SR.GetString(SR.InvalidArgument, "units", units));
}
return unitName.unit;
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.UnitName"]/*' />
/// <devdoc>
/// Simple private class to associate a font size unit with a text name.
/// </devdoc>
internal class UnitName {
internal string name;
internal GraphicsUnit unit;
internal static readonly UnitName[] names = new UnitName[] {
new UnitName("world", GraphicsUnit.World), // made up
new UnitName("display", GraphicsUnit.Display), // made up
new UnitName("px", GraphicsUnit.Pixel),
new UnitName("pt", GraphicsUnit.Point),
new UnitName("in", GraphicsUnit.Inch),
new UnitName("doc", GraphicsUnit.Document), // made up
new UnitName("mm", GraphicsUnit.Millimeter),
};
internal UnitName(string name, GraphicsUnit unit) {
this.name = name;
this.unit = unit;
}
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.FontNameConverter"]/*' />
/// <devdoc>
/// FontNameConverter is a type converter that is used to convert
/// a font name to and from various other representations.
/// </devdoc>
/// <internalonly/>
public sealed class FontNameConverter : TypeConverter, IDisposable {
private StandardValuesCollection values;
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.FontNameConverter.FontNameConverter"]/*' />
/// <devdoc>
/// Creates a new font name converter.
/// </devdoc>
public FontNameConverter() {
// Sink an event to let us know when the installed
// set of fonts changes.
//
SystemEvents.InstalledFontsChanged += new EventHandler(this.OnInstalledFontsChanged);
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.FontNameConverter.CanConvertFrom"]/*' />
/// <devdoc>
/// Determines if this converter can convert an object in the given source
/// type to the native type of the converter.
/// </devdoc>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
if (sourceType == typeof(string)) {
return true;
}
return base.CanConvertFrom(context, sourceType);
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.FontNameConverter.ConvertFrom"]/*' />
/// <devdoc>
/// Converts the given object to the converter's native type.
/// </devdoc>
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
if (value is string) {
return MatchFontName((string)value, context);
}
return base.ConvertFrom(context, culture, value);
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.IDisposable.Dispose"]/*' />
/// <devdoc>
/// Disposes this converter.
/// </devdoc>
void IDisposable.Dispose() {
SystemEvents.InstalledFontsChanged -= new EventHandler(this.OnInstalledFontsChanged);
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.FontNameConverter.GetStandardValues"]/*' />
/// <devdoc>
/// Retrieves a collection containing a set of standard values
/// for the data type this validator is designed for. This
/// will return null if the data type does not support a
/// standard set of values.
/// </devdoc>
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {
if (values == null) {
FontFamily[] fonts = FontFamily.Families;
Hashtable hash = new Hashtable();
for (int i = 0; i < fonts.Length; i++) {
string name = fonts[i].Name;
hash[name.ToLower(CultureInfo.InvariantCulture)] = name;
}
object[] array = new object[hash.Values.Count];
hash.Values.CopyTo(array, 0);
Array.Sort(array, Comparer.Default);
values = new StandardValuesCollection(array);
}
return values;
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.FontNameConverter.GetStandardValuesExclusive"]/*' />
/// <devdoc>
/// Determines if the list of standard values returned from
/// GetStandardValues is an exclusive list. If the list
/// is exclusive, then no other values are valid, such as
/// in an enum data type. If the list is not exclusive,
/// then there are other valid values besides the list of
/// standard values GetStandardValues provides.
/// </devdoc>
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) {
return false;
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.FontNameConverter.GetStandardValuesSupported"]/*' />
/// <devdoc>
/// Determines if this object supports a standard set of values
/// that can be picked from a list.
/// </devdoc>
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) {
return true;
}
private string MatchFontName(string name, ITypeDescriptorContext context) {
Debug.Assert(name != null, "Expected an actual font name to match in FontNameConverter::MatchFontName.");
// Try a partial match
//
string bestMatch = null;
name = name.ToLower(CultureInfo.InvariantCulture);
IEnumerator e = GetStandardValues(context).GetEnumerator();
while (e.MoveNext()) {
string fontName = e.Current.ToString().ToLower(CultureInfo.InvariantCulture);
if (fontName.Equals(name)) {
// For an exact match, return immediately
//
return e.Current.ToString();
}
else if (fontName.StartsWith(name)) {
if (bestMatch == null || fontName.Length <= bestMatch.Length) {
bestMatch = e.Current.ToString();
}
}
}
if (bestMatch == null) {
// no match... fall back on whatever was provided
bestMatch = name;
}
return bestMatch;
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.FontNameConverter.OnInstalledFontsChanged"]/*' />
/// <devdoc>
/// Called by system events when someone adds or removes a font. Here
/// we invalidate our font name collection.
/// </devdoc>
private void OnInstalledFontsChanged(object sender, EventArgs e) {
values = null;
}
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.FontUnitConverter"]/*' />
/// <devdoc>
/// FontUnitConverter strips out the members of GraphicsUnit that are invalid for fonts.
/// </devdoc>
/// <internalonly/>
public class FontUnitConverter : EnumConverter {
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.FontUnitConverter.FontUnitConverter"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public FontUnitConverter() : base(typeof(GraphicsUnit)) {
}
/// <include file='doc\FontConverter.uex' path='docs/doc[@for="FontConverter.FontUnitConverter.GetStandardValues"]/*' />
/// <internalonly/>
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {
if (Values == null) {
base.GetStandardValues(context); // sets "values"
ArrayList filteredValues = new ArrayList(Values);
filteredValues.Remove(GraphicsUnit.Display);
Values = new StandardValuesCollection(filteredValues);
}
return Values;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Drawing.Drawing2D;
using System.Globalization;
using System.IO;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
namespace System.Drawing.Imaging
{
// sdkinc\GDIplusImageAttributes.h
// There are 5 possible sets of color adjustments:
// ColorAdjustDefault,
// ColorAdjustBitmap,
// ColorAdjustBrush,
// ColorAdjustPen,
// ColorAdjustText,
// Bitmaps, Brushes, Pens, and Text will all use any color adjustments
// that have been set into the default ImageAttributes until their own
// color adjustments have been set. So as soon as any "Set" method is
// called for Bitmaps, Brushes, Pens, or Text, then they start from
// scratch with only the color adjustments that have been set for them.
// Calling Reset removes any individual color adjustments for a type
// and makes it revert back to using all the default color adjustments
// (if any). The SetToIdentity method is a way to force a type to
// have no color adjustments at all, regardless of what previous adjustments
// have been set for the defaults or for that type.
/// <summary>
/// Contains information about how image colors are manipulated during rendering.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public sealed class ImageAttributes : ICloneable, IDisposable
{
#if FINALIZATION_WATCH
private string allocationSite = Graphics.GetAllocationStack();
#endif
internal IntPtr nativeImageAttributes;
internal void SetNativeImageAttributes(IntPtr handle)
{
if (handle == IntPtr.Zero)
throw new ArgumentNullException(nameof(handle));
nativeImageAttributes = handle;
}
/// <summary>
/// Initializes a new instance of the <see cref='ImageAttributes'/> class.
/// </summary>
public ImageAttributes()
{
IntPtr newImageAttributes = IntPtr.Zero;
int status = Gdip.GdipCreateImageAttributes(out newImageAttributes);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
SetNativeImageAttributes(newImageAttributes);
}
internal ImageAttributes(IntPtr newNativeImageAttributes)
{
SetNativeImageAttributes(newNativeImageAttributes);
}
/// <summary>
/// Cleans up Windows resources for this <see cref='ImageAttributes'/>.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
#if FINALIZATION_WATCH
if (!disposing && nativeImageAttributes != IntPtr.Zero)
Debug.WriteLine("**********************\nDisposed through finalization:\n" + allocationSite);
#endif
if (nativeImageAttributes != IntPtr.Zero)
{
try
{
#if DEBUG
int status = !Gdip.Initialized ? Gdip.Ok :
#endif
Gdip.GdipDisposeImageAttributes(new HandleRef(this, nativeImageAttributes));
#if DEBUG
Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture));
#endif
}
catch (Exception ex)
{
if (ClientUtils.IsSecurityOrCriticalException(ex))
{
throw;
}
Debug.Fail("Exception thrown during Dispose: " + ex.ToString());
}
finally
{
nativeImageAttributes = IntPtr.Zero;
}
}
}
/// <summary>
/// Cleans up Windows resources for this <see cref='ImageAttributes'/>.
/// </summary>
~ImageAttributes()
{
Dispose(false);
}
/// <summary>
/// Creates an exact copy of this <see cref='ImageAttributes'/>.
/// </summary>
public object Clone()
{
IntPtr clone = IntPtr.Zero;
int status = Gdip.GdipCloneImageAttributes(
new HandleRef(this, nativeImageAttributes),
out clone);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
return new ImageAttributes(clone);
}
/// <summary>
/// Sets the 5 X 5 color adjust matrix to the specified <see cref='Matrix'/>.
/// </summary>
public void SetColorMatrix(ColorMatrix newColorMatrix)
{
SetColorMatrix(newColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Default);
}
/// <summary>
/// Sets the 5 X 5 color adjust matrix to the specified 'Matrix' with the specified 'ColorMatrixFlags'.
/// </summary>
public void SetColorMatrix(ColorMatrix newColorMatrix, ColorMatrixFlag flags)
{
SetColorMatrix(newColorMatrix, flags, ColorAdjustType.Default);
}
/// <summary>
/// Sets the 5 X 5 color adjust matrix to the specified 'Matrix' with the specified 'ColorMatrixFlags'.
/// </summary>
public void SetColorMatrix(ColorMatrix newColorMatrix, ColorMatrixFlag mode, ColorAdjustType type)
{
int status = Gdip.GdipSetImageAttributesColorMatrix(
new HandleRef(this, nativeImageAttributes),
type,
true,
newColorMatrix,
null,
mode);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
}
/// <summary>
/// Clears the color adjust matrix to all zeroes.
/// </summary>
public void ClearColorMatrix()
{
ClearColorMatrix(ColorAdjustType.Default);
}
/// <summary>
/// Clears the color adjust matrix.
/// </summary>
public void ClearColorMatrix(ColorAdjustType type)
{
int status = Gdip.GdipSetImageAttributesColorMatrix(
new HandleRef(this, nativeImageAttributes),
type,
false,
null,
null,
ColorMatrixFlag.Default);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
}
/// <summary>
/// Sets a color adjust matrix for image colors and a separate gray scale adjust matrix for gray scale values.
/// </summary>
public void SetColorMatrices(ColorMatrix newColorMatrix, ColorMatrix grayMatrix)
{
SetColorMatrices(newColorMatrix, grayMatrix, ColorMatrixFlag.Default, ColorAdjustType.Default);
}
public void SetColorMatrices(ColorMatrix newColorMatrix, ColorMatrix grayMatrix, ColorMatrixFlag flags)
{
SetColorMatrices(newColorMatrix, grayMatrix, flags, ColorAdjustType.Default);
}
public void SetColorMatrices(ColorMatrix newColorMatrix, ColorMatrix grayMatrix, ColorMatrixFlag mode,
ColorAdjustType type)
{
int status = Gdip.GdipSetImageAttributesColorMatrix(
new HandleRef(this, nativeImageAttributes),
type,
true,
newColorMatrix,
grayMatrix,
mode);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
}
public void SetThreshold(float threshold)
{
SetThreshold(threshold, ColorAdjustType.Default);
}
public void SetThreshold(float threshold, ColorAdjustType type)
{
int status = Gdip.GdipSetImageAttributesThreshold(
new HandleRef(this, nativeImageAttributes),
type,
true,
threshold);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
}
public void ClearThreshold()
{
ClearThreshold(ColorAdjustType.Default);
}
public void ClearThreshold(ColorAdjustType type)
{
int status = Gdip.GdipSetImageAttributesThreshold(
new HandleRef(this, nativeImageAttributes),
type,
false,
0.0f);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
}
public void SetGamma(float gamma)
{
SetGamma(gamma, ColorAdjustType.Default);
}
public void SetGamma(float gamma, ColorAdjustType type)
{
int status = Gdip.GdipSetImageAttributesGamma(
new HandleRef(this, nativeImageAttributes),
type,
true,
gamma);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
}
public void ClearGamma()
{
ClearGamma(ColorAdjustType.Default);
}
public void ClearGamma(ColorAdjustType type)
{
int status = Gdip.GdipSetImageAttributesGamma(
new HandleRef(this, nativeImageAttributes),
type,
false,
0.0f);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
}
public void SetNoOp()
{
SetNoOp(ColorAdjustType.Default);
}
public void SetNoOp(ColorAdjustType type)
{
int status = Gdip.GdipSetImageAttributesNoOp(
new HandleRef(this, nativeImageAttributes),
type,
true);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
}
public void ClearNoOp()
{
ClearNoOp(ColorAdjustType.Default);
}
public void ClearNoOp(ColorAdjustType type)
{
int status = Gdip.GdipSetImageAttributesNoOp(
new HandleRef(this, nativeImageAttributes),
type,
false);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
}
public void SetColorKey(Color colorLow, Color colorHigh)
{
SetColorKey(colorLow, colorHigh, ColorAdjustType.Default);
}
public void SetColorKey(Color colorLow, Color colorHigh, ColorAdjustType type)
{
int lowInt = colorLow.ToArgb();
int highInt = colorHigh.ToArgb();
int status = Gdip.GdipSetImageAttributesColorKeys(
new HandleRef(this, nativeImageAttributes),
type,
true,
lowInt,
highInt);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
}
public void ClearColorKey()
{
ClearColorKey(ColorAdjustType.Default);
}
public void ClearColorKey(ColorAdjustType type)
{
int zero = 0;
int status = Gdip.GdipSetImageAttributesColorKeys(
new HandleRef(this, nativeImageAttributes),
type,
false,
zero,
zero);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
}
public void SetOutputChannel(ColorChannelFlag flags)
{
SetOutputChannel(flags, ColorAdjustType.Default);
}
public void SetOutputChannel(ColorChannelFlag flags, ColorAdjustType type)
{
int status = Gdip.GdipSetImageAttributesOutputChannel(
new HandleRef(this, nativeImageAttributes),
type,
true,
flags);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
}
public void ClearOutputChannel()
{
ClearOutputChannel(ColorAdjustType.Default);
}
public void ClearOutputChannel(ColorAdjustType type)
{
int status = Gdip.GdipSetImageAttributesOutputChannel(
new HandleRef(this, nativeImageAttributes),
type,
false,
ColorChannelFlag.ColorChannelLast);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
}
public void SetOutputChannelColorProfile(string colorProfileFilename)
{
SetOutputChannelColorProfile(colorProfileFilename, ColorAdjustType.Default);
}
public void SetOutputChannelColorProfile(string colorProfileFilename,
ColorAdjustType type)
{
// Called in order to emulate exception behavior from netfx related to invalid file paths.
Path.GetFullPath(colorProfileFilename);
int status = Gdip.GdipSetImageAttributesOutputChannelColorProfile(
new HandleRef(this, nativeImageAttributes),
type,
true,
colorProfileFilename);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
}
public void ClearOutputChannelColorProfile()
{
ClearOutputChannel(ColorAdjustType.Default);
}
public void ClearOutputChannelColorProfile(ColorAdjustType type)
{
int status = Gdip.GdipSetImageAttributesOutputChannel(
new HandleRef(this, nativeImageAttributes),
type,
false,
ColorChannelFlag.ColorChannelLast);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
}
public void SetRemapTable(ColorMap[] map)
{
SetRemapTable(map, ColorAdjustType.Default);
}
public void SetRemapTable(ColorMap[] map, ColorAdjustType type)
{
int index = 0;
int mapSize = map.Length;
int size = 4; // Marshal.SizeOf(index.GetType());
IntPtr memory = Marshal.AllocHGlobal(checked(mapSize * size * 2));
try
{
for (index = 0; index < mapSize; index++)
{
Marshal.StructureToPtr(map[index].OldColor.ToArgb(), (IntPtr)((long)memory + index * size * 2), false);
Marshal.StructureToPtr(map[index].NewColor.ToArgb(), (IntPtr)((long)memory + index * size * 2 + size), false);
}
int status = Gdip.GdipSetImageAttributesRemapTable(
new HandleRef(this, nativeImageAttributes),
type,
true,
mapSize,
new HandleRef(null, memory));
if (status != Gdip.Ok)
{
throw Gdip.StatusException(status);
}
}
finally
{
Marshal.FreeHGlobal(memory);
}
}
public void ClearRemapTable()
{
ClearRemapTable(ColorAdjustType.Default);
}
public void ClearRemapTable(ColorAdjustType type)
{
int status = Gdip.GdipSetImageAttributesRemapTable(
new HandleRef(this, nativeImageAttributes),
type,
false,
0,
NativeMethods.NullHandleRef);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
}
public void SetBrushRemapTable(ColorMap[] map)
{
SetRemapTable(map, ColorAdjustType.Brush);
}
public void ClearBrushRemapTable()
{
ClearRemapTable(ColorAdjustType.Brush);
}
public void SetWrapMode(WrapMode mode)
{
SetWrapMode(mode, new Color(), false);
}
public void SetWrapMode(WrapMode mode, Color color)
{
SetWrapMode(mode, color, false);
}
public void SetWrapMode(WrapMode mode, Color color, bool clamp)
{
int status = Gdip.GdipSetImageAttributesWrapMode(
new HandleRef(this, nativeImageAttributes),
unchecked((int)mode),
color.ToArgb(),
clamp);
if (status != Gdip.Ok)
throw Gdip.StatusException(status);
}
public void GetAdjustedPalette(ColorPalette palette, ColorAdjustType type)
{
// does inplace adjustment
IntPtr memory = palette.ConvertToMemory();
try
{
int status = Gdip.GdipGetImageAttributesAdjustedPalette(
new HandleRef(this, nativeImageAttributes), new HandleRef(null, memory), type);
if (status != Gdip.Ok)
{
throw Gdip.StatusException(status);
}
palette.ConvertFromMemory(memory);
}
finally
{
if (memory != IntPtr.Zero)
{
Marshal.FreeHGlobal(memory);
}
}
}
}
}
| |
/* VRPhysicsDisableCollisions
* MiddleVR
* (c) MiddleVR
*/
using UnityEngine;
using System;
using System.Collections;
using MiddleVR_Unity3D;
[AddComponentMenu("MiddleVR/Physics/Disable Collisions")]
[RequireComponent(typeof(VRPhysicsBody))]
public class VRPhysicsDisableCollisions : MonoBehaviour {
#region Member Variables
[SerializeField]
private GameObject m_ConnectedBody = null;
private bool m_InitialActionProcessed = false;
#endregion
#region Member Properties
public GameObject ConnectedBody
{
get
{
return m_ConnectedBody;
}
set
{
m_ConnectedBody = value;
}
}
#endregion
#region MonoBehaviour Member Functions
protected void Start()
{
if (MiddleVR.VRClusterMgr.IsCluster() && !MiddleVR.VRClusterMgr.IsServer())
{
enabled = false;
return;
}
if (MiddleVR.VRPhysicsMgr == null)
{
MiddleVRTools.Log(0, "[X] PhysicsDisableCollisions: No PhysicsManager found.");
enabled = false;
return;
}
vrPhysicsEngine physicsEngine = MiddleVR.VRPhysicsMgr.GetPhysicsEngine();
if (physicsEngine == null)
{
MiddleVRTools.Log(0, "[X] PhysicsDisableCollisions: No PhysicsEngine found.");
enabled = false;
return;
}
}
protected void OnEnable()
{
if (m_InitialActionProcessed)
{
vrPhysicsBody physicsBody = GetPhysicsBodyInSimulation();
if (physicsBody != null)
{
EnableCollisions(physicsBody, false);
}
}
}
protected void OnDisable()
{
vrPhysicsBody physicsBody = GetPhysicsBodyInSimulation();
if (physicsBody != null)
{
EnableCollisions(physicsBody, true);
}
}
protected void Update()
{
if (!m_InitialActionProcessed)
{
vrPhysicsBody physicsBody = GetPhysicsBodyInSimulation();
if (physicsBody != null)
{
m_InitialActionProcessed = true;
EnableCollisions(physicsBody, false);
}
}
}
#endregion
#region VRPhysicsDisableCollisions Functions
protected vrPhysicsBody GetPhysicsBodyInSimulation()
{
if (MiddleVR.VRPhysicsMgr == null)
{
return null;
}
vrPhysicsEngine physicsEngine = MiddleVR.VRPhysicsMgr.GetPhysicsEngine();
if (physicsEngine == null)
{
return null;
}
vrPhysicsBody physicsBody = physicsEngine.GetBody(GetComponent<VRPhysicsBody>().PhysicsBodyName);
if (physicsBody != null && physicsBody.IsInSimulation())
{
return physicsBody;
}
else
{
return null;
}
}
protected void EnableCollisions(vrPhysicsBody physicsBody0, bool iEnabled)
{
bool operationDone = false;
vrPhysicsBody physicsBody1 = null;
if (m_ConnectedBody != null)
{
if (MiddleVR.VRPhysicsMgr == null)
{
return;
}
vrPhysicsEngine physicsEngine = MiddleVR.VRPhysicsMgr.GetPhysicsEngine();
if (physicsEngine == null)
{
return;
}
physicsBody1 = physicsEngine.GetBody(m_ConnectedBody.GetComponent<VRPhysicsBody>().PhysicsBodyName);
if (physicsBody1 == null)
{
MiddleVRTools.Log(0, "[X] PhysicsDisableCollisions: No PhysicsBody found in the connected body.");
return;
}
operationDone = physicsBody0.EnableCollisionsWith(physicsBody1, iEnabled);
}
else
{
operationDone = physicsBody0.EnableAllCollisions(iEnabled);
}
if (operationDone)
{
string againstTxt = (physicsBody1 != null ?
" against object '" + physicsBody1.GetName() + "'" :
" against the world scene"
);
if (iEnabled)
{
MiddleVRTools.Log(2, "[ ] PhysicsDisableCollisions: Enabled collisions for '" +
physicsBody0.GetName() + "'" + againstTxt + ".");
}
else
{
MiddleVRTools.Log(2, "[ ] PhysicsDisableCollisions: Disabled collisions for '" +
physicsBody0.GetName() + "'" + againstTxt + ".");
}
}
else
{
if (iEnabled)
{
MiddleVRTools.Log(0, "[X] PhysicsDisableCollisions: Failed to enable collisions for '" +
physicsBody0.GetName() + "'.");
}
else
{
MiddleVRTools.Log(0, "[X] PhysicsDisableCollisions: Failed to disable collisions for '" +
physicsBody0.GetName() + "'.");
}
}
}
#endregion
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace VersionOne.Localization
{
public interface ILocalizerResolver
{
string Resolve(string tag);
string Signature { get; }
TemplateStack GetTemplateStack();
}
public class TemplateStack
{
public IDictionary<string, string> Templates { get; set; }
public TemplateStack FallbackStack { get; set; }
}
public class Localizer : ILocalizerResolver
{
private const string SeparatorString = "\'";
private const char SeparatorChar = '\'';
private const char LeftBraceChar = '{';
private const char RightBraceChar = '}';
private const string LeftBracePlaceholderString = "\x2";
private const char LeftBracePlaceholderChar = '\x2';
private const string RightBracePlaceholderString = "\x3";
private const char RightBracePlaceholderChar = '\x3';
private static readonly Regex rxEmbeddedTag = new Regex(@"\{([^{}]*)\}", RegexOptions.Compiled);
private static readonly Regex rxDoubleLeftBrace = new Regex(@"\{\{", RegexOptions.Compiled);
private static readonly Regex rxDoubleRightBrace = new Regex(@"\}\}", RegexOptions.RightToLeft | RegexOptions.Compiled);
private static string StripLiteralBraces (string input)
{
return rxDoubleRightBrace.Replace(rxDoubleLeftBrace.Replace(input, LeftBracePlaceholderString), RightBracePlaceholderString);
}
private static string ReplaceLiteralBraces (string input)
{
StringBuilder s = new StringBuilder(input);
s.Replace(LeftBracePlaceholderChar, LeftBraceChar).Replace(RightBracePlaceholderChar, RightBraceChar);
return s.ToString();
}
private readonly IDictionary _templates = new Hashtable {{"", ""}};
private readonly IDictionary _resolved = Hashtable.Synchronized(new Hashtable());
private readonly Localizer _fallback;
private string _signature;
public Localizer (Localizer fallback)
{
_fallback = fallback;
}
public TemplateStack GetTemplateStack()
{
Dictionary<string, string> templates = new Dictionary<string, string>();
foreach (DictionaryEntry entry in _templates)
{
templates[(string) entry.Key] = (string) entry.Value;
}
return new TemplateStack {Templates = templates, FallbackStack = _fallback != null ? _fallback.GetTemplateStack() : null};
}
static readonly byte[] _valueSeparator = new byte[] { 0x01 };
static readonly byte[] _recordSeparator = new byte[] { 0x02 };
public string Signature
{
get
{
return _signature ?? (_signature = Convert.ToBase64String(ComputeSignature()));
}
}
private byte[] ComputeSignature()
{
using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
{
foreach (DictionaryEntry entry in _templates)
{
var keyBytes = Encoding.UTF8.GetBytes((string) entry.Key);
var valueBytes = Encoding.UTF8.GetBytes((string) entry.Value);
sha1.TransformBlock(keyBytes, 0, keyBytes.Length, keyBytes, 0);
sha1.TransformBlock(_valueSeparator, 0, _valueSeparator.Length, _valueSeparator, 0);
sha1.TransformBlock(valueBytes, 0, valueBytes.Length, valueBytes, 0);
sha1.TransformBlock(_recordSeparator, 0, _recordSeparator.Length, _recordSeparator, 0);
}
var fallbackSignatureBytes = _fallback != null ? _fallback.ComputeSignature() : new byte[0];
sha1.TransformFinalBlock(fallbackSignatureBytes, 0, fallbackSignatureBytes.Length);
return sha1.Hash;
}
}
public void Add (string tag, string translation)
{
_templates[tag] = translation;
_resolved.Clear();
_signature = null;
}
public void Remove (string tag)
{
_templates.Remove(tag);
_resolved.Clear();
_signature = null;
}
public string Resolve (string tag)
{
return Resolve(tag, null);
}
private string Resolve(string tag, Stack<string> resolvestack)
{
string translation = LookupCached(tag);
if (translation != null) return translation;
if (resolvestack == null)
resolvestack = new Stack<string>();
resolvestack.Push(tag);
string resolution = ResolveTemplate(tag, resolvestack);
resolvestack.Pop();
return resolution;
}
private string LookupCached (string tag)
{
return (string) _resolved[tag];
}
private string ResolveTemplate (string tag, Stack<string> resolvestack)
{
string template = FindTemplate(tag);
if (template == null) return Cache(tag, tag.Trim());
string translation = ExpandTemplate(template, tag, resolvestack).Trim();
return Cache(tag, translation);
}
private string Cache (string tag, string translation)
{
return (string) (_resolved[tag] = translation);
}
private string FindTemplate (string templateTag)
{
string tag = templateTag;
string template;
while ( (template = LookupTemplate(tag)) == null)
{
int dotindex = tag.LastIndexOf(SeparatorChar);
if (dotindex < 0) break;
tag = tag.Substring(0, dotindex);
}
if (template == null && _fallback != null)
template = _fallback.FindTemplate(templateTag);
return template;
}
private string LookupTemplate (string tag)
{
return (string) _templates[tag];
}
private string ExpandTemplate (string template, string tag, Stack<string> resolvestack)
{
string strippedtemplate = StripLiteralBraces(template);
string[] tagparts = tag.Split(SeparatorChar);
return ReplaceLiteralBraces(ExpandTemplate(strippedtemplate, tagparts, resolvestack));
}
private string ExpandTemplate (string template, string[] tagparts, Stack<string> resolvestack)
{
StringBuilder expanded = new StringBuilder(template);
for (;;)
{
MatchCollection matches = rxEmbeddedTag.Matches(expanded.ToString());
if (matches.Count == 0) break;
for (int i = matches.Count-1; i >= 0; --i)
{
Match m = matches[i];
string embeddedtag = m.Groups[1].Value;
string replacement = ResolveEmbedded(embeddedtag, tagparts, resolvestack);
expanded.Remove(m.Index, m.Length);
expanded.Insert(m.Index, replacement);
}
}
return expanded.ToString();
}
private string ResolveEmbedded (string embeddedtag, string[] tagparts, Stack<string> resolvestack)
{
string tag = Unembed(embeddedtag, tagparts);
return resolvestack.Contains(tag) ? tag : Resolve(tag, resolvestack);
}
private static string Unembed (string embeddedtag, string[] tagparts)
{
string[] embeds = embeddedtag.Split(SeparatorChar);
for (int i = 0; i < embeds.Length; ++i)
{
int index;
if (int.TryParse(embeds[i], out index))
{
embeds[i] = tagparts.Length > index ? tagparts[index] : string.Empty;
}
}
return string.Join(SeparatorString, embeds);
}
}
}
| |
//
// FieldValueReference.cs
//
// Authors: Lluis Sanchez Gual <lluis@novell.com>
// Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
// Copyright (c) 2012 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.
using System;
using System.Reflection;
using Mono.Debugging.Evaluation;
using Mono.Debugger.Soft;
using Mono.Debugging.Client;
using System.Collections.Generic;
using System.Linq;
namespace Mono.Debugging.Soft
{
public class FieldValueReference: SoftValueReference
{
FieldInfoMirror field;
object obj;
TypeMirror declaringType;
ObjectValueFlags flags;
string vname;
FieldReferenceBatch batch;
public FieldValueReference (EvaluationContext ctx, FieldInfoMirror field, object obj, TypeMirror declaringType, FieldReferenceBatch batch = null)
: this (ctx, field, obj, declaringType, null, ObjectValueFlags.Field, batch)
{
}
public FieldValueReference (EvaluationContext ctx, FieldInfoMirror field, object obj, TypeMirror declaringType, string vname, ObjectValueFlags vflags, FieldReferenceBatch batch = null): base (ctx)
{
this.field = field;
this.obj = obj;
this.declaringType = declaringType;
this.vname = vname;
this.batch = batch;
if (field.IsStatic)
this.obj = null;
var objectMirror = obj as ObjectMirror;
if (objectMirror != null)
EnsureContextHasDomain (objectMirror.Domain);
flags = GetFlags (field);
// if `vflags` already has an origin specified, we need to unset the `Field` flag which is always returned by GetFlags().
if ((vflags & ObjectValueFlags.OriginMask) != 0)
flags &= ~ObjectValueFlags.Field;
flags |= vflags;
if (obj is PrimitiveValue)
flags |= ObjectValueFlags.ReadOnly;
}
internal static ObjectValueFlags GetFlags (FieldInfoMirror field)
{
var flags = ObjectValueFlags.Field;
if (field.IsStatic)
flags |= ObjectValueFlags.Global;
if (field.IsPublic)
flags |= ObjectValueFlags.Public;
else if (field.IsPrivate)
flags |= ObjectValueFlags.Private;
else if (field.IsFamily)
flags |= ObjectValueFlags.Protected;
else if (field.IsFamilyAndAssembly)
flags |= ObjectValueFlags.Internal;
else if (field.IsFamilyOrAssembly)
flags |= ObjectValueFlags.InternalProtected;
return flags;
}
public override ObjectValueFlags Flags {
get {
return flags;
}
}
public override string Name {
get {
return vname ?? field.Name;
}
}
public override object Type {
get {
return field.FieldType;
}
}
public override object DeclaringType {
get {
return field.DeclaringType;
}
}
public override object Value {
get {
if (obj == null) {
// If the type hasn't already been loaded, invoke the .cctor() for types w/ the BeforeFieldInit attribute.
Context.Adapter.ForceLoadType (Context, declaringType);
return declaringType.GetValue (field, ((SoftEvaluationContext)Context).Thread);
} else if (obj is ObjectMirror) {
if (batch != null)
return batch.GetValue (field);
return ((ObjectMirror)obj).GetValue (field);
} else if (obj is StructMirror) {
StructMirror sm = (StructMirror)obj;
int idx = 0;
foreach (FieldInfoMirror f in sm.Type.GetFields ()) {
if (f.IsStatic) continue;
if (f == field)
break;
idx++;
}
return sm.Fields [idx];
} else if (obj is StringMirror) {
SoftEvaluationContext cx = (SoftEvaluationContext) Context;
StringMirror val = (StringMirror) obj;
FieldInfo rfield = typeof(string).GetField (field.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
return cx.Session.VirtualMachine.CreateValue (rfield.GetValue (val.Value));
} else {
SoftEvaluationContext cx = (SoftEvaluationContext) Context;
PrimitiveValue val = (PrimitiveValue) obj;
if (val.Value == null)
return null;
FieldInfo rfield = val.Value.GetType ().GetField (field.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
return cx.Session.VirtualMachine.CreateValue (rfield.GetValue (val.Value));
}
}
set {
if (obj == null)
declaringType.SetValue (field, (Value)value);
else if (obj is ObjectMirror) {
if (batch != null)
batch.Invalidate ();
((ObjectMirror)obj).SetValue (field, (Value)value);
}
else if (obj is StructMirror) {
StructMirror sm = (StructMirror)obj;
int idx = 0;
foreach (FieldInfoMirror f in sm.Type.GetFields ()) {
if (f.IsStatic) continue;
if (f == field)
break;
idx++;
}
if (idx != -1) {
sm.Fields [idx] = (Value)value;
// Structs are handled by-value in the debugger, so the source of the object has to be updated
if (ParentSource != null && obj != null)
ParentSource.Value = obj;
}
}
else
throw new NotSupportedException ();
}
}
internal string [] GetTupleElementNames ()
{
return GetTupleElementNames (field.GetCustomAttributes (true));
}
internal static string [] GetTupleElementNames (CustomAttributeDataMirror [] attrs)
{
var attr = attrs.FirstOrDefault (at => at.Constructor.DeclaringType.Name == "TupleElementNamesAttribute");
if (attr == null)
return null;
var attributeValue = attr.ConstructorArguments.Single ().Value;
var array = attributeValue as ArrayMirror;
if (array == null)
return null;
var values = array.GetValues (0, array.Length);
if (!values.Any ())
return null;
var result = new string [values.Count];
for (int i = 0; i < result.Length; i++) {
if (values [i] is StringMirror s)//other than string is null
result [i] = s.Value;
}
return result;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Roslyn.Test.Utilities;
using Xunit;
using Microsoft.CodeAnalysis.CSharp;
using System.Linq;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class InvocationExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
public InvocationExpressionSignatureHelpProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture)
{
}
internal override ISignatureHelpProvider CreateSignatureHelpProvider()
{
return new InvocationExpressionSignatureHelpProvider();
}
#region "Regular tests"
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationAfterCloseParen()
{
var markup = @"
class C
{
int Foo(int x)
{
[|Foo(Foo(x)$$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int C.Foo(int x)", currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationInsideLambda()
{
var markup = @"
using System;
class C
{
void Foo(Action<int> f)
{
[|Foo(i => Console.WriteLine(i)$$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(Action<int> f)", currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationInsideLambda2()
{
var markup = @"
using System;
class C
{
void Foo(Action<int> f)
{
[|Foo(i => Con$$sole.WriteLine(i)|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(Action<int> f)", currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutParameters()
{
var markup = @"
class C
{
void Foo()
{
[|Foo($$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutParametersMethodXmlComments()
{
var markup = @"
class C
{
/// <summary>
/// Summary for foo
/// </summary>
void Foo()
{
[|Foo($$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", "Summary for foo", null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersOn1()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo($$a, b|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersXmlCommentsOn1()
{
var markup = @"
class C
{
/// <summary>
/// Summary for Foo
/// </summary>
/// <param name=" + "\"a\">Param a</param>" + @"
/// <param name=" + "\"b\">Param b</param>" + @"
void Foo(int a, int b)
{
[|Foo($$a, b|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", "Summary for Foo", "Param a", currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersOn2()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo(a, $$b|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1));
Test(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersXmlComentsOn2()
{
var markup = @"
class C
{
/// <summary>
/// Summary for Foo
/// </summary>
/// <param name=" + "\"a\">Param a</param>" + @"
/// <param name=" + "\"b\">Param b</param>" + @"
void Foo(int a, int b)
{
[|Foo(a, $$b|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", "Summary for Foo", "Param b", currentParameterIndex: 1));
Test(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutClosingParen()
{
var markup = @"
class C
{
void Foo()
{
[|Foo($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutClosingParenWithParameters()
{
var markup =
@"class C
{
void Foo(int a, int b)
{
[|Foo($$a, b
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutClosingParenWithParametersOn2()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo(a, $$b
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1));
Test(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnLambda()
{
var markup = @"
using System;
class C
{
void Foo()
{
Action<int> f = (i) => Console.WriteLine(i);
[|f($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Action<int>(int obj)", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnMemberAccessExpression()
{
var markup = @"
class C
{
static void Bar(int a)
{
}
void Foo()
{
[|C.Bar($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Bar(int a)", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestExtensionMethod1()
{
var markup = @"
using System;
class C
{
void Method()
{
string s = ""Text"";
[|s.ExtensionMethod($$
|]}
}
public static class MyExtension
{
public static int ExtensionMethod(this string s, int x)
{
return s.Length;
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.Extension}) int string.ExtensionMethod(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
// TODO: Once we do the work to allow extension methods in nested types, we should change this.
Test(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestOptionalParameters()
{
var markup = @"
class Class1
{
void Test()
{
Foo($$
}
void Foo(int a = 42)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Class1.Foo([int a = 42])", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestNoInvocationOnEventNotInCurrentClass()
{
var markup = @"
using System;
class C
{
void Foo()
{
D d;
[|d.evt($$
|]}
}
public class D
{
public event Action evt;
}";
Test(markup);
}
[WorkItem(539712)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnNamedType()
{
var markup = @"
class Program
{
void Main()
{
C.Foo($$
}
}
class C
{
public static double Foo(double x)
{
return x;
}
public double Foo(double x, double y)
{
return x + y;
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("double C.Foo(double x)", string.Empty, string.Empty, currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(539712)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnInstance()
{
var markup = @"
class Program
{
void Main()
{
new C().Foo($$
}
}
class C
{
public static double Foo(double x)
{
return x;
}
public double Foo(double x, double y)
{
return x + y;
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("double C.Foo(double x, double y)", string.Empty, string.Empty, currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(545118)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestStatic1()
{
var markup = @"
class C
{
static void Foo()
{
Bar($$
}
static void Bar()
{
}
void Bar(int i)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void C.Bar()", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(545118)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestStatic2()
{
var markup = @"
class C
{
void Foo()
{
Bar($$
}
static void Bar()
{
}
void Bar(int i)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void C.Bar()", currentParameterIndex: 0),
new SignatureHelpTestItem("void C.Bar(int i)", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(543117)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnAnonymousType()
{
var markup = @"
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
var foo = new { Name = string.Empty, Age = 30 };
Foo(foo).Add($$);
}
static List<T> Foo<T>(T t)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
$@"void List<'a>.Add('a item)
{FeaturesResources.AnonymousTypes}
'a {FeaturesResources.Is} new {{ string Name, int Age }}",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: $@"
{FeaturesResources.AnonymousTypes}
'a {FeaturesResources.Is} new {{ string Name, int Age }}")
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnBaseExpression_ProtectedAccessibility()
{
var markup = @"
using System;
public class Base
{
protected virtual void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
base.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnBaseExpression_AbstractBase()
{
var markup = @"
using System;
public abstract class Base
{
protected abstract void Foo(int x);
}
public class Derived : Base
{
void Test()
{
base.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnThisExpression_ProtectedAccessibility()
{
var markup = @"
using System;
public class Base
{
protected virtual void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
this.Foo($$);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnThisExpression_ProtectedAccessibility_Overridden()
{
var markup = @"
using System;
public class Base
{
protected virtual void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
this.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Derived.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnThisExpression_ProtectedAccessibility_AbstractBase()
{
var markup = @"
using System;
public abstract class Base
{
protected abstract void Foo(int x);
}
public class Derived : Base
{
void Test()
{
this.Foo($$);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnThisExpression_ProtectedAccessibility_AbstractBase_Overridden()
{
var markup = @"
using System;
public abstract class Base
{
protected abstract void Foo(int x);
}
public class Derived : Base
{
void Test()
{
this.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Derived.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnBaseExpression_ProtectedInternalAccessibility()
{
var markup = @"
using System;
public class Base
{
protected internal void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
base.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnBaseMember_ProtectedAccessibility_ThroughType()
{
var markup = @"
using System;
public class Base
{
protected virtual void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
new Base().Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
Test(markup, null);
}
[WorkItem(968188)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnBaseExpression_PrivateAccessibility()
{
var markup = @"
using System;
public class Base
{
private void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
base.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
Test(markup, null);
}
#endregion
#region "Current Parameter Name"
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestCurrentParameterName()
{
var markup = @"
class C
{
void Foo(int someParameter, bool something)
{
Foo(something: false, someParameter: $$)
}
}";
VerifyCurrentParameterName(markup, "someParameter");
}
#endregion
#region "Trigger tests"
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnTriggerParens()
{
var markup = @"
class C
{
void Foo()
{
[|Foo($$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnTriggerComma()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo(23,$$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1));
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestNoInvocationOnSpace()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo(23, $$|]);
}
}";
Test(markup, usePreviousCharAsTrigger: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestTriggerCharacterInComment01()
{
var markup = @"
class C
{
void Foo(int a)
{
Foo(/*,$$*/);
}
}";
Test(markup, Enumerable.Empty<SignatureHelpTestItem>(), usePreviousCharAsTrigger: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestTriggerCharacterInComment02()
{
var markup = @"
class C
{
void Foo(int a)
{
Foo(//,$$
);
}
}";
Test(markup, Enumerable.Empty<SignatureHelpTestItem>(), usePreviousCharAsTrigger: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestTriggerCharacterInString01()
{
var markup = @"
class C
{
void Foo(int a)
{
Foo("",$$"");
}
}";
Test(markup, Enumerable.Empty<SignatureHelpTestItem>(), usePreviousCharAsTrigger: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestTriggerCharacters()
{
char[] expectedCharacters = { ',', '(' };
char[] unexpectedCharacters = { ' ', '[', '<' };
VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters);
}
#endregion
#region "EditorBrowsable tests"
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Method_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
Foo.Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Method_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
Foo.Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Method_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Foo().Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public void Bar()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Method_Overloads_OneBrowsableAlways_OneBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new Foo().Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar(int x)
{
}
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Method_Overloads_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new Foo().Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar(int x)
{
}
}";
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void OverriddenSymbolsFilteredFromSigHelp()
{
var markup = @"
class Program
{
void M()
{
new D().Foo($$
}
}";
var referencedCode = @"
public class B
{
public virtual void Foo(int original)
{
}
}
public class D : B
{
public override void Foo(int derived)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void D.Foo(int derived)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverClass()
{
var markup = @"
class Program
{
void M()
{
new C().Foo($$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public class C
{
public void Foo()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverBaseClass()
{
var markup = @"
class Program
{
void M()
{
new D().Foo($$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public class B
{
public void Foo()
{
}
}
public class D : B
{
public void Foo(int x)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void B.Foo()", string.Empty, null, currentParameterIndex: 0),
new SignatureHelpTestItem("void D.Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0),
};
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_BrowsableStateNeverMethodsInBaseClass()
{
var markup = @"
class Program : B
{
void M()
{
Foo($$
}
}";
var referencedCode = @"
public class B
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void B.Foo()", string.Empty, null, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new C<int>().Foo($$
}
}";
var referencedCode = @"
public class C<T>
{
public void Foo(T t) { }
public void Foo(int i) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed1()
{
var markup = @"
class Program
{
void M()
{
new C<int>().Foo($$
}
}";
var referencedCode = @"
public class C<T>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(T t) { }
public void Foo(int i) { }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed2()
{
var markup = @"
class Program
{
void M()
{
new C<int>().Foo($$
}
}";
var referencedCode = @"
public class C<T>
{
public void Foo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(int i) { }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new C<int>().Foo($$
}
}";
var referencedCode = @"
public class C<T>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(int i) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new C<int, int>().Foo($$
}
}";
var referencedCode = @"
public class C<T, U>
{
public void Foo(T t) { }
public void Foo(U u) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericType2CausingMethodSignatureEquality_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
new C<int, int>().Foo($$
}
}";
var referencedCode = @"
public class C<T, U>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(T t) { }
public void Foo(U u) { }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new C<int, int>().Foo($$
}
}";
var referencedCode = @"
public class C<T, U>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(U u) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
#endregion
#region "Awaitable tests"
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void AwaitableMethod()
{
var markup = @"
using System.Threading.Tasks;
class C
{
async Task Foo()
{
[|Foo($$|]);
}
}";
var description = $@"
{WorkspacesResources.Usage}
await Foo();";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.Awaitable}) Task C.Foo()", methodDocumentation: description, currentParameterIndex: 0));
TestSignatureHelpWithMscorlib45(markup, expectedOrderedItems, "C#");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void AwaitableMethod2()
{
var markup = @"
using System.Threading.Tasks;
class C
{
async Task<Task<int>> Foo()
{
[|Foo($$|]);
}
}";
var description = $@"
{WorkspacesResources.Usage}
Task<int> x = await Foo();";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.Awaitable}) Task<Task<int>> C.Foo()", methodDocumentation: description, currentParameterIndex: 0));
TestSignatureHelpWithMscorlib45(markup, expectedOrderedItems, "C#");
}
#endregion
[WorkItem(13849, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestSpecificity1()
{
var markup = @"
class Class1
{
static void Main()
{
var obj = new C<int>();
[|obj.M($$|])
}
}
class C<T>
{
/// <param name=""t"">Generic t</param>
public void M(T t) { }
/// <param name=""t"">Real t</param>
public void M(int t) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void C<int>.M(int t)", string.Empty, "Real t", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(530017)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void LongSignature()
{
var markup = @"
class C
{
void Foo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j, string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u, string v, string w, string x, string y, string z)
{
[|Foo($$|])
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
signature: "void C.Foo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j, string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u, string v, string w, string x, string y, string z)",
prettyPrintedSignature: @"void C.Foo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j,
string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u,
string v, string w, string x, string y, string z)",
currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void GenericExtensionMethod()
{
var markup = @"
interface IFoo
{
void Bar<T>();
}
static class FooExtensions
{
public static void Bar<T1, T2>(this IFoo foo) { }
}
class Program
{
static void Main()
{
IFoo f = null;
[|f.Bar($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void IFoo.Bar<T>()", currentParameterIndex: 0),
new SignatureHelpTestItem($"({CSharpFeaturesResources.Extension}) void IFoo.Bar<T1, T2>()", currentParameterIndex: 0),
};
// Extension methods are supported in Interactive/Script (yet).
Test(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithCrefXmlComments()
{
var markup = @"
class C
{
/// <summary>
/// Summary for foo. See method <see cref=""Bar"" />
/// </summary>
void Foo()
{
[|Foo($$|]);
}
void Bar() { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", "Summary for foo. See method C.Bar()", null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
void bar()
{
}
#endif
void foo()
{
bar($$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"void C.bar()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj2", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
void bar()
{
}
#endif
#if BAR
void foo()
{
bar($$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"void C.bar()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj3", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false);
}
[WorkItem(768697)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InstanceAndStaticMethodsShown1()
{
var markup = @"
class C
{
Foo Foo;
void M()
{
Foo.Bar($$
}
}
class Foo
{
public void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void Foo.Bar(int x)", currentParameterIndex: 0),
new SignatureHelpTestItem("void Foo.Bar(string s)", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(768697)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InstanceAndStaticMethodsShown2()
{
var markup = @"
class C
{
Foo Foo;
void M()
{
Foo.Bar($$"");
}
}
class Foo
{
public void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void Foo.Bar(int x)", currentParameterIndex: 0),
new SignatureHelpTestItem("void Foo.Bar(string s)", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(768697)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InstanceAndStaticMethodsShown3()
{
var markup = @"
class C
{
Foo Foo;
void M()
{
Foo.Bar($$
}
}
class Foo
{
public static void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void Foo.Bar(int x)", currentParameterIndex: 0),
new SignatureHelpTestItem("void Foo.Bar(string s)", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(768697)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InstanceAndStaticMethodsShown4()
{
var markup = @"
class C
{
void M()
{
Foo x;
x.Bar($$
}
}
class Foo
{
public static void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
Test(markup, expectedOrderedItems);
}
[WorkItem(768697)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InstanceAndStaticMethodsShown5()
{
var markup = @"
class C
{
void M()
{
Foo x;
x.Bar($$
}
}
class x { }
class Foo
{
public static void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
Test(markup, expectedOrderedItems);
}
[WorkItem(1067933)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InvokedWithNoToken()
{
var markup = @"
// foo($$";
Test(markup);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public void MethodOverloadDifferencesIgnored()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if ONE
void Do(int x){}
#endif
#if TWO
void Do(string x){}
#endif
void Shared()
{
this.Do($$
}
}]]></Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"void C.Do(int x)", currentParameterIndex: 0);
VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false);
}
[WorkItem(699, "https://github.com/dotnet/roslyn/issues/699")]
[WorkItem(1068424)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestGenericParameters1()
{
var markup = @"
class C
{
void M()
{
Foo(""""$$);
}
void Foo<T>(T a) { }
void Foo<T, U>(T a, U b) { }
}
";
var expectedOrderedItems = new List<SignatureHelpTestItem>()
{
new SignatureHelpTestItem("void C.Foo<string>(string a)", string.Empty, string.Empty, currentParameterIndex: 0),
new SignatureHelpTestItem("void C.Foo<T, U>(T a, U b)", string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(699, "https://github.com/dotnet/roslyn/issues/699")]
[WorkItem(1068424)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestGenericParameters2()
{
var markup = @"
class C
{
void M()
{
Foo("""", $$);
}
void Foo<T>(T a) { }
void Foo<T, U>(T a, U b) { }
}
";
var expectedOrderedItems = new List<SignatureHelpTestItem>()
{
new SignatureHelpTestItem("void C.Foo<T>(T a)", string.Empty),
new SignatureHelpTestItem("void C.Foo<T, U>(T a, U b)", string.Empty, string.Empty, currentParameterIndex: 1)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(4144, "https://github.com/dotnet/roslyn/issues/4144")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestSigHelpIsVisibleOnInaccessibleItem()
{
var markup = @"
using System.Collections.Generic;
class A
{
List<int> args;
}
class B : A
{
void M()
{
args.Add($$
}
}
";
Test(markup, new[] { new SignatureHelpTestItem("void List<int>.Add(int item)") });
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web.UI;
using System.Web.UI.WebControls;
using Vevo.Domain.DataInterfaces;
using Vevo.Shared.DataAccess;
using Vevo.Shared.Utilities;
using Vevo.WebAppLib;
using Vevo.Base.Domain;
public partial class Components_SearchFilter : Vevo.WebUI.International.BaseLanguageUserControl
{
private NameValueCollection FieldTypes
{
get
{
if (ViewState["FieldTypes"] == null)
ViewState["FieldTypes"] = new NameValueCollection();
return (NameValueCollection) ViewState["FieldTypes"];
}
}
private void ClearAllInput()
{
uxValueText.Text = String.Empty;
}
private string GenerateShowHideScript( bool textPanel, bool boolPanel, bool valueRangePanel, bool dateRangePanel )
{
string script;
if (textPanel)
script = String.Format( "document.getElementById('{0}').style.display = '';", uxTextPanel.ClientID );
else
script = String.Format( "document.getElementById('{0}').style.display = 'none';", uxTextPanel.ClientID );
if (boolPanel)
script += String.Format( "document.getElementById('{0}').style.display = '';", uxBooleanPanel.ClientID );
else
script += String.Format( "document.getElementById('{0}').style.display = 'none';", uxBooleanPanel.ClientID );
if (valueRangePanel)
script += String.Format( "document.getElementById('{0}').style.display = '';", uxValueRangePanel.ClientID );
else
script += String.Format( "document.getElementById('{0}').style.display = 'none';", uxValueRangePanel.ClientID );
if (dateRangePanel)
script += String.Format( "document.getElementById('{0}').style.display = '';", uxDateRangePanel.ClientID );
else
script += String.Format( "document.getElementById('{0}').style.display = 'none';", uxDateRangePanel.ClientID );
return script;
}
private void ShowTextFilterInput()
{
uxTextPanel.Style.Add( HtmlTextWriterStyle.Display, "" );
uxBooleanPanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxValueRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxDateRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
}
private void ShowBooleanFilterInput()
{
uxTextPanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxBooleanPanel.Style.Add( HtmlTextWriterStyle.Display, "" );
uxValueRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxDateRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
}
private void ShowValueRangeFilterInput()
{
uxTextPanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxBooleanPanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxValueRangePanel.Style.Add( HtmlTextWriterStyle.Display, "" );
uxDateRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
}
private void ShowDateRangeFilterInput()
{
uxTextPanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxBooleanPanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxValueRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxDateRangePanel.Style.Add( HtmlTextWriterStyle.Display, "" );
}
private void HideAllInput()
{
uxTextPanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxBooleanPanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxValueRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxDateRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
}
private string GetFilterType( Type dataType )
{
string type;
if (dataType == Type.GetType( "System.Byte" ) ||
dataType == Type.GetType( "System.SByte" ) ||
dataType == Type.GetType( "System.Char" ) ||
dataType == Type.GetType( "System.String" ))
{
type = SearchFilterType.Text.ToString();
}
else if (dataType == Type.GetType( "System.Boolean" ))
{
type = SearchFilterType.Boolean.ToString();
}
else if (
dataType == Type.GetType( "System.Decimal" ) ||
dataType == Type.GetType( "System.Double" ) ||
dataType == Type.GetType( "System.Int16" ) ||
dataType == Type.GetType( "System.Int32" ) ||
dataType == Type.GetType( "System.Int64" ) ||
dataType == Type.GetType( "System.UInt16" ) ||
dataType == Type.GetType( "System.UInt32" ) ||
dataType == Type.GetType( "System.UInt64" ))
{
type = SearchFilterType.ValueRange.ToString();
}
else if (dataType == Type.GetType( "System.DateTime" ))
{
type = SearchFilterType.Date.ToString();
}
else
{
type = String.Empty;
}
return type;
}
private SearchFilterType ParseSearchType( string searchFilterType )
{
SearchFilterType type;
if (String.Compare( searchFilterType, SearchFilterType.Text.ToString(), true ) == 0)
type = SearchFilterType.Text;
else if (String.Compare( searchFilterType, SearchFilterType.Boolean.ToString(), true ) == 0)
type = SearchFilterType.Boolean;
else if (String.Compare( searchFilterType, SearchFilterType.ValueRange.ToString(), true ) == 0)
type = SearchFilterType.ValueRange;
else if (String.Compare( searchFilterType, SearchFilterType.Date.ToString(), true ) == 0)
type = SearchFilterType.Date;
else
type = SearchFilterType.None;
return type;
}
private void RemoveSearchFilter()
{
SearchType = SearchFilterType.None;
FieldName = String.Empty;
FieldValue = String.Empty;
Value1 = String.Empty;
Value2 = String.Empty;
uxMessageLabel.Text = String.Empty;
}
private void RegisterDropDownPostback()
{
string script = "if(this.value == ''){ javascript:__doPostBack('" + uxFilterDrop.UniqueID + "',''); }";
foreach (ListItem item in uxFilterDrop.Items)
{
switch (ParseSearchType( FieldTypes[item.Value] ))
{
case SearchFilterType.Text:
script += "if(this.value == '" + item.Value + "'){" + GenerateShowHideScript( true, false, false, false ) + "}";
break;
case SearchFilterType.Boolean:
script += "if(this.value == '" + item.Value + "'){" + GenerateShowHideScript( false, true, false, false ) + "}";
break;
case SearchFilterType.ValueRange:
script += "if(this.value == '" + item.Value + "'){" + GenerateShowHideScript( false, false, true, false ) + "}";
break;
case SearchFilterType.Date:
script += "if(this.value == '" + item.Value + "'){" + GenerateShowHideScript( false, false, false, true ) + "}";
break;
}
}
script += "document.getElementById( '" + uxValueText.ClientID + "' ).value = '';";
script += "document.getElementById( '" + uxBooleanDrop.ClientID + "' ).value = 'Yes';";
script += "document.getElementById( '" + uxLowerText.ClientID + "' ).value = '';";
script += "document.getElementById( '" + uxUpperText.ClientID + "' ).value = '';";
script += "document.getElementById( '" + uxStartDateText.ClientID + "' ).value = '';";
script += "document.getElementById( '" + uxEndDateText.ClientID + "' ).value = '';";
uxFilterDrop.Attributes.Add( "onchange", script );
}
private void TieTextBoxesWithButtons()
{
WebUtilities.TieButton( this.Page, uxValueText, uxTextSearchImageButton );
WebUtilities.TieButton( this.Page, uxLowerText, uxValueRangeSearchImageButton );
WebUtilities.TieButton( this.Page, uxUpperText, uxValueRangeSearchImageButton );
WebUtilities.TieButton( this.Page, uxStartDateText, uxDateRangeImageButton );
WebUtilities.TieButton( this.Page, uxEndDateText, uxDateRangeImageButton );
}
private void DisplayTextSearchMessage( string fieldName, string value )
{
if (!String.IsNullOrEmpty( value ))
{
uxMessageLabel.Text =
"<br/>" +
String.Format( GetLanguageText( "TextMessage" ),
value, fieldName ) +
"<br/><br/>";
}
}
private void DisplayBooleanSearchMessage( string fieldName, string value )
{
bool boolValue;
if (Boolean.TryParse( value, out boolValue ))
{
uxMessageLabel.Text =
"<br/>" +
String.Format( GetLanguageText( "BooleanMessage" ),
ConvertUtilities.ToYesNo( boolValue ), fieldName ) +
"<br/><br/>";
}
}
private void DisplayValueRangeMessage( string fieldName, string value1, string value2 )
{
if (!String.IsNullOrEmpty( value1 ) && !String.IsNullOrEmpty( value2 ))
{
uxMessageLabel.Text =
"<br/>" +
String.Format( GetLanguageText( "ValueRangeBothMessage" ),
value1, value2, fieldName ) +
"<br/><br/>";
}
else if (!String.IsNullOrEmpty( value1 ))
{
uxMessageLabel.Text =
"<br/>" +
String.Format( GetLanguageText( "ValueRangeLowerOnlyMessage" ),
value1, fieldName ) +
"<br/><br/>";
}
else if (!String.IsNullOrEmpty( value2 ))
{
uxMessageLabel.Text =
"<br/>" +
String.Format( GetLanguageText( "ValueRangeUpperOnlyMessage" ),
value2, fieldName ) +
"<br/><br/>";
}
}
protected void Page_Load( object sender, EventArgs e )
{
TieTextBoxesWithButtons();
}
protected void uxFilterDrop_SelectedIndexChanged( object sender, EventArgs e )
{
switch (ParseSearchType( FieldTypes[uxFilterDrop.SelectedValue] ))
{
case SearchFilterType.Text:
ShowTextFilterInput();
break;
case SearchFilterType.Boolean:
ShowBooleanFilterInput();
break;
case SearchFilterType.ValueRange:
ShowValueRangeFilterInput();
break;
case SearchFilterType.Date:
ShowDateRangeFilterInput();
break;
default:
HideAllInput();
RemoveSearchFilter();
OnBubbleEvent( e );
break;
}
}
protected void uxTextSearchImageButton_Click( object sender, EventArgs e )
{
SearchType = SearchFilterType.Text;
FieldName = uxFilterDrop.SelectedValue;
FieldValue = uxFilterDrop.SelectedValue;
Value1 = uxValueText.Text;
Value2 = String.Empty;
DisplayTextSearchMessage( uxFilterDrop.SelectedItem.Text, Value1 );
// Propagate event to parent
OnBubbleEvent( e );
}
protected void uxBooleanSearchButton_Click( object sender, EventArgs e )
{
SearchType = SearchFilterType.Boolean;
FieldName = uxFilterDrop.SelectedValue;
FieldValue = uxFilterDrop.SelectedValue;
Value1 = uxBooleanDrop.SelectedValue;
Value2 = String.Empty;
DisplayBooleanSearchMessage( uxFilterDrop.SelectedItem.Text, Value1 );
// Propagate event to parent
OnBubbleEvent( e );
}
protected void uxValueRangeSearchButton_Click( object sender, EventArgs e )
{
PopulateValueRangeFilter(
SearchFilterType.ValueRange,
uxFilterDrop.SelectedValue,
uxFilterDrop.SelectedValue,
uxLowerText.Text,
uxUpperText.Text,
e );
}
protected void uxDateRangeButton_Click( object sender, EventArgs e )
{
PopulateValueRangeFilter(
SearchFilterType.Date,
uxFilterDrop.SelectedValue,
uxFilterDrop.SelectedValue,
uxStartDateText.Text,
uxEndDateText.Text,
e );
}
private void PopulateValueRangeFilter( SearchFilterType typeField,
string field, string value, string val1, string val2, EventArgs e )
{
SearchType = typeField;
FieldName = field;
FieldValue = value;
Value1 = val1;
Value2 = val2;
DisplayValueRangeMessage( uxFilterDrop.SelectedItem.Text, Value1, Value2 );
// Propagate event to parent
OnBubbleEvent( e );
}
public void SetUpSchema(
IList<TableSchemaItem> columnList,
params string[] excludingColumns )
{
uxFilterDrop.Items.Clear();
FieldTypes.Clear();
uxFilterDrop.Items.Add( new ListItem( GetLanguageText( "FilterShowAll" ), String.Empty ) );
FieldTypes[Resources.SearchFilterMessages.FilterShowAll] = SearchFilterType.None.ToString();
/*[$FilterBy][$LowerBound][$No][$SearchButton][$TextToSearch][$UpperBound][$Yes][$YesNoValue]*/
for (int i = 0; i < columnList.Count; i++)
{
if (!StringUtilities.IsStringInArray( excludingColumns, columnList[i].ColumnName, true ))
{
string type = GetFilterType( columnList[i].DataType );
if (!String.IsNullOrEmpty( type ))
{
uxFilterDrop.Items.Add( new ListItem( "[$" + columnList[i].ColumnName + "]", columnList[i].ColumnName ) );
FieldTypes[columnList[i].ColumnName] = type;
}
}
}
RegisterDropDownPostback();
}
public SearchFilterType SearchType
{
get
{
if (ViewState["SearchType"] == null)
return SearchFilterType.None;
else
return (SearchFilterType) ViewState["SearchType"];
}
set
{
ViewState["SearchType"] = value;
}
}
public string FieldName
{
get
{
if (ViewState["FieldName"] == null)
return String.Empty;
else
return (string) ViewState["FieldName"];
}
set
{
ViewState["FieldName"] = value;
}
}
public string FieldValue
{
get
{
if (ViewState["FieldValue"] == null)
return String.Empty;
else
return (string) ViewState["FieldValue"];
}
set
{
ViewState["FieldValue"] = value;
}
}
public string Value1
{
get
{
if (ViewState["Value1"] == null)
return String.Empty;
else
return (string) ViewState["Value1"];
}
set
{
ViewState["Value1"] = value;
}
}
public string Value2
{
get
{
if (ViewState["Value2"] == null)
return String.Empty;
else
return (string) ViewState["Value2"];
}
set
{
ViewState["Value2"] = value;
}
}
public void ClearFilter()
{
RemoveSearchFilter();
uxFilterDrop.SelectedValue = "";
HideAllInput();
}
}
| |
//
// Copyright (c) 2004-2020 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 !__IOS__ && !WINDOWS_PHONE && !__ANDROID__ && !NETSTANDARD || WCF_SUPPORTED
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
#if WCF_SUPPORTED
using System.ServiceModel;
using System.ServiceModel.Channels;
#endif
using System.Threading;
#if SILVERLIGHT
using System.Windows;
using System.Windows.Threading;
#endif
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
using NLog.LogReceiverService;
/// <summary>
/// Sends log messages to a NLog Receiver Service (using WCF or Web Services).
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/LogReceiverService-target">Documentation on NLog Wiki</seealso>
[Target("LogReceiverService")]
public class LogReceiverWebServiceTarget : Target
{
private readonly LogEventInfoBuffer buffer = new LogEventInfoBuffer(10000, false, 10000);
private bool inCall;
/// <summary>
/// Initializes a new instance of the <see cref="LogReceiverWebServiceTarget"/> class.
/// </summary>
public LogReceiverWebServiceTarget()
{
Parameters = new List<MethodCallParameter>();
}
/// <summary>
/// Initializes a new instance of the <see cref="LogReceiverWebServiceTarget"/> class.
/// </summary>
/// <param name="name">Name of the target.</param>
public LogReceiverWebServiceTarget(string name) : this()
{
Name = name;
}
/// <summary>
/// Gets or sets the endpoint address.
/// </summary>
/// <value>The endpoint address.</value>
/// <docgen category='Connection Options' order='10' />
[RequiredParameter]
public virtual string EndpointAddress { get; set; }
#if WCF_SUPPORTED
/// <summary>
/// Gets or sets the name of the endpoint configuration in WCF configuration file.
/// </summary>
/// <value>The name of the endpoint configuration.</value>
/// <docgen category='Connection Options' order='10' />
public string EndpointConfigurationName { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use binary message encoding.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool UseBinaryEncoding { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use a WCF service contract that is one way (fire and forget) or two way (request-reply)
/// </summary>
/// <docgen category='Connection Options' order='10' />
public bool UseOneWayContract { get; set; }
#endif
/// <summary>
/// Gets or sets the client ID.
/// </summary>
/// <value>The client ID.</value>
/// <docgen category='Payload Options' order='10' />
public Layout ClientId { get; set; }
/// <summary>
/// Gets the list of parameters.
/// </summary>
/// <value>The parameters.</value>
/// <docgen category='Payload Options' order='10' />
[ArrayParameter(typeof(MethodCallParameter), "parameter")]
public IList<MethodCallParameter> Parameters { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether to include per-event properties in the payload sent to the server.
/// </summary>
/// <docgen category='Payload Options' order='10' />
public bool IncludeEventProperties { get; set; }
/// <summary>
/// Called when log events are being sent (test hook).
/// </summary>
/// <param name="events">The events.</param>
/// <param name="asyncContinuations">The async continuations.</param>
/// <returns>True if events should be sent, false to stop processing them.</returns>
protected internal virtual bool OnSend(NLogEvents events, IEnumerable<AsyncLogEventInfo> asyncContinuations)
{
return true;
}
/// <summary>
/// Writes logging event to the log target. Must be overridden in inheriting
/// classes.
/// </summary>
/// <param name="logEvent">Logging event to be written out.</param>
protected override void Write(AsyncLogEventInfo logEvent)
{
Write((IList<AsyncLogEventInfo>)new[] { logEvent });
}
/// <summary>
/// NOTE! Obsolete, instead override Write(IList{AsyncLogEventInfo} logEvents)
///
/// Writes an array of logging events to the log target. By default it iterates on all
/// events and passes them to "Write" method. Inheriting classes can use this method to
/// optimize batch writes.
/// </summary>
/// <param name="logEvents">Logging events to be written out.</param>
[Obsolete("Instead override Write(IList<AsyncLogEventInfo> logEvents. Marked obsolete on NLog 4.5")]
protected override void Write(AsyncLogEventInfo[] logEvents)
{
Write((IList<AsyncLogEventInfo>)logEvents);
}
/// <summary>
/// Writes an array of logging events to the log target. By default it iterates on all
/// events and passes them to "Append" method. Inheriting classes can use this method to
/// optimize batch writes.
/// </summary>
/// <param name="logEvents">Logging events to be written out.</param>
protected override void Write(IList<AsyncLogEventInfo> logEvents)
{
// if web service call is being processed, buffer new events and return
// lock is being held here
if (inCall)
{
for (int i = 0; i < logEvents.Count; ++i)
{
PrecalculateVolatileLayouts(logEvents[i].LogEvent);
buffer.Append(logEvents[i]);
}
return;
}
// OptimizeBufferReuse = true, will reuse the input-array on method-exit (so we make clone here)
AsyncLogEventInfo[] logEventsArray = new AsyncLogEventInfo[logEvents.Count];
logEvents.CopyTo(logEventsArray, 0);
var networkLogEvents = TranslateLogEvents(logEventsArray);
Send(networkLogEvents, logEventsArray, null);
}
/// <summary>
/// Flush any pending log messages asynchronously (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
SendBufferedEvents(asyncContinuation);
}
/// <summary>
/// Add value to the <see cref="NLogEvents.Strings"/>, returns ordinal in <see cref="NLogEvents.Strings"/>
/// </summary>
/// <param name="context"></param>
/// <param name="stringTable">lookup so only unique items will be added to <see cref="NLogEvents.Strings"/></param>
/// <param name="value">value to add</param>
/// <returns></returns>
private static int AddValueAndGetStringOrdinal(NLogEvents context, Dictionary<string, int> stringTable, string value)
{
if (value == null || !stringTable.TryGetValue(value, out var stringIndex))
{
stringIndex = context.Strings.Count;
if (value != null)
{
//don't add null to the string table, that would crash
stringTable.Add(value, stringIndex);
}
context.Strings.Add(value);
}
return stringIndex;
}
private NLogEvents TranslateLogEvents(IList<AsyncLogEventInfo> logEvents)
{
if (logEvents.Count == 0 && !LogManager.ThrowExceptions)
{
InternalLogger.Error("LogReceiverServiceTarget(Name={0}): LogEvents array is empty, sending empty event...", Name);
return new NLogEvents();
}
string clientID = string.Empty;
if (ClientId != null)
{
clientID = ClientId.Render(logEvents[0].LogEvent);
}
var networkLogEvents = new NLogEvents
{
ClientName = clientID,
LayoutNames = new StringCollection(),
Strings = new StringCollection(),
BaseTimeUtc = logEvents[0].LogEvent.TimeStamp.ToUniversalTime().Ticks
};
var stringTable = new Dictionary<string, int>();
for (int i = 0; i < Parameters.Count; ++i)
{
networkLogEvents.LayoutNames.Add(Parameters[i].Name);
}
if (IncludeEventProperties)
{
AddEventProperties(logEvents, networkLogEvents);
}
networkLogEvents.Events = new NLogEvent[logEvents.Count];
for (int i = 0; i < logEvents.Count; ++i)
{
AsyncLogEventInfo ev = logEvents[i];
networkLogEvents.Events[i] = TranslateEvent(ev.LogEvent, networkLogEvents, stringTable);
}
return networkLogEvents;
}
private static void AddEventProperties(IList<AsyncLogEventInfo> logEvents, NLogEvents networkLogEvents)
{
for (int i = 0; i < logEvents.Count; ++i)
{
var ev = logEvents[i].LogEvent;
if (ev.HasProperties)
{
// add all event-level property names in 'LayoutNames' collection.
foreach (var prop in ev.Properties)
{
if (prop.Key is string propName && !networkLogEvents.LayoutNames.Contains(propName))
{
networkLogEvents.LayoutNames.Add(propName);
}
}
}
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Client is disposed asynchronously.")]
private void Send(NLogEvents events, IList<AsyncLogEventInfo> asyncContinuations, AsyncContinuation flushContinuations)
{
if (!OnSend(events, asyncContinuations))
{
if (flushContinuations != null)
flushContinuations(null);
return;
}
#if WCF_SUPPORTED
var client = CreateLogReceiver();
client.ProcessLogMessagesCompleted += (sender, e) =>
{
if (e.Error != null)
InternalLogger.Error(e.Error, "LogReceiverServiceTarget(Name={0}): Error while sending", Name);
// report error to the callers
for (int i = 0; i < asyncContinuations.Count; ++i)
{
asyncContinuations[i].Continuation(e.Error);
}
if (flushContinuations != null)
flushContinuations(e.Error);
// send any buffered events
SendBufferedEvents(null);
};
inCall = true;
#if SILVERLIGHT
if (!Deployment.Current.Dispatcher.CheckAccess())
{
Deployment.Current.Dispatcher.BeginInvoke(() => client.ProcessLogMessagesAsync(events));
}
else
{
client.ProcessLogMessagesAsync(events);
}
#else
client.ProcessLogMessagesAsync(events);
#endif
#else
var client = new SoapLogReceiverClient(this.EndpointAddress);
this.inCall = true;
client.BeginProcessLogMessages(
events,
result =>
{
Exception exception = null;
try
{
client.EndProcessLogMessages(result);
}
catch (Exception ex)
{
InternalLogger.Error(ex, "LogReceiverServiceTarget(Name={0}): Error while sending", Name);
if (ex.MustBeRethrownImmediately())
{
throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
}
exception = ex;
}
// report error to the callers
for (int i = 0; i < asyncContinuations.Count; ++i)
{
asyncContinuations[i].Continuation(exception);
}
if (flushContinuations != null)
flushContinuations(exception);
// send any buffered events
this.SendBufferedEvents(null);
},
null);
#endif
}
#if WCF_SUPPORTED
/// <summary>
/// Creating a new instance of WcfLogReceiverClient
///
/// Inheritors can override this method and provide their own
/// service configuration - binding and endpoint address
/// </summary>
/// <remarks>This method marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks>
[Obsolete("Use CreateLogReceiver instead. Marked obsolete before v4.3.11 and it may be removed in a future release.")]
protected virtual WcfLogReceiverClient CreateWcfLogReceiverClient()
{
WcfLogReceiverClient client;
if (string.IsNullOrEmpty(EndpointConfigurationName))
{
// endpoint not specified - use BasicHttpBinding
Binding binding;
if (UseBinaryEncoding)
{
binding = new CustomBinding(new BinaryMessageEncodingBindingElement(), new HttpTransportBindingElement());
}
else
{
binding = new BasicHttpBinding();
}
client = new WcfLogReceiverClient(UseOneWayContract, binding, new EndpointAddress(EndpointAddress));
}
else
{
client = new WcfLogReceiverClient(UseOneWayContract, EndpointConfigurationName, new EndpointAddress(EndpointAddress));
}
client.ProcessLogMessagesCompleted += ClientOnProcessLogMessagesCompleted;
return client;
}
/// <summary>
/// Creating a new instance of IWcfLogReceiverClient
///
/// Inheritors can override this method and provide their own
/// service configuration - binding and endpoint address
/// </summary>
/// <returns></returns>
/// <remarks>virtual is used by end users</remarks>
protected virtual IWcfLogReceiverClient CreateLogReceiver()
{
#pragma warning disable 612, 618
return CreateWcfLogReceiverClient();
#pragma warning restore 612, 618
}
private void ClientOnProcessLogMessagesCompleted(object sender, AsyncCompletedEventArgs asyncCompletedEventArgs)
{
var client = sender as IWcfLogReceiverClient;
if (client != null && client.State == CommunicationState.Opened)
{
try
{
client.Close();
}
catch
{
client.Abort();
}
}
}
#endif
private void SendBufferedEvents(AsyncContinuation flushContinuation)
{
try
{
lock (SyncRoot)
{
// clear inCall flag
AsyncLogEventInfo[] bufferedEvents = buffer.GetEventsAndClear();
if (bufferedEvents.Length > 0)
{
var networkLogEvents = TranslateLogEvents(bufferedEvents);
Send(networkLogEvents, bufferedEvents, flushContinuation);
}
else
{
// nothing in the buffer, clear in-call flag
inCall = false;
if (flushContinuation != null)
flushContinuation(null);
}
}
}
catch (Exception exception)
{
if (flushContinuation != null)
{
InternalLogger.Error(exception, "LogReceiverServiceTarget(Name={0}): Error in flush async", Name);
#if !NETSTANDARD
if (exception.MustBeRethrown())
throw;
#endif
flushContinuation(exception);
}
else
{
InternalLogger.Error(exception, "LogReceiverServiceTarget(Name={0}): Error in send async", Name);
#if !NETSTANDARD
if (exception.MustBeRethrownImmediately())
{
throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
}
#endif
}
}
}
internal NLogEvent TranslateEvent(LogEventInfo eventInfo, NLogEvents context, Dictionary<string, int> stringTable)
{
var nlogEvent = new NLogEvent();
nlogEvent.Id = eventInfo.SequenceID;
nlogEvent.MessageOrdinal = AddValueAndGetStringOrdinal(context, stringTable, eventInfo.FormattedMessage);
nlogEvent.LevelOrdinal = eventInfo.Level.Ordinal;
nlogEvent.LoggerOrdinal = AddValueAndGetStringOrdinal(context, stringTable, eventInfo.LoggerName);
nlogEvent.TimeDelta = eventInfo.TimeStamp.ToUniversalTime().Ticks - context.BaseTimeUtc;
for (int i = 0; i < Parameters.Count; ++i)
{
var param = Parameters[i];
var value = param.Layout.Render(eventInfo);
int stringIndex = AddValueAndGetStringOrdinal(context, stringTable, value);
nlogEvent.ValueIndexes.Add(stringIndex);
}
// layout names beyond Parameters.Count are per-event property names.
for (int i = Parameters.Count; i < context.LayoutNames.Count; ++i)
{
string value;
object propertyValue;
if (eventInfo.HasProperties && eventInfo.Properties.TryGetValue(context.LayoutNames[i], out propertyValue))
{
value = Convert.ToString(propertyValue, CultureInfo.InvariantCulture);
}
else
{
value = string.Empty;
}
int stringIndex = AddValueAndGetStringOrdinal(context, stringTable, value);
nlogEvent.ValueIndexes.Add(stringIndex);
}
if (eventInfo.Exception != null)
{
nlogEvent.ValueIndexes.Add(AddValueAndGetStringOrdinal(context, stringTable, eventInfo.Exception.ToString()));
}
return nlogEvent;
}
}
}
#endif
| |
// ==============================================================================
// This file is part of the Microsoft Dynamics CRM SDK Code Samples.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// This source code is intended only as a supplement to Microsoft
// Development Tools and/or on-line documentation. See these other
// materials for detailed information regarding Microsoft code samples.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// ==============================================================================
//<snippetReleaseISVActivities>
using System;
using System.Activities;
using System.Collections;
using System.Reflection;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Workflow;
namespace Microsoft.Crm.Sdk.Samples
{
//<snippetReleaseISVActivities2>
/// <summary>
/// Activity will return the next upcoming birthday that has just passed
///
/// If this year's birthday has not yet occurred, it will return this year's birthday
/// Otherwise, it will return the birthday for next year
///
/// A workflow can timeout when on this date
/// </summary>
[Persist]
public sealed partial class ReleaseScenario_UpdateNextBirthday : CodeActivity
{
protected override void Execute(CodeActivityContext executionContext)
{
IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
//Create an Organization Service
IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
IOrganizationService service = serviceFactory.CreateOrganizationService(context.InitiatingUserId);
//Retrieve the contact id
Guid contactId = this.Contact.Get(executionContext).Id;
//<snippetReleaseISVActivities1>
//Create the request
RetrieveRequest request = new RetrieveRequest();
request.ColumnSet = new ColumnSet(new string[] { "birthdate" });
request.Target = new EntityReference(EntityName.Contact, contactId);
//Retrieve the entity to determine what the birthdate is set at
Entity entity = (Entity)((RetrieveResponse)service.Execute(request)).Entity;
//</snippetReleaseISVActivities1>
//Extract the date out of the entity
DateTime? birthdate;
if (entity.Contains(ContactAttributes.Birthdate))
{
birthdate = (DateTime?)entity[ContactAttributes.Birthdate];
}
else
{
birthdate = null;
}
//Check to see if the current birthday is set. We don't want the activity to fail if the birthdate is not set
if (birthdate == null)
{
return;
}
//Calculate the next birthdate. Encapsulated in a methdo so that the method can be used in the test case for verification purposes
DateTime nextBirthdate = CalculateNextBirthday(birthdate.Value);
//Update the next birthday field on the entity
Entity updateEntity = new Entity(EntityName.Contact);
updateEntity.Id = contactId;
updateEntity["new_nextbirthday"] = nextBirthdate;
service.Update(updateEntity);
}
//Define the properties
[RequiredArgument]
[Input("Update Next Birthdate for")]
[ReferenceTarget("contact")]
public InArgument<EntityReference> Contact { get; set; }
private DateTime CalculateNextBirthday(DateTime birthdate)
{
DateTime nextBirthday = new DateTime(birthdate.Year, birthdate.Month, birthdate.Day);
//Check to see if this birthday occurred on a leap year
bool leapYearAdjust = false;
if (nextBirthday.Month == 2 && nextBirthday.Day == 29)
{
//Sanity check, was that year a leap year
if (DateTime.IsLeapYear(nextBirthday.Year))
{
//Check to see if the current year is a leap year
if (!DateTime.IsLeapYear(DateTime.Now.Year))
{
//Push the date to March 1st so that the date arithmetic will function correctly
nextBirthday = nextBirthday.AddDays(1);
leapYearAdjust = true;
}
}
else
{
throw new Exception("Invalid Birthdate specified", new ArgumentException("Birthdate"));
}
}
//Calculate the year difference
nextBirthday = nextBirthday.AddYears(DateTime.Now.Year - nextBirthday.Year);
//Check to see if the date was adjusted
if (leapYearAdjust && DateTime.IsLeapYear(nextBirthday.Year))
{
nextBirthday = nextBirthday.AddDays(-1);
}
return nextBirthday;
}
}
//</snippetReleaseISVActivities2>
//<snippetReleaseISVActivities3>
public sealed partial class ReleaseScenario_MessageName : CodeActivity
{
protected override void Execute(CodeActivityContext executionContext)
{
IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
//Set the variable
MessageName.Set(executionContext, context.MessageName);
}
//Define the properties
[Output("Message Name")]
public OutArgument<string> MessageName { get; set; }
}
//</snippetReleaseISVActivities3>
//<snippetReleaseISVActivities4>
/// <summary>
/// Calculates the credit score based on the SSN and name.
/// </summary>
/// <remarks>
/// This depends on a custom entity called Loan Application and customizations to Contact.
///
/// Loan Application requires the following properties:
/// <list>
/// <item>Schema Name: new_loanapplication</item>
/// <item>Attribute: new_loanapplicationid as the primary key</item>
/// <item>Attribute: new_creditscore of type int with min of 0 and max of 1000 (if it is to be updated)</item>
/// <item>Attribute: new_loanamount of type money with default min/max</item>
/// <item>Customize the form to include the attribute new_loanapplicantid</item>
/// </list>
///
/// Contact Requires the following customizations
/// <list>
/// <item>Attribute: new_ssn as nvarchar with max length of 15</item>
/// <item>One-To-Many Relationship with these properties:
/// <list>
/// <item>Relationship Definition Schema Name: new_loanapplicant</item>
/// <item>Relationship Definition Related Entity Name: Loan Application</item>
/// <item>Relationship Atttribute Schema Name: new_loanapplicantid</item>
/// <item>Relationship Behavior Type: Referential</item>
/// </list>
/// </item>
/// </list>
///
/// The activity takes, as input, a EntityReference to the Loan Application and a boolean indicating whether new_creditscore should be updated to the credit score.
/// </remarks>
/// <exception cref=">ArgumentNullException">Thrown when LoanApplication is null</exception>
/// <exception cref=">ArgumentException">Thrown when LoanApplication is not a EntityReference to a LoanApplication entity</exception>
public sealed partial class RetrieveCreditScore : CodeActivity
{
private const string CustomEntity = "new_loanapplication";
protected override void Execute(CodeActivityContext executionContext)
{
//Check to see if the EntityReference has been set
EntityReference loanApplication = this.LoanApplication.Get(executionContext);
if (loanApplication == null)
{
throw new InvalidOperationException("Loan Application has not been specified", new ArgumentNullException("Loan Application"));
}
else if (loanApplication.LogicalName != CustomEntity)
{
throw new InvalidOperationException("Loan Application must reference a Loan Application entity",
new ArgumentException("Loan Application must be of type Loan Application", "Loan Application"));
}
//Retrieve the CrmService so that we can retrieve the loan application
IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
IOrganizationService service = serviceFactory.CreateOrganizationService(context.InitiatingUserId);
//Retrieve the Loan Application Entity
Entity loanEntity;
{
//Create a request
RetrieveRequest retrieveRequest = new RetrieveRequest();
retrieveRequest.ColumnSet = new ColumnSet(new string[] { "new_loanapplicationid", "new_loanapplicantid" });
retrieveRequest.Target = loanApplication;
//Execute the request
RetrieveResponse retrieveResponse = (RetrieveResponse)service.Execute(retrieveRequest);
//Retrieve the Loan Application Entity
loanEntity = retrieveResponse.Entity as Entity;
}
//Retrieve the Contact Entity
Entity contactEntity;
{
//Create a request
EntityReference loanApplicantId = (EntityReference)loanEntity["new_loanapplicantid"];
RetrieveRequest retrieveRequest = new RetrieveRequest();
retrieveRequest.ColumnSet = new ColumnSet(new string[] { "fullname", "new_ssn", "birthdate" });
retrieveRequest.Target = loanApplicantId;
//Execute the request
RetrieveResponse retrieveResponse = (RetrieveResponse)service.Execute(retrieveRequest);
//Retrieve the Loan Application Entity
contactEntity = retrieveResponse.Entity as Entity;
}
//Retrieve the needed properties
string ssn = (string)contactEntity["new_ssn"];
string name = (string)contactEntity[ContactAttributes.FullName];
DateTime? birthdate = (DateTime?)contactEntity[ContactAttributes.Birthdate];
int creditScore;
//This is where the logic for retrieving the credit score would be inserted
//We are simply going to return a random number
creditScore = (new Random()).Next(0, 1000);
//Set the credit score property
this.CreditScore.Set(executionContext, creditScore);
//Check to see if the credit score should be saved to the entity
//If the value of the property has not been set or it is set to true
if (null != this.UpdateEntity && this.UpdateEntity.Get(executionContext))
{
//Create the entity
Entity updateEntity = new Entity(loanApplication.LogicalName);
updateEntity["new_loanapplicationid"] = loanEntity["new_loanapplicationid"];
updateEntity["new_creditscore"] = this.CreditScore.Get(executionContext);
//Update the entity
service.Update(updateEntity);
}
}
//Define the properties
[Input("Loan Application")]
[ReferenceTarget(CustomEntity)]
public InArgument<EntityReference> LoanApplication { get; set; }
[Input("Update Entity's Credit Score")]
[Default("true")]
public InArgument<bool> UpdateEntity { get; set; }
[Output("Credit Score")]
[AttributeTarget(CustomEntity, "new_creditscore")]
public OutArgument<int> CreditScore { get; set; }
}
//</snippetReleaseISVActivities4>
}
//</snippetReleaseISVActivities>
| |
// ------------------------------------------------------------------------------
// 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.
// ------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18010
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Microsoft.Live {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Live.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Another async operation is already in progress..
/// </summary>
internal static string AsyncOperationInProgress {
get {
return ResourceManager.GetString("AsyncOperationInProgress", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred while adding the request to the BackgroundTransferService..
/// </summary>
internal static string BackgroundTransferServiceAddError {
get {
return ResourceManager.GetString("BackgroundTransferServiceAddError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred while removing a request to the BackgroundTransferService..
/// </summary>
internal static string BackgroundTransferServiceRemoveError {
get {
return ResourceManager.GetString("BackgroundTransferServiceRemoveError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred while reading the response of the BackgroundUpload..
/// </summary>
internal static string BackgroundUploadResponseHandlerError {
get {
return ResourceManager.GetString("BackgroundUploadResponseHandlerError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to A connection to the server could not be established..
/// </summary>
internal static string ConnectionError {
get {
return ResourceManager.GetString("ConnectionError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User has not granted the application consent to access data in Windows Live..
/// </summary>
internal static string ConsentNotGranted {
get {
return ResourceManager.GetString("ConsentNotGranted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Input parameter '{0}' is invalid. '{0}' contains invalid characters..
/// </summary>
internal static string FileNameInvalid {
get {
return ResourceManager.GetString("FileNameInvalid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Input parameter '{0}' is invalid. '{0}' cannot be null or empty..
/// </summary>
internal static string InvalidNullOrEmptyParameter {
get {
return ResourceManager.GetString("InvalidNullOrEmptyParameter", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Input parameter '{0}' is invalid. '{0}' cannot be null..
/// </summary>
internal static string InvalidNullParameter {
get {
return ResourceManager.GetString("InvalidNullParameter", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The login page is already open..
/// </summary>
internal static string LoginPopupAlreadyOpen {
get {
return ResourceManager.GetString("LoginPopupAlreadyOpen", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to There was no response from the server for this request..
/// </summary>
internal static string NoResponseData {
get {
return ResourceManager.GetString("NoResponseData", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The method '{0}' must be called from the application's UI thread..
/// </summary>
internal static string NotOnUiThread {
get {
return ResourceManager.GetString("NotOnUiThread", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Could not determine the upload location. Make sure the path points to a file resource id..
/// </summary>
internal static string NoUploadLinkFound {
get {
return ResourceManager.GetString("NoUploadLinkFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Input parameter '{0}' is invalid. '{0}' must be a relative url..
/// </summary>
internal static string RelativeUrlRequired {
get {
return ResourceManager.GetString("RelativeUrlRequired", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Can not invoke the login page before the application root visual is rendered..
/// </summary>
internal static string RootVisualNotRendered {
get {
return ResourceManager.GetString("RootVisualNotRendered", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred while performing the operation. Please try again later..
/// </summary>
internal static string ServerError {
get {
return ResourceManager.GetString("ServerError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error occurred while performing the operation. Server returned a response with status {0}..
/// </summary>
internal static string ServerErrorWithStatus {
get {
return ResourceManager.GetString("ServerErrorWithStatus", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Input parameter '{0}' is invalid. Stream is not readable..
/// </summary>
internal static string StreamNotReadable {
get {
return ResourceManager.GetString("StreamNotReadable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Input parameter '{0}' is invalid. Stream is not writable..
/// </summary>
internal static string StreamNotWritable {
get {
return ResourceManager.GetString("StreamNotWritable", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Input parameter '{0}' is invalid. '{0}' must contain a filename..
/// </summary>
internal static string UriMissingFileName {
get {
return ResourceManager.GetString("UriMissingFileName", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Input parameter '{0}' is invalid. '{0}' must be rooted in \shared\transfers..
/// </summary>
internal static string UriMustBeRootedInSharedTransfers {
get {
return ResourceManager.GetString("UriMustBeRootedInSharedTransfers", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Input parameter '{0}' is invalid. '{0}' must be a valid URI..
/// </summary>
internal static string UrlInvalid {
get {
return ResourceManager.GetString("UrlInvalid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to User did not log in. Call LiveAuthClient.LoginAsync to log in..
/// </summary>
internal static string UserNotLoggedIn {
get {
return ResourceManager.GetString("UserNotLoggedIn", resourceCulture);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Baseline;
using Baseline.Dates;
using Marten.AsyncDaemon.Testing.TestingSupport;
using Marten.Events;
using Marten.Events.Daemon;
using Marten.Events.Projections;
using Marten.Exceptions;
using Marten.Testing.Events.Projections;
using Shouldly;
using Xunit;
using Xunit.Abstractions;
namespace Marten.AsyncDaemon.Testing.Resiliency
{
public class error_handling : DaemonContext
{
public error_handling(ITestOutputHelper output) : base(output)
{
}
[Fact]
public async Task projections_can_continue_with_handled_exceptions()
{
var projection1 = new SometimesFailingProjection("one");
projection1.StartThrowingExceptionsAtSequence(10, new ArithmeticException(), new ArithmeticException());
StoreOptions(opts =>
{
opts.Projections.Add(projection1, ProjectionLifecycle.Async);
opts.Projections.OnException<ArithmeticException>()
.RetryLater(50.Milliseconds(), 50.Milliseconds());
});
using var node = await StartDaemon();
NumberOfStreams = 10;
await PublishSingleThreaded();
await node.Tracker.WaitForHighWaterMark(NumberOfEvents);
node.StatusFor("one:All").ShouldBe(AgentStatus.Running);
}
[Fact]
public async Task projections_can_continue_with_handled_exceptions_after_a_pause()
{
// WARNING -- this test doesn't consistently pass if it's running with other tests,
// but should succeed running by itself.
var projection1 = new SometimesFailingProjection("one");
projection1.StartThrowingExceptionsAtSequence(10, new ArithmeticException(), new ArithmeticException(), new ArithmeticException());
StoreOptions(opts =>
{
opts.Projections.Add(projection1, ProjectionLifecycle.Async);
opts.Projections
.OnException<ApplyEventException>()
.AndInner<ArithmeticException>()
.RetryLater(50.Milliseconds(), 50.Milliseconds())
.Then.Pause(50.Milliseconds());
});
using var node = await StartDaemon();
var waiter = node.Tracker.WaitForShardCondition(
state => state.ShardName.EqualsIgnoreCase("one:All") && state.Action == ShardAction.Paused,
"one:All is Paused", 5.Minutes());
NumberOfStreams = 10;
await PublishSingleThreaded();
await waiter;
await node.Tracker.WaitForShardState("one:All", NumberOfEvents);
if (node.StatusFor("one:All") != AgentStatus.Running)
{
await Task.Delay(250.Milliseconds());
node.StatusFor("one:All").ShouldBe(AgentStatus.Running);
}
}
[Fact]
public async Task all_projections_can_continue_with_handled_exceptions_after_a_pause()
{
var projection1 = new SometimesFailingProjection("one");
projection1.StartThrowingExceptionsAtSequence(10, new ArithmeticException(), new ArithmeticException(), new ArithmeticException());
var projection2 = new SometimesFailingProjection("two");
StoreOptions(opts =>
{
opts.Projections.Add(projection1, ProjectionLifecycle.Async);
opts.Projections.Add(projection2, ProjectionLifecycle.Async);
opts.Projections.OnException<ApplyEventException>().AndInner<ArithmeticException>()
.RetryLater(50.Milliseconds(), 50.Milliseconds()).Then.PauseAll(50.Milliseconds());
});
using var node = await StartDaemon();
var waiter1 = node.Tracker.WaitForShardCondition(
state => state.ShardName.EqualsIgnoreCase("one:All") && state.Action == ShardAction.Paused,
"one:All is Paused", 1.Minutes());
var waiter2 = node.Tracker.WaitForShardCondition(
state => state.ShardName.EqualsIgnoreCase("one:All") && state.Action == ShardAction.Paused,
"one:All is Paused", 1.Minutes());
NumberOfStreams = 10;
await PublishSingleThreaded();
await waiter1;
await waiter2;
await node.Tracker.WaitForShardState("one:All", NumberOfEvents);
if (node.StatusFor("one:All") != AgentStatus.Running)
{
await Task.Delay(250.Milliseconds());
}
node.StatusFor("one:All").ShouldBe(AgentStatus.Running);
node.StatusFor("two:All").ShouldBe(AgentStatus.Running);
}
[Fact]
public async Task projections_stops_on_too_many_tries()
{
var projection1 = new SometimesFailingProjection("one");
projection1.StartThrowingExceptionsAtSequence(10, new ArithmeticException(), new ArithmeticException(), new ArithmeticException(), new ArithmeticException());
StoreOptions(opts =>
{
opts.Projections.Add(projection1, ProjectionLifecycle.Async);
opts.Projections.OnException<ArithmeticException>()
.RetryLater(50.Milliseconds(), 50.Milliseconds());
});
using var node = await StartDaemon();
NumberOfStreams = 10;
await PublishMultiThreaded(3);
await node.WaitForShardToStop("one:All");
node.StatusFor("one:All").ShouldBe(AgentStatus.Stopped);
}
[Fact]
public async Task projections_are_stopped_with_unhandled_exceptions()
{
var projection1 = new SometimesFailingProjection("one");
projection1.StartThrowingExceptionsAtSequence(10, new ArithmeticException(), new BadImageFormatException());
var projection2 = new SometimesFailingProjection("two");
StoreOptions(opts =>
{
opts.Projections.Add(projection1, ProjectionLifecycle.Async);
opts.Projections.Add(projection2, ProjectionLifecycle.Async);
opts.Projections.OnException<ArithmeticException>()
.RetryLater(50.Milliseconds(), 50.Milliseconds());
});
using var node = await StartDaemon();
NumberOfStreams = 10;
await PublishSingleThreaded();
await node.Tracker.WaitForHighWaterMark(NumberOfEvents);
await node.WaitForShardToStop("one:All");
node.StatusFor("one:All").ShouldBe(AgentStatus.Stopped);
node.StatusFor("two:All").ShouldBe(AgentStatus.Running);
}
[Fact]
public async Task configured_stop_all()
{
var projection1 = new SometimesFailingProjection("one");
projection1.StartThrowingExceptionsAtSequence(10, new DivideByZeroException());
var projection2 = new SometimesFailingProjection("two");
StoreOptions(opts =>
{
opts.Projections.Add(projection1, ProjectionLifecycle.Async);
opts.Projections.Add(projection2, ProjectionLifecycle.Async);
opts.Projections.OnException<ApplyEventException>().AndInner<DivideByZeroException>().StopAll();
});
using var node = await StartDaemon();
NumberOfStreams = 10;
await PublishSingleThreaded();
await node.Tracker.WaitForHighWaterMark(NumberOfEvents);
await node.WaitForShardToStop("two:All");
await node.WaitForShardToStop("one:All");
node.StatusFor("one:All").ShouldBe(AgentStatus.Stopped);
node.StatusFor("two:All").ShouldBe(AgentStatus.Stopped);
}
}
public class SometimesFailingProjection: EventProjection
{
public SometimesFailingProjection(string projectionName)
{
ProjectionName = projectionName;
}
private readonly IList<IMaybeThrower> _throwers = new List<IMaybeThrower>();
internal void FailEveryXTimes(int number, Func<Exception> func)
{
_throwers.Add(new SystematicFailure(number, func));
}
internal void StartThrowingExceptionsAtSequence(long sequence, params Exception[] exceptions)
{
var thrower = new StartThrowingExceptionsAtSequenceThrower(sequence, exceptions);
_throwers.Add(thrower);
}
public class StartThrowingExceptionsAtSequenceThrower: IMaybeThrower
{
private readonly long _sequence;
private readonly Queue<Exception> _exceptions;
public StartThrowingExceptionsAtSequenceThrower(long sequence, Exception[] exceptions)
{
_sequence = sequence;
_exceptions = new Queue<Exception>(exceptions);
}
public void Process(IEvent<Travel> travel)
{
if (travel.Sequence >= _sequence && _exceptions.Any())
{
throw _exceptions.Dequeue();
}
}
}
public void Project(IEvent<Travel> e, IDocumentOperations operations)
{
foreach (var thrower in _throwers)
{
thrower.Process(e);
}
}
public interface IMaybeThrower
{
void Process(IEvent<Travel> travel);
}
public class SystematicFailure: IMaybeThrower
{
private readonly int _number;
private readonly Func<Exception> _func;
public SystematicFailure(int number, Func<Exception> func)
{
_number = number;
_func = func;
}
public void Process(IEvent<Travel> travel)
{
if (travel.Sequence % _number == 0)
{
throw _func();
}
}
}
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\Character.h:210
namespace UnrealEngine
{
public partial class ACharacter : APawn
{
public ACharacter(IntPtr adress)
: base(adress)
{
}
public ACharacter(UObject Parent = null, string Name = "Character")
: base(IntPtr.Zero)
{
NativePointer = E_NewObject_ACharacter(Parent, Name);
NativeManager.AddNativeWrapper(NativePointer, this);
}
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern StringWrapper E_PROP_ACharacter_CapsuleComponentName_GET();
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern StringWrapper E_PROP_ACharacter_CharacterMovementComponentName_GET();
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_ACharacter_CrouchedEyeHeight_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_ACharacter_CrouchedEyeHeight_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern int E_PROP_ACharacter_JumpCurrentCount_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_ACharacter_JumpCurrentCount_SET(IntPtr Ptr, int Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_ACharacter_JumpForceTimeRemaining_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_ACharacter_JumpForceTimeRemaining_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_ACharacter_JumpKeyHoldTime_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_ACharacter_JumpKeyHoldTime_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern int E_PROP_ACharacter_JumpMaxCount_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_ACharacter_JumpMaxCount_SET(IntPtr Ptr, int Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_ACharacter_JumpMaxHoldTime_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_ACharacter_JumpMaxHoldTime_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_EVENT_ADD_ACharacter_LandedDelegate(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_EVENT_DEL_ACharacter_LandedDelegate(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern StringWrapper E_PROP_ACharacter_MeshComponentName_GET();
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_EVENT_ADD_ACharacter_MovementModeChangedDelegate(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_EVENT_DEL_ACharacter_MovementModeChangedDelegate(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_EVENT_ADD_ACharacter_OnCharacterMovementUpdated(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_EVENT_DEL_ACharacter_OnCharacterMovementUpdated(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_EVENT_ADD_ACharacter_OnReachedJumpApex(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_EVENT_DEL_ACharacter_OnReachedJumpApex(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_ACharacter_ProxyJumpForceStartedTime_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_ACharacter_ProxyJumpForceStartedTime_SET(IntPtr Ptr, float Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_ACharacter_RepRootMotion_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_ACharacter_RepRootMotion_SET(IntPtr Ptr, IntPtr Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_ACharacter_SavedRootMotion_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_ACharacter_SavedRootMotion_SET(IntPtr Ptr, IntPtr Value);
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_NewObject_ACharacter(IntPtr Parent, string Name);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_ApplyDamageMomentum(IntPtr self, float damageTaken, IntPtr damageEvent, IntPtr pawnInstigator, IntPtr damageCauser);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_BaseChange(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_CacheInitialMeshOffset(IntPtr self, IntPtr meshRelativeLocation, IntPtr meshRelativeRotation);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_ACharacter_CanCrouch(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_ACharacter_CanJump(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_ACharacter_CanJumpInternal(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_ACharacter_CanJumpInternal_Implementation(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_CheckJumpInput(IntPtr self, float deltaTime);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_ClearJumpInput(IntPtr self, float deltaTime);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_ClientAckGoodMove(IntPtr self, float timeStamp);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_ClientAckGoodMove_Implementation(IntPtr self, float timeStamp);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_ClientAdjustPosition(IntPtr self, float timeStamp, IntPtr newLoc, IntPtr newVel, IntPtr newBase, string newBaseBoneName, bool bHasBase, bool bBaseRelativePosition, byte serverMovementMode);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_ClientAdjustPosition_Implementation(IntPtr self, float timeStamp, IntPtr newLoc, IntPtr newVel, IntPtr newBase, string newBaseBoneName, bool bHasBase, bool bBaseRelativePosition, byte serverMovementMode);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_ClientAdjustRootMotionPosition(IntPtr self, float timeStamp, float serverMontageTrackPosition, IntPtr serverLoc, IntPtr serverRotation, float serverVelZ, IntPtr serverBase, string serverBoneName, bool bHasBase, bool bBaseRelativePosition, byte serverMovementMode);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_ClientAdjustRootMotionPosition_Implementation(IntPtr self, float timeStamp, float serverMontageTrackPosition, IntPtr serverLoc, IntPtr serverRotation, float serverVelZ, IntPtr serverBase, string serverBoneName, bool bHasBase, bool bBaseRelativePosition, byte serverMovementMode);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_ClientAdjustRootMotionSourcePosition(IntPtr self, float timeStamp, IntPtr serverRootMotion, bool bHasAnimRootMotion, float serverMontageTrackPosition, IntPtr serverLoc, IntPtr serverRotation, float serverVelZ, IntPtr serverBase, string serverBoneName, bool bHasBase, bool bBaseRelativePosition, byte serverMovementMode);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_ClientAdjustRootMotionSourcePosition_Implementation(IntPtr self, float timeStamp, IntPtr serverRootMotion, bool bHasAnimRootMotion, float serverMontageTrackPosition, IntPtr serverLoc, IntPtr serverRotation, float serverVelZ, IntPtr serverBase, string serverBoneName, bool bHasBase, bool bBaseRelativePosition, byte serverMovementMode);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_ClientCheatFly(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_ClientCheatFly_Implementation(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_ClientCheatGhost(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_ClientCheatGhost_Implementation(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_ClientCheatWalk(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_ClientCheatWalk_Implementation(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_ClientVeryShortAdjustPosition(IntPtr self, float timeStamp, IntPtr newLoc, IntPtr newBase, string newBaseBoneName, bool bHasBase, bool bBaseRelativePosition, byte serverMovementMode);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_ClientVeryShortAdjustPosition_Implementation(IntPtr self, float timeStamp, IntPtr newLoc, IntPtr newBase, string newBaseBoneName, bool bHasBase, bool bBaseRelativePosition, byte serverMovementMode);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_Crouch(IntPtr self, bool bClientSimulation);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_Falling(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_ACharacter_GetAnimRootMotionTranslationScale(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_ACharacter_GetBasedMovement(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_ACharacter_GetBaseRotationOffset(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_ACharacter_GetBaseRotationOffsetRotator(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_ACharacter_GetBaseTranslationOffset(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern ObjectPointerDescription E_ACharacter_GetCapsuleComponent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern ObjectPointerDescription E_ACharacter_GetCharacterMovement(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_ACharacter_GetJumpMaxHoldTime(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern ObjectPointerDescription E_ACharacter_GetMesh(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_ACharacter_GetReplicatedBasedMovement(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern byte E_ACharacter_GetReplicatedMovementMode(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_ACharacter_GetReplicatedServerLastTransformUpdateTimeStamp(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_ACharacter_HasAnyRootMotion(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_ACharacter_IsJumpProvidingForce(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_ACharacter_IsPlayingNetworkedRootMotionMontage(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_ACharacter_IsPlayingRootMotion(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_Jump(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_K2_OnEndCrouch(IntPtr self, float halfHeightAdjust, float scaledHalfHeightAdjust);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_K2_OnMovementModeChanged(IntPtr self, byte prevMovementMode, byte newMovementMode, byte prevCustomMode, byte newCustomMode);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_K2_OnStartCrouch(IntPtr self, float halfHeightAdjust, float scaledHalfHeightAdjust);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_K2_UpdateCustomMovement(IntPtr self, float deltaTime);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_Landed(IntPtr self, IntPtr hit);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_LaunchCharacter(IntPtr self, IntPtr launchVelocity, bool bXYOverride, bool bZOverride);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_MoveBlockedBy(IntPtr self, IntPtr impact);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_NotifyActorBeginOverlap(IntPtr self, IntPtr otherActor);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_NotifyActorEndOverlap(IntPtr self, IntPtr otherActor);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_NotifyJumpApex(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_OnEndCrouch(IntPtr self, float halfHeightAdjust, float scaledHalfHeightAdjust);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_OnJumped(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_OnJumped_Implementation(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_OnLanded(IntPtr self, IntPtr hit);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_OnLaunched(IntPtr self, IntPtr launchVelocity, bool bXYOverride, bool bZOverride);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_OnMovementModeChanged(IntPtr self, byte prevMovementMode, byte previousCustomMode);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_OnRep_IsCrouched(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_OnRep_ReplayLastTransformUpdateTimeStamp(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_OnRep_ReplicatedBasedMovement(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_OnRep_RootMotion(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_OnStartCrouch(IntPtr self, float halfHeightAdjust, float scaledHalfHeightAdjust);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_OnUpdateSimulatedPosition(IntPtr self, IntPtr oldLocation, IntPtr oldRotation);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_OnWalkingOffLedge(IntPtr self, IntPtr previousFloorImpactNormal, IntPtr previousFloorContactNormal, IntPtr previousLocation, float timeDelta);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_OnWalkingOffLedge_Implementation(IntPtr self, IntPtr previousFloorImpactNormal, IntPtr previousFloorContactNormal, IntPtr previousLocation, float timeDelta);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_ResetJumpState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_ACharacter_RestoreReplicatedMove(IntPtr self, IntPtr rootMotionRepMove);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_RootMotionDebugClientPrintOnScreen(IntPtr self, string inString);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_RootMotionDebugClientPrintOnScreen_Implementation(IntPtr self, string inString);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_SaveRelativeBasedMovement(IntPtr self, IntPtr newRelativeLocation, IntPtr newRotation, bool bRelativeRotation);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_ServerMoveOld(IntPtr self, float oldTimeStamp, IntPtr oldAccel, byte oldMoveFlags);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_ServerMoveOld_Implementation(IntPtr self, float oldTimeStamp, IntPtr oldAccel, byte oldMoveFlags);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_ACharacter_ServerMoveOld_Validate(IntPtr self, float oldTimeStamp, IntPtr oldAccel, byte oldMoveFlags);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_SetAnimRootMotionTranslationScale(IntPtr self, float inAnimRootMotionTranslationScale);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_SetBase(IntPtr self, IntPtr newBase, string boneName, bool bNotifyActor);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_ACharacter_ShouldNotifyLanded(IntPtr self, IntPtr hit);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_SimulatedRootMotionPositionFixup(IntPtr self, float deltaSeconds);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_StopAnimMontage(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_StopJumping(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_ACharacter_UnCrouch(IntPtr self, bool bClientSimulation);
#endregion
#region Property
/// <summary>
/// Name of the CapsuleComponent.
/// </summary>
public static string CapsuleComponentName
{
get => E_PROP_ACharacter_CapsuleComponentName_GET();
}
/// <summary>
/// Name of the CharacterMovement component. Use this name if you want to use a different class (with ObjectInitializer.SetDefaultSubobjectClass).
/// </summary>
public static string CharacterMovementComponentName
{
get => E_PROP_ACharacter_CharacterMovementComponentName_GET();
}
/// <summary>
/// Default crouched eye height
/// </summary>
public float CrouchedEyeHeight
{
get => E_PROP_ACharacter_CrouchedEyeHeight_GET(NativePointer);
set => E_PROP_ACharacter_CrouchedEyeHeight_SET(NativePointer, value);
}
/// <summary>
/// Tracks the current number of jumps performed.
/// <para>This is incremented in CheckJumpInput, used in CanJump_Implementation, and reset in OnMovementModeChanged. </para>
/// When providing overrides for these methods, it's recommended to either manually
/// <para>increment / reset this value, or call the Super:: method. </para>
/// </summary>
public int JumpCurrentCount
{
get => E_PROP_ACharacter_JumpCurrentCount_GET(NativePointer);
set => E_PROP_ACharacter_JumpCurrentCount_SET(NativePointer, value);
}
/// <summary>
/// Amount of jump force time remaining, if JumpMaxHoldTime > 0.
/// </summary>
public float JumpForceTimeRemaining
{
get => E_PROP_ACharacter_JumpForceTimeRemaining_GET(NativePointer);
set => E_PROP_ACharacter_JumpForceTimeRemaining_SET(NativePointer, value);
}
/// <summary>
/// Jump key Held Time.
/// <para>This is the time that the player has held the jump key, in seconds. </para>
/// </summary>
public float JumpKeyHoldTime
{
get => E_PROP_ACharacter_JumpKeyHoldTime_GET(NativePointer);
set => E_PROP_ACharacter_JumpKeyHoldTime_SET(NativePointer, value);
}
/// <summary>
/// The max number of jumps the character can perform.
/// <para>Note that if JumpMaxHoldTime is non zero and StopJumping is not called, the player </para>
/// may be able to perform and unlimited number of jumps. Therefore it is usually
/// <para>best to call StopJumping() when jump input has ceased (such as a button up event). </para>
/// </summary>
public int JumpMaxCount
{
get => E_PROP_ACharacter_JumpMaxCount_GET(NativePointer);
set => E_PROP_ACharacter_JumpMaxCount_SET(NativePointer, value);
}
/// <summary>
/// The max time the jump key can be held.
/// <para>Note that if StopJumping() is not called before the max jump hold time is reached, </para>
/// then the character will carry on receiving vertical velocity. Therefore it is usually
/// <para>best to call StopJumping() when jump input has ceased (such as a button up event). </para>
/// </summary>
public float JumpMaxHoldTime
{
get => E_PROP_ACharacter_JumpMaxHoldTime_GET(NativePointer);
set => E_PROP_ACharacter_JumpMaxHoldTime_SET(NativePointer, value);
}
/// <summary>
/// Name of the MeshComponent. Use this name if you want to prevent creation of the component (with ObjectInitializer.DoNotCreateDefaultSubobject).
/// </summary>
public static string MeshComponentName
{
get => E_PROP_ACharacter_MeshComponentName_GET();
}
/// <summary>
/// Track last time a jump force started for a proxy.
/// </summary>
public float ProxyJumpForceStartedTime
{
get => E_PROP_ACharacter_ProxyJumpForceStartedTime_GET(NativePointer);
set => E_PROP_ACharacter_ProxyJumpForceStartedTime_SET(NativePointer, value);
}
/// <summary>
/// Replicated Root Motion montage
/// </summary>
public FRepRootMotionMontage RepRootMotion
{
get => E_PROP_ACharacter_RepRootMotion_GET(NativePointer);
set => E_PROP_ACharacter_RepRootMotion_SET(NativePointer, value);
}
public FRootMotionSourceGroup SavedRootMotion
{
get => E_PROP_ACharacter_SavedRootMotion_GET(NativePointer);
set => E_PROP_ACharacter_SavedRootMotion_SET(NativePointer, value);
}
#endregion
#region Events
/// <summary>
/// Called upon landing when falling, to perform actions based on the Hit result.
/// <para>Note that movement mode is still "Falling" during this event. Current Velocity value is the velocity at the time of landing. </para>
/// Consider OnMovementModeChanged() as well, as that can be used once the movement mode changes to the new mode (most likely Walking).
/// <see cref="OnMovementModeChanged"/>
/// </summary>
/// <param name="hit">Result describing the landing that resulted in a valid landing spot.</param>
public event FLandedSignature LandedDelegate
{
add
{
E_EVENT_ADD_ACharacter_LandedDelegate(NativePointer);
_Event_LandedDelegate += value;
}
remove
{
E_EVENT_DEL_ACharacter_LandedDelegate(NativePointer);
_Event_LandedDelegate -= value;
}
}
private event FLandedSignature _Event_LandedDelegate;
internal void InvokeEvent_LandedDelegate(FHitResult hit)
{
_Event_LandedDelegate?.Invoke(hit);
}
/// <summary>
/// Multicast delegate for MovementMode changing.
/// </summary>
public event FMovementModeChangedSignature MovementModeChangedDelegate
{
add
{
E_EVENT_ADD_ACharacter_MovementModeChangedDelegate(NativePointer);
_Event_MovementModeChangedDelegate += value;
}
remove
{
E_EVENT_DEL_ACharacter_MovementModeChangedDelegate(NativePointer);
_Event_MovementModeChangedDelegate -= value;
}
}
private event FMovementModeChangedSignature _Event_MovementModeChangedDelegate;
internal void InvokeEvent_MovementModeChangedDelegate(ObjectPointerDescription character, EMovementMode prevMovementMode, byte previousCustomMode)
{
_Event_MovementModeChangedDelegate?.Invoke(character, prevMovementMode, previousCustomMode);
}
/// <summary>
/// Event triggered at the end of a CharacterMovementComponent movement update.
/// <para>This is the preferred event to use rather than the Tick event when performing custom updates to CharacterMovement properties based on the current state. </para>
/// This is mainly due to the nature of network updates, where client corrections in position from the server can cause multiple iterations of a movement update,
/// <para>which allows this event to update as well, while a Tick event would not. </para>
/// </summary>
/// <param name="deltaSeconds">Delta time in seconds for this update</param>
/// <param name="initialLocation">Location at the start of the update. May be different than the current location if movement occurred.</param>
/// <param name="initialVelocity">Velocity at the start of the update. May be different than the current velocity.</param>
public event FCharacterMovementUpdatedSignature OnCharacterMovementUpdated
{
add
{
E_EVENT_ADD_ACharacter_OnCharacterMovementUpdated(NativePointer);
_Event_OnCharacterMovementUpdated += value;
}
remove
{
E_EVENT_DEL_ACharacter_OnCharacterMovementUpdated(NativePointer);
_Event_OnCharacterMovementUpdated -= value;
}
}
private event FCharacterMovementUpdatedSignature _Event_OnCharacterMovementUpdated;
internal void InvokeEvent_OnCharacterMovementUpdated(float deltaSeconds, FVector oldLocation, FVector oldVelocity)
{
_Event_OnCharacterMovementUpdated?.Invoke(deltaSeconds, oldLocation, oldVelocity);
}
/// <summary>
/// Broadcast when Character's jump reaches its apex. Needs CharacterMovement->bNotifyApex = true
/// </summary>
public event FCharacterReachedApexSignature OnReachedJumpApex
{
add
{
E_EVENT_ADD_ACharacter_OnReachedJumpApex(NativePointer);
_Event_OnReachedJumpApex += value;
}
remove
{
E_EVENT_DEL_ACharacter_OnReachedJumpApex(NativePointer);
_Event_OnReachedJumpApex -= value;
}
}
private event FCharacterReachedApexSignature _Event_OnReachedJumpApex;
internal void InvokeEvent_OnReachedJumpApex()
{
_Event_OnReachedJumpApex?.Invoke();
}
#endregion
#region ExternMethods
/// <summary>
/// Apply momentum caused by damage.
/// </summary>
public virtual void ApplyDamageMomentum(float damageTaken, FDamageEvent damageEvent, APawn pawnInstigator, AActor damageCauser)
=> E_ACharacter_ApplyDamageMomentum(this, damageTaken, damageEvent, pawnInstigator, damageCauser);
/// <summary>
/// Event called after actor's base changes (if SetBase was requested to notify us with bNotifyPawn).
/// </summary>
protected virtual void BaseChange()
=> E_ACharacter_BaseChange(this);
/// <summary>
/// Cache mesh offset from capsule. This is used as the target for network smoothing interpolation, when the mesh is offset with lagged smoothing.
/// <para>This is automatically called during initialization; call this at runtime if you intend to change the default mesh offset from the capsule. </para>
/// <see cref="GetBaseTranslationOffset"/>
/// </summary>
public virtual void CacheInitialMeshOffset(FVector meshRelativeLocation, FRotator meshRelativeRotation)
=> E_ACharacter_CacheInitialMeshOffset(this, meshRelativeLocation, meshRelativeRotation);
/// <summary>
/// </summary>
/// <return>true</return>
public virtual bool CanCrouch()
=> E_ACharacter_CanCrouch(this);
/// <summary>
/// Check if the character can jump in the current state.
/// <para>The default implementation may be overridden or extended by implementing the custom CanJump event in Blueprints. </para>
/// @Return Whether the character can jump in the current state.
/// </summary>
public bool CanJump()
=> E_ACharacter_CanJump(this);
/// <summary>
/// Customizable event to check if the character can jump in the current state.
/// <para>Default implementation returns true if the character is on the ground and not crouching, </para>
/// has a valid CharacterMovementComponent and CanEverJump() returns true.
/// <para>Default implementation also allows for 'hold to jump higher' functionality: </para>
/// As well as returning true when on the ground, it also returns true when GetMaxJumpTime is more
/// <para>than zero and IsJumping returns true. </para>
/// @Return Whether the character can jump in the current state.
/// </summary>
protected bool CanJumpInternal()
=> E_ACharacter_CanJumpInternal(this);
protected virtual bool CanJumpInternal_Implementation()
=> E_ACharacter_CanJumpInternal_Implementation(this);
/// <summary>
/// Trigger jump if jump button has been pressed.
/// </summary>
public virtual void CheckJumpInput(float deltaTime)
=> E_ACharacter_CheckJumpInput(this, deltaTime);
/// <summary>
/// Update jump input state after having checked input.
/// </summary>
public virtual void ClearJumpInput(float deltaTime)
=> E_ACharacter_ClearJumpInput(this, deltaTime);
public void ClientAckGoodMove(float timeStamp)
=> E_ACharacter_ClientAckGoodMove(this, timeStamp);
public void ClientAckGoodMove_Implementation(float timeStamp)
=> E_ACharacter_ClientAckGoodMove_Implementation(this, timeStamp);
public void ClientAdjustPosition(float timeStamp, FVector newLoc, FVector newVel, UPrimitiveComponent newBase, string newBaseBoneName, bool bHasBase, bool bBaseRelativePosition, byte serverMovementMode)
=> E_ACharacter_ClientAdjustPosition(this, timeStamp, newLoc, newVel, newBase, newBaseBoneName, bHasBase, bBaseRelativePosition, serverMovementMode);
public void ClientAdjustPosition_Implementation(float timeStamp, FVector newLoc, FVector newVel, UPrimitiveComponent newBase, string newBaseBoneName, bool bHasBase, bool bBaseRelativePosition, byte serverMovementMode)
=> E_ACharacter_ClientAdjustPosition_Implementation(this, timeStamp, newLoc, newVel, newBase, newBaseBoneName, bHasBase, bBaseRelativePosition, serverMovementMode);
public void ClientAdjustRootMotionPosition(float timeStamp, float serverMontageTrackPosition, FVector serverLoc, FVector_NetQuantizeNormal serverRotation, float serverVelZ, UPrimitiveComponent serverBase, string serverBoneName, bool bHasBase, bool bBaseRelativePosition, byte serverMovementMode)
=> E_ACharacter_ClientAdjustRootMotionPosition(this, timeStamp, serverMontageTrackPosition, serverLoc, serverRotation, serverVelZ, serverBase, serverBoneName, bHasBase, bBaseRelativePosition, serverMovementMode);
public void ClientAdjustRootMotionPosition_Implementation(float timeStamp, float serverMontageTrackPosition, FVector serverLoc, FVector_NetQuantizeNormal serverRotation, float serverVelZ, UPrimitiveComponent serverBase, string serverBoneName, bool bHasBase, bool bBaseRelativePosition, byte serverMovementMode)
=> E_ACharacter_ClientAdjustRootMotionPosition_Implementation(this, timeStamp, serverMontageTrackPosition, serverLoc, serverRotation, serverVelZ, serverBase, serverBoneName, bHasBase, bBaseRelativePosition, serverMovementMode);
public void ClientAdjustRootMotionSourcePosition(float timeStamp, FRootMotionSourceGroup serverRootMotion, bool bHasAnimRootMotion, float serverMontageTrackPosition, FVector serverLoc, FVector_NetQuantizeNormal serverRotation, float serverVelZ, UPrimitiveComponent serverBase, string serverBoneName, bool bHasBase, bool bBaseRelativePosition, byte serverMovementMode)
=> E_ACharacter_ClientAdjustRootMotionSourcePosition(this, timeStamp, serverRootMotion, bHasAnimRootMotion, serverMontageTrackPosition, serverLoc, serverRotation, serverVelZ, serverBase, serverBoneName, bHasBase, bBaseRelativePosition, serverMovementMode);
public void ClientAdjustRootMotionSourcePosition_Implementation(float timeStamp, FRootMotionSourceGroup serverRootMotion, bool bHasAnimRootMotion, float serverMontageTrackPosition, FVector serverLoc, FVector_NetQuantizeNormal serverRotation, float serverVelZ, UPrimitiveComponent serverBase, string serverBoneName, bool bHasBase, bool bBaseRelativePosition, byte serverMovementMode)
=> E_ACharacter_ClientAdjustRootMotionSourcePosition_Implementation(this, timeStamp, serverRootMotion, bHasAnimRootMotion, serverMontageTrackPosition, serverLoc, serverRotation, serverVelZ, serverBase, serverBoneName, bHasBase, bBaseRelativePosition, serverMovementMode);
public void ClientCheatFly()
=> E_ACharacter_ClientCheatFly(this);
public virtual void ClientCheatFly_Implementation()
=> E_ACharacter_ClientCheatFly_Implementation(this);
public void ClientCheatGhost()
=> E_ACharacter_ClientCheatGhost(this);
public virtual void ClientCheatGhost_Implementation()
=> E_ACharacter_ClientCheatGhost_Implementation(this);
public void ClientCheatWalk()
=> E_ACharacter_ClientCheatWalk(this);
public virtual void ClientCheatWalk_Implementation()
=> E_ACharacter_ClientCheatWalk_Implementation(this);
public void ClientVeryShortAdjustPosition(float timeStamp, FVector newLoc, UPrimitiveComponent newBase, string newBaseBoneName, bool bHasBase, bool bBaseRelativePosition, byte serverMovementMode)
=> E_ACharacter_ClientVeryShortAdjustPosition(this, timeStamp, newLoc, newBase, newBaseBoneName, bHasBase, bBaseRelativePosition, serverMovementMode);
public void ClientVeryShortAdjustPosition_Implementation(float timeStamp, FVector newLoc, UPrimitiveComponent newBase, string newBaseBoneName, bool bHasBase, bool bBaseRelativePosition, byte serverMovementMode)
=> E_ACharacter_ClientVeryShortAdjustPosition_Implementation(this, timeStamp, newLoc, newBase, newBaseBoneName, bHasBase, bBaseRelativePosition, serverMovementMode);
/// <summary>
/// Request the character to start crouching. The request is processed on the next update of the CharacterMovementComponent.
/// <para>@see OnStartCrouch </para>
/// @see IsCrouched
/// <see cref="CharacterMovement"/>
/// </summary>
public virtual void Crouch(bool bClientSimulation)
=> E_ACharacter_Crouch(this, bClientSimulation);
/// <summary>
/// Called when the character's movement enters falling
/// </summary>
public virtual void Falling()
=> E_ACharacter_Falling(this);
/// <summary>
/// Returns current value of AnimRootMotionScale
/// </summary>
public float GetAnimRootMotionTranslationScale()
=> E_ACharacter_GetAnimRootMotionTranslationScale(this);
/// <summary>
/// Accessor for BasedMovement
/// </summary>
public FBasedMovementInfo GetBasedMovement()
=> E_ACharacter_GetBasedMovement(this);
/// <summary>
/// Get the saved rotation offset of mesh. This is how much extra rotation is applied from the capsule rotation.
/// </summary>
public virtual FQuat GetBaseRotationOffset()
=> E_ACharacter_GetBaseRotationOffset(this);
/// <summary>
/// Get the saved rotation offset of mesh. This is how much extra rotation is applied from the capsule rotation.
/// </summary>
public FRotator GetBaseRotationOffsetRotator()
=> E_ACharacter_GetBaseRotationOffsetRotator(this);
/// <summary>
/// Get the saved translation offset of mesh. This is how much extra offset is applied from the center of the capsule.
/// </summary>
public FVector GetBaseTranslationOffset()
=> E_ACharacter_GetBaseTranslationOffset(this);
/// <summary>
/// Returns CapsuleComponent subobject
/// </summary>
public UCapsuleComponent GetCapsuleComponent()
=> E_ACharacter_GetCapsuleComponent(this);
/// <summary>
/// Returns CharacterMovement subobject
/// </summary>
public UCharacterMovementComponent GetCharacterMovement()
=> E_ACharacter_GetCharacterMovement(this);
/// <summary>
/// Get the maximum jump time for the character.
/// <para>Note that if StopJumping() is not called before the max jump hold time is reached, </para>
/// then the character will carry on receiving vertical velocity. Therefore it is usually
/// <para>best to call StopJumping() when jump input has ceased (such as a button up event). </para>
/// </summary>
/// <return>Maximum</return>
public virtual float GetJumpMaxHoldTime()
=> E_ACharacter_GetJumpMaxHoldTime(this);
/// <summary>
/// Returns Mesh subobject
/// </summary>
public USkeletalMeshComponent GetMesh()
=> E_ACharacter_GetMesh(this);
/// <summary>
/// Accessor for ReplicatedBasedMovement
/// </summary>
public FBasedMovementInfo GetReplicatedBasedMovement()
=> E_ACharacter_GetReplicatedBasedMovement(this);
/// <summary>
/// Returns ReplicatedMovementMode
/// </summary>
public byte GetReplicatedMovementMode()
=> E_ACharacter_GetReplicatedMovementMode(this);
/// <summary>
/// Accessor for ReplicatedServerLastTransformUpdateTimeStamp.
/// </summary>
public float GetReplicatedServerLastTransformUpdateTimeStamp()
=> E_ACharacter_GetReplicatedServerLastTransformUpdateTimeStamp(this);
/// <summary>
/// True if we are playing root motion from any source right now (anim root motion, root motion source)
/// </summary>
public bool HasAnyRootMotion()
=> E_ACharacter_HasAnyRootMotion(this);
/// <summary>
/// True if jump is actively providing a force, such as when the jump key is held and the time it has been held is less than JumpMaxHoldTime.
/// <see cref="CharacterMovement"/>
/// </summary>
public virtual bool IsJumpProvidingForce()
=> E_ACharacter_IsJumpProvidingForce(this);
/// <summary>
/// True if we are playing Root Motion right now, through a Montage with RootMotionMode == ERootMotionMode::RootMotionFromMontagesOnly.
/// <para>This means code path for networked root motion is enabled. </para>
/// </summary>
public bool IsPlayingNetworkedRootMotionMontage()
=> E_ACharacter_IsPlayingNetworkedRootMotionMontage(this);
/// <summary>
/// True if we are playing Anim root motion right now
/// </summary>
public bool IsPlayingAnimRootMotion()
=> E_ACharacter_IsPlayingRootMotion(this);
/// <summary>
/// Make the character jump on the next update.
/// <para>If you want your character to jump according to the time that the jump key is held, </para>
/// then you can set JumpKeyHoldTime to some non-zero value. Make sure in this case to
/// <para>call StopJumping() when you want the jump's z-velocity to stop being applied (such </para>
/// as on a button up event), otherwise the character will carry on receiving the
/// <para>velocity until JumpKeyHoldTime is reached. </para>
/// </summary>
public virtual void Jump()
=> E_ACharacter_Jump(this);
/// <summary>
/// Event when Character stops crouching.
/// </summary>
/// <param name="halfHeightAdjust">difference between default collision half-height, and actual crouched capsule half-height.</param>
/// <param name="scaledHalfHeightAdjust">difference after component scale is taken in to account.</param>
public void K2_OnEndCrouch(float halfHeightAdjust, float scaledHalfHeightAdjust)
=> E_ACharacter_K2_OnEndCrouch(this, halfHeightAdjust, scaledHalfHeightAdjust);
/// <summary>
/// Called from CharacterMovementComponent to notify the character that the movement mode has changed.
/// </summary>
/// <param name="prevMovementMode">Movement mode before the change</param>
/// <param name="newMovementMode">New movement mode</param>
/// <param name="prevCustomMode">Custom mode before the change (applicable if PrevMovementMode is Custom)</param>
/// <param name="newCustomMode">New custom mode (applicable if NewMovementMode is Custom)</param>
public void K2_OnMovementModeChanged(EMovementMode prevMovementMode, EMovementMode newMovementMode, byte prevCustomMode, byte newCustomMode)
=> E_ACharacter_K2_OnMovementModeChanged(this, (byte)prevMovementMode, (byte)newMovementMode, prevCustomMode, newCustomMode);
/// <summary>
/// Event when Character crouches.
/// </summary>
/// <param name="halfHeightAdjust">difference between default collision half-height, and actual crouched capsule half-height.</param>
/// <param name="scaledHalfHeightAdjust">difference after component scale is taken in to account.</param>
public void K2_OnStartCrouch(float halfHeightAdjust, float scaledHalfHeightAdjust)
=> E_ACharacter_K2_OnStartCrouch(this, halfHeightAdjust, scaledHalfHeightAdjust);
/// <summary>
/// Event for implementing custom character movement mode. Called by CharacterMovement if MovementMode is set to Custom.
/// <para>@note C++ code should override UCharacterMovementComponent::PhysCustom() instead. </para>
/// <see cref="UCharacterMovementComponent"/>
/// </summary>
public void UpdateCustomMovement(float deltaTime)
=> E_ACharacter_K2_UpdateCustomMovement(this, deltaTime);
/// <summary>
/// Called upon landing when falling, to perform actions based on the Hit result. Triggers the OnLanded event.
/// <para>Note that movement mode is still "Falling" during this event. Current Velocity value is the velocity at the time of landing. </para>
/// Consider OnMovementModeChanged() as well, as that can be used once the movement mode changes to the new mode (most likely Walking).
/// <see cref="OnMovementModeChanged"/>
/// </summary>
/// <param name="hit">Result describing the landing that resulted in a valid landing spot.</param>
public virtual void Landed(FHitResult hit)
=> E_ACharacter_Landed(this, hit);
/// <summary>
/// Set a pending launch velocity on the Character. This velocity will be processed on the next CharacterMovementComponent tick,
/// <para>and will set it to the "falling" state. Triggers the OnLaunched event. </para>
/// @PARAM LaunchVelocity is the velocity to impart to the Character
/// <para>@PARAM bXYOverride if true replace the XY part of the Character's velocity instead of adding to it. </para>
/// @PARAM bZOverride if true replace the Z component of the Character's velocity instead of adding to it.
/// </summary>
public virtual void LaunchCharacter(FVector launchVelocity, bool bXYOverride, bool bZOverride)
=> E_ACharacter_LaunchCharacter(this, launchVelocity, bXYOverride, bZOverride);
/// <summary>
/// Called when pawn's movement is blocked
/// </summary>
/// <param name="impact">describes the blocking hit.</param>
public virtual void MoveBlockedBy(FHitResult impact)
=> E_ACharacter_MoveBlockedBy(this, impact);
public virtual void NotifyActorBeginOverlap(AActor otherActor)
=> E_ACharacter_NotifyActorBeginOverlap(this, otherActor);
public virtual void NotifyActorEndOverlap(AActor otherActor)
=> E_ACharacter_NotifyActorEndOverlap(this, otherActor);
/// <summary>
/// Called when character's jump reaches Apex. Needs CharacterMovement->bNotifyApex = true
/// </summary>
public virtual void NotifyJumpApex()
=> E_ACharacter_NotifyJumpApex(this);
/// <summary>
/// Called when Character stops crouching. Called on non-owned Characters through bIsCrouched replication.
/// </summary>
/// <param name="halfHeightAdjust">difference between default collision half-height, and actual crouched capsule half-height.</param>
/// <param name="scaledHalfHeightAdjust">difference after component scale is taken in to account.</param>
public virtual void OnEndCrouch(float halfHeightAdjust, float scaledHalfHeightAdjust)
=> E_ACharacter_OnEndCrouch(this, halfHeightAdjust, scaledHalfHeightAdjust);
/// <summary>
/// Event fired when the character has just started jumping
/// </summary>
public void OnJumped()
=> E_ACharacter_OnJumped(this);
public virtual void OnJumped_Implementation()
=> E_ACharacter_OnJumped_Implementation(this);
public void OnLanded(FHitResult hit)
=> E_ACharacter_OnLanded(this, hit);
public void OnLaunched(FVector launchVelocity, bool bXYOverride, bool bZOverride)
=> E_ACharacter_OnLaunched(this, launchVelocity, bXYOverride, bZOverride);
/// <summary>
/// Called from CharacterMovementComponent to notify the character that the movement mode has changed.
/// </summary>
/// <param name="prevMovementMode">Movement mode before the change</param>
/// <param name="prevCustomMode">Custom mode before the change (applicable if PrevMovementMode is Custom)</param>
public virtual void OnMovementModeChanged(EMovementMode prevMovementMode, byte previousCustomMode)
=> E_ACharacter_OnMovementModeChanged(this, (byte)prevMovementMode, previousCustomMode);
public virtual void OnRep_IsCrouched()
=> E_ACharacter_OnRep_IsCrouched(this);
public void OnRep_ReplayLastTransformUpdateTimeStamp()
=> E_ACharacter_OnRep_ReplayLastTransformUpdateTimeStamp(this);
public virtual void OnRep_ReplicatedBasedMovement()
=> E_ACharacter_OnRep_ReplicatedBasedMovement(this);
public void OnRep_RootMotion()
=> E_ACharacter_OnRep_RootMotion(this);
/// <summary>
/// Called when Character crouches. Called on non-owned Characters through bIsCrouched replication.
/// </summary>
/// <param name="halfHeightAdjust">difference between default collision half-height, and actual crouched capsule half-height.</param>
/// <param name="scaledHalfHeightAdjust">difference after component scale is taken in to account.</param>
public virtual void OnStartCrouch(float halfHeightAdjust, float scaledHalfHeightAdjust)
=> E_ACharacter_OnStartCrouch(this, halfHeightAdjust, scaledHalfHeightAdjust);
/// <summary>
/// Called on client after position update is received to respond to the new location and rotation.
/// <para>Actual change in location is expected to occur in CharacterMovement->SmoothCorrection(), after which this occurs. </para>
/// Default behavior is to check for penetration in a blocking object if bClientCheckEncroachmentOnNetUpdate is enabled, and set bSimGravityDisabled=true if so.
/// </summary>
public virtual void OnUpdateSimulatedPosition(FVector oldLocation, FQuat oldRotation)
=> E_ACharacter_OnUpdateSimulatedPosition(this, oldLocation, oldRotation);
/// <summary>
/// Event fired when the Character is walking off a surface and is about to fall because CharacterMovement->CurrentFloor became unwalkable.
/// <para>If CharacterMovement->MovementMode does not change during this event then the character will automatically start falling afterwards. </para>
/// @note Z velocity is zero during walking movement, and will be here as well. Another velocity can be computed here if desired and will be used when starting to fall.
/// </summary>
/// <param name="previousFloorImpactNormal">Normal of the previous walkable floor.</param>
/// <param name="previousFloorContactNormal">Normal of the contact with the previous walkable floor.</param>
/// <param name="previousLocation">Previous character location before movement off the ledge.</param>
/// <param name="timeTick">Time delta of movement update resulting in moving off the ledge.</param>
public void OnWalkingOffLedge(FVector previousFloorImpactNormal, FVector previousFloorContactNormal, FVector previousLocation, float timeDelta)
=> E_ACharacter_OnWalkingOffLedge(this, previousFloorImpactNormal, previousFloorContactNormal, previousLocation, timeDelta);
public virtual void OnWalkingOffLedge_Implementation(FVector previousFloorImpactNormal, FVector previousFloorContactNormal, FVector previousLocation, float timeDelta)
=> E_ACharacter_OnWalkingOffLedge_Implementation(this, previousFloorImpactNormal, previousFloorContactNormal, previousLocation, timeDelta);
/// <summary>
/// Marks character as not trying to jump
/// </summary>
public virtual void ResetJumpState()
=> E_ACharacter_ResetJumpState(this);
/// <summary>
/// Restore actor to an old buffered move.
/// </summary>
public bool RestoreReplicatedMove(FSimulatedRootMotionReplicatedMove rootMotionRepMove)
=> E_ACharacter_RestoreReplicatedMove(this, rootMotionRepMove);
public void RootMotionDebugClientPrintOnScreen(string inString)
=> E_ACharacter_RootMotionDebugClientPrintOnScreen(this, inString);
public virtual void RootMotionDebugClientPrintOnScreen_Implementation(string inString)
=> E_ACharacter_RootMotionDebugClientPrintOnScreen_Implementation(this, inString);
/// <summary>
/// Save a new relative location in BasedMovement and a new rotation with is either relative or absolute.
/// </summary>
public void SaveRelativeBasedMovement(FVector newRelativeLocation, FRotator newRotation, bool bRelativeRotation)
=> E_ACharacter_SaveRelativeBasedMovement(this, newRelativeLocation, newRotation, bRelativeRotation);
public void ServerMoveOld(float oldTimeStamp, FVector_NetQuantize10 oldAccel, byte oldMoveFlags)
=> E_ACharacter_ServerMoveOld(this, oldTimeStamp, oldAccel, oldMoveFlags);
public void ServerMoveOld_Implementation(float oldTimeStamp, FVector_NetQuantize10 oldAccel, byte oldMoveFlags)
=> E_ACharacter_ServerMoveOld_Implementation(this, oldTimeStamp, oldAccel, oldMoveFlags);
public bool ServerMoveOld_Validate(float oldTimeStamp, FVector_NetQuantize10 oldAccel, byte oldMoveFlags)
=> E_ACharacter_ServerMoveOld_Validate(this, oldTimeStamp, oldAccel, oldMoveFlags);
/// <summary>
/// Sets scale to apply to root motion translation on this Character
/// </summary>
public void SetAnimRootMotionTranslationScale(float inAnimRootMotionTranslationScale)
=> E_ACharacter_SetAnimRootMotionTranslationScale(this, inAnimRootMotionTranslationScale);
/// <summary>
/// Sets the component the Character is walking on, used by CharacterMovement walking movement to be able to follow dynamic objects.
/// </summary>
public virtual void SetBase(UPrimitiveComponent newBase, string boneName, bool bNotifyActor)
=> E_ACharacter_SetBase(this, newBase, boneName, bNotifyActor);
/// <summary>
/// Returns true if the Landed() event should be called. Used by CharacterMovement to prevent notifications while playing back network moves.
/// </summary>
public virtual bool ShouldNotifyLanded(FHitResult hit)
=> E_ACharacter_ShouldNotifyLanded(this, hit);
/// <summary>
/// Position fix up for Simulated Proxies playing Root Motion
/// </summary>
public void SimulatedRootMotionPositionFixup(float deltaSeconds)
=> E_ACharacter_SimulatedRootMotionPositionFixup(this, deltaSeconds);
/// <summary>
/// Stop Animation Montage. If nullptr, it will stop what's currently active. The Blend Out Time is taken from the montage asset that is being stopped.
/// </summary>
public virtual void StopAnimMontage()
=> E_ACharacter_StopAnimMontage(this);
/// <summary>
/// Stop the character from jumping on the next update.
/// <para>Call this from an input event (such as a button 'up' event) to cease applying </para>
/// jump Z-velocity. If this is not called, then jump z-velocity will be applied
/// <para>until JumpMaxHoldTime is reached. </para>
/// </summary>
public virtual void StopJumping()
=> E_ACharacter_StopJumping(this);
/// <summary>
/// Request the character to stop crouching. The request is processed on the next update of the CharacterMovementComponent.
/// <para>@see OnEndCrouch </para>
/// @see IsCrouched
/// <see cref="CharacterMovement"/>
/// </summary>
public virtual void UnCrouch(bool bClientSimulation)
=> E_ACharacter_UnCrouch(this, bClientSimulation);
#endregion
public static implicit operator IntPtr(ACharacter self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator ACharacter(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<ACharacter>(PtrDesc);
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// An ice cream shop
/// </summary>
public class IceCreamShop_Core : TypeCore, IFoodEstablishment
{
public IceCreamShop_Core()
{
this._TypeId = 134;
this._Id = "IceCreamShop";
this._Schema_Org_Url = "http://schema.org/IceCreamShop";
string label = "";
GetLabel(out label, "IceCreamShop", typeof(IceCreamShop_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155,106};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{106};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167,1,139,205};
}
/// <summary>
/// Either <code>Yes/No</code>, or a URL at which reservations can be made.
/// </summary>
private AcceptsReservations_Core acceptsReservations;
public AcceptsReservations_Core AcceptsReservations
{
get
{
return acceptsReservations;
}
set
{
acceptsReservations = value;
SetPropertyInstance(acceptsReservations);
}
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// Either the actual menu or a URL of the menu.
/// </summary>
private Menu_Core menu;
public Menu_Core Menu
{
get
{
return menu;
}
set
{
menu = value;
SetPropertyInstance(menu);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The cuisine of the restaurant.
/// </summary>
private ServesCuisine_Core servesCuisine;
public ServesCuisine_Core ServesCuisine
{
get
{
return servesCuisine;
}
set
{
servesCuisine = value;
SetPropertyInstance(servesCuisine);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
using NUnit.Framework;
using System;
using System.Linq;
using OpenQA.Selenium.Environment;
using System.Collections.ObjectModel;
using OpenQA.Selenium.Interactions;
using System.Collections.Generic;
namespace OpenQA.Selenium.IE
{
[TestFixture]
public class IeSpecificTests : DriverTestFixture
{
//[Test]
public void KeysTest()
{
List<string> keyComboNames = new List<string>()
{
"Control",
"Shift",
"Alt",
"Control + Shift",
"Control + Alt",
"Shift + Alt",
"Control + Shift + Alt"
};
List<string> colorNames = new List<string>()
{
"red",
"green",
"lightblue",
"yellow",
"lightgreen",
"silver",
"magenta"
};
List<List<string>> modifierCombonations = new List<List<string>>()
{
new List<string>() { Keys.Control },
new List<string>() { Keys.Shift },
new List<string>() { Keys.Alt },
new List<string>() { Keys.Control, Keys.Shift },
new List<string>() { Keys.Control, Keys.Alt },
new List<string>() { Keys.Shift, Keys.Alt },
new List<string>() { Keys.Control, Keys.Shift, Keys.Alt}
};
List<string> expectedColors = new List<string>()
{
"rgba(255, 0, 0, 1)",
"rgba(0, 128, 0, 1)",
"rgba(173, 216, 230, 1)",
"rgba(255, 255, 0, 1)",
"rgba(144, 238, 144, 1)",
"rgba(192, 192, 192, 1)",
"rgba(255, 0, 255, 1)"
};
bool passed = true;
string errors = string.Empty;
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("keyboard_shortcut.html");
IWebElement body = driver.FindElement(By.CssSelector("body"));
Actions actions = new Actions(driver);
for (int i = 0; i < keyComboNames.Count; i++)
{
for (int j = 0; j < modifierCombonations[i].Count; j++)
{
actions.KeyDown(modifierCombonations[i][j]);
}
actions.SendKeys("1");
// Alternatively, the following single line of code would release
// all modifier keys, instead of looping through each key.
// actions.SendKeys(Keys.Null);
for (int j = 0; j < modifierCombonations[i].Count; j++)
{
actions.KeyUp(modifierCombonations[i][j]);
}
actions.Perform();
string background = body.GetCssValue("background-color");
passed = passed && background == expectedColors[i];
if (background != expectedColors[i])
{
if (errors.Length > 0)
{
errors += "\n";
}
errors += string.Format("Key not properly processed for {0}. Background should be {1}, Expected: '{2}', Actual: '{3}'",
keyComboNames[i],
colorNames[i],
expectedColors[i],
background);
}
}
Assert.IsTrue(passed, errors);
}
//[Test]
public void InputOnChangeAlert()
{
driver.Url = alertsPage;
driver.FindElement(By.Id("input")).Clear();
IAlert alert = WaitFor<IAlert>(() => { return driver.SwitchTo().Alert(); }, "No alert found");
alert.Accept();
}
//[Test]
public void ScrollingFrameTest()
{
try
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("frameScrollPage.html");
WaitFor(FrameToExistAndBeSwitchedTo("scrolling_frame"), "No frame with name or id 'scrolling_frame' found");
IWebElement element = driver.FindElement(By.Name("scroll_checkbox"));
element.Click();
Assert.IsTrue(element.Selected);
driver.SwitchTo().DefaultContent();
WaitFor(FrameToExistAndBeSwitchedTo("scrolling_child_frame"), "No frame with name or id 'scrolling_child_frame' found");
WaitFor(FrameToExistAndBeSwitchedTo("scrolling_frame"), "No frame with name or id 'scrolling_frame' found");
element = driver.FindElement(By.Name("scroll_checkbox"));
element.Click();
Assert.IsTrue(element.Selected);
}
finally
{
driver.SwitchTo().DefaultContent();
}
}
//[Test]
public void AlertSelectTest()
{
driver.Url = alertsPage;
driver.FindElement(By.Id("value1")).Click();
IAlert alert = WaitFor<IAlert>(() => { return driver.SwitchTo().Alert(); }, "No alert found");
alert.Accept();
}
//[Test]
public void ShouldBeAbleToBrowseTransformedXml()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.Id("linkId")).Click();
// Using transformed XML (Issue 1203)
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("transformable.xml");
driver.FindElement(By.Id("x")).Click();
// Sleep is required; driver may not be fast enough after this Click().
System.Threading.Thread.Sleep(2000);
Assert.AreEqual("XHTML Test Page", driver.Title);
// Act on the result page to make sure the window handling is still valid.
driver.FindElement(By.Id("linkId")).Click();
Assert.AreEqual("We Arrive Here", driver.Title);
}
//[Test]
public void ShouldBeAbleToStartMoreThanOneInstanceOfTheIEDriverSimultaneously()
{
IWebDriver secondDriver = new InternetExplorerDriver();
driver.Url = xhtmlTestPage;
secondDriver.Url = formsPage;
Assert.AreEqual("XHTML Test Page", driver.Title);
Assert.AreEqual("We Leave From Here", secondDriver.Title);
// We only need to quit the second driver if the test passes
secondDriver.Quit();
}
//[Test]
public void ShouldPropagateSessionCookies()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("sessionCookie.html");
IWebElement setColorButton = driver.FindElement(By.Id("setcolorbutton"));
setColorButton.Click();
IWebElement openWindowButton = driver.FindElement(By.Id("openwindowbutton"));
openWindowButton.Click();
System.Threading.Thread.Sleep(2000);
string startWindow = driver.CurrentWindowHandle;
driver.SwitchTo().Window("cookiedestwindow");
string bodyStyle = driver.FindElement(By.TagName("body")).GetAttribute("style");
driver.Close();
driver.SwitchTo().Window(startWindow);
Assert.IsTrue(bodyStyle.Contains("BACKGROUND-COLOR: #80ffff") || bodyStyle.Contains("background-color: rgb(128, 255, 255)"));
}
//[Test]
public void ShouldHandleShowModalDialogWindows()
{
driver.Url = alertsPage;
string originalWindowHandle = driver.CurrentWindowHandle;
IWebElement element = driver.FindElement(By.Id("dialog"));
element.Click();
WaitFor(() => { return driver.WindowHandles.Count > 1; }, "Window count was not greater than 1");
ReadOnlyCollection<string> windowHandles = driver.WindowHandles;
Assert.AreEqual(2, windowHandles.Count);
string dialogHandle = string.Empty;
foreach (string handle in windowHandles)
{
if (handle != originalWindowHandle)
{
dialogHandle = handle;
break;
}
}
Assert.AreNotEqual(string.Empty, dialogHandle);
driver.SwitchTo().Window(dialogHandle);
IWebElement closeElement = driver.FindElement(By.Id("close"));
closeElement.Click();
WaitFor(() => { return driver.WindowHandles.Count == 1; }, "Window count was not 1");
windowHandles = driver.WindowHandles;
Assert.AreEqual(1, windowHandles.Count);
driver.SwitchTo().Window(originalWindowHandle);
}
//[Test]
public void ScrollTest()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("scroll.html");
driver.FindElement(By.Id("line8")).Click();
Assert.AreEqual("line8", driver.FindElement(By.Id("clicked")).Text);
driver.FindElement(By.Id("line1")).Click();
Assert.AreEqual("line1", driver.FindElement(By.Id("clicked")).Text);
}
//[Test]
public void ShouldNotScrollOverflowElementsWhichAreVisible()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("scroll2.html");
var list = driver.FindElement(By.TagName("ul"));
var item = list.FindElement(By.Id("desired"));
item.Click();
Assert.AreEqual(0, ((IJavaScriptExecutor)driver).ExecuteScript("return arguments[0].scrollTop;", list), "Should not have scrolled");
}
//[Test]
public void ShouldNotScrollIfAlreadyScrolledAndElementIsInView()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("scroll3.html");
driver.FindElement(By.Id("button1")).Click();
var scrollTop = GetScrollTop();
driver.FindElement(By.Id("button2")).Click();
Assert.AreEqual(scrollTop, GetScrollTop());
}
//[Test]
public void ShouldBeAbleToHandleCascadingModalDialogs()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("modal_dialogs/modalindex.html");
string parentHandle = driver.CurrentWindowHandle;
// Launch first modal
driver.FindElement(By.CssSelector("input[type='button'][value='btn1']")).Click();
WaitFor(() => { return driver.WindowHandles.Count > 1; }, "Window count was not greater than 1");
ReadOnlyCollection<string> windows = driver.WindowHandles;
string firstWindowHandle = windows.Except(new List<string>() { parentHandle }).First();
driver.SwitchTo().Window(firstWindowHandle);
Assert.AreEqual(2, windows.Count);
// Launch second modal
driver.FindElement(By.CssSelector("input[type='button'][value='btn2']")).Click();
WaitFor(() => { return driver.WindowHandles.Count > 2; }, "Window count was not greater than 2");
ReadOnlyCollection<string> windows_1 = driver.WindowHandles;
string secondWindowHandle = windows_1.Except(windows).First();
driver.SwitchTo().Window(secondWindowHandle);
Assert.AreEqual(3, windows_1.Count);
// Launch third modal
driver.FindElement(By.CssSelector("input[type='button'][value='btn3']")).Click();
WaitFor(() => { return driver.WindowHandles.Count > 3; }, "Window count was not greater than 3");
ReadOnlyCollection<string> windows_2 = driver.WindowHandles;
string finalWindowHandle = windows_2.Except(windows_1).First();
Assert.AreEqual(4, windows_2.Count);
driver.SwitchTo().Window(finalWindowHandle).Close();
driver.SwitchTo().Window(secondWindowHandle).Close();
driver.SwitchTo().Window(firstWindowHandle).Close();
driver.SwitchTo().Window(parentHandle);
}
//[Test]
public void ShouldBeAbleToHandleCascadingModalDialogsLaunchedWithJavaScriptLinks()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("modal_dialogs/modalindex.html");
string parentHandle = driver.CurrentWindowHandle;
// Launch first modal
driver.FindElement(By.CssSelector("a[id='lnk1']")).Click();
WaitFor(() => { return driver.WindowHandles.Count > 1; }, "Window count was not greater than 1");
ReadOnlyCollection<string> windows = driver.WindowHandles;
string firstWindowHandle = windows.Except(new List<string>() { parentHandle }).First();
driver.SwitchTo().Window(firstWindowHandle);
Assert.AreEqual(2, windows.Count);
// Launch second modal
driver.FindElement(By.CssSelector("a[id='lnk2']")).Click();
System.Threading.Thread.Sleep(5000);
WaitFor(() => { return driver.WindowHandles.Count > 2; }, "Window count was not greater than 2");
ReadOnlyCollection<string> windows_1 = driver.WindowHandles;
string secondWindowHandle = windows_1.Except(windows).First();
driver.SwitchTo().Window(secondWindowHandle);
Assert.AreEqual(3, windows_1.Count);
// Launch third modal
driver.FindElement(By.CssSelector("a[id='lnk3']")).Click();
WaitFor(() => { return driver.WindowHandles.Count > 3; }, "Window count was not greater than 3");
ReadOnlyCollection<string> windows_2 = driver.WindowHandles;
string finalWindowHandle = windows_2.Except(windows_1).First();
Assert.AreEqual(4, windows_2.Count);
driver.SwitchTo().Window(finalWindowHandle).Close();
driver.SwitchTo().Window(secondWindowHandle).Close();
driver.SwitchTo().Window(firstWindowHandle).Close();
driver.SwitchTo().Window(parentHandle);
}
//[Test]
public void TestInvisibleZOrder()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("elementObscuredByInvisibleElement.html");
IWebElement element = driver.FindElement(By.CssSelector("#gLink"));
element.Click();
}
private long GetScrollTop()
{
return (long)((IJavaScriptExecutor)driver).ExecuteScript("return document.body.scrollTop;");
}
private Func<bool> FrameToExistAndBeSwitchedTo(string frameName)
{
return () =>
{
try
{
driver.SwitchTo().Frame(frameName);
}
catch (NoSuchFrameException)
{
return false;
}
return true;
};
}
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Models.Membership;
using Umbraco.Cms.Tests.Common.Builders.Extensions;
using Umbraco.Cms.Tests.Common.Builders.Interfaces;
using Umbraco.Extensions;
namespace Umbraco.Cms.Tests.Common.Builders
{
public class UserBuilder : UserBuilder<object>
{
public UserBuilder()
: base(null)
{
}
}
public class UserBuilder<TParent>
: ChildBuilderBase<TParent, User>,
IWithIdBuilder,
IWithKeyBuilder,
IWithCreateDateBuilder,
IWithUpdateDateBuilder,
IWithNameBuilder,
IAccountBuilder
{
private int? _id;
private Guid? _key;
private DateTime? _createDate;
private DateTime? _updateDate;
private string _language;
private string _name;
private string _username;
private string _rawPasswordValue;
private string _passwordConfig;
private string _email;
private int? _failedPasswordAttempts;
private bool? _isApproved;
private bool? _isLockedOut;
private DateTime? _lastLockoutDate;
private DateTime? _lastLoginDate;
private DateTime? _lastPasswordChangeDate;
private string _suffix = string.Empty;
private string _defaultLang;
private string _comments;
private int? _sessionTimeout;
private int[] _startContentIds;
private int[] _startMediaIds;
private readonly List<UserGroupBuilder<UserBuilder<TParent>>> _userGroupBuilders = new List<UserGroupBuilder<UserBuilder<TParent>>>();
public UserBuilder(TParent parentBuilder)
: base(parentBuilder)
{
}
Guid? IWithKeyBuilder.Key
{
get => _key;
set => _key = value;
}
DateTime? IWithCreateDateBuilder.CreateDate
{
get => _createDate;
set => _createDate = value;
}
DateTime? IWithUpdateDateBuilder.UpdateDate
{
get => _updateDate;
set => _updateDate = value;
}
public UserBuilder<TParent> WithDefaultUILanguage(string defaultLang)
{
_defaultLang = defaultLang;
return this;
}
public UserBuilder<TParent> WithLanguage(string language)
{
_language = language;
return this;
}
public UserBuilder<TParent> WithUsername(string username)
{
_username = username;
return this;
}
public UserBuilder<TParent> WithComments(string comments)
{
_comments = comments;
return this;
}
public UserBuilder<TParent> WithSessionTimeout(int sessionTimeout)
{
_sessionTimeout = sessionTimeout;
return this;
}
public UserBuilder<TParent> WithStartContentId(int startContentId)
{
_startContentIds = new[] { startContentId };
return this;
}
public UserBuilder<TParent> WithStartContentIds(int[] startContentIds)
{
_startContentIds = startContentIds;
return this;
}
public UserBuilder<TParent> WithStartMediaId(int startMediaId)
{
_startMediaIds = new[] { startMediaId };
return this;
}
public UserBuilder<TParent> WithStartMediaIds(int[] startMediaIds)
{
_startMediaIds = startMediaIds;
return this;
}
public UserBuilder<TParent> WithSuffix(string suffix)
{
_suffix = suffix;
return this;
}
public UserGroupBuilder<UserBuilder<TParent>> AddUserGroup()
{
var builder = new UserGroupBuilder<UserBuilder<TParent>>(this);
_userGroupBuilders.Add(builder);
return builder;
}
public override User Build()
{
var id = _id ?? 0;
var defaultLang = _defaultLang ?? "en";
var globalSettings = new GlobalSettings { DefaultUILanguage = defaultLang };
Guid key = _key ?? Guid.NewGuid();
DateTime createDate = _createDate ?? DateTime.Now;
DateTime updateDate = _updateDate ?? DateTime.Now;
var name = _name ?? "TestUser" + _suffix;
var language = _language ?? globalSettings.DefaultUILanguage;
var username = _username ?? "TestUser" + _suffix;
var email = _email ?? "test" + _suffix + "@test.com";
var rawPasswordValue = _rawPasswordValue ?? "abcdefghijklmnopqrstuvwxyz";
var failedPasswordAttempts = _failedPasswordAttempts ?? 0;
var isApproved = _isApproved ?? false;
var isLockedOut = _isLockedOut ?? false;
DateTime lastLockoutDate = _lastLockoutDate ?? DateTime.Now;
DateTime lastLoginDate = _lastLoginDate ?? DateTime.Now;
DateTime lastPasswordChangeDate = _lastPasswordChangeDate ?? DateTime.Now;
var comments = _comments ?? string.Empty;
var sessionTimeout = _sessionTimeout ?? 0;
var startContentIds = _startContentIds ?? new[] { -1 };
var startMediaIds = _startMediaIds ?? new[] { -1 };
IEnumerable<IUserGroup> groups = _userGroupBuilders.Select(x => x.Build());
var result = new User(
globalSettings,
name,
email,
username,
rawPasswordValue)
{
Id = id,
Key = key,
CreateDate = createDate,
UpdateDate = updateDate,
Language = language,
FailedPasswordAttempts = failedPasswordAttempts,
IsApproved = isApproved,
IsLockedOut = isLockedOut,
LastLockoutDate = lastLockoutDate,
LastLoginDate = lastLoginDate,
LastPasswordChangeDate = lastPasswordChangeDate,
Comments = comments,
SessionTimeout = sessionTimeout,
StartContentIds = startContentIds,
StartMediaIds = startMediaIds,
};
foreach (IUserGroup readOnlyUserGroup in groups)
{
result.AddGroup(readOnlyUserGroup.ToReadOnlyGroup());
}
return result;
}
public static IEnumerable<IUser> CreateMulipleUsers(int amount, Action<int, IUser> onCreating = null)
{
var list = new List<IUser>();
for (var i = 0; i < amount; i++)
{
var name = "User No-" + i;
User user = new UserBuilder()
.WithName(name)
.WithEmail("test" + i + "@test.com")
.WithLogin("test" + i, "test" + i)
.Build();
onCreating?.Invoke(i, user);
user.ResetDirtyProperties(false);
list.Add(user);
}
return list;
}
public static User CreateUser(string suffix = "") =>
new UserBuilder()
.WithIsApproved(true)
.WithName("TestUser" + suffix)
.WithLogin("TestUser" + suffix, "testing")
.WithEmail("test" + suffix + "@test.com")
.Build();
int? IWithIdBuilder.Id
{
get => _id;
set => _id = value;
}
string IWithNameBuilder.Name
{
get => _name;
set => _name = value;
}
string IWithLoginBuilder.Username
{
get => _username;
set => _username = value;
}
string IWithLoginBuilder.RawPasswordValue
{
get => _rawPasswordValue;
set => _rawPasswordValue = value;
}
string IWithLoginBuilder.PasswordConfig
{
get => _passwordConfig;
set => _passwordConfig = value;
}
string IWithEmailBuilder.Email
{
get => _email;
set => _email = value;
}
int? IWithFailedPasswordAttemptsBuilder.FailedPasswordAttempts
{
get => _failedPasswordAttempts;
set => _failedPasswordAttempts = value;
}
bool? IWithIsApprovedBuilder.IsApproved
{
get => _isApproved;
set => _isApproved = value;
}
bool? IWithIsLockedOutBuilder.IsLockedOut
{
get => _isLockedOut;
set => _isLockedOut = value;
}
DateTime? IWithIsLockedOutBuilder.LastLockoutDate
{
get => _lastLockoutDate;
set => _lastLockoutDate = value;
}
DateTime? IWithLastLoginDateBuilder.LastLoginDate
{
get => _lastLoginDate;
set => _lastLoginDate = value;
}
DateTime? IWithLastPasswordChangeDateBuilder.LastPasswordChangeDate
{
get => _lastPasswordChangeDate;
set => _lastPasswordChangeDate = value;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Drawing.Imaging
{
using System.Runtime.InteropServices;
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[StructLayout(LayoutKind.Sequential)]
public sealed class EncoderParameter : IDisposable
{
#pragma warning disable CS0618 // Legacy code: We don't care about using obsolete API's.
[MarshalAs(UnmanagedType.Struct)]
#pragma warning restore CS0618
private Guid _parameterGuid; // GUID of the parameter
private int _numberOfValues; // Number of the parameter values
private EncoderParameterValueType _parameterValueType; // Value type, like ValueTypeLONG etc.
private IntPtr _parameterValue; // A pointer to the parameter values
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.Finalize"]/*' />
~EncoderParameter()
{
Dispose(false);
}
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.Encoder"]/*' />
/// <devdoc>
/// Gets/Sets the Encoder for the EncoderPameter.
/// </devdoc>
public Encoder Encoder
{
get
{
return new Encoder(_parameterGuid);
}
set
{
_parameterGuid = value.Guid;
}
}
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.Type"]/*' />
/// <devdoc>
/// Gets the EncoderParameterValueType object from the EncoderParameter.
/// </devdoc>
public EncoderParameterValueType Type
{
get
{
return _parameterValueType;
}
}
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.ValueType"]/*' />
/// <devdoc>
/// Gets the EncoderParameterValueType object from the EncoderParameter.
/// </devdoc>
public EncoderParameterValueType ValueType
{
get
{
return _parameterValueType;
}
}
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.NumberOfValues"]/*' />
/// <devdoc>
/// Gets the NumberOfValues from the EncoderParameter.
/// </devdoc>
public int NumberOfValues
{
get
{
return _numberOfValues;
}
}
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.Dispose"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Dispose()
{
Dispose(true);
GC.KeepAlive(this);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (_parameterValue != IntPtr.Zero)
Marshal.FreeHGlobal(_parameterValue);
_parameterValue = IntPtr.Zero;
}
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.EncoderParameter"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public EncoderParameter(Encoder encoder, byte value)
{
_parameterGuid = encoder.Guid;
_parameterValueType = EncoderParameterValueType.ValueTypeByte;
_numberOfValues = 1;
_parameterValue = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Byte)));
if (_parameterValue == IntPtr.Zero)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory);
Marshal.WriteByte(_parameterValue, value);
GC.KeepAlive(this);
}
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.EncoderParameter1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public EncoderParameter(Encoder encoder, byte value, bool undefined)
{
_parameterGuid = encoder.Guid;
if (undefined == true)
_parameterValueType = EncoderParameterValueType.ValueTypeUndefined;
else
_parameterValueType = EncoderParameterValueType.ValueTypeByte;
_numberOfValues = 1;
_parameterValue = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Byte)));
if (_parameterValue == IntPtr.Zero)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory);
Marshal.WriteByte(_parameterValue, value);
GC.KeepAlive(this);
}
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.EncoderParameter2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public EncoderParameter(Encoder encoder, short value)
{
_parameterGuid = encoder.Guid;
_parameterValueType = EncoderParameterValueType.ValueTypeShort;
_numberOfValues = 1;
_parameterValue = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Int16)));
if (_parameterValue == IntPtr.Zero)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory);
Marshal.WriteInt16(_parameterValue, value);
GC.KeepAlive(this);
}
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.EncoderParameter3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public EncoderParameter(Encoder encoder, long value)
{
_parameterGuid = encoder.Guid;
_parameterValueType = EncoderParameterValueType.ValueTypeLong;
_numberOfValues = 1;
_parameterValue = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Int32)));
if (_parameterValue == IntPtr.Zero)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory);
Marshal.WriteInt32(_parameterValue, unchecked((int)value));
GC.KeepAlive(this);
}
// Consider supporting a 'float' and converting to numerator/denominator
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.EncoderParameter4"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public EncoderParameter(Encoder encoder, int numerator, int denominator)
{
_parameterGuid = encoder.Guid;
_parameterValueType = EncoderParameterValueType.ValueTypeRational;
_numberOfValues = 1;
int size = Marshal.SizeOf(typeof(Int32));
_parameterValue = Marshal.AllocHGlobal(2 * size);
if (_parameterValue == IntPtr.Zero)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory);
Marshal.WriteInt32(_parameterValue, numerator);
Marshal.WriteInt32(Add(_parameterValue, size), denominator);
GC.KeepAlive(this);
}
// Consider supporting a 'float' and converting to numerator/denominator
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.EncoderParameter5"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public EncoderParameter(Encoder encoder, long rangebegin, long rangeend)
{
_parameterGuid = encoder.Guid;
_parameterValueType = EncoderParameterValueType.ValueTypeLongRange;
_numberOfValues = 1;
int size = Marshal.SizeOf(typeof(Int32));
_parameterValue = Marshal.AllocHGlobal(2 * size);
if (_parameterValue == IntPtr.Zero)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory);
Marshal.WriteInt32(_parameterValue, unchecked((int)rangebegin));
Marshal.WriteInt32(Add(_parameterValue, size), unchecked((int)rangeend));
GC.KeepAlive(this);
}
// Consider supporting a 'float' and converting to numerator/denominator
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.EncoderParameter6"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public EncoderParameter(Encoder encoder,
int numerator1, int demoninator1,
int numerator2, int demoninator2)
{
_parameterGuid = encoder.Guid;
_parameterValueType = EncoderParameterValueType.ValueTypeRationalRange;
_numberOfValues = 1;
int size = Marshal.SizeOf(typeof(Int32));
_parameterValue = Marshal.AllocHGlobal(4 * size);
if (_parameterValue == IntPtr.Zero)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory);
Marshal.WriteInt32(_parameterValue, numerator1);
Marshal.WriteInt32(Add(_parameterValue, size), demoninator1);
Marshal.WriteInt32(Add(_parameterValue, 2 * size), numerator2);
Marshal.WriteInt32(Add(_parameterValue, 3 * size), demoninator2);
GC.KeepAlive(this);
}
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.EncoderParameter7"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public EncoderParameter(Encoder encoder, string value)
{
_parameterGuid = encoder.Guid;
_parameterValueType = EncoderParameterValueType.ValueTypeAscii;
_numberOfValues = value.Length;
_parameterValue = Marshal.StringToHGlobalAnsi(value);
GC.KeepAlive(this);
if (_parameterValue == IntPtr.Zero)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory);
}
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.EncoderParameter8"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public EncoderParameter(Encoder encoder, byte[] value)
{
_parameterGuid = encoder.Guid;
_parameterValueType = EncoderParameterValueType.ValueTypeByte;
_numberOfValues = value.Length;
_parameterValue = Marshal.AllocHGlobal(_numberOfValues);
if (_parameterValue == IntPtr.Zero)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory);
Marshal.Copy(value, 0, _parameterValue, _numberOfValues);
GC.KeepAlive(this);
}
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.EncoderParameter9"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public EncoderParameter(Encoder encoder, byte[] value, bool undefined)
{
_parameterGuid = encoder.Guid;
if (undefined == true)
_parameterValueType = EncoderParameterValueType.ValueTypeUndefined;
else
_parameterValueType = EncoderParameterValueType.ValueTypeByte;
_numberOfValues = value.Length;
_parameterValue = Marshal.AllocHGlobal(_numberOfValues);
if (_parameterValue == IntPtr.Zero)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory);
Marshal.Copy(value, 0, _parameterValue, _numberOfValues);
GC.KeepAlive(this);
}
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.EncoderParameter10"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public EncoderParameter(Encoder encoder, short[] value)
{
_parameterGuid = encoder.Guid;
_parameterValueType = EncoderParameterValueType.ValueTypeShort;
_numberOfValues = value.Length;
int size = Marshal.SizeOf(typeof(short));
_parameterValue = Marshal.AllocHGlobal(checked(_numberOfValues * size));
if (_parameterValue == IntPtr.Zero)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory);
Marshal.Copy(value, 0, _parameterValue, _numberOfValues);
GC.KeepAlive(this);
}
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.EncoderParameter11"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public unsafe EncoderParameter(Encoder encoder, long[] value)
{
_parameterGuid = encoder.Guid;
_parameterValueType = EncoderParameterValueType.ValueTypeLong;
_numberOfValues = value.Length;
int size = Marshal.SizeOf(typeof(Int32));
_parameterValue = Marshal.AllocHGlobal(checked(_numberOfValues * size));
if (_parameterValue == IntPtr.Zero)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory);
int* dest = (int*)_parameterValue;
fixed (long* source = value)
{
for (int i = 0; i < value.Length; i++)
{
dest[i] = unchecked((int)source[i]);
}
}
GC.KeepAlive(this);
}
// Consider supporting a 'float' and converting to numerator/denominator
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.EncoderParameter12"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public EncoderParameter(Encoder encoder, int[] numerator, int[] denominator)
{
_parameterGuid = encoder.Guid;
if (numerator.Length != denominator.Length)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter);
_parameterValueType = EncoderParameterValueType.ValueTypeRational;
_numberOfValues = numerator.Length;
int size = Marshal.SizeOf(typeof(Int32));
_parameterValue = Marshal.AllocHGlobal(checked(_numberOfValues * 2 * size));
if (_parameterValue == IntPtr.Zero)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory);
for (int i = 0; i < _numberOfValues; i++)
{
Marshal.WriteInt32(Add(i * 2 * size, _parameterValue), (int)numerator[i]);
Marshal.WriteInt32(Add((i * 2 + 1) * size, _parameterValue), (int)denominator[i]);
}
GC.KeepAlive(this);
}
// Consider supporting a 'float' and converting to numerator/denominator
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.EncoderParameter13"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public EncoderParameter(Encoder encoder, long[] rangebegin, long[] rangeend)
{
_parameterGuid = encoder.Guid;
if (rangebegin.Length != rangeend.Length)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter);
_parameterValueType = EncoderParameterValueType.ValueTypeLongRange;
_numberOfValues = rangebegin.Length;
int size = Marshal.SizeOf(typeof(Int32));
_parameterValue = Marshal.AllocHGlobal(checked(_numberOfValues * 2 * size));
if (_parameterValue == IntPtr.Zero)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory);
for (int i = 0; i < _numberOfValues; i++)
{
Marshal.WriteInt32(Add(i * 2 * size, _parameterValue), unchecked((int)rangebegin[i]));
Marshal.WriteInt32(Add((i * 2 + 1) * size, _parameterValue), unchecked((int)rangeend[i]));
}
GC.KeepAlive(this);
}
// Consider supporting a 'float' and converting to numerator/denominator
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.EncoderParameter14"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public EncoderParameter(Encoder encoder,
int[] numerator1, int[] denominator1,
int[] numerator2, int[] denominator2)
{
_parameterGuid = encoder.Guid;
if (numerator1.Length != denominator1.Length ||
numerator1.Length != denominator2.Length ||
denominator1.Length != denominator2.Length)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter);
_parameterValueType = EncoderParameterValueType.ValueTypeRationalRange;
_numberOfValues = numerator1.Length;
int size = Marshal.SizeOf(typeof(Int32));
_parameterValue = Marshal.AllocHGlobal(checked(_numberOfValues * 4 * size));
if (_parameterValue == IntPtr.Zero)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory);
for (int i = 0; i < _numberOfValues; i++)
{
Marshal.WriteInt32(Add(_parameterValue, 4 * i * size), numerator1[i]);
Marshal.WriteInt32(Add(_parameterValue, (4 * i + 1) * size), denominator1[i]);
Marshal.WriteInt32(Add(_parameterValue, (4 * i + 2) * size), numerator2[i]);
Marshal.WriteInt32(Add(_parameterValue, (4 * i + 3) * size), denominator2[i]);
}
GC.KeepAlive(this);
}
// Consider supporting a 'float' and converting to numerator/denominator
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.EncoderParameter15"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[Obsolete("This constructor has been deprecated. Use EncoderParameter(Encoder encoder, int numberValues, EncoderParameterValueType type, IntPtr value) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public EncoderParameter(Encoder encoder, int NumberOfValues, int Type, int Value)
{
int size;
switch ((EncoderParameterValueType)Type)
{
case EncoderParameterValueType.ValueTypeByte:
case EncoderParameterValueType.ValueTypeAscii: size = 1; break;
case EncoderParameterValueType.ValueTypeShort: size = 2; break;
case EncoderParameterValueType.ValueTypeLong: size = 4; break;
case EncoderParameterValueType.ValueTypeRational:
case EncoderParameterValueType.ValueTypeLongRange: size = 2 * 4; break;
case EncoderParameterValueType.ValueTypeUndefined: size = 1; break;
case EncoderParameterValueType.ValueTypeRationalRange: size = 2 * 2 * 4; break;
default:
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.WrongState);
}
int bytes = checked(size * NumberOfValues);
_parameterValue = Marshal.AllocHGlobal(bytes);
if (_parameterValue == IntPtr.Zero)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory);
for (int i = 0; i < bytes; i++)
{
Marshal.WriteByte(Add(_parameterValue, i), Marshal.ReadByte((IntPtr)(Value + i)));
}
_parameterValueType = (EncoderParameterValueType)Type;
_numberOfValues = NumberOfValues;
_parameterGuid = encoder.Guid;
GC.KeepAlive(this);
}
/// <include file='doc\EncoderParameter.uex' path='docs/doc[@for="EncoderParameter.EncoderParameter16"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")]
public EncoderParameter(Encoder encoder, int numberValues, EncoderParameterValueType type, IntPtr value)
{
int size;
switch (type)
{
case EncoderParameterValueType.ValueTypeByte:
case EncoderParameterValueType.ValueTypeAscii: size = 1; break;
case EncoderParameterValueType.ValueTypeShort: size = 2; break;
case EncoderParameterValueType.ValueTypeLong: size = 4; break;
case EncoderParameterValueType.ValueTypeRational:
case EncoderParameterValueType.ValueTypeLongRange: size = 2 * 4; break;
case EncoderParameterValueType.ValueTypeUndefined: size = 1; break;
case EncoderParameterValueType.ValueTypeRationalRange: size = 2 * 2 * 4; break;
default:
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.WrongState);
}
int bytes = checked(size * numberValues);
_parameterValue = Marshal.AllocHGlobal(bytes);
if (_parameterValue == IntPtr.Zero)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory);
for (int i = 0; i < bytes; i++)
{
Marshal.WriteByte(Add(_parameterValue, i), Marshal.ReadByte((IntPtr)(value + i)));
}
_parameterValueType = type;
_numberOfValues = numberValues;
_parameterGuid = encoder.Guid;
GC.KeepAlive(this);
}
private static IntPtr Add(IntPtr a, int b)
{
return (IntPtr)((long)a + (long)b);
}
private static IntPtr Add(int a, IntPtr b)
{
return (IntPtr)((long)a + (long)b);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Examples.Sql
{
using System;
using System.Linq;
using Apache.Ignite.Core;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Affinity;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.ExamplesDll.Binary;
using Apache.Ignite.Linq;
/// <summary>
/// This example populates cache with sample data and runs several LINQ queries over this data.
/// <para />
/// 1) Build the project Apache.Ignite.ExamplesDll (select it -> right-click -> Build).
/// 2) Set this class as startup object (Apache.Ignite.Examples project -> right-click -> Properties ->
/// Application -> Startup object);
/// 3) Start example (F5 or Ctrl+F5).
/// <para />
/// This example can be run with standalone Apache Ignite.NET node:
/// 1) Run %IGNITE_HOME%/platforms/dotnet/bin/Apache.Ignite.exe:
/// Apache.Ignite.exe -configFileName=platforms\dotnet\examples\apache.ignite.examples\app.config
/// 2) Start example.
/// </summary>
public class LinqExample
{
/// <summary>Organization cache name.</summary>
private const string OrganizationCacheName = "dotnet_cache_query_organization";
/// <summary>Employee cache name.</summary>
private const string EmployeeCacheName = "dotnet_cache_query_employee";
/// <summary>Colocated employee cache name.</summary>
private const string EmployeeCacheNameColocated = "dotnet_cache_query_employee_colocated";
[STAThread]
public static void Main()
{
using (var ignite = Ignition.StartFromApplicationConfiguration())
{
Console.WriteLine();
Console.WriteLine(">>> Cache LINQ example started.");
var employeeCache = ignite.GetOrCreateCache<int, Employee>(
new CacheConfiguration(EmployeeCacheName, typeof(Employee)));
var employeeCacheColocated = ignite.GetOrCreateCache<AffinityKey, Employee>(
new CacheConfiguration(EmployeeCacheNameColocated, typeof(Employee)));
var organizationCache = ignite.GetOrCreateCache<int, Organization>(
new CacheConfiguration(OrganizationCacheName, new QueryEntity(typeof(int), typeof(Organization))));
// Populate cache with sample data entries.
PopulateCache(employeeCache);
PopulateCache(employeeCacheColocated);
PopulateCache(organizationCache);
// Run SQL query example.
QueryExample(employeeCache);
// Run compiled SQL query example.
CompiledQueryExample(employeeCache);
// Run SQL query with join example.
JoinQueryExample(employeeCacheColocated, organizationCache);
// Run SQL query with distributed join example.
DistributedJoinQueryExample(employeeCache, organizationCache);
// Run SQL fields query example.
FieldsQueryExample(employeeCache);
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine(">>> Example finished, press any key to exit ...");
Console.ReadKey();
}
/// <summary>
/// Queries employees that have provided ZIP code in address.
/// </summary>
/// <param name="cache">Cache.</param>
private static void QueryExample(ICache<int, Employee> cache)
{
const int zip = 94109;
IQueryable<ICacheEntry<int, Employee>> qry =
cache.AsCacheQueryable().Where(emp => emp.Value.Address.Zip == zip);
Console.WriteLine();
Console.WriteLine(">>> Employees with zipcode " + zip + ":");
foreach (ICacheEntry<int, Employee> entry in qry)
Console.WriteLine(">>> " + entry.Value);
}
/// <summary>
/// Queries employees that have provided ZIP code in address with a compiled query.
/// </summary>
/// <param name="cache">Cache.</param>
private static void CompiledQueryExample(ICache<int, Employee> cache)
{
const int zip = 94109;
var cache0 = cache.AsCacheQueryable();
// Compile cache query to eliminate LINQ overhead on multiple runs.
Func<int, IQueryCursor<ICacheEntry<int, Employee>>> qry =
CompiledQuery.Compile((int z) => cache0.Where(emp => emp.Value.Address.Zip == z));
Console.WriteLine();
Console.WriteLine(">>> Employees with zipcode {0} using compiled query:", zip);
foreach (ICacheEntry<int, Employee> entry in qry(zip))
Console.WriteLine(">>> " + entry.Value);
}
/// <summary>
/// Queries employees that work for organization with provided name.
/// </summary>
/// <param name="employeeCache">Employee cache.</param>
/// <param name="organizationCache">Organization cache.</param>
private static void JoinQueryExample(ICache<AffinityKey, Employee> employeeCache,
ICache<int, Organization> organizationCache)
{
const string orgName = "Apache";
IQueryable<ICacheEntry<AffinityKey, Employee>> employees = employeeCache.AsCacheQueryable();
IQueryable<ICacheEntry<int, Organization>> organizations = organizationCache.AsCacheQueryable();
IQueryable<ICacheEntry<AffinityKey, Employee>> qry =
from employee in employees
from organization in organizations
where employee.Value.OrganizationId == organization.Key && organization.Value.Name == orgName
select employee;
Console.WriteLine();
Console.WriteLine(">>> Employees working for " + orgName + ":");
foreach (ICacheEntry<AffinityKey, Employee> entry in qry)
Console.WriteLine(">>> " + entry.Value);
}
/// <summary>
/// Queries employees that work for organization with provided name.
/// </summary>
/// <param name="employeeCache">Employee cache.</param>
/// <param name="organizationCache">Organization cache.</param>
private static void DistributedJoinQueryExample(ICache<int, Employee> employeeCache,
ICache<int, Organization> organizationCache)
{
const string orgName = "Apache";
var queryOptions = new QueryOptions {EnableDistributedJoins = true};
IQueryable<ICacheEntry<int, Employee>> employees = employeeCache.AsCacheQueryable(queryOptions);
IQueryable<ICacheEntry<int, Organization>> organizations = organizationCache.AsCacheQueryable(queryOptions);
IQueryable<ICacheEntry<int, Employee>> qry =
from employee in employees
from organization in organizations
where employee.Value.OrganizationId == organization.Key && organization.Value.Name == orgName
select employee;
Console.WriteLine();
Console.WriteLine(">>> Employees working for " + orgName + ":");
foreach (ICacheEntry<int, Employee> entry in qry)
Console.WriteLine(">>> " + entry.Value);
}
/// <summary>
/// Queries names and salaries for all employees.
/// </summary>
/// <param name="cache">Cache.</param>
private static void FieldsQueryExample(ICache<int, Employee> cache)
{
var qry = cache.AsCacheQueryable().Select(entry => new {entry.Value.Name, entry.Value.Salary});
Console.WriteLine();
Console.WriteLine(">>> Employee names and their salaries:");
foreach (var row in qry)
Console.WriteLine(">>> [Name=" + row.Name + ", salary=" + row.Salary + ']');
}
/// <summary>
/// Populate cache with data for this example.
/// </summary>
/// <param name="cache">Cache.</param>
private static void PopulateCache(ICache<int, Organization> cache)
{
cache.Put(1, new Organization(
"Apache",
new Address("1065 East Hillsdale Blvd, Foster City, CA", 94404),
OrganizationType.Private,
DateTime.Now));
cache.Put(2, new Organization(
"Microsoft",
new Address("1096 Eddy Street, San Francisco, CA", 94109),
OrganizationType.Private,
DateTime.Now));
}
/// <summary>
/// Populate cache with data for this example.
/// </summary>
/// <param name="cache">Cache.</param>
private static void PopulateCache(ICache<AffinityKey, Employee> cache)
{
cache.Put(new AffinityKey(1, 1), new Employee(
"James Wilson",
12500,
new Address("1096 Eddy Street, San Francisco, CA", 94109),
new[] {"Human Resources", "Customer Service"},
1));
cache.Put(new AffinityKey(2, 1), new Employee(
"Daniel Adams",
11000,
new Address("184 Fidler Drive, San Antonio, TX", 78130),
new[] {"Development", "QA"},
1));
cache.Put(new AffinityKey(3, 1), new Employee(
"Cristian Moss",
12500,
new Address("667 Jerry Dove Drive, Florence, SC", 29501),
new[] {"Logistics"},
1));
cache.Put(new AffinityKey(4, 2), new Employee(
"Allison Mathis",
25300,
new Address("2702 Freedom Lane, San Francisco, CA", 94109),
new[] {"Development"},
2));
cache.Put(new AffinityKey(5, 2), new Employee(
"Breana Robbin",
6500,
new Address("3960 Sundown Lane, Austin, TX", 78130),
new[] {"Sales"},
2));
cache.Put(new AffinityKey(6, 2), new Employee(
"Philip Horsley",
19800,
new Address("2803 Elsie Drive, Sioux Falls, SD", 57104),
new[] {"Sales"},
2));
cache.Put(new AffinityKey(7, 2), new Employee(
"Brian Peters",
10600,
new Address("1407 Pearlman Avenue, Boston, MA", 12110),
new[] {"Development", "QA"},
2));
}
/// <summary>
/// Populate cache with data for this example.
/// </summary>
/// <param name="cache">Cache.</param>
private static void PopulateCache(ICache<int, Employee> cache)
{
cache.Put(1, new Employee(
"James Wilson",
12500,
new Address("1096 Eddy Street, San Francisco, CA", 94109),
new[] {"Human Resources", "Customer Service"},
1));
cache.Put(2, new Employee(
"Daniel Adams",
11000,
new Address("184 Fidler Drive, San Antonio, TX", 78130),
new[] {"Development", "QA"},
1));
cache.Put(3, new Employee(
"Cristian Moss",
12500,
new Address("667 Jerry Dove Drive, Florence, SC", 29501),
new[] {"Logistics"},
1));
cache.Put(4, new Employee(
"Allison Mathis",
25300,
new Address("2702 Freedom Lane, San Francisco, CA", 94109),
new[] {"Development"},
2));
cache.Put(5, new Employee(
"Breana Robbin",
6500,
new Address("3960 Sundown Lane, Austin, TX", 78130),
new[] {"Sales"},
2));
cache.Put(6, new Employee(
"Philip Horsley",
19800,
new Address("2803 Elsie Drive, Sioux Falls, SD", 57104),
new[] {"Sales"},
2));
cache.Put(7, new Employee(
"Brian Peters",
10600,
new Address("1407 Pearlman Avenue, Boston, MA", 12110),
new[] {"Development", "QA"},
2));
}
}
}
| |
// 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 gagvr = Google.Ads.GoogleAds.V10.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>DetailedDemographic</c> resource.</summary>
public sealed partial class DetailedDemographicName : gax::IResourceName, sys::IEquatable<DetailedDemographicName>
{
/// <summary>The possible contents of <see cref="DetailedDemographicName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/detailedDemographics/{detailed_demographic_id}</c>
/// .
/// </summary>
CustomerDetailedDemographic = 1,
}
private static gax::PathTemplate s_customerDetailedDemographic = new gax::PathTemplate("customers/{customer_id}/detailedDemographics/{detailed_demographic_id}");
/// <summary>Creates a <see cref="DetailedDemographicName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="DetailedDemographicName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static DetailedDemographicName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new DetailedDemographicName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="DetailedDemographicName"/> with the pattern
/// <c>customers/{customer_id}/detailedDemographics/{detailed_demographic_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="detailedDemographicId">
/// The <c>DetailedDemographic</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// A new instance of <see cref="DetailedDemographicName"/> constructed from the provided ids.
/// </returns>
public static DetailedDemographicName FromCustomerDetailedDemographic(string customerId, string detailedDemographicId) =>
new DetailedDemographicName(ResourceNameType.CustomerDetailedDemographic, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), detailedDemographicId: gax::GaxPreconditions.CheckNotNullOrEmpty(detailedDemographicId, nameof(detailedDemographicId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="DetailedDemographicName"/> with pattern
/// <c>customers/{customer_id}/detailedDemographics/{detailed_demographic_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="detailedDemographicId">
/// The <c>DetailedDemographic</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="DetailedDemographicName"/> with pattern
/// <c>customers/{customer_id}/detailedDemographics/{detailed_demographic_id}</c>.
/// </returns>
public static string Format(string customerId, string detailedDemographicId) =>
FormatCustomerDetailedDemographic(customerId, detailedDemographicId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="DetailedDemographicName"/> with pattern
/// <c>customers/{customer_id}/detailedDemographics/{detailed_demographic_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="detailedDemographicId">
/// The <c>DetailedDemographic</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="DetailedDemographicName"/> with pattern
/// <c>customers/{customer_id}/detailedDemographics/{detailed_demographic_id}</c>.
/// </returns>
public static string FormatCustomerDetailedDemographic(string customerId, string detailedDemographicId) =>
s_customerDetailedDemographic.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(detailedDemographicId, nameof(detailedDemographicId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="DetailedDemographicName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/detailedDemographics/{detailed_demographic_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="detailedDemographicName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="DetailedDemographicName"/> if successful.</returns>
public static DetailedDemographicName Parse(string detailedDemographicName) => Parse(detailedDemographicName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="DetailedDemographicName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/detailedDemographics/{detailed_demographic_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="detailedDemographicName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="DetailedDemographicName"/> if successful.</returns>
public static DetailedDemographicName Parse(string detailedDemographicName, bool allowUnparsed) =>
TryParse(detailedDemographicName, allowUnparsed, out DetailedDemographicName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="DetailedDemographicName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/detailedDemographics/{detailed_demographic_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="detailedDemographicName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="DetailedDemographicName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string detailedDemographicName, out DetailedDemographicName result) =>
TryParse(detailedDemographicName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="DetailedDemographicName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/detailedDemographics/{detailed_demographic_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="detailedDemographicName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="DetailedDemographicName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string detailedDemographicName, bool allowUnparsed, out DetailedDemographicName result)
{
gax::GaxPreconditions.CheckNotNull(detailedDemographicName, nameof(detailedDemographicName));
gax::TemplatedResourceName resourceName;
if (s_customerDetailedDemographic.TryParseName(detailedDemographicName, out resourceName))
{
result = FromCustomerDetailedDemographic(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(detailedDemographicName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private DetailedDemographicName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string detailedDemographicId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
DetailedDemographicId = detailedDemographicId;
}
/// <summary>
/// Constructs a new instance of a <see cref="DetailedDemographicName"/> class from the component parts of
/// pattern <c>customers/{customer_id}/detailedDemographics/{detailed_demographic_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="detailedDemographicId">
/// The <c>DetailedDemographic</c> ID. Must not be <c>null</c> or empty.
/// </param>
public DetailedDemographicName(string customerId, string detailedDemographicId) : this(ResourceNameType.CustomerDetailedDemographic, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), detailedDemographicId: gax::GaxPreconditions.CheckNotNullOrEmpty(detailedDemographicId, nameof(detailedDemographicId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>DetailedDemographic</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed
/// resource name.
/// </summary>
public string DetailedDemographicId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerDetailedDemographic: return s_customerDetailedDemographic.Expand(CustomerId, DetailedDemographicId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as DetailedDemographicName);
/// <inheritdoc/>
public bool Equals(DetailedDemographicName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(DetailedDemographicName a, DetailedDemographicName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(DetailedDemographicName a, DetailedDemographicName b) => !(a == b);
}
public partial class DetailedDemographic
{
/// <summary>
/// <see cref="gagvr::DetailedDemographicName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal DetailedDemographicName ResourceNameAsDetailedDemographicName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::DetailedDemographicName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::DetailedDemographicName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
internal DetailedDemographicName DetailedDemographicName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::DetailedDemographicName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::DetailedDemographicName"/>-typed view over the <see cref="Parent"/> resource name
/// property.
/// </summary>
internal DetailedDemographicName ParentAsDetailedDemographicName
{
get => string.IsNullOrEmpty(Parent) ? null : gagvr::DetailedDemographicName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
}
| |
using System;
namespace Org.BouncyCastle.Math.EC
{
public class F2MFieldElement : ECFieldElement
{
/**
* Indicates gaussian normal basis representation (GNB). Number chosen
* according to X9.62. GNB is not implemented at present.
*/
public const int Gnb = 1;
/**
* Indicates trinomial basis representation (Tpb). Number chosen
* according to X9.62.
*/
public const int Tpb = 2;
/**
* Indicates pentanomial basis representation (Ppb). Number chosen
* according to X9.62.
*/
public const int Ppb = 3;
/**
* Tpb or Ppb.
*/
private readonly int _representation;
/**
* The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>.
*/
private readonly int _m;
/**
* Tpb: The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction polynomial
* <code>f(z)</code>.<br/>
* Ppb: The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br/>
*/
private readonly int _k1;
/**
* Tpb: Always set to <code>0</code><br/>
* Ppb: The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br/>
*/
private readonly int _k2;
/**
* Tpb: Always set to <code>0</code><br/>
* Ppb: The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br/>
*/
private readonly int _k3;
/**
* The <code>IntArray</code> holding the bits.
*/
private readonly IntArray _x;
/**
* The number of <code>int</code>s required to hold <code>m</code> bits.
*/
private readonly int _t;
/**
* Constructor for Ppb.
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param x The IBigInteger representing the value of the field element.
*/
public F2MFieldElement(int m, int k1, int k2, int k3, IBigInteger x)
{
// t = m / 32 rounded up to the next integer
_t = (m + 31) >> 5;
_x = new IntArray(x, _t);
if ((k2 == 0) && (k3 == 0))
{
_representation = Tpb;
}
else
{
if (k2 >= k3)
throw new ArgumentException("k2 must be smaller than k3");
if (k2 <= 0)
throw new ArgumentException("k2 must be larger than 0");
_representation = Ppb;
}
if (x.SignValue < 0)
throw new ArgumentException("x value cannot be negative");
_m = m;
_k1 = k1;
_k2 = k2;
_k3 = k3;
}
/**
* Constructor for Tpb.
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction
* polynomial <code>f(z)</code>.
* @param x The IBigInteger representing the value of the field element.
*/
public F2MFieldElement(int m, int k, IBigInteger x)
: this(m, k, 0, 0, x)
{
// Set k1 to k, and set k2 and k3 to 0
}
private F2MFieldElement(int m, int k1, int k2, int k3, IntArray x)
{
_t = (m + 31) >> 5;
_x = x;
_m = m;
_k1 = k1;
_k2 = k2;
_k3 = k3;
if ((k2 == 0) && (k3 == 0))
{
_representation = Tpb;
}
else
{
_representation = Ppb;
}
}
public override IBigInteger ToBigInteger()
{
return _x.ToBigInteger();
}
public override string FieldName
{
get { return "F2m"; }
}
public override int FieldSize
{
get { return _m; }
}
/**
* Checks, if the ECFieldElements <code>a</code> and <code>b</code>
* are elements of the same field <code>F<sub>2<sup>m</sup></sub></code>
* (having the same representation).
* @param a field element.
* @param b field element to be compared.
* @throws ArgumentException if <code>a</code> and <code>b</code>
* are not elements of the same field
* <code>F<sub>2<sup>m</sup></sub></code> (having the same
* representation).
*/
public static void CheckFieldElements(ECFieldElement a, ECFieldElement b)
{
if (!(a is F2MFieldElement) || !(b is F2MFieldElement))
{
throw new ArgumentException("Field elements are not "
+ "both instances of F2mFieldElement");
}
var aF2M = (F2MFieldElement)a;
var bF2M = (F2MFieldElement)b;
if ((aF2M._m != bF2M._m) || (aF2M._k1 != bF2M._k1) || (aF2M._k2 != bF2M._k2) || (aF2M._k3 != bF2M._k3))
{
throw new ArgumentException("Field elements are not "
+ "elements of the same field F2m");
}
if (aF2M._representation != bF2M._representation)
{
// Should never occur
throw new ArgumentException(
"One of the field "
+ "elements are not elements has incorrect representation");
}
}
public override ECFieldElement Add(ECFieldElement b)
{
// No check performed here for performance reasons. Instead the
// elements involved are checked in ECPoint.F2m
// checkFieldElements(this, b);
var iarrClone = _x.Copy();
var bF2M = (F2MFieldElement)b;
iarrClone.AddShifted(bF2M._x, 0);
return new F2MFieldElement(_m, _k1, _k2, _k3, iarrClone);
}
public override ECFieldElement Subtract(ECFieldElement b)
{
// Addition and subtraction are the same in F2m
return Add(b);
}
public override ECFieldElement Multiply(ECFieldElement b)
{
// Right-to-left comb multiplication in the IntArray
// Input: Binary polynomials a(z) and b(z) of degree at most m-1
// Output: c(z) = a(z) * b(z) mod f(z)
// No check performed here for performance reasons. Instead the
// elements involved are checked in ECPoint.F2m
// checkFieldElements(this, b);
var bF2M = (F2MFieldElement)b;
var mult = _x.Multiply(bF2M._x, _m);
mult.Reduce(_m, new[] { _k1, _k2, _k3 });
return new F2MFieldElement(_m, _k1, _k2, _k3, mult);
}
public override ECFieldElement Divide(ECFieldElement b)
{
// There may be more efficient implementations
var bInv = b.Invert();
return Multiply(bInv);
}
public override ECFieldElement Negate()
{
// -x == x holds for all x in F2m
return this;
}
public override ECFieldElement Square()
{
var squared = _x.Square(_m);
squared.Reduce(_m, new[] { _k1, _k2, _k3 });
return new F2MFieldElement(_m, _k1, _k2, _k3, squared);
}
public override ECFieldElement Invert()
{
// Inversion in F2m using the extended Euclidean algorithm
// Input: A nonzero polynomial a(z) of degree at most m-1
// Output: a(z)^(-1) mod f(z)
// u(z) := a(z)
var uz = _x.Copy();
// v(z) := f(z)
var vz = new IntArray(_t);
vz.SetBit(_m);
vz.SetBit(0);
vz.SetBit(this._k1);
if (this._representation == Ppb)
{
vz.SetBit(this._k2);
vz.SetBit(this._k3);
}
// g1(z) := 1, g2(z) := 0
var g1Z = new IntArray(_t);
g1Z.SetBit(0);
var g2Z = new IntArray(_t);
// while u != 0
while (uz.GetUsedLength() > 0)
// while (uz.bitLength() > 1)
{
// j := deg(u(z)) - deg(v(z))
var j = uz.BitLength - vz.BitLength;
// If j < 0 then: u(z) <-> v(z), g1(z) <-> g2(z), j := -j
if (j < 0)
{
var uzCopy = uz;
uz = vz;
vz = uzCopy;
var g1ZCopy = g1Z;
g1Z = g2Z;
g2Z = g1ZCopy;
j = -j;
}
// u(z) := u(z) + z^j * v(z)
// Note, that no reduction modulo f(z) is required, because
// deg(u(z) + z^j * v(z)) <= max(deg(u(z)), j + deg(v(z)))
// = max(deg(u(z)), deg(u(z)) - deg(v(z)) + deg(v(z))
// = deg(u(z))
// uz = uz.xor(vz.ShiftLeft(j));
// jInt = n / 32
var jInt = j >> 5;
// jInt = n % 32
var jBit = j & 0x1F;
var vzShift = vz.ShiftLeft(jBit);
uz.AddShifted(vzShift, jInt);
// g1(z) := g1(z) + z^j * g2(z)
// g1z = g1z.xor(g2z.ShiftLeft(j));
var g2ZShift = g2Z.ShiftLeft(jBit);
g1Z.AddShifted(g2ZShift, jInt);
}
return new F2MFieldElement(this._m, this._k1, this._k2, this._k3, g2Z);
}
public override ECFieldElement Sqrt()
{
throw new ArithmeticException("Not implemented");
}
/**
* @return the representation of the field
* <code>F<sub>2<sup>m</sup></sub></code>, either of
* {@link F2mFieldElement.Tpb} (trinomial
* basis representation) or
* {@link F2mFieldElement.Ppb} (pentanomial
* basis representation).
*/
public int Representation
{
get { return _representation; }
}
/**
* @return the degree <code>m</code> of the reduction polynomial
* <code>f(z)</code>.
*/
public int M
{
get { return _m; }
}
/**
* @return Tpb: The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction polynomial
* <code>f(z)</code>.<br/>
* Ppb: The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br/>
*/
public int K1
{
get { return _k1; }
}
/**
* @return Tpb: Always returns <code>0</code><br/>
* Ppb: The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br/>
*/
public int K2
{
get { return _k2; }
}
/**
* @return Tpb: Always set to <code>0</code><br/>
* Ppb: The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br/>
*/
public int K3
{
get { return _k3; }
}
public override bool Equals(object obj)
{
if (obj == this)
return true;
var other = obj as F2MFieldElement;
return other != null && Equals(other);
}
protected bool Equals(F2MFieldElement other)
{
return _m == other._m
&& _k1 == other._k1
&& _k2 == other._k2
&& _k3 == other._k3
&& _representation == other._representation
&& base.Equals(other);
}
public override int GetHashCode()
{
return _m.GetHashCode()
^ _k1.GetHashCode()
^ _k2.GetHashCode()
^ _k3.GetHashCode()
^ _representation.GetHashCode()
^ base.GetHashCode();
}
}
}
| |
using UnityEngine;
using Stratus;
using System.Collections.Generic;
using System;
namespace Stratus
{
/// <summary>
/// A library of functions common for game AI
/// </summary>
public static class StratusDetection
{
//------------------------------------------------------------------------/
// Enumerations
//------------------------------------------------------------------------/
public enum RelativeRange { Nearest, Farthest }
public enum ComparisonOperation { GreaterOrEqualThan, LesserThan }
//------------------------------------------------------------------------/
// Methods
//------------------------------------------------------------------------/
/// <summary>
/// Checks whether the target is in range
/// </summary>
/// <param name="source">The source object</param>
/// <param name="target">The target object</param>
/// <param name="range">The range at which we are checking</param>
/// <returns></returns>
public static bool CheckRange(Transform source, Transform target, float range)
{
return CheckRange(source, target.position, range);
}
/// <summary>
/// Checks whether the target is in range of the source
/// </summary>
/// <param name="source">The source object</param>
/// <param name="target">The target position</param>
/// <param name="range">The range at which we are checking</param>
/// <returns></returns>
public static bool CheckRange(Transform source, Vector3 target, float range)
{
float dist = Vector3.Distance(target, source.position);
bool inRange = (dist <= range);
//Trace.Script("Distance = " + dist);
return inRange;
}
/// <summary>
/// Checks whether the target is within the field of view of the source
/// </summary>
/// <returns></returns>
public static bool CheckFieldOfView(Transform source, Transform target, float fov)
{
// Compute the vector pointing from the source towards the target
Vector3 toTarget = target.position - source.position;
// If the dot product between the source and the target is less than the cosine
// of the field of view, the target is within it
var dot = Vector3.Dot(source.forward, toTarget.normalized);
if (dot > Mathf.Cos(Mathf.Deg2Rad * fov / 2f))
{
return true;
}
return false;
}
/// <summary>
/// Checks whether there is a direct line of sight between the source and the target
/// </summary>
/// <param name="source"></param>
/// <param name="target"></param>
/// <param name="range"></param>
/// <returns></returns>
public static bool CheckLineOfSight(Transform source, Transform target, float range)
{
return Physics.Raycast(source.position, source.position - target.position, range);
}
/// <summary>
/// Draws a field of view using Unity's 3D GUI
/// </summary>
/// <param name="source"></param>
/// <param name="fov"></param>
/// <param name="range"></param>
public static void DrawFieldOfView(Transform source, float fov, float range, Color color, bool fixRotation = false)
{
#if UNITY_EDITOR
UnityEditor.Handles.color = color;
Vector3 forward = source.forward;
if (fixRotation)
forward.y = 0f;
Vector3 vec = Quaternion.Euler(0f, -fov / 2f, 0f) * forward;
UnityEditor.Handles.DrawSolidArc(source.position, Vector3.up, vec, fov, range);
#endif
}
/// <summary>
/// Draws the range of an agent from its center as a disk
/// </summary>
/// <param name="source"></param>
/// <param name="range"></param>
/// <param name="color"></param>
public static void DrawRange(Transform source, float range, Color color)
{
#if UNITY_EDITOR
UnityEditor.Handles.color = color;
UnityEditor.Handles.DrawSolidDisc(source.position, Vector3.up, range);
#endif
}
/// <summary>
/// Given an array of available targets, finds the nearest or farthest target
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">The source object that is looking for targets</param>
/// <param name="targets">An array of possible targets</param>
/// <param name="relativeRange">Whether we are looking for the nearest or farthest target</param>
/// <param name="range">The maximum range between the source and any given target</param>
/// <returns></returns>
public static T FindTarget<T>(Transform source, T[] targets, RelativeRange relativeRange, float range = Mathf.Infinity) where T : MonoBehaviour
{
// Calculate distances to all targets
var distances = new Dictionary<float, T>();
foreach (var target in targets)
{
var dist = Vector3.Distance(source.position, target.transform.position);
// If the target is within range of the source
if (dist <= range)
distances.Add(dist, target);
}
// BRANCH:
// a.) Find the nearest target
if (relativeRange == RelativeRange.Nearest)
{
float nearestDist = Mathf.Infinity;
T nearestTarget = null;
foreach (var target in distances)
{
if (target.Key < nearestDist)
nearestTarget = target.Value;
}
return nearestTarget;
}
// b.) Find the farthest target
else if (relativeRange == RelativeRange.Farthest)
{
float farthestDist = Mathf.NegativeInfinity;
T farthestTarget = null;
foreach (var target in distances)
{
if (target.Key > farthestDist)
{
farthestTarget = target.Value;
}
}
return farthestTarget;
}
return null;
}
/// <summary>
/// Finds the nearest target from the source
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="targets"></param>
/// <param name="range"></param>
/// <returns></returns>
public static T FindNearestTarget<T>(Transform source, T[] targets, float range = Mathf.Infinity) where T : MonoBehaviour
{
// Calculate distances to all targets
var distances = CalculateDistances(source, targets, range);
// Find the nearest target
float nearestDist = Mathf.Infinity;
T nearestTarget = null;
foreach (var target in distances)
{
if (target.Key < nearestDist)
nearestTarget = target.Value;
}
return nearestTarget;
}
/// <summary>
/// Finds the farthest target from the source
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="targets"></param>
/// <param name="range"></param>
/// <returns></returns>
public static T FindFarthestTarget<T>(Transform source, T[] targets, float range = Mathf.Infinity) where T : MonoBehaviour
{
// Calculate distances to all targets
var distances = CalculateDistances(source, targets, range);
// Find the farthest target
float farthestDist = Mathf.NegativeInfinity;
T farthestTarget = null;
foreach (var target in distances)
{
if (target.Key > farthestDist)
{
farthestTarget = target.Value;
}
}
return farthestTarget;
}
/// <summary>
/// Finds the distances between the source and every available target
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="targets"></param>
/// <param name="range"></param>
/// <returns>A dictionary of float/target pairs.</returns>
public static List<KeyValuePair<float, T>> CalculateDistances<T>(Transform source, T[] targets, float range = Mathf.Infinity) where T : MonoBehaviour
{
// Calculate distances to all targets
var distances = new List<KeyValuePair<float, T>>();
foreach (var target in targets)
{
//Trace.Script("target = " + target.name);
var dist = Vector3.Distance(source.position, target.transform.position);
// If the target is within range of the source
if (dist <= range)
distances.Add(new KeyValuePair<float, T>(dist, target));
}
return distances;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
//!
/*!
* \brief The main class that computes all the reactions.
* \details This class initializes from files and execute all the reactions.
The reactions that are currently implemented are :
- Degradation
- Diffusion (Fick)
- Enzyme reaction with effectors (EnzymeReaction)
- Promoter expressions (Promoter)
*/
public class ReactionEngine : MonoBehaviour {
//////////////////////////////// singleton fields & methods ////////////////////////////////
private const string gameObjectName = "ReactionEngine";
private static ReactionEngine _instance;
public static ReactionEngine get()
{
if (_instance == null)
{
Debug.LogWarning("ReactionEngine get was badly initialized");
_instance = GameObject.Find(gameObjectName).GetComponent<ReactionEngine>();
}
return _instance;
}
void Awake()
{
// Debug.Log(this.GetType() + " Awake");
if ((_instance != null) && (_instance != this))
{
Debug.LogError(this.GetType() + " has two running instances");
}
else
{
_instance = this;
initializeIfNecessary();
}
}
void OnDestroy()
{
// Debug.Log(this.GetType() + " OnDestroy " + (_instance == this));
_instance = (_instance == this) ? null : _instance;
}
private bool _initialized = false;
private void initializeIfNecessary()
{
if (!_initialized)
{
FileLoader fileLoader = new FileLoader();
_reactionsSets = new LinkedList<ReactionSet>();
_moleculesSets = new LinkedList<MoleculeSet>();
_mediums = new LinkedList<Medium>();
//TODO there is only one file in _moleculesFiles and in _reactionsFiles
foreach (string file in _reactionsFiles)
{
LinkedList<ReactionSet> lr = fileLoader.loadObjectsFromFile<ReactionSet>(file, "reactions");
if (null != lr)
LinkedListExtensions.AppendRange<ReactionSet>(_reactionsSets, lr);
}
foreach (string file in _moleculesFiles)
{
// Debug.Log(this.GetType() + " Awake() loading molecules from file");
LinkedList<MoleculeSet> lm = fileLoader.loadObjectsFromFile<MoleculeSet>(file, "molecules");
if (null != lm)
LinkedListExtensions.AppendRange<MoleculeSet>(_moleculesSets, lm);
// Debug.Log(this.GetType() + " Awake() loading molecules from file done"
// + ": _moleculesSets=" + Logger.ToString<MoleculeSet>(_moleculesSets));
}
foreach (string file in _mediumsFiles)
{
LinkedList<Medium> lmed = fileLoader.loadObjectsFromFile<Medium>(file, "Medium");
if (null != lmed)
LinkedListExtensions.AppendRange<Medium>(_mediums, lmed);
}
foreach (Medium medium in _mediums)
{
medium.Init(_reactionsSets, _moleculesSets);
medium.enableSequential(enableSequential);
medium.enableNoise(enableNoise);
medium.enableEnergy(enableEnergy);
medium.enableShufflingReactionOrder = enableShufflingReactionOrder;
}
// Debug.Log(this.GetType() + " Awake() FickReactions starting");
_fick = new Fick();
_fick.loadFicksReactionsFromFiles(_fickFiles, _mediums);
// Debug.Log(this.GetType() + " Awake() activeTransport starting");
_activeTransport = new ActiveTransport();
_activeTransport.loadActiveTransportReactionsFromFiles(_activeTransportFiles, _mediums);
// Debug.Log(this.GetType() + " Awake() done");
_initialized = true;
}
}
void Start()
{
// Debug.Log(this.GetType() + " Start");
}
////////////////////////////////////////////////////////////////////////////////////////////
private Fick _fick; //!< The Fick class that manages molecules diffusions between medium
private ActiveTransport _activeTransport; //!< The class that manages Active transport reactions.
private LinkedList<Medium> _mediums; //!< The list that contains all the mediums
private LinkedList<ReactionSet> _reactionsSets; //!< The list that contains the reactions sets
private LinkedList<MoleculeSet> _moleculesSets; //!< The list that contains the molecules sets
public string[] _mediumsFiles; //!< all the medium files
public string[] _reactionsFiles; //!< all the reaction files
public string[] _moleculesFiles; //!< all the molecule files
public string[] _fickFiles; //!< all the Fick diffusion files
public string[] _activeTransportFiles; //!< all the Fick diffusion files
public const float reactionSpeed = 50f; //!< Global reaction speed
public bool enableSequential; //!< Enable sequential mode (if reactions are computed one after the other)
public bool enableNoise; //!< Add Noise in each Reaction
public bool enableEnergy; //!< Enable energy consumption
public bool enableShufflingReactionOrder; //!< Randomize reaction computation order in mediums
public bool enableShufflingMediumOrder; //!< Randomize medium computation order
private bool _paused; //!< Simulation state
public Fick getFick() { return _fick; }
/*!
\brief Adds an IReaction to a medium
\param mediumId The medium ID.
\param reaction The reaction to add.
*/
public void addReactionToMedium(int mediumId, Reaction reaction)
{
// Debug.Log(this.GetType() + " addReactionToMedium("+mediumId+", "+reaction+")");
Medium med = ReactionEngine.getMediumFromId(mediumId, _mediums);
if (med == null) {
Debug.LogWarning(this.GetType() + " addReactionToMedium medium #"+mediumId+"not found");
return ;
}
/*TODO FIXME USEFULNESS?/////////////////////////////////////////////////////////////////////
ReactionSet reactionsSet = null;
string medName = med.getName()+"Reactions";
foreach (ReactionSet rs in _reactionsSets) {
if (rs.id == medName) reactionsSet = rs;
}
if (reactionsSet != null) {
reactionsSet.reactions.AddLast(IReaction.copyReaction(reaction));
} else {
Debug.LogWarning(this.GetType() + " addReactionToMedium reactionsSet == null");
}
//////////////////////////////////////////////////////////////////////////////////////////*/
med.addReaction(Reaction.copyReaction(reaction));
}
/*!
\brief remove a reaction from a medium
\param mediumId The medium ID.
\param name The reaction's name.
*/
public void removeReactionFromMediumByName(int mediumId, string name)
{
Medium med = ReactionEngine.getMediumFromId(mediumId, _mediums);
if (med == null)
return ;
med.removeReactionByName(name);
}
/* !
\brief Remove from the specified medium the reaction that has the same characteristics as the one given as parameter
\param mediumId The Id of the medium to remove from.
\param reaction The model of reaction to remove.
\param checkNameAndMedium Whether the name and medium must be taken into account or not.
*/
public void removeReaction(int mediumId, Reaction reaction, bool checkNameAndMedium = false)
{
Medium med = ReactionEngine.getMediumFromId(mediumId, _mediums);
if (med == null)
{
Debug.LogWarning(this.GetType() + " removeReaction could not find medium with id "+mediumId);
return ;
}
med.removeReaction(reaction, checkNameAndMedium);
}
//! Return the Medium reference corresponding to the given id
/*!
\param id The id of searched Medium.
\param list The Medium list where to search in.
*/
public static Medium getMediumFromId(int id, LinkedList<Medium> list)
{
foreach (Medium med in list)
if (med.getId() == id)
return med;
return null;
}
//! Return the Molecule reference corresponding to the given name
/*!
\param name The name of the molecule
\param molecules The molecule list where to search in.
*/
public static Molecule getMoleculeFromName(string name, Dictionary<string, Molecule> molecules)
{
if (null != molecules) {
if (molecules.ContainsKey (name))
return molecules [name];
}
return null;
}
//! Return the ReactionSet reference corresponding to the given id
/*!
\param id The id of the ReactionSet
\param list The list of ReactionSet where to search in
*/
public static ReactionSet getReactionSetFromId(string id, LinkedList<ReactionSet> list)
{
foreach (ReactionSet reactSet in list)
if (reactSet.getStringId() == id)
return reactSet;
return null;
}
//! Tell if a Molecule is already present in a Molecule list (based on the name attribute)
/*!
\param mol Molecule to match.
\param list Molecule list where to search in.
*/
public static bool isMoleculeDuplicated(Molecule mol, Dictionary<string, Molecule> list)
{
foreach (Molecule mol2 in list.Values)
if (mol2.getName() == mol.getName())
return true;
return false;
}
/*!
\brief Return the List of mediums.
\return Return the List of mediums.
*/
public LinkedList<Medium> getMediumList()
{
return _mediums;
}
//! Return an ArrayList that contains all the differents molecules from a list of MoleculeSet
/*!
\param list the list of MoleculeSet
*/
public static Dictionary<string, Molecule> getAllMoleculesFromMoleculeSets(LinkedList<MoleculeSet> list)
{
var molecules = new Dictionary<string, Molecule>();
foreach (MoleculeSet molSet in list)
{
foreach (Molecule mol in molSet.molecules.Values)
if (!isMoleculeDuplicated(mol, molecules))
molecules.Add(mol.getName(), mol);
}
return molecules;
}
//! Return the MoleculeSet of a list of MoleculeSet corresponding to an id
/*!
\param id The id of the MoleculeSet
\param list The list of MoleculeSet
*/
public static MoleculeSet getMoleculeSetFromId(string id, LinkedList<MoleculeSet> list)
{
foreach (MoleculeSet molSet in list)
if (molSet.getStringId() == id)
return molSet;
return null;
}
public Dictionary<string, Molecule> getMoleculesFromMedium(int id) {
//"warn" parameter is true to indicate that there is no such Medium
//as the one needed to get molecules
Medium medium = LinkedListExtensions.Find<Medium>(
_mediums
, m => m.getId() == id
, true
, " ReactionEngine getMoleculesFromMedium("+id+")");
if (medium != null) {
return medium.getMolecules();
} else {
return null;
}
}
//TODO manage reaction speed for smooth pausing
public void Pause(bool pause) {
_paused = pause;
}
public static bool isPaused()
{
return _instance._paused;
}
//! This function is called at each frame
public void Update()
{
if(_paused) {
// Debug.Log(this.GetType() + " Update paused");
} else {
_fick.react();
if (enableShufflingMediumOrder)
LinkedListExtensions.Shuffle<Medium>(_mediums);
foreach (Medium medium in _mediums)
medium.Update();
// Debug.Log(this.GetType() + " Update() update of mediums done");
if (!enableSequential) {
foreach (Medium medium in _mediums)
medium.updateMoleculesConcentrations();
// Debug.Log(this.GetType() + " Update() update of mol cc in mediums done");
}
}
}
}
| |
//
// Copyright (C) Microsoft. All rights reserved.
//
using System;
using System.Management.Automation;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Base class for object-based event registration.
/// </summary>
public abstract class ObjectEventRegistrationBase : PSCmdlet
{
#region parameters
/// <summary>
/// Parameter for an identifier for this event subscription
/// </summary>
[Parameter(Position = 100)]
public string SourceIdentifier
{
get
{
return _sourceIdentifier;
}
set
{
_sourceIdentifier = value;
}
}
private string _sourceIdentifier = Guid.NewGuid().ToString();
/// <summary>
/// Parameter for any action to be invoked when the event arrives
/// </summary>
[Parameter(Position = 101)]
public ScriptBlock Action
{
get
{
return _action;
}
set
{
_action = value;
}
}
private ScriptBlock _action = null;
/// <summary>
/// Parameter for additional data to be associated with this event subscription
/// </summary>
[Parameter]
public PSObject MessageData
{
get
{
return _messageData;
}
set
{
_messageData = value;
}
}
private PSObject _messageData = null;
/// <summary>
/// Parameter for the flag that determines if this subscription is used to support
/// other subscriptions
/// </summary>
[Parameter]
public SwitchParameter SupportEvent
{
get
{
return _supportEvent;
}
set
{
_supportEvent = value;
}
}
private SwitchParameter _supportEvent = new SwitchParameter();
/// <summary>
/// Parameter for the flag that determines whether this
/// subscription will forward its events to the PowerShell client during remote executions
/// </summary>
[Parameter]
public SwitchParameter Forward
{
get
{
return _forward;
}
set
{
_forward = value;
}
}
private SwitchParameter _forward = new SwitchParameter();
/// <summary>
/// Parameter to indicate that the subscriber should be auto-unregistered after being triggered for specified times.
/// If the value is equal or less than zero, there is no limit on the number of times the event can be triggered without being unregistered
/// </summary>
[Parameter]
public int MaxTriggerCount
{
get
{
return _maxTriggerCount;
}
set
{
_maxTriggerCount = value <= 0 ? 0 : value;
}
}
private int _maxTriggerCount = 0;
#endregion parameters
/// <summary>
/// Returns the object that generates events to be monitored
/// </summary>
protected abstract Object GetSourceObject();
/// <summary>
/// Returns the event name to be monitored on the input object
/// </summary>
protected abstract String GetSourceObjectEventName();
/// <summary>
/// Gets the subscriber generated by this command
/// </summary>
protected PSEventSubscriber NewSubscriber
{
get { return _newSubscriber; }
}
private PSEventSubscriber _newSubscriber;
/// <summary>
/// Check arguments
/// </summary>
protected override void BeginProcessing()
{
if (((bool)_forward) && (_action != null))
{
ThrowTerminatingError(
new ErrorRecord(
new ArgumentException(EventingResources.ActionAndForwardNotSupported),
"ACTION_AND_FORWARD_NOT_SUPPORTED",
ErrorCategory.InvalidOperation,
null));
}
}
/// <summary>
/// Subscribe to the event on the object
/// </summary>
protected override void EndProcessing()
{
Object inputObject = PSObject.Base(GetSourceObject());
string eventName = GetSourceObjectEventName();
try
{
if (
((inputObject != null) || (eventName != null)) &&
(Events.GetEventSubscribers(_sourceIdentifier).GetEnumerator().MoveNext())
)
{
// Detect if the event identifier already exists
ErrorRecord errorRecord = new ErrorRecord(
new ArgumentException(
String.Format(
System.Globalization.CultureInfo.CurrentCulture,
EventingResources.SubscriberExists, _sourceIdentifier)),
"SUBSCRIBER_EXISTS",
ErrorCategory.InvalidArgument,
inputObject);
WriteError(errorRecord);
}
else
{
_newSubscriber =
Events.SubscribeEvent(
inputObject,
eventName,
_sourceIdentifier, _messageData, _action, (bool)_supportEvent, (bool)_forward, _maxTriggerCount);
if ((_action != null) && (!(bool)_supportEvent))
WriteObject(_newSubscriber.Action);
}
}
catch (ArgumentException e)
{
ErrorRecord errorRecord = new ErrorRecord(
e,
"INVALID_REGISTRATION",
ErrorCategory.InvalidArgument,
inputObject);
WriteError(errorRecord);
}
catch (InvalidOperationException e)
{
ErrorRecord errorRecord = new ErrorRecord(
e,
"INVALID_REGISTRATION",
ErrorCategory.InvalidOperation,
inputObject);
WriteError(errorRecord);
}
}
}
}
| |
// <copyright file="RemoteWebElement.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using OpenQA.Selenium.Interactions.Internal;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Remote
{
/// <summary>
/// RemoteWebElement allows you to have access to specific items that are found on the page
/// </summary>
/// <seealso cref="IWebElement"/>
/// <seealso cref="ILocatable"/>
public class RemoteWebElement : IWebElement, IFindsByLinkText, IFindsById, IFindsByName, IFindsByTagName, IFindsByClassName, IFindsByXPath, IFindsByPartialLinkText, IFindsByCssSelector, IWrapsDriver, ILocatable, ITakesScreenshot, IWebElementReference
{
private RemoteWebDriver driver;
private string elementId;
/// <summary>
/// Initializes a new instance of the <see cref="RemoteWebElement"/> class.
/// </summary>
/// <param name="parentDriver">The <see cref="RemoteWebDriver"/> instance hosting this element.</param>
/// <param name="id">The ID assigned to the element.</param>
public RemoteWebElement(RemoteWebDriver parentDriver, string id)
{
this.driver = parentDriver;
this.elementId = id;
}
/// <summary>
/// Gets the <see cref="IWebDriver"/> used to find this element.
/// </summary>
public IWebDriver WrappedDriver
{
get { return this.driver; }
}
/// <summary>
/// Gets the tag name of this element.
/// </summary>
/// <remarks>
/// The <see cref="TagName"/> property returns the tag name of the
/// element, not the value of the name attribute. For example, it will return
/// "input" for an element specified by the HTML markup <input name="foo" />.
/// </remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public string TagName
{
get
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
Response commandResponse = this.Execute(DriverCommand.GetElementTagName, parameters);
return commandResponse.Value.ToString();
}
}
/// <summary>
/// Gets the innerText of this element, without any leading or trailing whitespace,
/// and with other whitespace collapsed.
/// </summary>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public string Text
{
get
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
Response commandResponse = this.Execute(DriverCommand.GetElementText, parameters);
return commandResponse.Value.ToString();
}
}
/// <summary>
/// Gets a value indicating whether or not this element is enabled.
/// </summary>
/// <remarks>The <see cref="Enabled"/> property will generally
/// return <see langword="true"/> for everything except explicitly disabled input elements.</remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public bool Enabled
{
get
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
Response commandResponse = this.Execute(DriverCommand.IsElementEnabled, parameters);
return (bool)commandResponse.Value;
}
}
/// <summary>
/// Gets a value indicating whether or not this element is selected.
/// </summary>
/// <remarks>This operation only applies to input elements such as checkboxes,
/// options in a select element and radio buttons.</remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public bool Selected
{
get
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
Response commandResponse = this.Execute(DriverCommand.IsElementSelected, parameters);
return (bool)commandResponse.Value;
}
}
/// <summary>
/// Gets a <see cref="Point"/> object containing the coordinates of the upper-left corner
/// of this element relative to the upper-left corner of the page.
/// </summary>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public Point Location
{
get
{
string getLocationCommand = DriverCommand.GetElementLocation;
if (this.driver.IsSpecificationCompliant)
{
getLocationCommand = DriverCommand.GetElementRect;
}
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.Id);
Response commandResponse = this.Execute(getLocationCommand, parameters);
Dictionary<string, object> rawPoint = (Dictionary<string, object>)commandResponse.Value;
int x = Convert.ToInt32(rawPoint["x"], CultureInfo.InvariantCulture);
int y = Convert.ToInt32(rawPoint["y"], CultureInfo.InvariantCulture);
return new Point(x, y);
}
}
/// <summary>
/// Gets a <see cref="Size"/> object containing the height and width of this element.
/// </summary>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public Size Size
{
get
{
string getSizeCommand = DriverCommand.GetElementSize;
if (this.driver.IsSpecificationCompliant)
{
getSizeCommand = DriverCommand.GetElementRect;
}
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.Id);
Response commandResponse = this.Execute(getSizeCommand, parameters);
Dictionary<string, object> rawSize = (Dictionary<string, object>)commandResponse.Value;
int width = Convert.ToInt32(rawSize["width"], CultureInfo.InvariantCulture);
int height = Convert.ToInt32(rawSize["height"], CultureInfo.InvariantCulture);
return new Size(width, height);
}
}
/// <summary>
/// Gets a value indicating whether or not this element is displayed.
/// </summary>
/// <remarks>The <see cref="Displayed"/> property avoids the problem
/// of having to parse an element's "style" attribute to determine
/// visibility of an element.</remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public bool Displayed
{
get
{
Response commandResponse = null;
Dictionary<string, object> parameters = new Dictionary<string, object>();
if (this.driver.IsSpecificationCompliant)
{
string atom = GetAtom("isDisplayed.js");
parameters.Add("script", atom);
parameters.Add("args", new object[] { this.ToElementReference().ToDictionary() });
commandResponse = this.Execute(DriverCommand.ExecuteScript, parameters);
}
else
{
parameters.Add("id", this.Id);
commandResponse = this.Execute(DriverCommand.IsElementDisplayed, parameters);
}
return (bool)commandResponse.Value;
}
}
/// <summary>
/// Gets the point where the element would be when scrolled into view.
/// </summary>
public Point LocationOnScreenOnceScrolledIntoView
{
get
{
Response commandResponse;
Dictionary<string, object> rawLocation;
if (this.driver.IsSpecificationCompliant)
{
object scriptResponse = this.driver.ExecuteScript("var rect = arguments[0].getBoundingClientRect(); return {'x': rect.left, 'y': rect.top};", this);
rawLocation = scriptResponse as Dictionary<string, object>;
}
else
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.Id);
commandResponse = this.Execute(DriverCommand.GetElementLocationOnceScrolledIntoView, parameters);
rawLocation = (Dictionary<string, object>)commandResponse.Value;
}
int x = Convert.ToInt32(rawLocation["x"], CultureInfo.InvariantCulture);
int y = Convert.ToInt32(rawLocation["y"], CultureInfo.InvariantCulture);
return new Point(x, y);
}
}
/// <summary>
/// Gets the coordinates identifying the location of this element using
/// various frames of reference.
/// </summary>
public ICoordinates Coordinates
{
get { return new RemoteCoordinates(this); }
}
/// <summary>
/// Gets the internal ID of the element.
/// </summary>
string IWebElementReference.ElementReferenceId
{
get { return this.elementId; }
}
/// <summary>
/// Gets the ID of the element
/// </summary>
/// <remarks>This property is internal to the WebDriver instance, and is
/// not intended to be used in your code. The element's ID has no meaning
/// outside of internal WebDriver usage, so it would be improper to scope
/// it as public. However, both subclasses of <see cref="RemoteWebElement"/>
/// and the parent driver hosting the element have a need to access the
/// internal element ID. Therefore, we have two properties returning the
/// same value, one scoped as internal, the other as protected.</remarks>
protected string Id
{
get { return this.elementId; }
}
/// <summary>
/// Clears the content of this element.
/// </summary>
/// <remarks>If this element is a text entry element, the <see cref="Clear"/>
/// method will clear the value. It has no effect on other elements. Text entry elements
/// are defined as elements with INPUT or TEXTAREA tags.</remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public void Clear()
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
this.Execute(DriverCommand.ClearElement, parameters);
}
/// <summary>
/// Simulates typing text into the element.
/// </summary>
/// <param name="text">The text to type into the element.</param>
/// <remarks>The text to be typed may include special characters like arrow keys,
/// backspaces, function keys, and so on. Valid special keys are defined in
/// <see cref="Keys"/>.</remarks>
/// <seealso cref="Keys"/>
/// <exception cref="InvalidElementStateException">Thrown when the target element is not enabled.</exception>
/// <exception cref="ElementNotVisibleException">Thrown when the target element is not visible.</exception>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public void SendKeys(string text)
{
if (text == null)
{
throw new ArgumentNullException("text", "text cannot be null");
}
if (this.driver.FileDetector.IsFile(text))
{
text = this.UploadFile(text);
}
// N.B. The Java remote server expects a CharSequence as the value input to
// SendKeys. In JSON, these are serialized as an array of strings, with a
// single character to each element of the array. Thus, we must use ToCharArray()
// to get the same effect.
// TODO: Remove either "keysToSend" or "value" property, whichever is not the
// appropriate one for spec compliance.
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
if (this.driver.IsSpecificationCompliant)
{
parameters.Add("text", text);
parameters.Add("value", text.ToCharArray());
}
else
{
parameters.Add("value", new object[] { text });
}
this.Execute(DriverCommand.SendKeysToElement, parameters);
}
/// <summary>
/// Submits this element to the web server.
/// </summary>
/// <remarks>If this current element is a form, or an element within a form,
/// then this will be submitted to the web server. If this causes the current
/// page to change, then this method will attempt to block until the new page
/// is loaded.</remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public void Submit()
{
if (this.driver.IsSpecificationCompliant)
{
string elementType = this.GetAttribute("type");
if (elementType != null && elementType == "submit")
{
this.Click();
}
else
{
IWebElement form = this.FindElement(By.XPath("./ancestor-or-self::form"));
this.driver.ExecuteScript(
"var e = arguments[0].ownerDocument.createEvent('Event');" +
"e.initEvent('submit', true, true);" +
"if (arguments[0].dispatchEvent(e)) { arguments[0].submit(); }", form);
}
}
else
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
this.Execute(DriverCommand.SubmitElement, parameters);
}
}
/// <summary>
/// Clicks this element.
/// </summary>
/// <remarks>
/// Click this element. If the click causes a new page to load, the <see cref="Click"/>
/// method will attempt to block until the page has loaded. After calling the
/// <see cref="Click"/> method, you should discard all references to this
/// element unless you know that the element and the page will still be present.
/// Otherwise, any further operations performed on this element will have an undefined
/// behavior.
/// </remarks>
/// <exception cref="InvalidElementStateException">Thrown when the target element is not enabled.</exception>
/// <exception cref="ElementNotVisibleException">Thrown when the target element is not visible.</exception>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public void Click()
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
this.Execute(DriverCommand.ClickElement, parameters);
}
/// <summary>
/// Gets the value of the specified attribute for this element.
/// </summary>
/// <param name="attributeName">The name of the attribute.</param>
/// <returns>The attribute's current value. Returns a <see langword="null"/> if the
/// value is not set.</returns>
/// <remarks>The <see cref="GetAttribute"/> method will return the current value
/// of the attribute, even if the value has been modified after the page has been
/// loaded. Note that the value of the following attributes will be returned even if
/// there is no explicit attribute on the element:
/// <list type="table">
/// <listheader>
/// <term>Attribute name</term>
/// <term>Value returned if not explicitly specified</term>
/// <term>Valid element types</term>
/// </listheader>
/// <item>
/// <description>checked</description>
/// <description>checked</description>
/// <description>Check Box</description>
/// </item>
/// <item>
/// <description>selected</description>
/// <description>selected</description>
/// <description>Options in Select elements</description>
/// </item>
/// <item>
/// <description>disabled</description>
/// <description>disabled</description>
/// <description>Input and other UI elements</description>
/// </item>
/// </list>
/// </remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public string GetAttribute(string attributeName)
{
Response commandResponse = null;
string attributeValue = string.Empty;
Dictionary<string, object> parameters = new Dictionary<string, object>();
if (this.driver.IsSpecificationCompliant)
{
string atom = GetAtom("getAttribute.js");
parameters.Add("script", atom);
parameters.Add("args", new object[] { this.ToElementReference().ToDictionary(), attributeName });
commandResponse = this.Execute(DriverCommand.ExecuteScript, parameters);
}
else
{
parameters.Add("id", this.elementId);
parameters.Add("name", attributeName);
commandResponse = this.Execute(DriverCommand.GetElementAttribute, parameters);
}
if (commandResponse.Value == null)
{
attributeValue = null;
}
else
{
attributeValue = commandResponse.Value.ToString();
// Normalize string values of boolean results as lowercase.
if (commandResponse.Value is bool)
{
attributeValue = attributeValue.ToLowerInvariant();
}
}
return attributeValue;
}
/// <summary>
/// Gets the value of a JavaScript property of this element.
/// </summary>
/// <param name="propertyName">The name JavaScript the JavaScript property to get the value of.</param>
/// <returns>The JavaScript property's current value. Returns a <see langword="null"/> if the
/// value is not set or the property does not exist.</returns>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public string GetProperty(string propertyName)
{
string propertyValue = string.Empty;
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.Id);
parameters.Add("name", propertyName);
Response commandResponse = this.Execute(DriverCommand.GetElementProperty, parameters);
if (commandResponse.Value == null)
{
propertyValue = null;
}
else
{
propertyValue = commandResponse.Value.ToString();
}
return propertyValue;
}
/// <summary>
/// Gets the value of a CSS property of this element.
/// </summary>
/// <param name="propertyName">The name of the CSS property to get the value of.</param>
/// <returns>The value of the specified CSS property.</returns>
/// <remarks>The value returned by the <see cref="GetCssValue"/>
/// method is likely to be unpredictable in a cross-browser environment.
/// Color values should be returned as hex strings. For example, a
/// "background-color" property set as "green" in the HTML source, will
/// return "#008000" for its value.</remarks>
/// <exception cref="StaleElementReferenceException">Thrown when the target element is no longer valid in the document DOM.</exception>
public string GetCssValue(string propertyName)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.Id);
if (this.driver.IsSpecificationCompliant)
{
parameters.Add("name", propertyName);
}
else
{
parameters.Add("propertyName", propertyName);
}
Response commandResponse = this.Execute(DriverCommand.GetElementValueOfCssProperty, parameters);
return commandResponse.Value.ToString();
}
/// <summary>
/// Finds all <see cref="IWebElement">IWebElements</see> within the current context
/// using the given mechanism.
/// </summary>
/// <param name="by">The locating mechanism to use.</param>
/// <returns>A <see cref="ReadOnlyCollection{T}"/> of all <see cref="IWebElement">WebElements</see>
/// matching the current criteria, or an empty list if nothing matches.</returns>
public ReadOnlyCollection<IWebElement> FindElements(By by)
{
if (by == null)
{
throw new ArgumentNullException("by", "by cannot be null");
}
return by.FindElements(this);
}
/// <summary>
/// Finds the first <see cref="IWebElement"/> using the given method.
/// </summary>
/// <param name="by">The locating mechanism to use.</param>
/// <returns>The first matching <see cref="IWebElement"/> on the current context.</returns>
/// <exception cref="NoSuchElementException">If no element matches the criteria.</exception>
public IWebElement FindElement(By by)
{
if (by == null)
{
throw new ArgumentNullException("by", "by cannot be null");
}
return by.FindElement(this);
}
/// <summary>
/// Finds the first of elements that match the link text supplied
/// </summary>
/// <param name="linkText">Link text of element </param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementByLinkText("linktext")
/// </code>
/// </example>
public IWebElement FindElementByLinkText(string linkText)
{
return this.FindElement("link text", linkText);
}
/// <summary>
/// Finds the first of elements that match the link text supplied
/// </summary>
/// <param name="linkText">Link text of element </param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByLinkText("linktext")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByLinkText(string linkText)
{
return this.FindElements("link text", linkText);
}
/// <summary>
/// Finds the first element in the page that matches the ID supplied
/// </summary>
/// <param name="id">ID of the element</param>
/// <returns>IWebElement object so that you can interact with that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementById("id")
/// </code>
/// </example>
public IWebElement FindElementById(string id)
{
if (this.driver.IsSpecificationCompliant)
{
return this.FindElement("css selector", "#" + RemoteWebDriver.EscapeCssSelector(id));
}
return this.FindElement("id", id);
}
/// <summary>
/// Finds the first element in the page that matches the ID supplied
/// </summary>
/// <param name="id">ID of the Element</param>
/// <returns>ReadOnlyCollection of Elements that match the object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsById("id")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsById(string id)
{
if (this.driver.IsSpecificationCompliant)
{
return this.FindElements("css selector", "#" + RemoteWebDriver.EscapeCssSelector(id));
}
return this.FindElements("id", id);
}
/// <summary>
/// Finds the first of elements that match the name supplied
/// </summary>
/// <param name="name">Name of the element</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// elem = driver.FindElementsByName("name")
/// </code>
/// </example>
public IWebElement FindElementByName(string name)
{
// Element finding mechanism is not allowed by the W3C WebDriver
// specification, but rather should be implemented as a function
// of other finder mechanisms as documented in the spec.
// Implementation after spec reaches recommendation should be as
// follows:
// return this.FindElement("css selector", "*[name=\"" + name + "\"]");
if (this.driver.IsSpecificationCompliant)
{
return this.FindElement("css selector", "*[name=\"" + name + "\"]");
}
return this.FindElement("name", name);
}
/// <summary>
/// Finds a list of elements that match the name supplied
/// </summary>
/// <param name="name">Name of element</param>
/// <returns>ReadOnlyCollect of IWebElement objects so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByName("name")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByName(string name)
{
// Element finding mechanism is not allowed by the W3C WebDriver
// specification, but rather should be implemented as a function
// of other finder mechanisms as documented in the spec.
// Implementation after spec reaches recommendation should be as
// follows:
// return this.FindElements("css selector", "*[name=\"" + name + "\"]");
if (this.driver.IsSpecificationCompliant)
{
return this.FindElements("css selector", "*[name=\"" + name + "\"]");
}
return this.FindElements("name", name);
}
/// <summary>
/// Finds the first of elements that match the DOM Tag supplied
/// </summary>
/// <param name="tagName">tag name of the element</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementsByTagName("tag")
/// </code>
/// </example>
public IWebElement FindElementByTagName(string tagName)
{
// Element finding mechanism is not allowed by the W3C WebDriver
// specification, but rather should be implemented as a function
// of other finder mechanisms as documented in the spec.
// Implementation after spec reaches recommendation should be as
// follows:
// return this.FindElement("css selector", tagName);
if (this.driver.IsSpecificationCompliant)
{
return this.FindElement("css selector", tagName);
}
return this.FindElement("tag name", tagName);
}
/// <summary>
/// Finds a list of elements that match the DOM Tag supplied
/// </summary>
/// <param name="tagName">DOM Tag of the element on the page</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByTagName("tag")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByTagName(string tagName)
{
// Element finding mechanism is not allowed by the W3C WebDriver
// specification, but rather should be implemented as a function
// of other finder mechanisms as documented in the spec.
// Implementation after spec reaches recommendation should be as
// follows:
// return this.FindElements("css selector", tagName);
if (this.driver.IsSpecificationCompliant)
{
return this.FindElements("css selector", tagName);
}
return this.FindElements("tag name", tagName);
}
/// <summary>
/// Finds the first element in the page that matches the CSS Class supplied
/// </summary>
/// <param name="className">CSS class name of the element on the page</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementByClassName("classname")
/// </code>
/// </example>
public IWebElement FindElementByClassName(string className)
{
// Element finding mechanism is not allowed by the W3C WebDriver
// specification, but rather should be implemented as a function
// of other finder mechanisms as documented in the spec.
// Implementation after spec reaches recommendation should be as
// follows:
// return this.FindElement("css selector", "." + className);
if (this.driver.IsSpecificationCompliant)
{
return this.FindElement("css selector", "." + RemoteWebDriver.EscapeCssSelector(className));
}
return this.FindElement("class name", className);
}
/// <summary>
/// Finds a list of elements that match the class name supplied
/// </summary>
/// <param name="className">CSS class name of the elements on the page</param>
/// <returns>ReadOnlyCollection of IWebElement object so that you can interact with those objects</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByClassName("classname")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByClassName(string className)
{
// Element finding mechanism is not allowed by the W3C WebDriver
// specification, but rather should be implemented as a function
// of other finder mechanisms as documented in the spec.
// Implementation after spec reaches recommendation should be as
// follows:
// return this.FindElements("css selector", "." + className);
if (this.driver.IsSpecificationCompliant)
{
return this.FindElements("css selector", "." + RemoteWebDriver.EscapeCssSelector(className));
}
return this.FindElements("class name", className);
}
/// <summary>
/// Finds the first of elements that match the XPath supplied
/// </summary>
/// <param name="xpath">xpath to the element</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementsByXPath("//table/tbody/tr/td/a");
/// </code>
/// </example>
public IWebElement FindElementByXPath(string xpath)
{
return this.FindElement("xpath", xpath);
}
/// <summary>
/// Finds a list of elements that match the XPath supplied
/// </summary>
/// <param name="xpath">xpath to element on the page</param>
/// <returns>ReadOnlyCollection of IWebElement objects so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByXpath("//tr/td/a")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByXPath(string xpath)
{
return this.FindElements("xpath", xpath);
}
/// <summary>
/// Finds the first of elements that match the part of the link text supplied
/// </summary>
/// <param name="partialLinkText">part of the link text</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementsByPartialLinkText("partOfLink")
/// </code>
/// </example>
public IWebElement FindElementByPartialLinkText(string partialLinkText)
{
return this.FindElement("partial link text", partialLinkText);
}
/// <summary>
/// Finds a list of elements that match the link text supplied
/// </summary>
/// <param name="partialLinkText">part of the link text</param>
/// <returns>ReadOnlyCollection<![CDATA[<IWebElement>]]> objects so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByPartialLinkText("partOfTheLink")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByPartialLinkText(string partialLinkText)
{
return this.FindElements("partial link text", partialLinkText);
}
/// <summary>
/// Finds the first element matching the specified CSS selector.
/// </summary>
/// <param name="cssSelector">The id to match.</param>
/// <returns>The first <see cref="IWebElement"/> matching the criteria.</returns>
public IWebElement FindElementByCssSelector(string cssSelector)
{
return this.FindElement("css selector", cssSelector);
}
/// <summary>
/// Finds all elements matching the specified CSS selector.
/// </summary>
/// <param name="cssSelector">The CSS selector to match.</param>
/// <returns>A <see cref="ReadOnlyCollection{T}"/> containing all
/// <see cref="IWebElement">IWebElements</see> matching the criteria.</returns>
public ReadOnlyCollection<IWebElement> FindElementsByCssSelector(string cssSelector)
{
return this.FindElements("css selector", cssSelector);
}
/// <summary>
/// Gets a <see cref="Screenshot"/> object representing the image of this element on the screen.
/// </summary>
/// <returns>A <see cref="Screenshot"/> object containing the image.</returns>
public Screenshot GetScreenshot()
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
// Get the screenshot as base64.
Response screenshotResponse = this.Execute(DriverCommand.ElementScreenshot, parameters);
string base64 = screenshotResponse.Value.ToString();
// ... and convert it.
return new Screenshot(base64);
}
/// <summary>
/// Returns a string that represents the current <see cref="RemoteWebElement"/>.
/// </summary>
/// <returns>A string that represents the current <see cref="RemoteWebElement"/>.</returns>
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "Element (id = {0})", this.elementId);
}
/// <summary>
/// Method to get the hash code of the element
/// </summary>
/// <returns>Integer of the hash code for the element</returns>
public override int GetHashCode()
{
return this.elementId.GetHashCode();
}
/// <summary>
/// Compares if two elements are equal
/// </summary>
/// <param name="obj">Object to compare against</param>
/// <returns>A boolean if it is equal or not</returns>
public override bool Equals(object obj)
{
IWebElement other = obj as IWebElement;
if (other == null)
{
return false;
}
IWrapsElement objAsWrapsElement = obj as IWrapsElement;
if (objAsWrapsElement != null)
{
other = objAsWrapsElement.WrappedElement;
}
RemoteWebElement otherAsElement = other as RemoteWebElement;
if (otherAsElement == null)
{
return false;
}
if (this.elementId == otherAsElement.Id)
{
// For drivers that implement ID equality, we can check for equal IDs
// here, and expect them to be equal. There is a potential danger here
// where two different elements are assigned the same ID.
return true;
}
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.Id);
parameters.Add("other", otherAsElement.Id);
Response response = this.Execute(DriverCommand.ElementEquals, parameters);
object value = response.Value;
return value != null && value is bool && (bool)value;
}
/// <summary>
/// Converts an object into an object that represents an element for the wire protocol.
/// </summary>
/// <returns>A <see cref="Dictionary{TKey, TValue}"/> that represents an element in the wire protocol.</returns>
Dictionary<string, object> IWebElementReference.ToDictionary()
{
Dictionary<string, object> elementDictionary = new Dictionary<string, object>();
elementDictionary.Add("element-6066-11e4-a52e-4f735466cecf", this.elementId);
return elementDictionary;
}
/// <summary>
/// Finds a child element matching the given mechanism and value.
/// </summary>
/// <param name="mechanism">The mechanism by which to find the element.</param>
/// <param name="value">The value to use to search for the element.</param>
/// <returns>The first <see cref="IWebElement"/> matching the given criteria.</returns>
protected IWebElement FindElement(string mechanism, string value)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
parameters.Add("using", mechanism);
parameters.Add("value", value);
Response commandResponse = this.Execute(DriverCommand.FindChildElement, parameters);
return this.driver.GetElementFromResponse(commandResponse);
}
/// <summary>
/// Finds all child elements matching the given mechanism and value.
/// </summary>
/// <param name="mechanism">The mechanism by which to find the elements.</param>
/// <param name="value">The value to use to search for the elements.</param>
/// <returns>A collection of all of the <see cref="IWebElement">IWebElements</see> matching the given criteria.</returns>
protected ReadOnlyCollection<IWebElement> FindElements(string mechanism, string value)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", this.elementId);
parameters.Add("using", mechanism);
parameters.Add("value", value);
Response commandResponse = this.Execute(DriverCommand.FindChildElements, parameters);
return this.driver.GetElementsFromResponse(commandResponse);
}
/// <summary>
/// Executes a command on this element using the specified parameters.
/// </summary>
/// <param name="commandToExecute">The <see cref="DriverCommand"/> to execute against this element.</param>
/// <param name="parameters">A <see cref="Dictionary{K, V}"/> containing names and values of the parameters for the command.</param>
/// <returns>The <see cref="Response"/> object containing the result of the command execution.</returns>
protected Response Execute(string commandToExecute, Dictionary<string, object> parameters)
{
return this.driver.InternalExecute(commandToExecute, parameters);
}
private static string GetAtom(string atomResourceName)
{
string atom = string.Empty;
using (Stream atomStream = ResourceUtilities.GetResourceStream(atomResourceName, atomResourceName))
{
using (StreamReader atomReader = new StreamReader(atomStream))
{
atom = atomReader.ReadToEnd();
}
}
string wrappedAtom = string.Format(CultureInfo.InvariantCulture, "return ({0}).apply(null, arguments);", atom);
return wrappedAtom;
}
private string UploadFile(string localFile)
{
string base64zip = string.Empty;
try
{
using (MemoryStream fileUploadMemoryStream = new MemoryStream())
{
using (ZipStorer zipArchive = ZipStorer.Create(fileUploadMemoryStream, string.Empty))
{
string fileName = Path.GetFileName(localFile);
zipArchive.AddFile(ZipStorer.CompressionMethod.Deflate, localFile, fileName, string.Empty);
base64zip = Convert.ToBase64String(fileUploadMemoryStream.ToArray());
}
}
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("file", base64zip);
Response response = this.Execute(DriverCommand.UploadFile, parameters);
return response.Value.ToString();
}
catch (IOException e)
{
throw new WebDriverException("Cannot upload " + localFile, e);
}
}
private IWebElementReference ToElementReference()
{
return this as IWebElementReference;
}
}
}
| |
using Express;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IFC4.Generators
{
public class CsharpLanguageGenerator : ILanguageGenerator
{
private Dictionary<string,SelectType> selectData = new Dictionary<string, SelectType>();
public Dictionary<string,SelectType> SelectData
{
get{return selectData;}
set{selectData = value;}
}
public string Assignment(AttributeData data)
{
return $"\t\t\t{data.Name} = {data.ParameterName};";
}
public string Allocation(AttributeData data)
{
if (data.IsCollection)
{
return $"\t\t\t{data.Name} = new {data.Type}();";
}
return string.Empty;
}
public string AttributeDataType(bool isCollection, int rank, string type, bool isGeneric)
{
if (isCollection)
{
return $"{string.Join("", Enumerable.Repeat("List<", rank))}{type}{string.Join("", Enumerable.Repeat(">", rank))}";
}
// Item is used in functions.
if(isGeneric)
{
return "T";
}
// https://github.com/ikeough/IFC-gen/issues/25
if(type == "IfcSiUnitName")
{
return "IfcSIUnitName";
}
return type;
}
public string AttributeDataString(AttributeData data)
{
var prop = string.Empty;
if(data.IsDerived)
{
var isNew = data.IsDerived && data.HidesParentAttributeOfSameName ? "new " : string.Empty;
var name = data.Name;
prop = $@"
[JsonIgnore]
{isNew}public {data.Type} {name}{{get{{throw new NotImplementedException($""Derived property logic has been implemented for {name}."");}}}} // derived";
}
else
{
var tags = new List<string>();
if(data.IsOptional) tags.Add("optional");
if(data.IsInverse) tags.Add("inverse");
var opt = data.IsOptional ? "optional" : string.Empty;
var inverse = data.IsInverse ? "inverse" : string.Empty;
prop = $"\t\tpublic {data.Type} {data.Name}{{get;set;}} {(tags.Any()? "// " + string.Join(",",tags) : string.Empty)}";
}
return prop;
}
public string AttributeStepString(AttributeData data, bool isDerivedInChild)
{
var step = $"\t\t\tparameters.Add({data.Name} != null ? {data.Name}.ToStepValue() : \"$\");";
if(isDerivedInChild)
{
step = "\t\t\tparameters.Add(\"*\");";
return step;
}
// TODO: Not all enums are called xxxEnum. This emits code which causes
// 'never equal to null' errors. Find a better way to handle enums which don't
// end in 'enum'.
if (data.Type.EndsWith("Enum") | data.Type == "bool" | data.Type == "int" | data.Type == "double")
{
step = $"\t\t\tparameters.Add({data.Name}.ToStepValue());";
}
return step;
}
private string WrappedType(WrapperType data)
{
if (data.IsCollectionType)
{
return $"{string.Join("", Enumerable.Repeat("List<", data.Rank))}{data.WrappedType}{string.Join("", Enumerable.Repeat(">", data.Rank))}";
}
return data.WrappedType;
}
public string SimpleTypeString(WrapperType data)
{
var result =
$@"
using System;
using System.ComponentModel;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;
using STEP;
namespace IFC
{{
/// <summary>
/// http://www.buildingsmart-tech.org/ifc/IFC4/final/html/link/{data.Name.ToLower()}.htm
/// </summary>
public class {data.Name} : BaseIfc
{{
internal {WrappedType(data)} value;
public {data.Name}({WrappedType(data)} value){{ this.value = value; }}
public static implicit operator {WrappedType(data)}({data.Name} v){{ return v.value; }}
public static implicit operator {data.Name}({WrappedType(data)} v){{ return new {data.Name}(v); }}
public static {data.Name} FromJSON(string json){{ return JsonConvert.DeserializeObject<{data.Name}>(json); }}
public override string ToString(){{ return value.ToString(); }}
public override string ToStepValue(bool isSelectOption = false){{
if(isSelectOption){{ return $""{{GetType().Name.ToUpper()}}({{value.ToStepValue(isSelectOption)}})""; }}
else{{ return value.ToStepValue(isSelectOption); }}
}}
}}
}}
";
return result;
}
public string EnumTypeString(EnumType data)
{
var result =
$@"
using System;
using System.ComponentModel;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;
using STEP;
namespace IFC
{{
/// <summary>
/// http://www.buildingsmart-tech.org/ifc/IFC4/final/html/link/{data.Name.ToLower()}.htm
/// </summary>
public enum {data.Name} {{{string.Join(",", data.Values)}}}
}}
";
return result;
}
public string SelectTypeString(SelectType data)
{
var constructors = new StringBuilder();
foreach(var value in data.Values)
{
// There is one select in IFC that
// has an option which is an enum, which
// does not inherit from BaseIfc.
if(value == "IfcNullStyle")
{
continue;
}
constructors.AppendLine($"\t\tpublic {data.Name}({value} choice){{ this.choice = choice; }}");
}
var result =
$@"
using System;
using System.ComponentModel;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;
using STEP;
namespace IFC
{{
public class {data.Name} : Select
{{
{constructors.ToString()}
}}
}}
";
return result;
}
public string EntityConstructorParams(Entity data, bool includeOptional)
{
// Constructor parameters include the union of this type's attributes and all super type attributes.
// A constructor parameter is created for every attribute which does not derive
// from IFCRelationship.
var parents = data.ParentsAndSelf().Reverse();
var attrs = parents.SelectMany(p => p.Attributes);
if (!attrs.Any())
{
return string.Empty;
}
var validAttrs = includeOptional ? AttributesWithOptional(attrs) : AttributesWithoutOptional(attrs);
return string.Join(",", validAttrs.Select(a => $"{a.Type} {a.ParameterName}"));
}
public string EntityBaseConstructorParams(Entity data, bool includeOptional)
{
// Base constructor parameters include the union of all super type attributes.
var parents = data.Parents().Reverse();
var attrs = parents.SelectMany(p => p.Attributes);
if (!attrs.Any())
{
return string.Empty;
}
var validAttrs = includeOptional ? AttributesWithOptional(attrs) : AttributesWithoutOptional(attrs);
return string.Join(",", validAttrs.Select(a => $"{a.ParameterName}"));
}
public string EntityString(Entity data)
{
var super = "BaseIfc";
var newMod = string.Empty;
if (data.Subs.Any())
{
super = data.Subs[0].Name; ;
newMod = "new";
}
var modifier = data.IsAbstract ? "abstract" : string.Empty;
// Create two constructors, one which includes optional parameters and
// one which does not. We need to check whether any of the parent types
// have optional attributes as well, to avoid the case where the current type
// doesn't have optional parameters, but a base type does.
string constructors;
if (data.ParentsAndSelf().SelectMany(e => e.Attributes.Where(a => a.IsOptional)).Any())
{
constructors = $@"
/// <summary>
/// Construct a {data.Name} with all required attributes.
/// </summary>
public {data.Name}({ConstructorParams(data, false)}):base({BaseConstructorParams(data, false)})
{{
{Allocations(data, true)}
{Assignments(data, false)}
}}
/// <summary>
/// Construct a {data.Name} with required and optional attributes.
/// </summary>
[JsonConstructor]
public {data.Name}({ConstructorParams(data, true)}):base({BaseConstructorParams(data, true)})
{{
{Allocations(data, false)}
{Assignments(data, true)}
}}";
}
else
{
constructors = $@"
/// <summary>
/// Construct a {data.Name} with all required attributes.
/// </summary>
[JsonConstructor]
public {data.Name}({ConstructorParams(data, false)}):base({BaseConstructorParams(data, false)})
{{
{Allocations(data, true)}
{Assignments(data, false)}
}}";
}
var classStr =
$@"
using System;
using System.ComponentModel;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;
using STEP;
namespace IFC
{{
/// <summary>
/// <see href=""http://www.buildingsmart-tech.org/ifc/IFC4/final/html/link/{data.Name.ToLower()}.htm""/>
/// </summary>
public {modifier} partial class {data.Name} : {super}
{{
{data.Properties(selectData)}
{constructors}
public static {newMod} {data.Name} FromJSON(string json){{ return JsonConvert.DeserializeObject<{data.Name}>(json); }}
{StepParameters(data)}
}}
}}
";
return classStr;
}
public string StepParameters(Entity data)
{
if(data.IsAbstract)
{
return string.Empty;
}
var stepParameters = $@"
public override string GetStepParameters()
{{
var parameters = new List<string>();
{data.StepProperties()}
return string.Join("", "", parameters.ToArray());
}}";
return stepParameters;
}
public string EntityTest(Entity data)
{
return string.Empty;
}
public string FileExtension
{
get { return "g.cs"; }
}
public string ParseSimpleType(ExpressParser.SimpleTypeContext context)
{
var type = string.Empty;
if (context.binaryType() != null)
{
type = "byte[]";
}
else if (context.booleanType() != null)
{
type = "bool";
}
else if (context.integerType() != null)
{
type = "int";
}
else if (context.logicalType() != null)
{
type = "bool?";
}
else if (context.numberType() != null)
{
type = "double";
}
else if (context.realType() != null)
{
type = "double";
}
else if (context.stringType() != null)
{
type = "string";
}
return type;
}
private string Assignments(Entity entity, bool includeOptional)
{
var attrs = includeOptional ? AttributesWithOptional(entity.Attributes) : AttributesWithoutOptional(entity.Attributes);
if (!attrs.Any())
{
return string.Empty;
}
var assignBuilder = new StringBuilder();
foreach (var a in attrs)
{
var assign = Assignment(a);
if (!string.IsNullOrEmpty(assign))
{
assignBuilder.AppendLine(assign);
}
}
return assignBuilder.ToString();
}
private string Allocations(Entity entity, bool includeOptional)
{
var allocBuilder = new StringBuilder();
var attrs = entity.Attributes.Where(a => !a.IsDerived)
.Where(a => a.IsInverse || includeOptional && a.IsOptional);
foreach (var a in attrs)
{
var alloc = Allocation(a);
if (!string.IsNullOrEmpty(alloc))
{
allocBuilder.AppendLine(alloc);
}
}
return allocBuilder.ToString();
}
internal IEnumerable<AttributeData> AttributesWithOptional(IEnumerable<AttributeData> ad)
{
return ad.Where(a => !a.IsInverse)
.Where(a => !a.IsDerived);
}
internal IEnumerable<AttributeData> AttributesWithoutOptional(IEnumerable<AttributeData> ad)
{
return ad.Where(a => !a.IsInverse)
.Where(a => !a.IsDerived)
.Where(a => !a.IsOptional);
}
/// <summary>
/// Return a set of constructor parameters in the form 'Type name1, Type name2'
/// </summary>
/// <returns></returns>
private string ConstructorParams(Entity data, bool includeOptional)
{
return EntityConstructorParams(data, includeOptional);
}
/// <summary>
/// Return a set of constructor params in the form `name1, name2`.
/// </summary>
/// <returns></returns>
private string BaseConstructorParams(Entity data, bool includeOptional)
{
return EntityBaseConstructorParams(data, includeOptional);
}
public void GenerateManifest(string directory, IEnumerable<string> names){}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
namespace Scintilla.Configuration
{
/// <summary>
///
/// </summary>
public enum PropertyType
{
/// <summary>
///
/// </summary>
Property = 0,
/// <summary>
///
/// </summary>
Comment,
/// <summary>
///
/// </summary>
Import,
/// <summary>
///
/// </summary>
If,
/// <summary>
///
/// </summary>
IgnoredLine,
/// <summary>
///
/// </summary>
EmptyLine
}
/// <summary>
///
/// </summary>
/// <param name="file"></param>
/// <param name="propertyType"></param>
/// <param name="key"></param>
/// <param name="val"></param>
/// <returns></returns>
public delegate bool PropertyReadDelegate(ConfigResource resource, PropertyType propertyType, Queue<string> keyQueue, string key, string val);
public delegate string PropertyGetValueDelegate(string key);
public delegate bool PropertyContainsKeyDelegate(string key);
/// <summary>
/// A class that reads in ths properties from the
/// Justin Greenwood - justin.greenwood@gmail.com
/// </summary>
public static class PropertiesReader
{
private static Regex regExFindVars = new Regex(@"[\$][\(](?<varname>.*?)[\)]", RegexOptions.Compiled);
private static Regex regExKeyValPairs = new Regex(@"[\s]*(?:(?<key>[^,]*?)[\s]*:[\s]*(?<value>[^,^:]*[,]*?)|(?<single>[^,^:]*[,]*?))[\s]*", RegexOptions.Compiled);
private static PropertyGetValueDelegate getValue;
private static PropertyContainsKeyDelegate containsKey;
private static int replaceCount = 0;
private enum ReadMode
{
Key = 0,
Value,
Import,
If,
FlushWhiteSpace
}
public static void Read(FileInfo propsFileInfo, PropertyReadDelegate propertyRead)
{
Read(new ConfigResource(propsFileInfo), propertyRead);
}
/// <summary>
///
/// </summary>
/// <param name="propsFileInfo"></param>
/// <param name="propertyRead"></param>
public static void Read(ConfigResource resource, PropertyReadDelegate propertyRead)
{
if (!resource.Exists) return;
StreamReader reader = new StreamReader(resource.OpenRead());
char c = ' ', prev = '\\';
int lastStart = 0, ignoreCount = 0;
bool ignoreProperties = false;
string key = null, var = null;
StringBuilder currentVar = new StringBuilder();
StringBuilder currentToken = new StringBuilder();
Queue<string> queue = new Queue<string>();
StringBuilder currentTokenPiece = new StringBuilder();
ReadMode mode = ReadMode.Key;
ReadMode nextModeAfterSpaces = ReadMode.Key;
string line = reader.ReadLine();
while (line != null)
{
int start = 0;
bool skipLine = false;
while ((start < line.Length) && char.IsWhiteSpace(line[start])) ++start;
if (start >= line.Length)
{
propertyRead(resource, PropertyType.EmptyLine, queue, string.Empty, string.Empty);
}
else if (line[start] == '#')
{
propertyRead(resource, PropertyType.Comment, queue, "#", line);
}
else
{
if (ignoreProperties)
{
if ((ignoreCount == 0) || (start == lastStart))
{
ignoreCount++;
lastStart = start;
skipLine = true;
}
else
{
ignoreCount = 0;
ignoreProperties = false;
}
}
if (skipLine)
{
propertyRead(resource, PropertyType.EmptyLine, queue, string.Empty, string.Empty);
}
else
{
for (int i = start; i < line.Length; i++)
{
c = line[i];
if (mode == ReadMode.Key)
{
if (c == '=')
{
if (currentTokenPiece.Length > 0)
{
queue.Enqueue(currentTokenPiece.ToString());
}
currentTokenPiece.Remove(0, currentTokenPiece.Length);
key = currentToken.ToString();
currentToken.Remove(0, currentToken.Length);
mode = ReadMode.Value;
continue;
}
else if (char.IsWhiteSpace(c))
{
key = currentToken.ToString();
currentToken.Remove(0, currentToken.Length);
currentTokenPiece.Remove(0, currentTokenPiece.Length);
if (key == "if")
{
nextModeAfterSpaces = ReadMode.If;
}
else if (key == "import")
{
nextModeAfterSpaces = ReadMode.Import;
}
else
{
break;
}
mode = ReadMode.FlushWhiteSpace;
continue;
}
else if (c == '.')
{
currentToken.Append(c);
queue.Enqueue(currentTokenPiece.ToString());
currentTokenPiece.Remove(0, currentTokenPiece.Length);
}
else
{
currentTokenPiece.Append(c);
currentToken.Append(c);
}
}
else if (mode == ReadMode.FlushWhiteSpace)
{
if (!char.IsWhiteSpace(c))
{
currentToken.Append(c);
mode = nextModeAfterSpaces;
}
}
else if (mode == ReadMode.Import)
{
currentToken.Append(c);
}
else if (mode == ReadMode.If)
{
currentToken.Append(c);
}
else if (mode == ReadMode.Value)
{
currentToken.Append(c);
}
prev = c;
}
if (prev != '\\')
{
var = currentToken.ToString();
if (mode == ReadMode.If)
{
ignoreProperties = propertyRead(resource, PropertyType.If, queue, key, var);
}
else if (mode == ReadMode.Import)
{
// Open another file inline with this one.
if (propertyRead(resource, PropertyType.Import, queue, key, var))
{
ConfigResource res = resource.GetLocalConfigResource(string.Format(@"{0}.properties", var));
//success = res.Exists;
//FileInfo fileToImport = new FileInfo(string.Format(@"{0}\{1}.properties", propsFileInfo.Directory.FullName, var));
if (res.Exists)
{
Read(res, propertyRead);
}
}
}
else if (mode == ReadMode.Value)
{
propertyRead(resource, PropertyType.Property, queue, key, var);
}
currentToken.Remove(0, currentToken.Length);
queue.Clear();
key = null;
mode = ReadMode.Key;
}
else
{
currentToken.Remove(currentToken.Length - 1, 1);
}
}
}
line = reader.ReadLine();
}
reader.Close();
if (key != null)
{
var = currentToken.ToString();
propertyRead(resource, PropertyType.Property, queue, key, var);
}
}
#region Evaluate String with embedded variables
/// <summary>
///
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string Evaluate(string str, PropertyGetValueDelegate getValueDel, PropertyContainsKeyDelegate containsKeyDel)
{
string tmp = str;
if ((getValueDel != null) && (containsKeyDel != null))
{
getValue = getValueDel;
containsKey = containsKeyDel;
do
{
replaceCount = 0;
tmp = regExFindVars.Replace(tmp, new MatchEvaluator(ReplaceVariableMatch));
} while (replaceCount > 0);
}
return tmp;
}
/// <summary>
///
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
private static string ReplaceVariableMatch(Match m)
{
string output = m.Value;
if ((getValue != null) && (containsKey != null))
{
if ((m.Groups["varname"].Length > 0) && (m.Groups["varname"].Captures.Count > 0))
{
Capture capture = m.Groups["varname"].Captures[0];
if (containsKey(capture.Value))
{
output = getValue(capture.Value);
}
else
{
output = string.Empty;
}
replaceCount++;
}
}
return output;
}
#endregion
#region Parse out "key:value," pairs for those properties that use them.
public static Dictionary<string, string> GetKeyValuePairs(string str)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
GetKeyValuePairs(str, dictionary);
return dictionary;
}
/// <summary>
///
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static void GetKeyValuePairs(string str, IDictionary<string, string> dictionary)
{
MatchCollection matches = regExKeyValPairs.Matches(str);
foreach (Match m in matches)
{
if (((m.Groups["key"].Length > 0) && (m.Groups["key"].Captures.Count > 0)) &&
((m.Groups["value"].Length > 0) && (m.Groups["value"].Captures.Count > 0)))
{
string captureKey = m.Groups["key"].Captures[0].Value;
string captureValue = m.Groups["value"].Captures[0].Value;
if (!string.IsNullOrEmpty(captureKey))
{
dictionary[captureKey] = (captureValue != null) ? captureValue : Boolean.TrueString;
}
}
else if ((m.Groups["single"].Length > 0) && (m.Groups["single"].Captures.Count > 0))
{
string captureKey = m.Groups["single"].Captures[0].Value;
if (!string.IsNullOrEmpty(captureKey))
{
dictionary[captureKey] = Boolean.TrueString;
}
}
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using NUnit.Framework;
using OpenQA.Selenium;
namespace Protractor.Extensions
{
public static class Extensions
{
private static string result = null;
private static Regex Reg;
private static MatchCollection Matches;
public static string FindMatch(this string element_text, string match_string, string match_name)
{
result = null;
Reg = new Regex(match_string,
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
Matches = Reg.Matches(element_text);
foreach (Match Match in Matches)
{
if (Match.Length != 0)
{
foreach (Capture Capture in Match.Groups[match_name].Captures)
{
if (result == null)
{
result = Capture.ToString();
}
}
}
}
return result;
}
public static string FindMatch(this string element_text, string match_string)
{
string match_name = match_string.FindMatch("(?:<(?<result>[^>]+)>)", "result");
result = null;
Reg = new Regex(match_string,
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
Matches = Reg.Matches(element_text);
foreach (Match Match in Matches)
{
if (Match.Length != 0)
{
foreach (Capture Capture in Match.Groups[match_name].Captures)
{
if (result == null)
{
result = Capture.ToString();
}
}
}
}
return result;
}
public static void Highlight(this NgWebDriver ngDriver, IWebElement element, int highlight_timeout = 100, int px = 3, string color = "yellow")
{
IWebDriver driver = ngDriver.WrappedDriver;
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].style.border='" + px + "px solid " + color + "'", element);
Thread.Sleep(highlight_timeout);
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].style.border=''", element);
}
public static void Highlight(this IWebDriver driver, IWebElement element, int highlight_timeout = 100, int px = 3, string color = "yellow")
{
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].style.border='" + px + "px solid " + color + "'", element);
Thread.Sleep(highlight_timeout);
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].style.border=''", element);
}
public static string CssSelectorOf(this NgWebElement ngWebElement)
{
string getCssSelectorOfElement = @"
var get_css_selector_of = function(element) {
if (!(element instanceof Element))
return;
var path = [];
while (element.nodeType === Node.ELEMENT_NODE) {
var selector = element.nodeName.toLowerCase();
if (element.id) {
if (element.id.indexOf('-') > -1) {
selector += '[id = ""' + element.id + '""]';
} else {
selector += '#' + element.id;
}
path.unshift(selector);
break;
} else {
var element_sibling = element;
var sibling_cnt = 1;
while (element_sibling = element_sibling.previousElementSibling) {
if (element_sibling.nodeName.toLowerCase() == selector)
sibling_cnt++;
}
if (sibling_cnt != 1)
selector += ':nth-of-type(' + sibling_cnt + ')';
}
path.unshift(selector);
element = element.parentNode;
}
return path.join(' > ');
}
return get_css_selector_of(arguments[0]);
";
return ((IJavaScriptExecutor)ngWebElement.NgDriver.WrappedDriver).ExecuteScript(getCssSelectorOfElement, ngWebElement.WrappedElement).ToString();
}
public static string XPathOf(this NgWebElement ngWebElement)
{
string getXpathOfElement = @"
var get_xpath_of = function(element) {
var elementTagName = element.tagName.toLowerCase();
if (element.id != '') {
return '//' + elementTagName + '[@id=""' + element.id + '""]';
} else if (element.name && document.getElementsByName(element.name).length === 1) {
return '//' + elementTagName + '[@name=""' + element.name + '""]';
}
if (element === document.body) {
return '/html/' + elementTagName;
}
var sibling_count = 0;
var siblings = element.parentNode.childNodes;
siblings_length = siblings.length;
for (cnt = 0; cnt < siblings_length; cnt++) {
var sibling_element = siblings[cnt];
if (sibling_element.nodeType !== 1) { // not ELEMENT_NODE
continue;
}
if (sibling_element === element) {
return sibling_count > 0 ? get_xpath_of(element.parentNode) + '/' + elementTagName + '[' + (sibling_count + 1) + ']' : get_xpath_of(element.parentNode) + '/' + elementTagName;
}
if (sibling_element.nodeType === 1 && sibling_element.tagName.toLowerCase() === elementTagName) {
sibling_count++;
}
}
return;
};
return get_xpath_of(arguments[0]);
";
return ((IJavaScriptExecutor)ngWebElement.NgDriver.WrappedDriver).ExecuteScript(getXpathOfElement, ngWebElement.WrappedElement).ToString();
}
public static T Execute<T>(this IWebDriver driver, string script, params Object[] args)
{
return (T)((IJavaScriptExecutor)driver).ExecuteScript(script, args);
}
public static List<Dictionary<String, String>> ScopeOf(this NgWebElement ngWebElement)
{
string getScopeOfElement = "return angular.element(arguments[0]).scope();";
IWebDriver driver = ngWebElement.NgDriver.WrappedDriver;
List<Dictionary<String, String>> result = new List<Dictionary<string, string>>();
IEnumerable<Object> raw_data = driver.Execute<IEnumerable<Object>>(getScopeOfElement, ngWebElement.WrappedElement);
foreach (var element in (IEnumerable<Object>)raw_data)
{
Dictionary<String, String> row = new Dictionary<String, String>();
Dictionary<String, Object> dic = (Dictionary<String, Object>)element;
foreach (object key in dic.Keys)
{
Object val = null;
if (!dic.TryGetValue(key.ToString(), out val)) { val = ""; }
row.Add(key.ToString(), val.ToString());
}
result.Add(row);
}
return result;
}
public static List<Dictionary<String, String>> ScopeDataOf(this NgWebElement ngWebElement, string scopeData)
{
string getScopeData = String.Format("return angular.element(arguments[0]).scope().{0};", scopeData);
IWebDriver driver = ngWebElement.NgDriver.WrappedDriver;
List<Dictionary<String, String>> result = new List<Dictionary<string, string>>();
IEnumerable<Object> raw_data = driver.Execute<IEnumerable<Object>>(getScopeData, ngWebElement.WrappedElement);
foreach (var element in (IEnumerable<Object>)raw_data)
{
Dictionary<String, String> row = new Dictionary<String, String>();
Dictionary<String, Object> dic = (Dictionary<String, Object>)element;
foreach (object key in dic.Keys)
{
Object val = null;
if (!dic.TryGetValue(key.ToString(), out val)) { val = ""; }
row.Add(key.ToString(), val.ToString());
}
result.Add(row);
}
return result;
}
public static String IdentityOf(this NgWebElement ngWebElement)
{
string getIdentityOfElement = "return angular.identity(angular.element(arguments[0])).html();";
return ((IJavaScriptExecutor)ngWebElement.NgDriver.WrappedDriver).ExecuteScript(getIdentityOfElement, ngWebElement.WrappedElement).ToString();
}
}
}
| |
using System;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using OrchardCore.ContentManagement;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.Descriptors;
using OrchardCore.Menu.Models;
namespace OrchardCore.Menu
{
public class MenuShapes : IShapeTableProvider
{
public void Discover(ShapeTableBuilder builder)
{
builder.Describe("Menu")
.OnProcessing(async context =>
{
dynamic menu = context.Shape;
string identifier = menu.ContentItemId ?? menu.Alias;
if (String.IsNullOrEmpty(identifier))
{
return;
}
menu.Classes.Add("menu");
// Menu population is executed when processing the shape so that its value
// can be cached. IShapeDisplayEvents is called before the ShapeDescriptor
// events and thus this code can be cached.
var shapeFactory = context.ServiceProvider.GetRequiredService<IShapeFactory>();
var contentManager = context.ServiceProvider.GetRequiredService<IContentManager>();
var aliasManager = context.ServiceProvider.GetRequiredService<IContentAliasManager>();
string contentItemId = menu.Alias != null
? await aliasManager.GetContentItemIdAsync(menu.Alias)
: menu.ContentItemId;
if (contentItemId == null)
{
return;
}
var menuContentItem = await contentManager.GetAsync(contentItemId);
if (menuContentItem == null)
{
return;
}
menu.ContentItem = menuContentItem;
menu.MenuName = menuContentItem.DisplayText;
var menuItems = menuContentItem.As<MenuItemsListPart>()?.MenuItems;
if (menuItems == null)
{
return;
}
string differentiator = FormatName((string)menu.MenuName);
if (!String.IsNullOrEmpty(differentiator))
{
// Menu__[MenuName] e.g. Menu-MainMenu
menu.Metadata.Alternates.Add("Menu__" + differentiator);
menu.Differentiator = differentiator;
}
// The first level of menu item shapes is created.
// Each other level is created when the menu item is displayed.
foreach (var contentItem in menuItems)
{
var shape = await shapeFactory.CreateAsync("MenuItem", Arguments.From(new
{
ContentItem = contentItem,
Level = 0,
Menu = menu,
Differentiator = differentiator
}));
// Don't use Items.Add() or the collection won't be sorted
menu.Add(shape);
}
});
builder.Describe("MenuItem")
.OnDisplaying(async context =>
{
dynamic menuItem = context.Shape;
ContentItem menuContentItem = menuItem.ContentItem;
var menu = menuItem.Menu;
int level = menuItem.Level;
string differentiator = menuItem.Differentiator;
var shapeFactory = context.ServiceProvider.GetRequiredService<IShapeFactory>();
var menuItems = menuContentItem.As<MenuItemsListPart>()?.MenuItems;
if (menuItems != null)
{
foreach (var contentItem in menuItems)
{
var shape = await shapeFactory.CreateAsync("MenuItem", Arguments.From(new
{
ContentItem = contentItem,
Level = level + 1,
Menu = menu,
Differentiator = differentiator
}));
// Don't use Items.Add() or the collection won't be sorted
menuItem.Add(shape);
}
}
var encodedContentType = EncodeAlternateElement(menuContentItem.ContentItem.ContentType);
// MenuItem__level__[level] e.g. MenuItem-level-2
menuItem.Metadata.Alternates.Add("MenuItem__level__" + level);
// MenuItem__[ContentType] e.g. MenuItem-HtmlMenuItem
// MenuItem__[ContentType]__level__[level] e.g. MenuItem-HtmlMenuItem-level-2
menuItem.Metadata.Alternates.Add("MenuItem__" + encodedContentType);
menuItem.Metadata.Alternates.Add("MenuItem__" + encodedContentType + "__level__" + level);
if (!String.IsNullOrEmpty(differentiator))
{
// MenuItem__[MenuName] e.g. MenuItem-MainMenu
// MenuItem__[MenuName]__level__[level] e.g. MenuItem-MainMenu-level-2
menuItem.Metadata.Alternates.Add("MenuItem__" + differentiator);
menuItem.Metadata.Alternates.Add("MenuItem__" + differentiator + "__level__" + level);
// MenuItem__[MenuName]__[ContentType] e.g. MenuItem-MainMenu-HtmlMenuItem
// MenuItem__[MenuName]__[ContentType]__level__[level] e.g. MenuItem-MainMenu-HtmlMenuItem-level-2
menuItem.Metadata.Alternates.Add("MenuItem__" + differentiator + "__" + encodedContentType);
menuItem.Metadata.Alternates.Add("MenuItem__" + differentiator + "__" + encodedContentType + "__level__" + level);
}
});
builder.Describe("MenuItemLink")
.OnDisplaying(displaying =>
{
dynamic menuItem = displaying.Shape;
int level = menuItem.Level;
string differentiator = menuItem.Differentiator;
ContentItem menuContentItem = menuItem.ContentItem;
var encodedContentType = EncodeAlternateElement(menuContentItem.ContentItem.ContentType);
menuItem.Metadata.Alternates.Add("MenuItemLink__level__" + level);
// MenuItemLink__[ContentType] e.g. MenuItemLink-HtmlMenuItem
// MenuItemLink__[ContentType]__level__[level] e.g. MenuItemLink-HtmlMenuItem-level-2
menuItem.Metadata.Alternates.Add("MenuItemLink__" + encodedContentType);
menuItem.Metadata.Alternates.Add("MenuItemLink__" + encodedContentType + "__level__" + level);
if (!String.IsNullOrEmpty(differentiator))
{
// MenuItemLink__[MenuName] e.g. MenuItemLink-MainMenu
// MenuItemLink__[MenuName]__level__[level] e.g. MenuItemLink-MainMenu-level-2
menuItem.Metadata.Alternates.Add("MenuItemLink__" + differentiator);
menuItem.Metadata.Alternates.Add("MenuItemLink__" + differentiator + "__level__" + level);
// MenuItemLink__[MenuName]__[ContentType] e.g. MenuItemLink-MainMenu-HtmlMenuItem
// MenuItemLink__[MenuName]__[ContentType] e.g. MenuItemLink-MainMenu-HtmlMenuItem-level-2
menuItem.Metadata.Alternates.Add("MenuItemLink__" + differentiator + "__" + encodedContentType);
menuItem.Metadata.Alternates.Add("MenuItemLink__" + differentiator + "__" + encodedContentType + "__level__" + level);
}
});
}
/// <summary>
/// Encodes dashed and dots so that they don't conflict in filenames
/// </summary>
/// <param name="alternateElement"></param>
/// <returns></returns>
private string EncodeAlternateElement(string alternateElement)
{
return alternateElement.Replace("-", "__").Replace('.', '_');
}
/// <summary>
/// Converts "foo-ba r" to "FooBaR"
/// </summary>
private static string FormatName(string name)
{
if (String.IsNullOrEmpty(name))
{
return null;
}
name = name.Trim();
var nextIsUpper = true;
var result = new StringBuilder(name.Length);
for (var i = 0; i < name.Length; i++)
{
var c = name[i];
if (c == '-' || char.IsWhiteSpace(c))
{
nextIsUpper = true;
continue;
}
if (nextIsUpper)
{
result.Append(c.ToString().ToUpper());
}
else
{
result.Append(c);
}
nextIsUpper = false;
}
return result.ToString();
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System {
//Only contains static methods. Does not require serialization
using System;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Security;
using System.Runtime;
[System.Runtime.InteropServices.ComVisible(true)]
public static partial class Buffer
{
#if !MONO
// Copies from one primitive array to another primitive array without
// respecting types. This calls memmove internally. The count and
// offset parameters here are in bytes. If you want to use traditional
// array element indices and counts, use Array.Copy.
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void BlockCopy(Array src, int srcOffset,
Array dst, int dstOffset, int count);
#endif
// A very simple and efficient memmove that assumes all of the
// parameter validation has already been done. The count and offset
// parameters here are in bytes. If you want to use traditional
// array element indices and counts, use Array.Copy.
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool InternalBlockCopy(Array src, int srcOffsetBytes,
Array dst, int dstOffsetBytes, int byteCount);
// This is ported from the optimized CRT assembly in memchr.asm. The JIT generates
// pretty good code here and this ends up being within a couple % of the CRT asm.
// It is however cross platform as the CRT hasn't ported their fast version to 64-bit
// platforms.
//
[System.Security.SecurityCritical] // auto-generated
internal unsafe static int IndexOfByte(byte* src, byte value, int index, int count)
{
Contract.Assert(src != null, "src should not be null");
byte* pByte = src + index;
// Align up the pointer to sizeof(int).
while (((int)pByte & 3) != 0)
{
if (count == 0)
return -1;
else if (*pByte == value)
return (int) (pByte - src);
count--;
pByte++;
}
// Fill comparer with value byte for comparisons
//
// comparer = 0/0/value/value
uint comparer = (((uint)value << 8) + (uint)value);
// comparer = value/value/value/value
comparer = (comparer << 16) + comparer;
// Run through buffer until we hit a 4-byte section which contains
// the byte we're looking for or until we exhaust the buffer.
while (count > 3)
{
// Test the buffer for presence of value. comparer contains the byte
// replicated 4 times.
uint t1 = *(uint*)pByte;
t1 = t1 ^ comparer;
uint t2 = 0x7efefeff + t1;
t1 = t1 ^ 0xffffffff;
t1 = t1 ^ t2;
t1 = t1 & 0x81010100;
// if t1 is zero then these 4-bytes don't contain a match
if (t1 != 0)
{
// We've found a match for value, figure out which position it's in.
int foundIndex = (int) (pByte - src);
if (pByte[0] == value)
return foundIndex;
else if (pByte[1] == value)
return foundIndex + 1;
else if (pByte[2] == value)
return foundIndex + 2;
else if (pByte[3] == value)
return foundIndex + 3;
}
count -= 4;
pByte += 4;
}
// Catch any bytes that might be left at the tail of the buffer
while (count > 0)
{
if (*pByte == value)
return (int) (pByte - src);
count--;
pByte++;
}
// If we don't have a match return -1;
return -1;
}
#if !MONO
// Returns a bool to indicate if the array is of primitive data types
// or not.
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool IsPrimitiveTypeArray(Array array);
#endif
// Gets a particular byte out of the array. The array must be an
// array of primitives.
//
// This essentially does the following:
// return ((byte*)array) + index.
//
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern byte _GetByte(Array array, int index);
#if !MONO
[System.Security.SecuritySafeCritical] // auto-generated
public static byte GetByte(Array array, int index)
{
// Is the array present?
if (array == null)
throw new ArgumentNullException("array");
// Is it of primitive types?
if (!IsPrimitiveTypeArray(array))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), "array");
// Is the index in valid range of the array?
if (index < 0 || index >= _ByteLength(array))
throw new ArgumentOutOfRangeException("index");
return _GetByte(array, index);
}
#endif
// Sets a particular byte in an the array. The array must be an
// array of primitives.
//
// This essentially does the following:
// *(((byte*)array) + index) = value.
//
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _SetByte(Array array, int index, byte value);
#if !MONO
[System.Security.SecuritySafeCritical] // auto-generated
public static void SetByte(Array array, int index, byte value)
{
// Is the array present?
if (array == null)
throw new ArgumentNullException("array");
// Is it of primitive types?
if (!IsPrimitiveTypeArray(array))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), "array");
// Is the index in valid range of the array?
if (index < 0 || index >= _ByteLength(array))
throw new ArgumentOutOfRangeException("index");
// Make the FCall to do the work
_SetByte(array, index, value);
}
#endif
// Gets a particular byte out of the array. The array must be an
// array of primitives.
//
// This essentially does the following:
// return array.length * sizeof(array.UnderlyingElementType).
//
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int _ByteLength(Array array);
#if !MONO
[System.Security.SecuritySafeCritical] // auto-generated
public static int ByteLength(Array array)
{
// Is the array present?
if (array == null)
throw new ArgumentNullException("array");
// Is it of primitive types?
if (!IsPrimitiveTypeArray(array))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), "array");
return _ByteLength(array);
}
#endif
[System.Security.SecurityCritical] // auto-generated
internal unsafe static void ZeroMemory(byte* src, long len)
{
while(len-- > 0)
*(src + len) = 0;
}
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal unsafe static void Memcpy(byte[] dest, int destIndex, byte* src, int srcIndex, int len) {
Contract.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!");
Contract.Assert(dest.Length - destIndex >= len, "not enough bytes in dest");
// If dest has 0 elements, the fixed statement will throw an
// IndexOutOfRangeException. Special-case 0-byte copies.
if (len==0)
return;
fixed(byte* pDest = dest) {
Memcpy(pDest + destIndex, src + srcIndex, len);
}
}
[SecurityCritical]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal unsafe static void Memcpy(byte* pDest, int destIndex, byte[] src, int srcIndex, int len)
{
Contract.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!");
Contract.Assert(src.Length - srcIndex >= len, "not enough bytes in src");
// If dest has 0 elements, the fixed statement will throw an
// IndexOutOfRangeException. Special-case 0-byte copies.
if (len==0)
return;
fixed(byte* pSrc = src) {
Memcpy(pDest + destIndex, pSrc + srcIndex, len);
}
}
#if !MONO
// This is tricky to get right AND fast, so lets make it useful for the whole Fx.
// E.g. System.Runtime.WindowsRuntime!WindowsRuntimeBufferExtensions.MemCopy uses it.
// This method has a slightly different behavior on arm and other platforms.
// On arm this method behaves like memcpy and does not handle overlapping buffers.
// While on other platforms it behaves like memmove and handles overlapping buffers.
// This behavioral difference is unfortunate but intentional because
// 1. This method is given access to other internal dlls and this close to release we do not want to change it.
// 2. It is difficult to get this right for arm and again due to release dates we would like to visit it later.
[FriendAccessAllowed]
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.None)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
#if ARM
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal unsafe static extern void Memcpy(byte* dest, byte* src, int len);
#else // ARM
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
internal unsafe static void Memcpy(byte* dest, byte* src, int len) {
Contract.Assert(len >= 0, "Negative length in memcopy!");
Memmove(dest, src, (uint)len);
}
#endif // ARM
// This method has different signature for x64 and other platforms and is done for performance reasons.
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.None)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
#if WIN64
internal unsafe static void Memmove(byte* dest, byte* src, ulong len)
#else
internal unsafe static void Memmove(byte* dest, byte* src, uint len)
#endif
{
// P/Invoke into the native version when the buffers are overlapping and the copy needs to be performed backwards
// This check can produce false positives for lengths greater than Int32.MaxInt. It is fine because we want to use PInvoke path for the large lengths anyway.
#if WIN64
if ((ulong)dest - (ulong)src < len) goto PInvoke;
#else
if (((uint)dest - (uint)src) < len) goto PInvoke;
#endif
//
// This is portable version of memcpy. It mirrors what the hand optimized assembly versions of memcpy typically do.
//
// Ideally, we would just use the cpblk IL instruction here. Unfortunately, cpblk IL instruction is not as efficient as
// possible yet and so we have this implementation here for now.
//
switch (len)
{
case 0:
return;
case 1:
*dest = *src;
return;
case 2:
*(short *)dest = *(short *)src;
return;
case 3:
*(short *)dest = *(short *)src;
*(dest + 2) = *(src + 2);
return;
case 4:
*(int *)dest = *(int *)src;
return;
case 5:
*(int*)dest = *(int*)src;
*(dest + 4) = *(src + 4);
return;
case 6:
*(int*)dest = *(int*)src;
*(short*)(dest + 4) = *(short*)(src + 4);
return;
case 7:
*(int*)dest = *(int*)src;
*(short*)(dest + 4) = *(short*)(src + 4);
*(dest + 6) = *(src + 6);
return;
case 8:
#if WIN64
*(long*)dest = *(long*)src;
#else
*(int*)dest = *(int*)src;
*(int*)(dest + 4) = *(int*)(src + 4);
#endif
return;
case 9:
#if WIN64
*(long*)dest = *(long*)src;
#else
*(int*)dest = *(int*)src;
*(int*)(dest + 4) = *(int*)(src + 4);
#endif
*(dest + 8) = *(src + 8);
return;
case 10:
#if WIN64
*(long*)dest = *(long*)src;
#else
*(int*)dest = *(int*)src;
*(int*)(dest + 4) = *(int*)(src + 4);
#endif
*(short*)(dest + 8) = *(short*)(src + 8);
return;
case 11:
#if WIN64
*(long*)dest = *(long*)src;
#else
*(int*)dest = *(int*)src;
*(int*)(dest + 4) = *(int*)(src + 4);
#endif
*(short*)(dest + 8) = *(short*)(src + 8);
*(dest + 10) = *(src + 10);
return;
case 12:
#if WIN64
*(long*)dest = *(long*)src;
#else
*(int*)dest = *(int*)src;
*(int*)(dest + 4) = *(int*)(src + 4);
#endif
*(int*)(dest + 8) = *(int*)(src + 8);
return;
case 13:
#if WIN64
*(long*)dest = *(long*)src;
#else
*(int*)dest = *(int*)src;
*(int*)(dest + 4) = *(int*)(src + 4);
#endif
*(int*)(dest + 8) = *(int*)(src + 8);
*(dest + 12) = *(src + 12);
return;
case 14:
#if WIN64
*(long*)dest = *(long*)src;
#else
*(int*)dest = *(int*)src;
*(int*)(dest + 4) = *(int*)(src + 4);
#endif
*(int*)(dest + 8) = *(int*)(src + 8);
*(short*)(dest + 12) = *(short*)(src + 12);
return;
case 15:
#if WIN64
*(long*)dest = *(long*)src;
#else
*(int*)dest = *(int*)src;
*(int*)(dest + 4) = *(int*)(src + 4);
#endif
*(int*)(dest + 8) = *(int*)(src + 8);
*(short*)(dest + 12) = *(short*)(src + 12);
*(dest + 14) = *(src + 14);
return;
case 16:
#if WIN64
*(long*)dest = *(long*)src;
*(long*)(dest + 8) = *(long*)(src + 8);
#else
*(int*)dest = *(int*)src;
*(int*)(dest + 4) = *(int*)(src + 4);
*(int*)(dest + 8) = *(int*)(src + 8);
*(int*)(dest + 12) = *(int*)(src + 12);
#endif
return;
default:
break;
}
// P/Invoke into the native version for large lengths
if (len >= 512) goto PInvoke;
if (((int)dest & 3) != 0)
{
if (((int)dest & 1) != 0)
{
*dest = *src;
src++;
dest++;
len--;
if (((int)dest & 2) == 0)
goto Aligned;
}
*(short *)dest = *(short *)src;
src += 2;
dest += 2;
len -= 2;
Aligned: ;
}
#if WIN64
if (((int)dest & 4) != 0)
{
*(int *)dest = *(int *)src;
src += 4;
dest += 4;
len -= 4;
}
#endif
#if WIN64
ulong count = len / 16;
#else
uint count = len / 16;
#endif
while (count > 0)
{
#if WIN64
((long*)dest)[0] = ((long*)src)[0];
((long*)dest)[1] = ((long*)src)[1];
#else
((int*)dest)[0] = ((int*)src)[0];
((int*)dest)[1] = ((int*)src)[1];
((int*)dest)[2] = ((int*)src)[2];
((int*)dest)[3] = ((int*)src)[3];
#endif
dest += 16;
src += 16;
count--;
}
if ((len & 8) != 0)
{
#if WIN64
((long*)dest)[0] = ((long*)src)[0];
#else
((int*)dest)[0] = ((int*)src)[0];
((int*)dest)[1] = ((int*)src)[1];
#endif
dest += 8;
src += 8;
}
if ((len & 4) != 0)
{
((int*)dest)[0] = ((int*)src)[0];
dest += 4;
src += 4;
}
if ((len & 2) != 0)
{
((short*)dest)[0] = ((short*)src)[0];
dest += 2;
src += 2;
}
if ((len & 1) != 0)
*dest = *src;
return;
PInvoke:
_Memmove(dest, src, len);
}
// Non-inlinable wrapper around the QCall that avoids poluting the fast path
// with P/Invoke prolog/epilog.
[SecurityCritical]
[ResourceExposure(ResourceScope.None)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
#if WIN64
private unsafe static void _Memmove(byte* dest, byte* src, ulong len)
#else
private unsafe static void _Memmove(byte* dest, byte* src, uint len)
#endif
{
__Memmove(dest, src, len);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[SecurityCritical]
[ResourceExposure(ResourceScope.None)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
#if WIN64
extern private unsafe static void __Memmove(byte* dest, byte* src, ulong len);
#else
extern private unsafe static void __Memmove(byte* dest, byte* src, uint len);
#endif
// The attributes on this method are chosen for best JIT performance.
// Please do not edit unless intentional.
[System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
[CLSCompliant(false)]
public static unsafe void MemoryCopy(void* source, void* destination, long destinationSizeInBytes, long sourceBytesToCopy)
{
if (sourceBytesToCopy > destinationSizeInBytes)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sourceBytesToCopy);
}
#if WIN64
Memmove((byte*)destination, (byte*)source, checked((ulong) sourceBytesToCopy));
#else
Memmove((byte*)destination, (byte*)source, checked((uint)sourceBytesToCopy));
#endif // WIN64
}
// The attributes on this method are chosen for best JIT performance.
// Please do not edit unless intentional.
[System.Security.SecurityCritical]
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
[CLSCompliant(false)]
public static unsafe void MemoryCopy(void* source, void* destination, ulong destinationSizeInBytes, ulong sourceBytesToCopy)
{
if (sourceBytesToCopy > destinationSizeInBytes)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sourceBytesToCopy);
}
#if WIN64
Memmove((byte*)destination, (byte*)source, sourceBytesToCopy);
#else
Memmove((byte*)destination, (byte*)source, checked((uint)sourceBytesToCopy));
#endif // WIN64
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using AppxPackaing;
using Shell;
using Wox.Infrastructure;
using Wox.Infrastructure.Logger;
using IStream = AppxPackaing.IStream;
using Rect = System.Windows.Rect;
using NLog;
using System.Collections.Concurrent;
using Microsoft.Win32;
using System.Xml;
namespace Wox.Plugin.Program.Programs
{
[Serializable]
public class UWP
{
public string FullName { get; }
public string FamilyName { get; }
public string Name { get; set; }
public string Location { get; set; }
public Application[] Apps { get; set; }
public PackageVersion Version { get; set; }
private static readonly NLog.Logger Logger = LogManager.GetCurrentClassLogger();
public UWP(string id, string location)
{
FullName = id;
string[] parts = id.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
FamilyName = $"{parts[0]}_{parts[parts.Length - 1]}";
Location = location;
}
/// <exception cref="ArgumentException"
private void InitializeAppInfo()
{
var path = Path.Combine(Location, "AppxManifest.xml");
using (var reader = XmlReader.Create(path))
{
bool success = reader.ReadToFollowing("Package");
if (!success) { throw new ArgumentException($"Cannot read Package key from {path}"); }
Version = PackageVersion.Unknown;
for (int i = 0; i < reader.AttributeCount; i++)
{
string schema = reader.GetAttribute(i);
if (schema != null)
{
if (schema == "http://schemas.microsoft.com/appx/manifest/foundation/windows10")
{
Version = PackageVersion.Windows10;
}
else if (schema == "http://schemas.microsoft.com/appx/2013/manifest")
{
Version = PackageVersion.Windows81;
}
else if (schema == "http://schemas.microsoft.com/appx/2010/manifest")
{
Version = PackageVersion.Windows8;
}
else
{
continue;
}
}
}
if (Version == PackageVersion.Unknown)
{
throw new ArgumentException($"Unknowen schema version {path}");
}
success = reader.ReadToFollowing("Identity");
if (!success) { throw new ArgumentException($"Cannot read Identity key from {path}"); }
if (success)
{
Name = reader.GetAttribute("Name");
}
success = reader.ReadToFollowing("Applications");
if (!success) { throw new ArgumentException($"Cannot read Applications key from {path}"); }
success = reader.ReadToDescendant("Application");
if (!success) { throw new ArgumentException($"Cannot read Applications key from {path}"); }
List<Application> apps = new List<Application>();
do
{
string id = reader.GetAttribute("Id");
reader.ReadToFollowing("uap:VisualElements");
string displayName = reader.GetAttribute("DisplayName");
string description = reader.GetAttribute("Description");
string backgroundColor = reader.GetAttribute("BackgroundColor");
string appListEntry = reader.GetAttribute("AppListEntry");
if (appListEntry == "none")
{
continue;
}
string logoUri = string.Empty;
if (Version == PackageVersion.Windows10)
{
logoUri = reader.GetAttribute("Square44x44Logo");
}
else if (Version == PackageVersion.Windows81)
{
logoUri = reader.GetAttribute("Square30x30Logo");
}
else if (Version == PackageVersion.Windows8)
{
logoUri = reader.GetAttribute("SmallLogo");
}
else
{
throw new ArgumentException($"Unknowen schema version {path}");
}
if (string.IsNullOrEmpty(displayName) || string.IsNullOrEmpty(id))
{
continue;
}
string userModelId = $"{FamilyName}!{id}";
Application app = new Application(this, userModelId, FullName, Name, displayName, description, logoUri, backgroundColor);
apps.Add(app);
} while (reader.ReadToFollowing("Application"));
Apps = apps.ToArray();
}
}
public static Application[] All()
{
ConcurrentBag<Application> bag = new ConcurrentBag<Application>();
Parallel.ForEach(PackageFoldersFromRegistry(), (package, state) =>
{
try
{
package.InitializeAppInfo();
foreach (var a in package.Apps)
{
bag.Add(a);
}
}
catch (Exception e)
{
e.Data.Add(nameof(package.FullName), package.FullName);
e.Data.Add(nameof(package.Location), package.Location);
Logger.WoxError($"Cannot parse UWP {package.Location}", e);
}
}
);
return bag.ToArray();
}
public static List<UWP> PackageFoldersFromRegistry()
{
var actiable = new HashSet<string>();
string activableReg = @"Software\Classes\ActivatableClasses\Package";
var activableRegSubkey = Registry.CurrentUser.OpenSubKey(activableReg);
foreach (string name in activableRegSubkey.GetSubKeyNames())
{
actiable.Add(name);
}
var packages = new List<UWP>();
string packageReg = @"Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\Repository\Packages";
var packageRegSubkey = Registry.CurrentUser.OpenSubKey(packageReg);
foreach (var name in packageRegSubkey.GetSubKeyNames())
{
var packageKey = packageRegSubkey.OpenSubKey(name);
var framework = packageKey.GetValue("Framework");
if (framework != null)
{
if ((int)framework == 1)
{
continue;
}
}
var valueFolder = packageKey.GetValue("PackageRootFolder");
var valueID = packageKey.GetValue("PackageID");
if (valueID != null && valueFolder != null && actiable.Contains(valueID))
{
string location = (string)valueFolder;
string id = (string)valueID;
UWP uwp = new UWP(id, location);
packages.Add(uwp);
}
}
// only exception windows.immersivecontrolpanel_10.0.2.1000_neutral_neutral_cw5n1h2txyewy
string settingsID = actiable.First(a => a.StartsWith("windows.immersivecontrolpanel"));
string settingsLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "ImmersiveControlPanel");
UWP swttings = new UWP(settingsID, settingsLocation);
packages.Add(swttings);
return packages;
}
public override string ToString()
{
return FullName;
}
public override bool Equals(object obj)
{
if (obj is UWP uwp)
{
return FullName.Equals(uwp.FullName);
}
else
{
return false;
}
}
public override int GetHashCode()
{
return FullName.GetHashCode();
}
[Serializable]
public class Application : IProgram
{
public string DisplayName { get; set; }
public string Description { get; set; }
public string UserModelId { get; set; }
public string BackgroundColor { get; set; }
public string Name => DisplayName;
public string Location => Package.Location;
public bool Enabled { get; set; }
public string LogoPath { get; set; }
public UWP Package { get; set; }
public Result Result(string query, IPublicAPI api)
{
var result = new Result
{
SubTitle = Package.Location,
Icon = Logo,
ContextData = this,
Action = e =>
{
Launch(api);
return true;
}
};
string title;
if (Description.Length >= DisplayName.Length &&
Description.Substring(0, DisplayName.Length) == DisplayName)
{
title = Description;
result.Title = title;
var match = StringMatcher.FuzzySearch(query, title);
result.Score = match.Score;
result.TitleHighlightData = match.MatchData;
}
else if (!string.IsNullOrEmpty(Description))
{
title = $"{DisplayName}: {Description}";
var match1 = StringMatcher.FuzzySearch(query, DisplayName);
var match2 = StringMatcher.FuzzySearch(query, title);
if (match1.Score > match2.Score)
{
result.Score = match1.Score;
result.TitleHighlightData = match1.MatchData;
}
else
{
result.Score = match2.Score;
result.TitleHighlightData = match2.MatchData;
}
result.Title = title;
}
else
{
title = DisplayName;
result.Title = title;
var match = StringMatcher.FuzzySearch(query, title);
result.Score = match.Score;
result.TitleHighlightData = match.MatchData;
}
return result;
}
public List<Result> ContextMenus(IPublicAPI api)
{
var contextMenus = new List<Result>
{
new Result
{
Title = api.GetTranslation("wox_plugin_program_open_containing_folder"),
Action = _ =>
{
Main.StartProcess(Process.Start, new ProcessStartInfo(Package.Location));
return true;
},
IcoPath = "Images/folder.png"
}
};
return contextMenus;
}
private async void Launch(IPublicAPI api)
{
var appManager = new ApplicationActivationManager();
uint unusedPid;
const string noArgs = "";
const ACTIVATEOPTIONS noFlags = ACTIVATEOPTIONS.AO_NONE;
await Task.Run(() =>
{
try
{
appManager.ActivateApplication(UserModelId, noArgs, noFlags, out unusedPid);
}
catch (Exception)
{
var name = "Plugin: Program";
var message = $"Can't start UWP: {DisplayName}";
api.ShowMsg(name, message, string.Empty);
}
});
}
public Application(UWP package, string userModelID, string fullName, string name, string displayname, string description, string logoUri, string backgroundColor)
{
UserModelId = userModelID;
Enabled = true;
Package = package;
DisplayName = ResourcesFromPri(fullName, name, displayname);
Description = ResourcesFromPri(fullName, name, description);
LogoPath = PathFromUri(fullName, name, Location, logoUri);
BackgroundColor = backgroundColor;
}
internal string ResourcesFromPri(string packageFullName, string packageName, string resourceReference)
{
const string prefix = "ms-resource:";
string result = "";
Logger.WoxTrace($"package: <{packageFullName}> res ref: <{resourceReference}>");
if (!string.IsNullOrWhiteSpace(resourceReference) && resourceReference.StartsWith(prefix))
{
string key = resourceReference.Substring(prefix.Length);
string parsed;
// DisplayName
// Microsoft.ScreenSketch_10.1907.2471.0_x64__8wekyb3d8bbwe -> ms-resource:AppName/Text
// Microsoft.OneConnect_5.2002.431.0_x64__8wekyb3d8bbwe -> ms-resource:/OneConnectStrings/OneConnect/AppDisplayName
// ImmersiveControlPanel -> ms-resource:DisplayName
// Microsoft.ConnectivityStore_1.1604.4.0_x64__8wekyb3d8bbwe -> ms-resource://Microsoft.ConnectivityStore/MSWifiResources/AppDisplayName
if (key.StartsWith("//"))
{
parsed = $"{prefix}{key}";
}
else
{
if (!key.StartsWith("/"))
{
key = $"/{key}";
}
if (!key.ToLower().Contains("resources") && key.Count(c => c == '/') < 3)
{
key = $"/Resources{key}";
}
parsed = $"{prefix}//{packageName}{key}";
}
Logger.WoxTrace($"resourceReference {resourceReference} parsed <{parsed}> package <{packageFullName}>");
try
{
result = ResourceFromPriInternal(packageFullName, parsed);
}
catch (Exception e)
{
e.Data.Add(nameof(resourceReference), resourceReference);
e.Data.Add(nameof(ResourcesFromPri) + nameof(parsed), parsed);
e.Data.Add(nameof(ResourcesFromPri) + nameof(packageFullName), packageFullName);
throw e;
}
}
else
{
result = resourceReference;
}
Logger.WoxTrace($"package: <{packageFullName}> pri resource result: <{result}>");
return result;
}
private string PathFromUri(string packageFullName, string packageName, string packageLocation, string fileReference)
{
// all https://msdn.microsoft.com/windows/uwp/controls-and-patterns/tiles-and-notifications-app-assets
// windows 10 https://msdn.microsoft.com/en-us/library/windows/apps/dn934817.aspx
// windows 8.1 https://msdn.microsoft.com/en-us/library/windows/apps/hh965372.aspx#target_size
// windows 8 https://msdn.microsoft.com/en-us/library/windows/apps/br211475.aspx
Logger.WoxTrace($"package: <{packageFullName}> file ref: <{fileReference}>");
string path = Path.Combine(packageLocation, fileReference);
if (File.Exists(path))
{
// for 28671Petrroll.PowerPlanSwitcher_0.4.4.0_x86__ge82akyxbc7z4
return path;
}
else
{
// https://docs.microsoft.com/en-us/windows/uwp/app-resources/pri-apis-scenario-1
string parsed = $"ms-resource:///Files/{fileReference.Replace("\\", "/")}";
try
{
string result = ResourceFromPriInternal(packageFullName, parsed);
Logger.WoxTrace($"package: <{packageFullName}> pri file result: <{result}>");
return result;
}
catch (Exception e)
{
e.Data.Add(nameof(fileReference), fileReference);
e.Data.Add(nameof(PathFromUri) + nameof(parsed), parsed);
e.Data.Add(nameof(PathFromUri) + nameof(packageFullName), packageFullName);
throw e;
}
}
}
/// https://docs.microsoft.com/en-us/windows/win32/api/shlwapi/nf-shlwapi-shloadindirectstring
/// use makepri to check whether the resource can be get, the error message is usually useless
/// makepri.exe dump /if "a\resources.pri" /of b.xml
private string ResourceFromPriInternal(string packageFullName, string parsed)
{
Logger.WoxTrace($"package: <{packageFullName}> pri parsed: <{parsed}>");
// following error probally due to buffer to small
// '200' violates enumeration constraint of '100 120 140 160 180'.
// 'Microsoft Corporation' violates pattern constraint of '\bms-resource:.{1,256}'.
var outBuffer = new StringBuilder(512);
string source = $"@{{{packageFullName}? {parsed}}}";
var capacity = (uint)outBuffer.Capacity;
var hResult = SHLoadIndirectString(source, outBuffer, capacity, IntPtr.Zero);
if (hResult == Hresult.Ok)
{
var loaded = outBuffer.ToString();
if (!string.IsNullOrEmpty(loaded))
{
return loaded;
}
else
{
Logger.WoxError($"Can't load null or empty result pri {source} in uwp location {Package.Location}");
return string.Empty;
}
}
else
{
var e = Marshal.GetExceptionForHR((int)hResult);
e.Data.Add(nameof(source), source);
e.Data.Add(nameof(packageFullName), packageFullName);
e.Data.Add(nameof(parsed), parsed);
Logger.WoxError($"Load pri failed {source} location {Package.Location}", e);
return string.Empty;
}
}
internal string LogoUriFromManifest(IAppxManifestApplication app)
{
var logoKeyFromVersion = new Dictionary<PackageVersion, string>
{
{ PackageVersion.Windows10, "Square44x44Logo" },
{ PackageVersion.Windows81, "Square30x30Logo" },
{ PackageVersion.Windows8, "SmallLogo" },
};
if (logoKeyFromVersion.ContainsKey(Package.Version))
{
var key = logoKeyFromVersion[Package.Version];
var logoUri = app.GetStringValue(key);
return logoUri;
}
else
{
return string.Empty;
}
}
public ImageSource Logo()
{
var logo = ImageFromPath(LogoPath);
var plated = PlatedImage(logo);
// todo magic! temp fix for cross thread object
plated.Freeze();
return plated;
}
private BitmapImage ImageFromPath(string path)
{
if (File.Exists(path))
{
var image = new BitmapImage(new Uri(path));
return image;
}
else
{
Logger.WoxError($"|Unable to get logo for {UserModelId} from {path} and located in {Package.Location}");
return new BitmapImage(new Uri(Constant.ErrorIcon));
}
}
private ImageSource PlatedImage(BitmapImage image)
{
if (!string.IsNullOrEmpty(BackgroundColor) && BackgroundColor != "transparent")
{
var width = image.Width;
var height = image.Height;
var x = 0;
var y = 0;
var group = new DrawingGroup();
var converted = ColorConverter.ConvertFromString(BackgroundColor);
if (converted != null)
{
var color = (Color)converted;
var brush = new SolidColorBrush(color);
var pen = new Pen(brush, 1);
var backgroundArea = new Rect(0, 0, width, width);
var rectabgle = new RectangleGeometry(backgroundArea);
var rectDrawing = new GeometryDrawing(brush, pen, rectabgle);
group.Children.Add(rectDrawing);
var imageArea = new Rect(x, y, image.Width, image.Height);
var imageDrawing = new ImageDrawing(image, imageArea);
group.Children.Add(imageDrawing);
// http://stackoverflow.com/questions/6676072/get-system-drawing-bitmap-of-a-wpf-area-using-visualbrush
var visual = new DrawingVisual();
var context = visual.RenderOpen();
context.DrawDrawing(group);
context.Close();
const int dpiScale100 = 96;
var bitmap = new RenderTargetBitmap(
Convert.ToInt32(width), Convert.ToInt32(height),
dpiScale100, dpiScale100,
PixelFormats.Pbgra32
);
bitmap.Render(visual);
return bitmap;
}
else
{
Logger.WoxError($"Unable to convert background string {BackgroundColor} to color for {Package.Location}");
return new BitmapImage(new Uri(Constant.ErrorIcon));
}
}
else
{
// todo use windows theme as background
return image;
}
}
public override string ToString()
{
return $"{DisplayName}: {Description}";
}
}
public enum PackageVersion
{
Windows10,
Windows81,
Windows8,
Unknown
}
[Flags]
private enum Stgm : uint
{
Read = 0x0,
ShareExclusive = 0x10,
ShareDenyNone = 0x40,
}
private enum Hresult : uint
{
Ok = 0x0000,
}
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern Hresult SHCreateStreamOnFileEx(string fileName, Stgm grfMode, uint attributes, bool create,
IStream reserved, out IStream stream);
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern Hresult SHLoadIndirectString(string pszSource, StringBuilder pszOutBuf, uint cchOutBuf,
IntPtr ppvReserved);
}
}
| |
/*
| Version 10.1.84
| Copyright 2013 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
using System;
using System.Diagnostics;
using System.Data.Objects.DataClasses;
using ESRI.ArcLogistics.Data;
using DataModel = ESRI.ArcLogistics.Data.DataModel;
using ESRI.ArcLogistics.DomainObjects.Attributes;
using ESRI.ArcLogistics.DomainObjects.Validation;
using System.Collections;
namespace ESRI.ArcLogistics.DomainObjects
{
/// <summary>
/// Class that represents vehicle specialty.
/// </summary>
/// <remarks>
/// Typically vehicle specialty means some vehicle's capability. For example, vehicle specialty may be that it has a refrigerated trailer.
/// </remarks>
public class VehicleSpecialty : DataObject, IMarkableAsDeleted,
ISupportOwnerCollection
{
#region public static properties
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Name of the Name property.
/// </summary>
public static string PropertyNameName
{
get { return PROP_NAME_Name;}
}
/// <summary>
/// Name of the Comment property.
/// </summary>
public static string PropertyNameComment
{
get { return PROP_NAME_Comment;}
}
#endregion // Constants
#region constructors
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Initializes a new instance of the <c>VehicleSpecialty</c> class.
/// </summary>
public VehicleSpecialty()
: base(DataModel.VehicleSpecialties.CreateVehicleSpecialties(Guid.NewGuid()))
{
base.SetCreationTime();
}
internal VehicleSpecialty(DataModel.VehicleSpecialties entity)
: base(entity)
{
Debug.Assert(0 < entity.CreationTime); // NOTE: must be inited
}
#endregion constructors
#region public members
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Gets the object's type title.
/// </summary>
public override string TypeTitle
{
get { return Properties.Resources.VehicleSpecialty; }
}
/// <summary>
/// Gets the object's globally unique identifier.
/// </summary>
public override Guid Id
{
get { return _Entity.Id; }
}
/// <summary>
/// Gets\sets object creation time.
/// </summary>
/// <exception cref="T:System.ArgumentNullException">Although property can get null value
/// (for backward compatibility with existent plug-ins) it is not actually supported.</exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">Although property can get 0 or less value
/// (for backward compatibility with existent plug-ins) it is not actually supported.</exception>
public override long? CreationTime
{
get
{
Debug.Assert(0 < _Entity.CreationTime); // NOTE: must be inited
return _Entity.CreationTime;
}
set
{
if (!value.HasValue)
throw new ArgumentNullException(); // exception
if (value.Value <= 0)
throw new ArgumentOutOfRangeException(); // exception
_Entity.CreationTime = value.Value;
}
}
/// <summary>
/// Vehicle specialty name.
/// </summary>
[DomainProperty("DomainPropertyNameName", true)]
[DuplicateNameValidator]
[NameNotNullValidator]
public override string Name
{
get { return _Entity.Name; }
set
{
// Save current name.
var name = _Entity.Name;
// Set new name.
_Entity.Name = value;
// Raise Property changed event for all items which
// has the same name, as item's old name.
if ((this as ISupportOwnerCollection).OwnerCollection != null)
DataObjectValidationHelper.RaisePropertyChangedForDuplicate((this as ISupportOwnerCollection).OwnerCollection, name);
NotifyPropertyChanged(PROP_NAME_Name);
}
}
/// <summary>
/// Arbitrary text about the vehicle specialty.
/// </summary>
[DomainProperty("DomainPropertyNameComment")]
public string Comment
{
get { return _Entity.Comment; }
set
{
_Entity.Comment = value;
NotifyPropertyChanged(PROP_NAME_Comment);
}
}
#endregion public members
#region public methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Returns the name of the vehicle specialty.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return this.Name;
}
#endregion public methods
#region ICloneable interface members
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns></returns>
public override object Clone()
{
VehicleSpecialty obj = new VehicleSpecialty();
this.CopyTo(obj);
return obj;
}
#endregion ICloneable interface members
#region ICopyable interface members
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Copies all the object's data to the target data object.
/// </summary>
/// <param name="obj">Target data object.</param>
public override void CopyTo(DataObject obj)
{
Debug.Assert(obj is VehicleSpecialty);
VehicleSpecialty spec = obj as VehicleSpecialty;
spec.Name = this.Name;
spec.Comment = this.Comment;
}
#endregion ICopyable interface members
#region IMarkableAsDeleted interface members
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Gets or sets a value indicating whether data object is marked as deleted.
/// </summary>
bool IMarkableAsDeleted.IsMarkedAsDeleted
{
get { return _Entity.Deleted; }
set { _Entity.Deleted = value; }
}
#endregion IMarkableAsDeleted interface members
#region ISupportOwnerCollection Members
/// <summary>
/// Collection in which this DataObject is placed.
/// </summary>
IEnumerable ISupportOwnerCollection.OwnerCollection
{
get;
set;
}
#endregion
#region private properties
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
private DataModel.VehicleSpecialties _Entity
{
get
{
return (DataModel.VehicleSpecialties)base.RawEntity;
}
}
#endregion private properties
#region private constants
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Name of the Name property.
/// </summary>
private const string PROP_NAME_Name = "Name";
/// <summary>
/// Name of the Comment property.
/// </summary>
private const string PROP_NAME_Comment = "Comment";
#endregion // Constants
}
}
| |
using System.Drawing;
using GuiLabs.Canvas.Renderer;
using GuiLabs.Utils;
namespace GuiLabs.Canvas.Controls
{
public partial class UniversalControl
{
#region Design
public enum UniversalControlDesign
{
NoBackground,
VerticalLine,
LightHorizontalGradient,
Rectangle,
BlockLike,
Gamma,
TableLike
}
private static UniversalControlDesign mDesign = DefaultDesign;
public static UniversalControlDesign Design
{
get
{
return mDesign;
}
set
{
mDesign = value;
}
}
#endregion
#region Draw
private Rect rect1 = new Rect();
private Rect rect2 = new Rect();
protected override void DrawBorder(IRenderer Renderer)
{
if (Design == UniversalControlDesign.VerticalLine
&& !this.IsFocused)
{
return;
}
base.DrawBorder(Renderer);
}
public override void DrawSelectionBorder(IRenderer renderer)
{
if (Design == UniversalControlDesign.VerticalLine)
{
return;
}
base.DrawSelectionBorder(renderer);
}
protected override void DrawRectangleLike(IRenderer renderer)
{
if (this.LinearLayoutStrategy.Orientation == OrientationType.Horizontal)
{
rect1.Size.Y = 0;
rect2.Set(
Bounds.Location.X + Box.Borders.Left,
Bounds.Location.Y + Box.Borders.Top,
HCompartment.Bounds.Size.X,
Bounds.Size.Y - Box.Borders.TopAndBottom);
}
else
{
rect1.Set(
VMembers.Bounds.Location.X,
Bounds.Location.Y + Box.Borders.Top,
Bounds.Right - VMembers.Bounds.Location.X - Box.Borders.Right,
HCompartment.Bounds.Size.Y + 2);
rect2.Set(
Bounds.Location.X + Box.Borders.Left,
Bounds.Location.Y + Box.Borders.Top,
rect1.Location.X - Bounds.Location.X - Box.Borders.Left,
Bounds.Size.Y - Box.Borders.TopAndBottom);
}
switch (Design)
{
case UniversalControlDesign.BlockLike:
DrawBlockLike(renderer);
break;
case UniversalControlDesign.TableLike:
DrawTableLike(renderer);
break;
case UniversalControlDesign.Rectangle:
base.DrawRectangleLike(renderer);
break;
case UniversalControlDesign.LightHorizontalGradient:
DrawLightHorizontalGradient(renderer);
break;
case UniversalControlDesign.VerticalLine:
DrawVerticalLine(renderer);
break;
case UniversalControlDesign.Gamma:
DrawGamma(renderer);
break;
default:
break;
}
}
private void DrawBlockLike(IRenderer renderer)
{
if (this.Collapsed)
{
rect2.Size.Y = rect1.Size.Y;
}
rect2.Location.Y += rect1.Size.Y;
rect2.Size.Y -= rect1.Size.Y;
renderer.DrawOperations.FillRectangle(
rect2,
CurrentStyle.FillStyleInfo);
Color darker = Colors.ScaleColor(CurrentStyle.FillColor, 0.85f);
renderer.DrawOperations.DrawRectangle(
rect2,
darker
);
}
private void DrawTableLike(IRenderer renderer)
{
rect1.Location.X = Bounds.Location.X;
rect1.Location.Y = Bounds.Location.Y;
rect1.Size.X = Bounds.Size.X;
renderer.DrawOperations.DrawFilledRectangle(
rect1,
CurrentStyle.LineStyleInfo,
CurrentStyle.FillStyleInfo);
}
private void DrawLightHorizontalGradient(IRenderer renderer)
{
rect2.Size.X += 50;
renderer.DrawOperations.GradientFillRectangle(
rect2,
CurrentStyle.FillStyleInfo.FillColor,
System.Drawing.Color.White,
System.Drawing.Drawing2D.LinearGradientMode.Horizontal);
}
private void DrawVerticalLine(IRenderer renderer)
{
if (this.Collapsed)
{
return;
}
int x = rect2.Location.X;
int y1 = HCompartment.Bounds.Bottom + HCompartment.Box.Margins.Bottom;
int y2 = rect2.Bottom;
if (OpenCurly.Visible)
{
y1 += OpenCurly.Bounds.Height;
}
if (CloseCurly.Visible)
{
y2 -= CloseCurly.Bounds.Height;
}
if (OffsetCurlies)
{
x += CurrentStyle.FontStyleInfo.Font.SpaceCharSize.X;
}
renderer.DrawOperations.DrawLine(
x,
y1,
x,
y2,
Color.Gainsboro,
CurrentStyle.LineWidth);
}
private void DrawGamma(IRenderer renderer)
{
if (this.LinearLayoutStrategy.Orientation == OrientationType.Vertical)
{
rect1.Location.X = this.Bounds.Location.X + this.Box.Borders.Left;
rect1.Location.Y = this.Bounds.Location.Y + this.Box.Borders.Top;
rect1.Size.X = this.Bounds.Size.X - this.Box.Borders.LeftAndRight;
rect1.Size.Y = rect1.Size.Y - this.Box.Borders.TopAndBottom;
renderer.DrawOperations.FillRectangle(
rect1,
Style.FillStyleInfo);
}
if (this.Collapsed)
{
rect2.Size.Y = rect1.Size.Y;
}
rect2.Location.Y += rect1.Size.Y;
rect2.Size.Y -= rect1.Size.Y;
renderer.DrawOperations.FillRectangle(
rect2,
CurrentStyle.FillStyleInfo.FillColor);
//Color darker = Colors.ScaleColor(CurrentStyle.FillColor, 0.85f);
//renderer.DrawOperations.DrawRectangle(
// rect2,
// darker
// );
}
#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;
using Xunit;
namespace System.Linq.Tests
{
public class CastTests : EnumerableBasedTests
{
[Fact]
public void CastIntToLongThrows()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
var rst = q.AsQueryable().Cast<long>();
Assert.Throws<InvalidCastException>(() => { foreach (var t in rst) ; });
}
[Fact]
public void CastByteToUShortThrows()
{
var q = from x in new byte[] { 0, 255, 127, 128, 1, 33, 99 }
select x;
var rst = q.AsQueryable().Cast<ushort>();
Assert.Throws<InvalidCastException>(() => { foreach (var t in rst) ; });
}
[Fact]
public void EmptySource()
{
object[] source = { };
Assert.Empty(source.AsQueryable().Cast<int>());
}
[Fact]
public void NullableIntFromAppropriateObjects()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, i };
int?[] expected = { -4, 1, 2, 3, 9, i };
Assert.Equal(expected, source.AsQueryable().Cast<int?>());
}
[Fact]
public void LongFromNullableIntInObjectsThrows()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, i };
IQueryable<long> cast = source.AsQueryable().Cast<long>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void LongFromNullableIntInObjectsIncludingNullThrows()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, null, i };
IQueryable<long?> cast = source.AsQueryable().Cast<long?>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void NullableIntFromAppropriateObjectsIncludingNull()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, null, i };
int?[] expected = { -4, 1, 2, 3, 9, null, i };
Assert.Equal(expected, source.AsQueryable().Cast<int?>());
}
[Fact]
public void ThrowOnUncastableItem()
{
object[] source = { -4, 1, 2, 3, 9, "45" };
int[] expectedBeginning = { -4, 1, 2, 3, 9 };
IQueryable<int> cast = source.AsQueryable().Cast<int>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
Assert.Equal(expectedBeginning, cast.Take(5));
Assert.Throws<InvalidCastException>(() => cast.ElementAt(5));
}
[Fact]
public void ThrowCastingIntToDouble()
{
int[] source = new int[] { -4, 1, 2, 9 };
IQueryable<double> cast = source.AsQueryable().Cast<double>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
private static void TestCastThrow<T>(object o)
{
byte? i = 10;
object[] source = { -1, 0, o, i };
IQueryable<T> cast = source.AsQueryable().Cast<T>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowOnHeterogenousSource()
{
TestCastThrow<long?>(null);
TestCastThrow<long>(9L);
}
[Fact]
public void CastToString()
{
object[] source = { "Test1", "4.5", null, "Test2" };
string[] expected = { "Test1", "4.5", null, "Test2" };
Assert.Equal(expected, source.AsQueryable().Cast<string>());
}
[Fact]
public void ArrayConversionThrows()
{
Assert.Throws<InvalidCastException>(() => new[] { -4 }.AsQueryable().Cast<long>().ToList());
}
[Fact]
public void FirstElementInvalidForCast()
{
object[] source = { "Test", 3, 5, 10 };
IQueryable<int> cast = source.AsQueryable().Cast<int>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void LastElementInvalidForCast()
{
object[] source = { -5, 9, 0, 5, 9, "Test" };
IQueryable<int> cast = source.AsQueryable().Cast<int>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void NullableIntFromNullsAndInts()
{
object[] source = { 3, null, 5, -4, 0, null, 9 };
int?[] expected = { 3, null, 5, -4, 0, null, 9 };
Assert.Equal(expected, source.Cast<int?>());
}
[Fact]
public void ThrowCastingIntToLong()
{
int[] source = new int[] { -4, 1, 2, 3, 9 };
IQueryable<long> cast = source.AsQueryable().Cast<long>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowCastingIntToNullableLong()
{
int[] source = new int[] { -4, 1, 2, 3, 9 };
IQueryable<long?> cast = source.AsQueryable().Cast<long?>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowCastingNullableIntToLong()
{
int?[] source = new int?[] { -4, 1, 2, 3, 9 };
IQueryable<long> cast = source.AsQueryable().Cast<long>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowCastingNullableIntToNullableLong()
{
int?[] source = new int?[] { -4, 1, 2, 3, 9, null };
IQueryable<long?> cast = source.AsQueryable().Cast<long?>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void CastingNullToNonnullableIsNullReferenceException()
{
int?[] source = new int?[] { -4, 1, null, 3 };
IQueryable<int> cast = source.AsQueryable().Cast<int>();
Assert.Throws<NullReferenceException>(() => cast.ToList());
}
[Fact]
public void NullSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IQueryable<object>)null).Cast<string>());
}
[Fact]
public void Cast()
{
var count = (new object[] { 0, 1, 2 }).AsQueryable().Cast<int>().Count();
Assert.Equal(3, count);
}
}
}
| |
// 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 Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
/// <summary>
/// Named pipe server
/// </summary>
public sealed partial class NamedPipeServerStream : PipeStream
{
[SecurityCritical]
private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
HandleInheritability inheritability)
{
Debug.Assert(pipeName != null && pipeName.Length != 0, "fullPipeName is null or empty");
Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
Debug.Assert(inBufferSize >= 0, "inBufferSize is negative");
Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
Debug.Assert((maxNumberOfServerInstances >= 1 && maxNumberOfServerInstances <= 254) || (maxNumberOfServerInstances == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid");
Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");
string fullPipeName = Path.GetFullPath(@"\\.\pipe\" + pipeName);
// Make sure the pipe name isn't one of our reserved names for anonymous pipes.
if (String.Equals(fullPipeName, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved);
}
int openMode = ((int)direction) |
(maxNumberOfServerInstances == 1 ? Interop.Kernel32.FileOperations.FILE_FLAG_FIRST_PIPE_INSTANCE : 0) |
(int)options;
// We automatically set the ReadMode to match the TransmissionMode.
int pipeModes = (int)transmissionMode << 2 | (int)transmissionMode << 1;
// Convert -1 to 255 to match win32 (we asserted that it is between -1 and 254).
if (maxNumberOfServerInstances == MaxAllowedServerInstances)
{
maxNumberOfServerInstances = 255;
}
Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability);
SafePipeHandle handle = Interop.Kernel32.CreateNamedPipe(fullPipeName, openMode, pipeModes,
maxNumberOfServerInstances, outBufferSize, inBufferSize, 0, ref secAttrs);
if (handle.IsInvalid)
{
throw Win32Marshal.GetExceptionForLastWin32Error();
}
InitializeHandle(handle, false, (options & PipeOptions.Asynchronous) != 0);
}
// This will wait until the client calls Connect(). If we return from this method, we guarantee that
// the client has returned from its Connect call. The client may have done so before this method
// was called (but not before this server is been created, or, if we were servicing another client,
// not before we called Disconnect), in which case, there may be some buffer already in the pipe waiting
// for us to read. See NamedPipeClientStream.Connect for more information.
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
public void WaitForConnection()
{
CheckConnectOperationsServerWithHandle();
if (IsAsync)
{
WaitForConnectionCoreAsync(CancellationToken.None).GetAwaiter().GetResult();
}
else
{
if (!Interop.Kernel32.ConnectNamedPipe(InternalHandle, IntPtr.Zero))
{
int errorCode = Marshal.GetLastWin32Error();
if (errorCode != Interop.Errors.ERROR_PIPE_CONNECTED)
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
// pipe already connected
if (errorCode == Interop.Errors.ERROR_PIPE_CONNECTED && State == PipeState.Connected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected);
}
// If we reach here then a connection has been established. This can happen if a client
// connects in the interval between the call to CreateNamedPipe and the call to ConnectNamedPipe.
// In this situation, there is still a good connection between client and server, even though
// ConnectNamedPipe returns zero.
}
State = PipeState.Connected;
}
}
public Task WaitForConnectionAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}
if (!IsAsync)
{
return Task.Factory.StartNew(s => ((NamedPipeServerStream)s).WaitForConnection(),
this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
return WaitForConnectionCoreAsync(cancellationToken);
}
[SecurityCritical]
public void Disconnect()
{
CheckDisconnectOperations();
// Disconnect the pipe.
if (!Interop.Kernel32.DisconnectNamedPipe(InternalHandle))
{
throw Win32Marshal.GetExceptionForLastWin32Error();
}
State = PipeState.Disconnected;
}
// Gets the username of the connected client. Not that we will not have access to the client's
// username until it has written at least once to the pipe (and has set its impersonationLevel
// argument appropriately).
[SecurityCritical]
public String GetImpersonationUserName()
{
CheckWriteOperations();
StringBuilder userName = new StringBuilder(Interop.Kernel32.CREDUI_MAX_USERNAME_LENGTH + 1);
if (!Interop.Kernel32.GetNamedPipeHandleState(InternalHandle, IntPtr.Zero, IntPtr.Zero,
IntPtr.Zero, IntPtr.Zero, userName, userName.Capacity))
{
throw WinIOError(Marshal.GetLastWin32Error());
}
return userName.ToString();
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
// This method calls a delegate while impersonating the client. Note that we will not have
// access to the client's security token until it has written at least once to the pipe
// (and has set its impersonationLevel argument appropriately).
public void RunAsClient(PipeStreamImpersonationWorker impersonationWorker)
{
CheckWriteOperations();
ExecuteHelper execHelper = new ExecuteHelper(impersonationWorker, InternalHandle);
RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(tryCode, cleanupCode, execHelper);
// now handle win32 impersonate/revert specific errors by throwing corresponding exceptions
if (execHelper._impersonateErrorCode != 0)
{
WinIOError(execHelper._impersonateErrorCode);
}
else if (execHelper._revertImpersonateErrorCode != 0)
{
WinIOError(execHelper._revertImpersonateErrorCode);
}
}
// the following are needed for CER
private static RuntimeHelpers.TryCode tryCode = new RuntimeHelpers.TryCode(ImpersonateAndTryCode);
private static RuntimeHelpers.CleanupCode cleanupCode = new RuntimeHelpers.CleanupCode(RevertImpersonationOnBackout);
private static void ImpersonateAndTryCode(Object helper)
{
ExecuteHelper execHelper = (ExecuteHelper)helper;
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
if (Interop.Advapi32.ImpersonateNamedPipeClient(execHelper._handle))
{
execHelper._mustRevert = true;
}
else
{
execHelper._impersonateErrorCode = Marshal.GetLastWin32Error();
}
}
if (execHelper._mustRevert)
{ // impersonate passed so run user code
execHelper._userCode();
}
}
private static void RevertImpersonationOnBackout(Object helper, bool exceptionThrown)
{
ExecuteHelper execHelper = (ExecuteHelper)helper;
if (execHelper._mustRevert)
{
if (!Interop.Advapi32.RevertToSelf())
{
execHelper._revertImpersonateErrorCode = Marshal.GetLastWin32Error();
}
}
}
internal class ExecuteHelper
{
internal PipeStreamImpersonationWorker _userCode;
internal SafePipeHandle _handle;
internal bool _mustRevert;
internal int _impersonateErrorCode;
internal int _revertImpersonateErrorCode;
[SecurityCritical]
internal ExecuteHelper(PipeStreamImpersonationWorker userCode, SafePipeHandle handle)
{
_userCode = userCode;
_handle = handle;
}
}
// Async version of WaitForConnection. See the comments above for more info.
private unsafe Task WaitForConnectionCoreAsync(CancellationToken cancellationToken)
{
CheckConnectOperationsServerWithHandle();
if (!IsAsync)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotAsync);
}
var completionSource = new ConnectionCompletionSource(this, cancellationToken);
if (!Interop.Kernel32.ConnectNamedPipe(InternalHandle, completionSource.Overlapped))
{
int errorCode = Marshal.GetLastWin32Error();
switch (errorCode)
{
case Interop.Errors.ERROR_IO_PENDING:
break;
// If we are here then the pipe is already connected, or there was an error
// so we should unpin and free the overlapped.
case Interop.Errors.ERROR_PIPE_CONNECTED:
// IOCompletitionCallback will not be called because we completed synchronously.
completionSource.ReleaseResources();
if (State == PipeState.Connected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected);
}
completionSource.SetCompletedSynchronously();
// We return a cached task instead of TaskCompletionSource's Task allowing the GC to collect it.
return Task.CompletedTask;
default:
completionSource.ReleaseResources();
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
// If we are here then connection is pending.
completionSource.RegisterForCancellation();
return completionSource.Task;
}
private void CheckConnectOperationsServerWithHandle()
{
if (InternalHandle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
CheckConnectOperationsServer();
}
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2014 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit mindtouch.com;
* please review the licensing section.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.IO;
using System.Text;
using log4net;
using log4net.Core;
using log4net.ObjectRenderer;
using MindTouch.Tasking;
namespace MindTouch {
/// <summary>
/// Provides extension and static helper methods for working with a log4Net <see cref="ILog"/> instance.
/// </summary>
public static class LogUtils {
//--- Constants ---
private static readonly Type _type = typeof(LogUtils);
//--- Extension Methods ---
/// <summary>
/// Short-cut for <see cref="ILogger.IsEnabledFor"/> with <see cref="Level.Trace"/>.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <returns><see langword="True"/> if the the logger is running trace loggging.</returns>
public static bool IsTraceEnabled(this ILog log) {
return log.Logger.IsEnabledFor(Level.Trace);
}
/// <summary>
/// Log a method call at <see cref="Level.Trace"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="method">Method name.</param>
/// <param name="args">Method arguments.</param>
public static void TraceMethodCall(this ILog log, string method, params object[] args) {
if(log.IsTraceEnabled()) {
log.Logger.Log(_type, Level.Trace, string.Format("{0}{1}", method, Render(args)), null);
}
}
/// <summary>
/// Log an exception in a specific method at <see cref="Level.Trace"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="exception">Exception that triggered this log call.</param>
/// <param name="method">Method name.</param>
/// <param name="args">Method arguments.</param>
public static void TraceExceptionMethodCall(this ILog log, Exception exception, string method, params object[] args) {
if(log.IsTraceEnabled()) {
log.Logger.Log(_type, Level.Trace, string.Format("{0}{1}", method, Render(args)), exception);
}
}
/// <summary>
/// Log a formatted string at <see cref="Level.Trace"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="format">A format string.</param>
/// <param name="args">Format string parameters.</param>
public static void TraceFormat(this ILog log, string format, params object[] args) {
if(log.IsTraceEnabled()) {
log.Logger.Log(_type, Level.Trace, string.Format(format, args), null);
}
}
/// <summary>
/// Log a method call at <see cref="Level.Debug"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="method">Method name.</param>
/// <param name="args">Method arguments.</param>
public static void DebugMethodCall(this ILog log, string method, params object[] args) {
if(log.IsDebugEnabled) {
log.DebugFormat("{0}{1}", method, Render(args));
}
}
/// <summary>
/// Log an exception in a specific method at <see cref="Level.Debug"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="exception">Exception that triggered this log call.</param>
/// <param name="method">Method name.</param>
/// <param name="args">Method arguments.</param>
public static void DebugExceptionMethodCall(this ILog log, Exception exception, string method, params object[] args) {
if(log.IsDebugEnabled) {
log.Debug(string.Format("{0}{1}", method, Render(args)), exception);
}
}
/// <summary>
/// Log an exception with a formatted text message.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="exception">Exception that triggered this log call.</param>
/// <param name="message">Message format string.</param>
/// <param name="args">Format arguments.</param>
public static void DebugFormat(this ILog log, Exception exception, string message, params object[] args) {
if(log.IsDebugEnabled) {
log.Debug(string.Format(message,args),exception);
}
}
/// <summary>
/// Log a method call at <see cref="Level.Info"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="method">Method name.</param>
/// <param name="args">Method arguments.</param>
public static void InfoMethodCall(this ILog log, string method, params object[] args) {
if(log.IsInfoEnabled) {
log.InfoFormat("{0}{1}", method, Render(args));
}
}
/// <summary>
/// Log a method call at <see cref="Level.Warn"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="method">Method name.</param>
/// <param name="args">Method arguments.</param>
public static void WarnMethodCall(this ILog log, string method, params object[] args) {
if(log.IsWarnEnabled) {
log.WarnFormat("{0}{1}", method, Render(args));
}
}
/// <summary>
/// Log an exception in a specific method at <see cref="Level.Warn"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="exception">Exception that triggered this log call.</param>
/// <param name="method">Method name.</param>
/// <param name="args">Method arguments.</param>
public static void WarnExceptionMethodCall(this ILog log, Exception exception, string method, params object[] args) {
if(log.IsWarnEnabled) {
log.Warn(string.Format("{0}{1}", method, Render(args)), exception);
}
}
/// <summary>
/// Log a formatted string message about an exception at <see cref="Level.Warn"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="exception">Exception that triggered this log call.</param>
/// <param name="format">A format string.</param>
/// <param name="args">Format string parameters.</param>
public static void WarnExceptionFormat(this ILog log, Exception exception, string format, params object[] args) {
if(log.IsWarnEnabled) {
log.Warn(string.Format(format, args), exception);
}
}
/// <summary>
/// Log an exception in a specific method at <see cref="Level.Error"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="exception">Exception that triggered this log call.</param>
/// <param name="method">Method name.</param>
/// <param name="args">Method arguments.</param>
public static void ErrorExceptionMethodCall(this ILog log, Exception exception, string method, params object[] args) {
if(log.IsErrorEnabled) {
log.Error(string.Format("{0}{1}", method, Render(args)), exception);
}
}
/// <summary>
/// Log a formatted string message about an exception at <see cref="Level.Error"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="exception">Exception that triggered this log call.</param>
/// <param name="format">A format string.</param>
/// <param name="args">Format string parameters.</param>
public static void ErrorExceptionFormat(this ILog log, Exception exception, string format, params object[] args) {
if(log.IsErrorEnabled) {
log.Error(string.Format(format, args), exception);
}
}
//--- Class Methods ---
/// <summary>
/// Create an <see cref="ILog"/> instance for the enclosing type.
/// </summary>
/// <returns></returns>
public static ILog CreateLog() {
var frame = new System.Diagnostics.StackFrame(1, false);
var type = frame.GetMethod().DeclaringType;
return LogManager.GetLogger(type);
}
/// <summary>
/// This methods is deprecated please use <see cref="CreateLog()"/>instead.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
[Obsolete("This methods is deprecated please use LogUtils.CreateLog() instead.")]
public static ILog CreateLog<T>() {
return LogManager.GetLogger(typeof(T));
}
/// <summary>
/// Create an <see cref="ILog"/> instance for a given type.
/// </summary>
/// <param name="classType">Type of class to create the logger for</param>
/// <returns></returns>
public static ILog CreateLog(Type classType) {
return LogManager.GetLogger(classType);
}
private static string Render(ICollection args) {
if((args == null) || (args.Count == 0)) {
return string.Empty;
}
var builder = new StringBuilder();
Render(builder, args);
return builder.ToString();
}
private static void Render(StringBuilder builder, object arg) {
if(arg is ICollection) {
builder.Append("(");
RenderCollection(builder, (ICollection)arg);
builder.Append(")");
} else {
builder.Append(arg);
}
}
private static void RenderCollection(StringBuilder builder, ICollection args) {
if(args is IDictionary) {
var dict = (IDictionary)args;
var first = true;
foreach(var key in dict.Keys) {
// append ',' if need be
if(!first) {
builder.Append(", ");
}
first = false;
// append item in collection
try {
var arg = dict[key];
builder.Append(key);
builder.Append("=");
Render(builder, arg);
} catch { }
}
} else {
var first = true;
foreach(var arg in args) {
// append ',' if need be
if(!first) {
builder.Append(", ");
}
first = false;
// append item in collection
try {
Render(builder, arg);
} catch { }
}
}
}
}
}
namespace MindTouch.Logging {
internal class ExceptionRenderer : IObjectRenderer {
//--- Methods ---
public void RenderObject(RendererMap rendererMap, object obj, TextWriter writer) {
if(obj is Exception) {
writer.Write(((Exception)obj).GetCoroutineStackTrace());
}
}
}
}
| |
//
// (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.Text;
using System.Windows.Forms;
using Autodesk.Revit;
using Autodesk.Revit.DB;
namespace Revit.SDK.Samples.ViewPrinter.CS
{
public enum VisibleType
{
VT_ViewOnly,
VT_SheetOnly,
VT_BothViewAndSheet,
VT_None
}
public interface ISettingNameOperation
{
string SettingName
{
get;
set;
}
string Prefix
{
get;
}
int SettingCount
{
get;
}
bool Rename(string name);
bool SaveAs(string newName);
}
/// <summary>
/// Define some config data which is useful in this sample.
/// </summary>
public static class ConstData
{
/// <summary>
/// The const string data which is used as the name
/// for InSessionPrintSetting and InSessionViewSheetSet data
/// </summary>
public const string InSessionName = "<In-Session>";
}
/// <summary>
/// Exposes the View/Sheet Set interfaces just like
/// the View/Sheet Set Dialog (File->Print...; selected views/sheets->Select...) in UI.
/// </summary>
public class ViewSheets : ISettingNameOperation
{
Document m_doc;
ViewSheetSetting m_viewSheetSetting;
public ViewSheets(Document doc)
{
m_doc = doc;
m_viewSheetSetting = doc.PrintManager.ViewSheetSetting;
}
public string SettingName
{
get
{
IViewSheetSet theSet = m_viewSheetSetting.CurrentViewSheetSet;
return (theSet is ViewSheetSet) ?
(theSet as ViewSheetSet).Name : ConstData.InSessionName;
}
set
{
if (value == ConstData.InSessionName)
{
m_viewSheetSetting.CurrentViewSheetSet = m_viewSheetSetting.InSession;
return;
}
foreach (ViewSheetSet viewSheetSet in m_doc.ViewSheetSets)
{
if (viewSheetSet.Name.Equals(value as string))
{
m_viewSheetSetting.CurrentViewSheetSet = viewSheetSet;
return;
}
}
}
}
public string Prefix
{
get
{
return "Set ";
}
}
public int SettingCount
{
get
{
return m_doc.ViewSheetSets.Size;
}
}
public bool SaveAs(string newName)
{
try
{
return m_viewSheetSetting.SaveAs(newName);
}
catch (Exception ex)
{
PrintMgr.MyMessageBox(ex.Message);
return false;
}
}
public bool Rename(string name)
{
try
{
return m_viewSheetSetting.Rename(name);
}
catch (Exception ex)
{
PrintMgr.MyMessageBox(ex.Message);
return false;
}
}
public List<string> ViewSheetSetNames
{
get
{
List<string> names = new List<string>();
foreach (ViewSheetSet viewSheetSet in m_doc.ViewSheetSets)
{
names.Add(viewSheetSet.Name);
}
names.Add(ConstData.InSessionName);
return names;
}
}
public bool Save()
{
try
{
return m_viewSheetSetting.Save();
}
catch (Exception)
{
return false;
}
}
public void Revert()
{
try
{
m_viewSheetSetting.Revert();
}
catch (Exception ex)
{
PrintMgr.MyMessageBox(ex.Message);
}
}
public bool Delete()
{
try
{
return m_viewSheetSetting.Delete();
}
catch (Exception ex)
{
PrintMgr.MyMessageBox(ex.Message);
return false;
}
}
public List<Autodesk.Revit.DB.View> AvailableViewSheetSet(VisibleType visibleType)
{
if (visibleType == VisibleType.VT_None)
return null;
List<Autodesk.Revit.DB.View> views = new List<Autodesk.Revit.DB.View>();
foreach (Autodesk.Revit.DB.View view in m_viewSheetSetting.AvailableViews)
{
if (view.ViewType == Autodesk.Revit.DB.ViewType.DrawingSheet
&& visibleType == VisibleType.VT_ViewOnly)
{
continue; // filter out sheets.
}
if (view.ViewType != Autodesk.Revit.DB.ViewType.DrawingSheet
&& visibleType == VisibleType.VT_SheetOnly)
{
continue; // filter out views.
}
views.Add(view);
}
return views;
}
public bool IsSelected(string viewName)
{
foreach (Autodesk.Revit.DB.View view in m_viewSheetSetting.CurrentViewSheetSet.Views)
{
if (viewName.Equals(view.ViewType.ToString() + ": " + view.ViewName))
{
return true;
}
}
return false;
}
public void ChangeCurrentViewSheetSet(List<string> names)
{
ViewSet selectedViews = new ViewSet();
if (null != names && 0 < names.Count)
{
foreach (Autodesk.Revit.DB.View view in m_viewSheetSetting.AvailableViews)
{
if (names.Contains(view.ViewType.ToString() + ": " + view.ViewName))
{
selectedViews.Insert(view);
}
}
}
IViewSheetSet viewSheetSet = m_viewSheetSetting.CurrentViewSheetSet;
viewSheetSet.Views = selectedViews;
Save();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter;
using Microsoft.Protocols.TestSuites.FileSharing.Common.TestSuite;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace Microsoft.Protocols.TestSuites.FileSharing.ServerFailover.TestSuite
{
public partial class FileServerFailoverExtendedTest : ServerFailoverTestBase
{
#region Test Cases
[TestMethod]
[TestCategory(TestCategories.Cluster)]
[TestCategory(TestCategories.Smb30)]
[TestCategory(TestCategories.Positive)]
[Description("Operate files with lock during failover and expect the lock is maintained after failover.")]
public void FileServerFailover_Lock()
{
FILEID fileIdBeforeFailover;
uint treeIdBeforeFailover;
BaseTestSite.Log.Add(LogEntryKind.TestStep, "BeforeFailover: Connect to general file server {0}.", TestConfig.ClusteredFileServerName);
ConnectGeneralFileServerBeforeFailover(TestConfig.ClusteredFileServerName, out treeIdBeforeFailover);
#region CREATE a durable open with flag DHANDLE_FLAG_PERSISTENT
BaseTestSite.Log.Add(LogEntryKind.TestStep, "BeforeFailover: CREATE a durable open with flag DHANDLE_FLAG_PERSISTENT.");
Smb2CreateContextResponse[] serverCreateContexts;
createGuid = Guid.NewGuid();
status = clientBeforeFailover.Create(
treeIdBeforeFailover,
fileName,
CreateOptions_Values.FILE_NON_DIRECTORY_FILE,
out fileIdBeforeFailover,
out serverCreateContexts,
RequestedOplockLevel_Values.OPLOCK_LEVEL_NONE,
new Smb2CreateContextRequest[] {
new Smb2CreateDurableHandleRequestV2
{
CreateGuid = createGuid,
Flags = CREATE_DURABLE_HANDLE_REQUEST_V2_Flags.DHANDLE_FLAG_PERSISTENT,
Timeout = 3600000,
},
new Smb2CreateQueryOnDiskId
{
},
});
#endregion
#region WRITE content to file
BaseTestSite.Log.Add(LogEntryKind.TestStep, "BeforeFailover: WRITE content to file.");
status = clientBeforeFailover.Write(treeIdBeforeFailover, fileIdBeforeFailover, contentWrite);
#endregion
#region Request byte range lock
LOCK_ELEMENT[] locks = new LOCK_ELEMENT[1];
uint lockSequence = 0;
locks[0].Offset = 0;
locks[0].Length = (ulong)TestConfig.WriteBufferLengthInKb * 1024;
locks[0].Flags = LOCK_ELEMENT_Flags_Values.LOCKFLAG_SHARED_LOCK;
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"Client1 start to lock a byte range for file \"{0}\" with parameters offset:{1}, length:{2}, flags: {3}",
fileName, locks[0].Offset, locks[0].Length, locks[0].Flags.ToString());
status = clientBeforeFailover.Lock(treeIdBeforeFailover, lockSequence++, fileIdBeforeFailover, locks);
#endregion
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"Do failover of the file server.");
FailoverServer(currentAccessIp, TestConfig.ClusteredFileServerName, FileServerType.GeneralFileServer);
FILEID fileIdAfterFailover = FILEID.Zero;
uint treeIdAfterFailover;
BaseTestSite.Log.Add(LogEntryKind.TestStep, "AfterFailover: Reconnect to the same general file server {0}.", TestConfig.ClusteredFileServerName);
ReconnectServerAfterFailover(TestConfig.ClusteredFileServerName, FileServerType.GeneralFileServer, out treeIdAfterFailover);
#region CREATE to reconnect previous duarable open with flag DHANDLE_FLAG_PERSISTENT
BaseTestSite.Log.Add(LogEntryKind.TestStep, "AfterFailover: CREATE to reconnect previous duarable open with flag DHANDLE_FLAG_PERSISTENT.");
status = DoUntilSucceed(
() => clientAfterFailover.Create(
treeIdAfterFailover,
fileName,
CreateOptions_Values.FILE_NON_DIRECTORY_FILE,
out fileIdAfterFailover,
out serverCreateContexts,
RequestedOplockLevel_Values.OPLOCK_LEVEL_NONE,
new Smb2CreateContextRequest[] {
new Smb2CreateDurableHandleReconnectV2
{
FileId = new FILEID { Persistent = fileIdBeforeFailover.Persistent },
CreateGuid = createGuid,
Flags = CREATE_DURABLE_HANDLE_RECONNECT_V2_Flags.DHANDLE_FLAG_PERSISTENT
},
},
checker: (header, response) => { }),
TestConfig.FailoverTimeout,
"Retry Create until succeed within timeout span");
#endregion
#region READ and WRITE
BaseTestSite.Log.Add(LogEntryKind.TestStep, "AfterFailover: Read the contents written before failover.");
status = clientAfterFailover.Read(
treeIdAfterFailover,
fileIdAfterFailover,
0,
(uint)contentWrite.Length,
out contentRead);
BaseTestSite.Log.Add(LogEntryKind.TestStep, "AfterFailover: Verify the contents are the same as the one written before failover.");
BaseTestSite.Assert.IsTrue(
contentWrite.Equals(contentRead),
"Content read after failover should be identical to that written before failover.");
BaseTestSite.Log.Add(LogEntryKind.TestStep, "AfterFailover: Write contents to the locking range, it MUST NOT be allowed.");
status = clientAfterFailover.Write(
treeIdAfterFailover,
fileIdAfterFailover,
contentWrite,
checker: (header, response) =>
{
BaseTestSite.Assert.AreNotEqual(
Smb2Status.STATUS_SUCCESS,
header.Status,
"All opens MUST NOT be allowed to write within the range when SMB2_LOCKFLAG_SHARED_LOCK set");
BaseTestSite.CaptureRequirementIfAreEqual(
Smb2Status.STATUS_FILE_LOCK_CONFLICT,
header.Status,
RequirementCategory.STATUS_FILE_LOCK_CONFLICT.Id,
RequirementCategory.STATUS_FILE_LOCK_CONFLICT.Description);
});
#endregion
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"From client3: Read and write the locking range when the file is locked, it should fail.");
ValidateByteLockRangeFromAnotherClient(true, TestConfig.ClusteredFileServerName, fileName);
#region Unlock byte range
locks[0].Flags = LOCK_ELEMENT_Flags_Values.LOCKFLAG_UNLOCK;
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"AfterFailover: Client2 attempts to unlock the range");
status = clientAfterFailover.Lock(treeIdAfterFailover, lockSequence++, fileIdAfterFailover, locks);
#endregion
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"From client3: Read and write the locking range from a separate client when the file is unlocked, it should succeed.");
ValidateByteLockRangeFromAnotherClient(false, TestConfig.ClusteredFileServerName, fileName);
status = clientAfterFailover.Close(treeIdAfterFailover, fileIdAfterFailover);
status = clientAfterFailover.TreeDisconnect(treeIdAfterFailover);
status = clientAfterFailover.LogOff();
}
#endregion
#region Common Methods
/// <summary>
/// Read and write file within byte lock range when the file is locked or unlocked
/// </summary>
/// <param name="isLocked">Set true to indicate that byte lock range is taken on the file</param>
/// <param name="serverName">Name of file server to access</param>
/// <param name="targetFileName">Target file name to read and write</param>
private void ValidateByteLockRangeFromAnotherClient(bool isLocked, string serverName, string targetFileName)
{
uint status = 0;
Smb2FunctionalClient client = new Smb2FunctionalClient(TestConfig.Timeout, TestConfig, BaseTestSite);
client = new Smb2FunctionalClient(TestConfig.Timeout, TestConfig, BaseTestSite);
client.ConnectToServer(TestConfig.UnderlyingTransport, serverName, currentAccessIp);
status = client.Negotiate(TestConfig.RequestDialects, TestConfig.IsSMB1NegotiateEnabled);
status = client.SessionSetup(
TestConfig.DefaultSecurityPackage,
serverName,
TestConfig.AccountCredential,
TestConfig.UseServerGssToken);
uint treeId;
status = client.TreeConnect(uncSharePath, out treeId);
Smb2CreateContextResponse[] serverCreateContexts;
FILEID fileId;
status = client.Create(
treeId,
targetFileName,
CreateOptions_Values.FILE_NON_DIRECTORY_FILE,
out fileId,
out serverCreateContexts);
string data;
Random random = new Random();
uint offset = (uint)random.Next(0, TestConfig.WriteBufferLengthInKb * 1024 - 1);
uint length = (uint)random.Next(0, (int)(TestConfig.WriteBufferLengthInKb * 1024 - offset));
status = client.Read(treeId, fileId, offset, length, out data);
status = client.Write(treeId, fileId, contentWrite, checker: (header, response) => { });
if (isLocked)
{
BaseTestSite.Assert.AreNotEqual(
Smb2Status.STATUS_SUCCESS,
status,
"Write content to locked range of file from different client is not expected to success");
BaseTestSite.CaptureRequirementIfAreEqual(
Smb2Status.STATUS_FILE_LOCK_CONFLICT,
status,
RequirementCategory.STATUS_FILE_LOCK_CONFLICT.Id,
RequirementCategory.STATUS_FILE_LOCK_CONFLICT.Description);
}
else
{
BaseTestSite.Assert.AreEqual(
Smb2Status.STATUS_SUCCESS,
status,
"Write content in file should succeed, actual status is {0}", Smb2Status.GetStatusCode(status));
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
using Fixtures.Azure;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// SubscriptionInMethodOperations operations.
/// </summary>
internal partial class SubscriptionInMethodOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, ISubscriptionInMethodOperations
{
/// <summary>
/// Initializes a new instance of the SubscriptionInMethodOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal SubscriptionInMethodOperations(AutoRestAzureSpecialParametersTestClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestAzureSpecialParametersTestClient
/// </summary>
public AutoRestAzureSpecialParametersTestClient Client { get; private set; }
/// <summary>
/// POST method with subscriptionId modeled in the method. pass in
/// subscription id = '1234-5678-9012-3456' to succeed
/// </summary>
/// <param name='subscriptionId'>
/// This should appear as a method parameter, use value '1234-5678-9012-3456'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostMethodLocalValidWithHttpMessagesAsync(string subscriptionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (subscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("subscriptionId", subscriptionId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostMethodLocalValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/method/string/none/path/local/1234-5678-9012-3456/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId));
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// POST method with subscriptionId modeled in the method. pass in
/// subscription id = null, client-side validation should prevent you from
/// making this call
/// </summary>
/// <param name='subscriptionId'>
/// This should appear as a method parameter, use value null, client-side
/// validation should prvenet the call
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostMethodLocalNullWithHttpMessagesAsync(string subscriptionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (subscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("subscriptionId", subscriptionId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostMethodLocalNull", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/method/string/none/path/local/null/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId));
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// POST method with subscriptionId modeled in the method. pass in
/// subscription id = '1234-5678-9012-3456' to succeed
/// </summary>
/// <param name='subscriptionId'>
/// Should appear as a method parameter -use value '1234-5678-9012-3456'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostPathLocalValidWithHttpMessagesAsync(string subscriptionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (subscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("subscriptionId", subscriptionId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostPathLocalValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/path/string/none/path/local/1234-5678-9012-3456/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId));
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// POST method with subscriptionId modeled in the method. pass in
/// subscription id = '1234-5678-9012-3456' to succeed
/// </summary>
/// <param name='subscriptionId'>
/// The subscriptionId, which appears in the path, the value is always
/// '1234-5678-9012-3456'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostSwaggerLocalValidWithHttpMessagesAsync(string subscriptionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (subscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("subscriptionId", subscriptionId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostSwaggerLocalValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/swagger/string/none/path/local/1234-5678-9012-3456/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId));
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using CoreFXTestLibrary;
using System;
namespace System.Threading.Tasks.Test.Unit
{
public sealed class ParallelForUnitTests
{
[Fact]
public static void ParallelForTest0()
{
TestParameters parameters = new TestParameters(API.For64, StartIndexBase.Int32)
{
Count = 0,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest1()
{
TestParameters parameters = new TestParameters(API.For64, StartIndexBase.Int32)
{
Count = 10,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.Stop,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest2()
{
TestParameters parameters = new TestParameters(API.For64, StartIndexBase.Int32)
{
Count = 10,
ParallelOption = WithParallelOption.WithDOP,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest3()
{
TestParameters parameters = new TestParameters(API.For64, StartIndexBase.Int32)
{
Count = 1,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.Stop,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest4()
{
TestParameters parameters = new TestParameters(API.For64, StartIndexBase.Int32)
{
Count = 1,
ParallelOption = WithParallelOption.WithDOP,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest5()
{
TestParameters parameters = new TestParameters(API.For64, StartIndexBase.Int32)
{
Count = 2,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest6()
{
TestParameters parameters = new TestParameters(API.For64, StartIndexBase.Int32)
{
Count = 2,
ParallelOption = WithParallelOption.WithDOP,
StateOption = ActionWithState.Stop,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest7()
{
TestParameters parameters = new TestParameters(API.For64, StartIndexBase.Int32)
{
Count = 97,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest8()
{
TestParameters parameters = new TestParameters(API.For64, StartIndexBase.Int32)
{
Count = 97,
ParallelOption = WithParallelOption.WithDOP,
StateOption = ActionWithState.Stop,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest9()
{
TestParameters parameters = new TestParameters(API.For, StartIndexBase.Zero)
{
Count = 0,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest10()
{
TestParameters parameters = new TestParameters(API.For, StartIndexBase.Zero)
{
Count = 10,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest11()
{
TestParameters parameters = new TestParameters(API.For, StartIndexBase.Zero)
{
Count = 10,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.Stop,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest12()
{
TestParameters parameters = new TestParameters(API.For, StartIndexBase.Zero)
{
Count = 10,
ParallelOption = WithParallelOption.WithDOP,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest13()
{
TestParameters parameters = new TestParameters(API.For, StartIndexBase.Zero)
{
Count = 1,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.Stop,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest14()
{
TestParameters parameters = new TestParameters(API.For, StartIndexBase.Zero)
{
Count = 1,
ParallelOption = WithParallelOption.WithDOP,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest15()
{
TestParameters parameters = new TestParameters(API.For, StartIndexBase.Zero)
{
Count = 2,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest16()
{
TestParameters parameters = new TestParameters(API.For, StartIndexBase.Zero)
{
Count = 2,
ParallelOption = WithParallelOption.WithDOP,
StateOption = ActionWithState.Stop,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest17()
{
TestParameters parameters = new TestParameters(API.For, StartIndexBase.Zero)
{
Count = 97,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.Stop,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest18()
{
TestParameters parameters = new TestParameters(API.For, StartIndexBase.Zero)
{
Count = 97,
ParallelOption = WithParallelOption.WithDOP,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest19()
{
TestParameters parameters = new TestParameters(API.ForeachOnArray, StartIndexBase.Zero)
{
Count = 0,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest20()
{
TestParameters parameters = new TestParameters(API.ForeachOnArray, StartIndexBase.Zero)
{
Count = 10,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.Stop,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest21()
{
TestParameters parameters = new TestParameters(API.ForeachOnArray, StartIndexBase.Zero)
{
Count = 10,
ParallelOption = WithParallelOption.WithDOP,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest22()
{
TestParameters parameters = new TestParameters(API.ForeachOnArray, StartIndexBase.Zero)
{
Count = 1,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest23()
{
TestParameters parameters = new TestParameters(API.ForeachOnArray, StartIndexBase.Zero)
{
Count = 1,
ParallelOption = WithParallelOption.WithDOP,
StateOption = ActionWithState.Stop,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest24()
{
TestParameters parameters = new TestParameters(API.ForeachOnArray, StartIndexBase.Zero)
{
Count = 2,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.Stop,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest25()
{
TestParameters parameters = new TestParameters(API.ForeachOnArray, StartIndexBase.Zero)
{
Count = 2,
ParallelOption = WithParallelOption.WithDOP,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest26()
{
TestParameters parameters = new TestParameters(API.ForeachOnArray, StartIndexBase.Zero)
{
Count = 97,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.Stop,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest27()
{
TestParameters parameters = new TestParameters(API.ForeachOnArray, StartIndexBase.Zero)
{
Count = 97,
ParallelOption = WithParallelOption.WithDOP,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest28()
{
TestParameters parameters = new TestParameters(API.ForeachOnList, StartIndexBase.Zero)
{
Count = 0,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest29()
{
TestParameters parameters = new TestParameters(API.ForeachOnList, StartIndexBase.Zero)
{
Count = 10,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.Stop,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest30()
{
TestParameters parameters = new TestParameters(API.ForeachOnList, StartIndexBase.Zero)
{
Count = 10,
ParallelOption = WithParallelOption.WithDOP,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest31()
{
TestParameters parameters = new TestParameters(API.ForeachOnList, StartIndexBase.Zero)
{
Count = 1,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest32()
{
TestParameters parameters = new TestParameters(API.ForeachOnList, StartIndexBase.Zero)
{
Count = 1,
ParallelOption = WithParallelOption.WithDOP,
StateOption = ActionWithState.Stop,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest33()
{
TestParameters parameters = new TestParameters(API.ForeachOnList, StartIndexBase.Zero)
{
Count = 2,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest34()
{
TestParameters parameters = new TestParameters(API.ForeachOnList, StartIndexBase.Zero)
{
Count = 2,
ParallelOption = WithParallelOption.WithDOP,
StateOption = ActionWithState.Stop,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest35()
{
TestParameters parameters = new TestParameters(API.ForeachOnList, StartIndexBase.Zero)
{
Count = 97,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest36()
{
TestParameters parameters = new TestParameters(API.ForeachOnList, StartIndexBase.Zero)
{
Count = 97,
ParallelOption = WithParallelOption.WithDOP,
StateOption = ActionWithState.Stop,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest37()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 0,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest38()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 10,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest39()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 10,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.Stop,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest40()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 10,
ParallelOption = WithParallelOption.WithDOP,
StateOption = ActionWithState.Stop,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest41()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 1,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest42()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 1,
ParallelOption = WithParallelOption.WithDOP,
StateOption = ActionWithState.Stop,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest43()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 2,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest44()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 2,
ParallelOption = WithParallelOption.WithDOP,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest45()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 2,
ParallelOption = WithParallelOption.WithDOP,
StateOption = ActionWithState.Stop,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest46()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 97,
ParallelOption = WithParallelOption.None,
StateOption = ActionWithState.None,
LocalOption = ActionWithLocal.HasFinally,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForTest47()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 97,
ParallelOption = WithParallelOption.WithDOP,
StateOption = ActionWithState.Stop,
LocalOption = ActionWithLocal.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
}
}
| |
using Signum.Engine.Files;
using Signum.Engine.Processes;
using Signum.Entities.Basics;
using Signum.Entities.MachineLearning;
using Signum.Entities.Processes;
using Signum.Entities.Reflection;
using Signum.Utilities.Reflection;
using System.Collections.Concurrent;
namespace Signum.Engine.MachineLearning;
public class PredictorTrainingState
{
internal CancellationTokenSource CancellationTokenSource;
public PredictorTrainingContext Context;
public PredictorTrainingState(CancellationTokenSource cancellationTokenSource, PredictorTrainingContext context)
{
CancellationTokenSource = cancellationTokenSource;
Context = context;
}
}
public class PublicationSettings
{
public object QueryName;
public Func<PredictorEntity, Entity>? OnPublicate;
public PublicationSettings(object queryName)
{
QueryName = queryName;
}
}
public static class PredictorLogic
{
[AutoExpressionField]
public static IQueryable<PredictSimpleResultEntity> SimpleResults(this PredictorEntity e) =>
As.Expression(() => Database.Query<PredictSimpleResultEntity>().Where(a => a.Predictor.Is(e)));
[AutoExpressionField]
public static IQueryable<PredictorCodificationEntity> Codifications(this PredictorEntity e) =>
As.Expression(() => Database.Query<PredictorCodificationEntity>().Where(a => a.Predictor.Is(e)));
[AutoExpressionField]
public static IQueryable<PredictorEpochProgressEntity> EpochProgresses(this PredictorEntity e) =>
As.Expression(() => Database.Query<PredictorEpochProgressEntity>().Where(a => a.Predictor.Is(e)));
public static Dictionary<PredictorAlgorithmSymbol, IPredictorAlgorithm> Algorithms = new Dictionary<PredictorAlgorithmSymbol, IPredictorAlgorithm>();
public static void RegisterAlgorithm(PredictorAlgorithmSymbol symbol, IPredictorAlgorithm algorithm)
{
Algorithms.Add(symbol, algorithm);
}
public static Dictionary<PredictorResultSaverSymbol, IPredictorResultSaver> ResultSavers = new Dictionary<PredictorResultSaverSymbol, IPredictorResultSaver>();
public static void RegisterResultSaver(PredictorResultSaverSymbol symbol, IPredictorResultSaver algorithm)
{
ResultSavers.Add(symbol, algorithm);
}
public static Dictionary<PredictorPublicationSymbol, PublicationSettings> Publications = new Dictionary<PredictorPublicationSymbol, PublicationSettings>();
public static void RegisterPublication(PredictorPublicationSymbol publication, PublicationSettings settings)
{
Publications.Add(publication, settings);
}
public static ConcurrentDictionary<Lite<PredictorEntity>, PredictorTrainingState> Trainings = new ConcurrentDictionary<Lite<PredictorEntity>, PredictorTrainingState>();
public static PredictorTrainingContext? GetTrainingContext(Lite<PredictorEntity> lite)
{
return Trainings.TryGetC(lite)?.Context;
}
public static void Start(SchemaBuilder sb, IFileTypeAlgorithm predictorFileAlgorithm)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
sb.Settings.AssertIgnored((PredictorEntity p) => p.MainQuery.Filters.Single().Pinned, "use PredictorLogic", "by calling PredictorLogic.IgnorePinned in Starter.OverrideAttributes");
sb.Settings.AssertIgnored((PredictorSubQueryEntity p) => p.Filters.Single().Pinned, "use PredictorLogic", "by calling PredictorLogic.IgnorePinned in Starter.OverrideAttributes");
sb.Include<PredictorEntity>()
.WithVirtualMList(p => p.SubQueries, mc => mc.Predictor)
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.Name,
e.MainQuery.Query,
e.Algorithm,
e.State,
e.TrainingException,
});
PredictorGraph.Register();
sb.Include<PredictorSubQueryEntity>()
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.Name,
e.Query,
e.Predictor
});
sb.Include<PredictorCodificationEntity>()
.WithUniqueIndex(pc => new { pc.Predictor, pc.Index, pc.Usage })
.WithExpressionFrom((PredictorEntity e) => e.Codifications())
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.Predictor,
e.Index,
e.Usage,
e.OriginalColumnIndex,
e.SubQueryIndex,
e.SplitKey0,
e.SplitKey1,
e.SplitKey2,
e.IsValue,
e.Min,
e.Max,
e.Average,
e.StdDev,
});
sb.Include<PredictorEpochProgressEntity>()
.WithExpressionFrom((PredictorEntity e) => e.EpochProgresses())
.WithQuery(() => e => new
{
Entity = e,
e.Predictor,
e.Id,
e.Epoch,
e.Ellapsed,
e.LossTraining,
e.AccuracyTraining,
e.LossValidation,
e.AccuracyValidation,
});
FileTypeLogic.Register(PredictorFileType.PredictorFile, predictorFileAlgorithm);
SymbolLogic<PredictorAlgorithmSymbol>.Start(sb, () => Algorithms.Keys);
SymbolLogic<PredictorColumnEncodingSymbol>.Start(sb, () => Algorithms.Values.SelectMany(a => a.GetRegisteredEncodingSymbols()).Distinct());
SymbolLogic<PredictorResultSaverSymbol>.Start(sb, () => ResultSavers.Keys);
SymbolLogic<PredictorPublicationSymbol>.Start(sb, () => Publications.Keys);
sb.Schema.EntityEvents<PredictorEntity>().Retrieved += PredictorEntity_Retrieved;
sb.Schema.EntityEvents<PredictorSubQueryEntity>().Retrieved += PredictorMultiColumnEntity_Retrieved;
Validator.PropertyValidator((PredictorColumnEmbedded c) => c.Encoding).StaticPropertyValidation += Column_StaticPropertyValidation;
Validator.PropertyValidator((PredictorSubQueryColumnEmbedded c) => c.Token).StaticPropertyValidation += GroupKey_StaticPropertyValidation;
Validator.PropertyValidator((PredictorSubQueryEntity c) => c.Columns).StaticPropertyValidation += SubQueryColumns_StaticPropertyValidation;
sb.Include<PredictSimpleResultEntity>()
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.Predictor,
e.Target,
e.Type,
e.OriginalValue,
e.PredictedValue,
e.OriginalCategory,
e.PredictedCategory,
});
RegisterResultSaver(PredictorSimpleResultSaver.StatisticsOnly, new PredictorSimpleSaver { SaveAllResults = false });
RegisterResultSaver(PredictorSimpleResultSaver.Full, new PredictorSimpleSaver { SaveAllResults = true });
sb.Schema.EntityEvents<PredictorEntity>().PreUnsafeDelete += query =>
{
Database.Query<PredictSimpleResultEntity>().Where(a => query.Contains(a.Predictor.Entity)).UnsafeDelete();
return null;
};
sb.Schema.WhenIncluded<ProcessEntity>(() =>
{
sb.Schema.Settings.AssertImplementedBy((ProcessEntity p) => p.Data, typeof(PredictorEntity));
sb.Schema.Settings.AssertImplementedBy((ProcessEntity p) => p.Data, typeof(AutoconfigureNeuralNetworkEntity));
ProcessLogic.Register(PredictorProcessAlgorithm.AutoconfigureNeuralNetwork, new AutoconfigureNeuralNetworkAlgorithm());
new Graph<ProcessEntity>.ConstructFrom<PredictorEntity>(PredictorOperation.AutoconfigureNetwork)
{
CanConstruct = p => p.AlgorithmSettings is NeuralNetworkSettingsEntity ? null : ValidationMessage._0ShouldBeOfType1.NiceToString(p.NicePropertyName(_ => _.AlgorithmSettings), typeof(NeuralNetworkSettingsEntity).NiceName()),
Construct = (p, _) =>
{
return ProcessLogic.Create(PredictorProcessAlgorithm.AutoconfigureNeuralNetwork, new AutoconfigureNeuralNetworkEntity
{
InitialPredictor = p.ToLite()
});
}
}.Register();
});
}
}
public static void IgnorePinned(SchemaBuilder sb)
{
sb.Settings.FieldAttributes((PredictorEntity p) => p.MainQuery.Filters.Single().Pinned).Add(new IgnoreAttribute());
sb.Settings.FieldAttributes((PredictorSubQueryEntity p) => p.Filters.Single().Pinned).Add(new IgnoreAttribute());
}
static string? SubQueryColumns_StaticPropertyValidation(PredictorSubQueryEntity sq, PropertyInfo pi)
{
var p = sq.GetParentEntity<PredictorEntity>()!;
var tokens = GetParentKeys(p.MainQuery);
var current = sq.Columns.Where(a => a.Usage == PredictorSubQueryColumnUsage.ParentKey);
if (tokens.Count != current.Count())
return PredictorMessage.ThereShouldBe0ColumnsWith12Currently3.NiceToString(
tokens.Count,
ReflectionTools.GetPropertyInfo((PredictorSubQueryColumnEmbedded c) => c.Usage),
PredictorSubQueryColumnUsage.ParentKey.NiceToString(),
current.Count());
return null;
}
static string? GroupKey_StaticPropertyValidation(PredictorSubQueryColumnEmbedded column, PropertyInfo pi)
{
var sq = column.GetParentEntity<PredictorSubQueryEntity>()!;
var p = sq.GetParentEntity<PredictorEntity>()!;
if (column.Token != null && column.Usage == PredictorSubQueryColumnUsage.ParentKey)
{
var index = sq.Columns.Where(a => a.Usage == PredictorSubQueryColumnUsage.ParentKey).IndexOf(column);
var tokens = GetParentKeys(p.MainQuery);
var token = tokens.ElementAtOrDefault(index);
if (token == null)
return null;
if (!Compatible(token, column.Token.Token))
return PredictorMessage.TheTypeOf01DoesNotMatch23.NiceToString(column.Token.Token, column.Token.Token.NiceTypeName, token, token.NiceTypeName);
}
return null;
}
internal static List<QueryToken> GetParentKeys(PredictorMainQueryEmbedded mainQuery)
{
if (mainQuery.GroupResults)
return mainQuery.Columns.Select(a => a.Token.Token).Where(t => !(t is AggregateToken)).ToList();
var qd = QueryLogic.Queries.QueryDescription(mainQuery.Query.ToQueryName());
return new List<QueryToken> { QueryUtils.Parse("Entity", qd, 0) };
}
public static bool Compatible(QueryToken subQuery, QueryToken mainQuery)
{
if (subQuery.Type == mainQuery.Type)
return true;
var subQueryImp = subQuery.GetImplementations();
var mainQueryImp = mainQuery.GetImplementations();
if (subQueryImp == null || mainQueryImp == null)
return false;
if (subQueryImp.Value.IsByAll || mainQueryImp.Value.IsByAll)
return true;
if (subQueryImp.Value.Types.Intersect(mainQueryImp.Value.Types).Any())
return true;
return false;
}
static string? Column_StaticPropertyValidation(PredictorColumnEmbedded column, PropertyInfo pi)
{
var mq = column.GetParentEntity<PredictorMainQueryEmbedded>();
var p = mq.GetParentEntity<PredictorEntity>();
if (p.Algorithm == null)
return null;
var algorithm = Algorithms.GetOrThrow(p.Algorithm);
return algorithm.ValidateEncodingProperty(p, null, column.Encoding, column.Usage, column.Token);
}
static string? SubQueryColumn_StaticPropertyValidation(PredictorSubQueryColumnEmbedded column, PropertyInfo pi)
{
var sq = column.GetParentEntity<PredictorSubQueryEntity>();
var p = sq.GetParentEntity<PredictorEntity>()!;
if (p.Algorithm == null || column.Usage == PredictorSubQueryColumnUsage.ParentKey || column.Usage == PredictorSubQueryColumnUsage.SplitBy)
return null;
var algorithm = Algorithms.GetOrThrow(p.Algorithm);
var usage = column.Usage == PredictorSubQueryColumnUsage.Input ? PredictorColumnUsage.Input : PredictorColumnUsage.Output;
return algorithm.ValidateEncodingProperty(p, sq, column.Encoding, usage, column.Token);
}
public static void TrainSync(this PredictorEntity p, bool autoReset = true, Action<string, decimal?>? onReportProgres = null, CancellationToken? cancellationToken = null)
{
if(autoReset)
{
if (p.State == PredictorState.Trained || p.State == PredictorState.Error)
p.Execute(PredictorOperation.Untrain);
else if(p.State == PredictorState.Training)
p.Execute(PredictorOperation.CancelTraining);
}
p.User = UserHolder.Current.ToLite();
p.State = PredictorState.Training;
p.Save();
var ctx = new PredictorTrainingContext(p, cancellationToken ?? new CancellationTokenSource().Token);
var lastWithProgress = false;
if (onReportProgres != null)
ctx.OnReportProgres += onReportProgres;
else
ctx.OnReportProgres += (message, progress) =>
{
if (progress == null)
{
if (lastWithProgress)
Console.WriteLine();
SafeConsole.WriteLineColor(ConsoleColor.White, message);
}
else
{
SafeConsole.WriteLineColor(ConsoleColor.White, $"{progress:P} - {message}");
lastWithProgress = true;
}
};
DoTraining(ctx);
}
static void StartTrainingAsync(PredictorEntity p)
{
var cancellationSource = new CancellationTokenSource();
var ctx = new PredictorTrainingContext(p, cancellationSource.Token);
var state = new PredictorTrainingState(cancellationSource, ctx);
if (!Trainings.TryAdd(p.ToLite(), state))
throw new InvalidOperationException(PredictorMessage._0IsAlreadyBeingTrained.NiceToString(p));
using (ExecutionContext.SuppressFlow())
{
Task.Run(() =>
{
var user = ExecutionMode.Global().Using(_ => p.User!.RetrieveAndRemember());
using (UserHolder.UserSession(user))
{
try
{
DoTraining(ctx);
}
finally
{
Trainings.TryRemove(p.ToLite(), out var _);
}
}
});
}
}
static void DoTraining(PredictorTrainingContext ctx)
{
using (HeavyProfiler.Log("DoTraining"))
{
try
{
if (ctx.Predictor.ResultSaver != null)
{
var saver = ResultSavers.GetOrThrow(ctx.Predictor.ResultSaver);
saver.AssertValid(ctx.Predictor);
}
PredictorLogicQuery.RetrieveData(ctx);
PredictorCodificationLogic.CreatePredictorCodifications(ctx);
var algorithm = Algorithms.GetOrThrow(ctx.Predictor.Algorithm);
using (HeavyProfiler.Log("Train"))
algorithm.Train(ctx);
if (ctx.Predictor.ResultSaver != null)
{
using (HeavyProfiler.Log("ResultSaver"))
{
var saver = ResultSavers.GetOrThrow(ctx.Predictor.ResultSaver);
saver.SavePredictions(ctx);
}
}
ctx.Predictor.State = PredictorState.Trained;
using (OperationLogic.AllowSave<PredictorEntity>())
ctx.Predictor.Save();
}
catch (OperationCanceledException)
{
var p = ctx.Predictor.ToLite().Retrieve();
CleanTrained(p);
p.State = PredictorState.Draft;
using (OperationLogic.AllowSave<PredictorEntity>())
p.Save();
}
catch (Exception ex)
{
ex.Data["entity"] = ctx.Predictor;
var e = ex.LogException();
var p = ctx.Predictor.ToLite().Retrieve();
p.State = PredictorState.Error;
p.TrainingException = e.ToLite();
using (OperationLogic.AllowSave<PredictorEntity>())
p.Save();
}
}
}
static void CleanTrained(PredictorEntity e)
{
PredictorPredictLogic.TrainedPredictorCache.Remove(e.ToLite());
e.TrainingException = null;
foreach (var fp in e.Files)
{
fp.DeleteFileOnCommit();
}
e.ClassificationTraining = null;
e.ClassificationValidation = null;
e.RegressionTraining = null;
e.RegressionValidation = null;
e.Files.Clear();
e.Codifications().UnsafeDelete();
e.EpochProgresses().UnsafeDelete();
}
public static PredictorEntity ParseData(this PredictorEntity predictor)
{
predictor.MainQuery.ParseData();
predictor.SubQueries.ForEach(sq => sq.ParseData());
return predictor;
}
public static void ParseData(this PredictorMainQueryEmbedded mainQuery)
{
QueryDescription description = QueryLogic.Queries.QueryDescription(mainQuery.Query.ToQueryName());
mainQuery.ParseData(description);
}
static void PredictorEntity_Retrieved(PredictorEntity predictor, PostRetrievingContext ctx)
{
predictor.MainQuery.ParseData();
}
public static void ParseData(this PredictorSubQueryEntity subQuery)
{
QueryDescription description = QueryLogic.Queries.QueryDescription(subQuery.Query.ToQueryName());
subQuery.ParseData(description);
}
static void PredictorMultiColumnEntity_Retrieved(PredictorSubQueryEntity subQuery, PostRetrievingContext ctx)
{
subQuery.ParseData();
}
public class PredictorGraph : Graph<PredictorEntity, PredictorState>
{
public static void Register()
{
GetState = f => f.State;
new Execute(PredictorOperation.Save)
{
FromStates = { PredictorState.Draft, PredictorState.Error, PredictorState.Trained },
ToStates = { PredictorState.Draft, PredictorState.Error, PredictorState.Trained },
CanBeNew = true,
CanBeModified = true,
Execute = (e, _) => { },
}.Register();
new Execute(PredictorOperation.Train)
{
FromStates = { PredictorState.Draft },
ToStates = { PredictorState.Training },
CanBeNew = true,
CanBeModified = true,
Execute = (p, _) =>
{
p.User = UserHolder.Current.ToLite();
p.State = PredictorState.Training;
p.Save();
StartTrainingAsync(p);
},
}.Register();
new Execute(PredictorOperation.Untrain)
{
FromStates = { PredictorState.Trained, PredictorState.Error },
ToStates = { PredictorState.Draft },
Execute = (e, _) =>
{
CleanTrained(e);
e.State = PredictorState.Draft;
},
}.Register();
new Execute(PredictorOperation.CancelTraining)
{
FromStates = { PredictorState.Training },
ToStates = { PredictorState.Training, PredictorState.Draft },
Execute = (e, _) =>
{
if (Trainings.TryGetValue(e.ToLite(), out var state))
{
state.CancellationTokenSource.Cancel();
}
else
{
CleanTrained(e);
e.State = PredictorState.Draft;
e.Save();
}
},
}.Register();
new Execute(PredictorOperation.StopTraining)
{
FromStates = { PredictorState.Training },
ToStates = { PredictorState.Training },
Execute = (e, _) =>
{
if (Trainings.TryGetValue(e.ToLite(), out var state))
{
state.Context.StopTraining = true;
}
if (GraphExplorer.IsGraphModified(e))
throw new InvalidOperationException();
},
}.Register();
new Execute(PredictorOperation.Publish)
{
CanExecute = p => PredictorLogic.Publications.Values.Any(a => object.Equals(a.QueryName, p.MainQuery.Query.ToQueryName())) ? null : PredictorMessage.NoPublicationsForQuery0Registered.NiceToString(p.MainQuery),
FromStates = { PredictorState.Trained },
ToStates = { PredictorState.Trained },
Execute = (e, arg) =>
{
var publication = arg.GetArg<PredictorPublicationSymbol>();
Database.Query<PredictorEntity>()
.Where(a => a.Publication.Is(publication))
.UnsafeUpdate()
.Set(a => a.Publication, a => null)
.Execute();
e.Publication = publication;
e.Save();
},
}.Register();
new Graph<Entity>.ConstructFrom<PredictorEntity>(PredictorOperation.AfterPublishProcess)
{
CanConstruct = p =>
p.State != PredictorState.Trained ? ValidationMessage._0Or1ShouldBeSet.NiceToString(ReflectionTools.GetPropertyInfo(() => p.State), p.State.NiceToString()) : p.Publication == null ? ValidationMessage._0IsNotSet.NiceToString(ReflectionTools.GetPropertyInfo(() => p.Publication)) :
Publications.GetOrThrow(p.Publication).OnPublicate == null ? PredictorMessage.NoPublicationsProcessRegisteredFor0.NiceToString(p.Publication) :
null,
Construct = (p, _) => Publications.GetOrThrow(p.Publication!).OnPublicate!(p)
}.Register();
new Delete(PredictorOperation.Delete)
{
FromStates = { PredictorState.Draft, PredictorState.Trained },
Delete = (e, _) =>
{
foreach (var fp in e.Files)
{
fp.DeleteFileOnCommit();
}
e.EpochProgresses().UnsafeDelete();
e.Codifications().UnsafeDelete();
e.Delete();
},
}.Register();
new Graph<PredictorEntity>.ConstructFrom<PredictorEntity>(PredictorOperation.Clone)
{
Construct = (e, _) => new PredictorEntity
{
Name = e.Name.HasText() ? (e.Name + " (2)") : "",
State = PredictorState.Draft,
Algorithm = e.Algorithm,
ResultSaver = e.ResultSaver,
MainQuery = e.MainQuery.Clone(),
SubQueries = e.SubQueries.Select(a => a.Clone()).ToMList(),
AlgorithmSettings = e.AlgorithmSettings.Clone(),
Settings = e.Settings.Clone(),
},
}.Register();
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// A placeholder for a binary blob
/// First published in XenServer 5.0.
/// </summary>
public partial class Blob : XenObject<Blob>
{
#region Constructors
public Blob()
{
}
public Blob(string uuid,
string name_label,
string name_description,
long size,
bool pubblic,
DateTime last_updated,
string mime_type)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.size = size;
this.pubblic = pubblic;
this.last_updated = last_updated;
this.mime_type = mime_type;
}
/// <summary>
/// Creates a new Blob from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Blob(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new Blob from a Proxy_Blob.
/// </summary>
/// <param name="proxy"></param>
public Blob(Proxy_Blob proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Blob.
/// </summary>
public override void UpdateFrom(Blob update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
size = update.size;
pubblic = update.pubblic;
last_updated = update.last_updated;
mime_type = update.mime_type;
}
internal void UpdateFrom(Proxy_Blob proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
name_label = proxy.name_label == null ? null : proxy.name_label;
name_description = proxy.name_description == null ? null : proxy.name_description;
size = proxy.size == null ? 0 : long.Parse(proxy.size);
pubblic = (bool)proxy.pubblic;
last_updated = proxy.last_updated;
mime_type = proxy.mime_type == null ? null : proxy.mime_type;
}
public Proxy_Blob ToProxy()
{
Proxy_Blob result_ = new Proxy_Blob();
result_.uuid = uuid ?? "";
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.size = size.ToString();
result_.pubblic = pubblic;
result_.last_updated = last_updated;
result_.mime_type = mime_type ?? "";
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Blob
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("size"))
size = Marshalling.ParseLong(table, "size");
if (table.ContainsKey("pubblic"))
pubblic = Marshalling.ParseBool(table, "pubblic");
if (table.ContainsKey("last_updated"))
last_updated = Marshalling.ParseDateTime(table, "last_updated");
if (table.ContainsKey("mime_type"))
mime_type = Marshalling.ParseString(table, "mime_type");
}
public bool DeepEquals(Blob other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._size, other._size) &&
Helper.AreEqual2(this._pubblic, other._pubblic) &&
Helper.AreEqual2(this._last_updated, other._last_updated) &&
Helper.AreEqual2(this._mime_type, other._mime_type);
}
internal static List<Blob> ProxyArrayToObjectList(Proxy_Blob[] input)
{
var result = new List<Blob>();
foreach (var item in input)
result.Add(new Blob(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, Blob server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_name_label, server._name_label))
{
Blob.set_name_label(session, opaqueRef, _name_label);
}
if (!Helper.AreEqual2(_name_description, server._name_description))
{
Blob.set_name_description(session, opaqueRef, _name_description);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static Blob get_record(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_record(session.opaque_ref, _blob);
else
return new Blob(session.proxy.blob_get_record(session.opaque_ref, _blob ?? "").parse());
}
/// <summary>
/// Get a reference to the blob instance with the specified UUID.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Blob> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<Blob>.Create(session.proxy.blob_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get all the blob instances with the given label.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<Blob>> get_by_name_label(Session session, string _label)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_by_name_label(session.opaque_ref, _label);
else
return XenRef<Blob>.Create(session.proxy.blob_get_by_name_label(session.opaque_ref, _label ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static string get_uuid(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_uuid(session.opaque_ref, _blob);
else
return session.proxy.blob_get_uuid(session.opaque_ref, _blob ?? "").parse();
}
/// <summary>
/// Get the name/label field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static string get_name_label(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_name_label(session.opaque_ref, _blob);
else
return session.proxy.blob_get_name_label(session.opaque_ref, _blob ?? "").parse();
}
/// <summary>
/// Get the name/description field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static string get_name_description(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_name_description(session.opaque_ref, _blob);
else
return session.proxy.blob_get_name_description(session.opaque_ref, _blob ?? "").parse();
}
/// <summary>
/// Get the size field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static long get_size(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_size(session.opaque_ref, _blob);
else
return long.Parse(session.proxy.blob_get_size(session.opaque_ref, _blob ?? "").parse());
}
/// <summary>
/// Get the public field of the given blob.
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static bool get_public(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_public(session.opaque_ref, _blob);
else
return (bool)session.proxy.blob_get_public(session.opaque_ref, _blob ?? "").parse();
}
/// <summary>
/// Get the last_updated field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static DateTime get_last_updated(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_last_updated(session.opaque_ref, _blob);
else
return session.proxy.blob_get_last_updated(session.opaque_ref, _blob ?? "").parse();
}
/// <summary>
/// Get the mime_type field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static string get_mime_type(Session session, string _blob)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_mime_type(session.opaque_ref, _blob);
else
return session.proxy.blob_get_mime_type(session.opaque_ref, _blob ?? "").parse();
}
/// <summary>
/// Set the name/label field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
/// <param name="_label">New value to set</param>
public static void set_name_label(Session session, string _blob, string _label)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.blob_set_name_label(session.opaque_ref, _blob, _label);
else
session.proxy.blob_set_name_label(session.opaque_ref, _blob ?? "", _label ?? "").parse();
}
/// <summary>
/// Set the name/description field of the given blob.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
/// <param name="_description">New value to set</param>
public static void set_name_description(Session session, string _blob, string _description)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.blob_set_name_description(session.opaque_ref, _blob, _description);
else
session.proxy.blob_set_name_description(session.opaque_ref, _blob ?? "", _description ?? "").parse();
}
/// <summary>
/// Set the public field of the given blob.
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
/// <param name="_public">New value to set</param>
public static void set_public(Session session, string _blob, bool _public)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.blob_set_public(session.opaque_ref, _blob, _public);
else
session.proxy.blob_set_public(session.opaque_ref, _blob ?? "", _public).parse();
}
/// <summary>
/// Create a placeholder for a binary blob
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_mime_type">The mime-type of the blob. Defaults to 'application/octet-stream' if the empty string is supplied</param>
public static XenRef<Blob> create(Session session, string _mime_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_create(session.opaque_ref, _mime_type);
else
return XenRef<Blob>.Create(session.proxy.blob_create(session.opaque_ref, _mime_type ?? "").parse());
}
/// <summary>
/// Create a placeholder for a binary blob
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_mime_type">The mime-type of the blob. Defaults to 'application/octet-stream' if the empty string is supplied</param>
/// <param name="_public">True if the blob should be publicly available First published in XenServer 6.1.</param>
public static XenRef<Blob> create(Session session, string _mime_type, bool _public)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_create(session.opaque_ref, _mime_type, _public);
else
return XenRef<Blob>.Create(session.proxy.blob_create(session.opaque_ref, _mime_type ?? "", _public).parse());
}
/// <summary>
///
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_blob">The opaque_ref of the given blob</param>
public static void destroy(Session session, string _blob)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.blob_destroy(session.opaque_ref, _blob);
else
session.proxy.blob_destroy(session.opaque_ref, _blob ?? "").parse();
}
/// <summary>
/// Return a list of all the blobs known to the system.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Blob>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_all(session.opaque_ref);
else
return XenRef<Blob>.Create(session.proxy.blob_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the blob Records at once, in a single XML RPC call
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Blob>, Blob> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.blob_get_all_records(session.opaque_ref);
else
return XenRef<Blob>.Create<Proxy_Blob>(session.proxy.blob_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
Changed = true;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
Changed = true;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// Size of the binary data, in bytes
/// </summary>
public virtual long size
{
get { return _size; }
set
{
if (!Helper.AreEqual(value, _size))
{
_size = value;
Changed = true;
NotifyPropertyChanged("size");
}
}
}
private long _size;
/// <summary>
/// True if the blob is publicly accessible
/// First published in XenServer 6.1.
/// </summary>
public virtual bool pubblic
{
get { return _pubblic; }
set
{
if (!Helper.AreEqual(value, _pubblic))
{
_pubblic = value;
Changed = true;
NotifyPropertyChanged("pubblic");
}
}
}
private bool _pubblic = false;
/// <summary>
/// Time at which the data in the blob was last updated
/// </summary>
[JsonConverter(typeof(XenDateTimeConverter))]
public virtual DateTime last_updated
{
get { return _last_updated; }
set
{
if (!Helper.AreEqual(value, _last_updated))
{
_last_updated = value;
Changed = true;
NotifyPropertyChanged("last_updated");
}
}
}
private DateTime _last_updated;
/// <summary>
/// The mime type associated with this object. Defaults to 'application/octet-stream' if the empty string is supplied
/// </summary>
public virtual string mime_type
{
get { return _mime_type; }
set
{
if (!Helper.AreEqual(value, _mime_type))
{
_mime_type = value;
Changed = true;
NotifyPropertyChanged("mime_type");
}
}
}
private string _mime_type = "";
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Apache License, Version 2.0.
// 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.Text;
using System.Reflection;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using Common;
namespace Randoop
{
public interface IReflectionFilter
{
bool OkToUse(FieldInfo f, out string message);
bool OkToUse(MethodInfo m, out string message);
bool OkToUse(ConstructorInfo c, out string mssage);
bool OkToUse(Type c, out string message);
}
public class ConfigFilesFilter : IReflectionFilter
{
private readonly List<string> require_types = new List<string>();
private readonly List<string> require_members = new List<string>();
private readonly List<string> require_fields = new List<string>();
private readonly List<string> forbid_types = new List<string>();
private readonly List<string> forbid_members = new List<string>();
private readonly List<string> forbid_fields = new List<string>();
private ConfigFilesFilter()
{
}
public ConfigFilesFilter(RandoopConfiguration config)
{
if (config == null) throw new ArgumentNullException("config");
Common.StringReader r = new StringReader();
foreach (FileName path in config.forbid_typesFiles)
forbid_types.AddRange(r.Read(path.fileName));
foreach (FileName path in config.forbid_membersFiles)
forbid_members.AddRange(r.Read(path.fileName));
foreach (FileName path in config.forbid_fieldsFiles)
forbid_fields.AddRange(r.Read(path.fileName));
foreach (FileName path in config.require_typesFiles)
require_types.AddRange(r.Read(path.fileName));
foreach (FileName path in config.require_membersFiles)
require_members.AddRange(r.Read(path.fileName));
foreach (FileName path in config.require_fieldsFiles)
require_fields.AddRange(r.Read(path.fileName));
}
public static ConfigFilesFilter CreateDefaultConfigFilesFilter()
{
ConfigFilesFilter f = new ConfigFilesFilter();
Common.StringReader r = new Common.StringReader();
f.require_types.AddRange(r.Read(Common.Enviroment.RequiretypesDefaultConfigFile));
f.require_members.AddRange(r.Read(Common.Enviroment.RequiremembersDefaultConfigFile));
f.require_fields.AddRange(r.Read(Common.Enviroment.RequirefieldsDefaultConfigFile));
f.forbid_types.AddRange(r.Read(Common.Enviroment.ForbidtypesDefaultConfigFile));
f.forbid_members.AddRange(r.Read(Common.Enviroment.ForbidmembersDefaultConfigFile));
f.forbid_fields.AddRange(r.Read(Common.Enviroment.ForbidfieldsDefaultConfigFile));
return f;
}
public bool OkToUse(FieldInfo f, out string message)
{
if (f == null) throw new ArgumentNullException("f");
return OkToUseInternal(f.ToString(), this.require_fields, this.forbid_fields, out message);
}
public bool OkToUse(MethodInfo m, out string message)
{
if (m == null) throw new ArgumentNullException("m");
string toCheckStr = m.DeclaringType.ToString() + "." + m.ToString(); //xiao.qu@us.abb.com
return OkToUseInternal(toCheckStr + "/" + m.ReturnType.ToString(), this.require_members, this.forbid_members, out message); //xiao.qu@us.abb.com
//return OkToUseInternal(m.ToString() + "/" + m.ReturnType.ToString(), this.require_members, this.forbid_members, out message); //xiao.qu@us.abb.com
}
public bool OkToUse(ConstructorInfo c, out string message)
{
if (c == null) throw new ArgumentNullException("c");
string toCheckStr = c.DeclaringType.ToString() + "." + c.ToString(); //xiao.qu@us.abb.com
return OkToUseInternal(toCheckStr, this.require_members, this.forbid_members, out message); //xiao.qu@us.abb.com
//return OkToUseInternal(c.ToString(), this.require_members, this.forbid_members, out message); //xiao.qu@us.abb.com
}
public bool OkToUse(Type t, out string message)
{
if (t == null) throw new ArgumentNullException("t");
return OkToUseInternal(t.ToString(), this.require_types, this.forbid_types, out message);
}
private static bool OkToUseInternal(string s, List<string> restrict, List<string> forbid, out string message)
{
bool matchesAtLeasOneRestrictPattern = false;
foreach (string pattern in restrict)
if (WildcardMatcher.Matches(pattern, s))
{
matchesAtLeasOneRestrictPattern = true;
break;
}
if (!matchesAtLeasOneRestrictPattern)
{
message = "Will not use: matches no restrict pattern:" + s;
return false;
}
foreach (string pattern in forbid)
{
if (WildcardMatcher.Matches(pattern, s, out message))
{
message = "Will not use: matches forbid pattern \"" + pattern + "\":" + s;
return false;
}
}
message = "@@@OK1" + s;
return true;
}
public void PrintFilter(System.IO.TextWriter textWriter)
{
if (textWriter == null) throw new ArgumentNullException("textWriter");
textWriter.WriteLine("========== Patterns for allowed types:");
foreach (string s in this.require_types)
{
textWriter.WriteLine(s);
}
textWriter.WriteLine("========== Patterns for forbidden types:");
foreach (string s in this.forbid_types)
{
textWriter.WriteLine(s);
}
textWriter.WriteLine("========== Patterns for allowed methods/constructors:");
foreach (string s in this.require_members)
{
textWriter.WriteLine(s);
}
textWriter.WriteLine("========== Patterns for forbidden methods/constructors:");
foreach (string s in this.forbid_members)
{
textWriter.WriteLine(s);
}
textWriter.WriteLine("========== Patterns for allowed fields:");
foreach (string s in this.require_fields)
{
textWriter.WriteLine(s);
}
textWriter.WriteLine("========== Patterns for forbidden fields:");
foreach (string s in this.forbid_fields)
{
textWriter.WriteLine(s);
}
}
}
// Main Filters used in different classes
/// <summary>
/// A filter that is composed of other filters
/// Interpreted as the intersection of filters
/// </summary>
public class ComposableFilter : IReflectionFilter
{
Collection<IReflectionFilter> filters = new Collection<IReflectionFilter>();
public ComposableFilter(params IReflectionFilter[] f)
{
foreach (IReflectionFilter filter in f)
filters.Add(filter);
}
public void Add(IReflectionFilter f)
{
filters.Add(f);
}
public bool OkToUse(FieldInfo f, out string message)
{
message = null;
foreach (IReflectionFilter filter in filters)
if (!filter.OkToUse(f, out message))
return false;
return true;
}
public bool OkToUse(MethodInfo m, out string message)
{
message = null;
foreach (IReflectionFilter filter in filters)
if (!filter.OkToUse(m, out message))
return false;
return true;
}
public bool OkToUse(ConstructorInfo c, out string message)
{
message = null;
foreach (IReflectionFilter filter in filters)
if (!filter.OkToUse(c, out message))
return false;
return true;
}
public bool OkToUse(Type t, out string message)
{
message = null;
foreach (IReflectionFilter filter in filters)
if (!filter.OkToUse(t, out message))
return false;
return true;
}
}
/// <summary>
/// This filter can be created with two different behaviors.
/// If created with useInternal==false, then only public members are ok.
/// This is the filter to modify if we want to prevent something from being explored
/// </summary>
public class VisibilityFilter : IReflectionFilter
{
public bool useStaticMethods;
public bool useInternal;
public VisibilityFilter(RandoopConfiguration env)
{
this.useStaticMethods = env.usestatic;
this.useInternal = env.useinternal;
}
public VisibilityFilter(bool useStatic, bool useInternal)
{
this.useStaticMethods = useStatic;
this.useInternal = useInternal;
}
public bool OkToUse(FieldInfo fi, out string message)
{
//Console.Write("FFF" + fi.ToString() + " ");
if (!fi.IsPublic)
{
//Console.WriteLine("FALSE");
message = "Will not use: field is not public: " + fi.ToString();
return false;
}
// Since we only currently use fields for FieldSettingTransformers,
// we do not want any fields that cannot be modified.
if (fi.IsInitOnly)
{
message = "Will not use: field is readonly: " + fi.ToString();
return false;
}
if (fi.IsLiteral)
{
message = "Will not use: field is const: " + fi.ToString();
return false;
}
// We probably don't want to modify static fields because
// our notion of plans does not account for global state.
if (fi.IsStatic)
{
//Console.WriteLine("FALSE");
message = "Will not use: field is static: " + fi.ToString();
return false;
}
//Console.WriteLine("TRUE");
message = "@@@OK6" + fi.ToString();
return true;
}
public bool OkToUse(Type t, out string message)
{
// The only purpose of including an interface would be to
// add the methods they declare to the list of methods to
// explore. But this is not necessary because classes that
// implement the interface will declare these methods, so
// we'll get the methods when we process the implementing
// classes. Also, a method may implement an interface but
// declare the implemented methods private (for example).
if (t.IsInterface)
{
message = "Will not use: type is interface: " + t.ToString();
return false;
}
if (ReflectionUtils.IsSubclassOrEqual(t, typeof(System.Delegate)))
{
message = "Will not use: type is delegate: " + t.ToString();
return false;
}
if (!useInternal && !t.IsPublic)
{
message = "Will not use: type is no public: " + t.ToString();
return false;
}
if (t.IsNested)
{
if (t.IsNestedPrivate)
{
message = "Will not use: type is nested private: " + t.ToString();
return false;
}
}
else
{
if (t.IsNotPublic)
{
message = "Will not use: type is not public: " + t.ToString();
return false;
}
}
message = "@@@OK7" + t.ToString();
return true;
}
public bool OkToUse(ConstructorInfo c, out string message)
{
if (c.DeclaringType.IsAbstract)
{
message = "Will not use: constructor's declaring type is abstract: " + c.ToString();
return false;
}
return OkToUseBase(c, out message);
}
public bool OkToUse(MethodInfo m, out string message)
{
return OkToUseBase(m, out message);
}
/// <summary>
/// TODO: Resolve IsPublic, IsNotPublic semantics of reflection
/// </summary>
/// <param name="ci"></param>
/// <returns></returns>
private bool OkToUseBase(MethodBase ci, out string message)
{
if (ci.IsAbstract)
{
message = "Will not use: method or constructor is abstract: " + ci.ToString();
return false;
}
foreach (ParameterInfo pi in ci.GetParameters())
{
if (pi.ParameterType.Name.EndsWith("&"))
{
message = "Will not use: method or constructor has a parameter containing \"&\": " + ci.ToString();
return false;
}
if (pi.IsOut)
{
message = "Will not use: method or constructor has an out parameter: " + ci.ToString();
return false;
}
if (pi.ParameterType.IsGenericParameter)
{
message = "Will not use: method or constructor has a generic parameter: " + ci.ToString();
return false;
}
}
if (!this.useInternal && !ci.IsPublic)
{
message = "Will not use: method or constructor is not public: " + ci.ToString();
return false;
}
if (ci.IsPrivate)
{
message = "Will not use: method or constructor is private: " + ci.ToString();
return false;
}
if (ci.IsStatic)
{
if (!useStaticMethods)
{
message = "Will not use: method or constructor is static: " + ci.ToString();
return false;
}
}
if (ci.DeclaringType.Equals(typeof(object)))
{
message = "Will not use: method is System.Object's: " + ci.ToString();
return false;
}
foreach (Attribute attr in ci.GetCustomAttributes(true))
{
if (attr is ObsoleteAttribute)
{
//WriteLine("Obsolete Method " + ci.DeclaringType + "::" + ci.Name + "()" + "detected\n");
message = "Will not use: has attribute System.ObsoleteAttribute: " + ci.ToString();
return false;
}
//TODO: there are still cases where an obsolete method is not caught. e.g. System.Xml.XmlSchema::ElementType
}
message = "@@@OK8" + ci.ToString();
return true;
}
}
}
| |
/*
Bullet for XNA Copyright (c) 2003-2007 Vsevolod Klementjev http://www.codeplex.com/xnadevru
Bullet original C++ version Copyright (c) 2003-2007 Erwin Coumans http://bulletphysics.com
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
namespace XnaDevRu.BulletX.Dynamics
{
public class SimpleDynamicsWorld : DynamicsWorld
{
private IConstraintSolver _constraintSolver;
private bool _ownsConstraintSolver;
private Vector3 _gravity;
private IDebugDraw _debugDrawer;
/// <summary>
/// this btSimpleDynamicsWorld constructor creates dispatcher, broadphase pairCache and constraintSolver
/// </summary>
/// <param name="dispatcher"></param>
/// <param name="pairCache"></param>
/// <param name="constraintSolver"></param>
public SimpleDynamicsWorld(IDispatcher dispatcher, OverlappingPairCache pairCache, IConstraintSolver constraintSolver)
: base(dispatcher, pairCache)
{
_constraintSolver = constraintSolver;
_ownsConstraintSolver = false;
_gravity = new Vector3(0, 0, -10);
}
public override Vector3 Gravity
{
set
{
_gravity = value;
for (int i = 0; i < CollisionObjects.Count; i++)
{
CollisionObject colObj = CollisionObjects[i];
RigidBody body = RigidBody.Upcast(colObj);
if (body != null)
{
body.Gravity = value;
}
}
}
}
public override IConstraintSolver ConstraintSolver
{
set
{
_ownsConstraintSolver = false;
_constraintSolver = value;
}
}
public override IDebugDraw DebugDrawer
{
get
{
return _debugDrawer;
}
set
{
_debugDrawer = value;
}
}
public override void StepSimulation(float timeStep, int numSubsteps, float fixedTimeStep)
{
//apply gravity, predict motion
PredictUnconstraintMotion(timeStep);
DispatcherInfo dispatchInfo = new DispatcherInfo();
dispatchInfo.TimeStep = timeStep;
dispatchInfo.StepCount = 0;
dispatchInfo.DebugDraw = DebugDrawer;
//perform collision detection
PerformDiscreteCollisionDetection();
//solve contact constraints
int numManifolds = Dispatcher.ManifoldCount;
if (numManifolds != 0)
{
List<PersistentManifold> manifolds = (Dispatcher as CollisionDispatcher).Manifolds;
//int numManifolds = m_dispatcher1.GetNumManifolds();
ContactSolverInfo infoGlobal = new ContactSolverInfo();
infoGlobal.TimeStep = timeStep;
_constraintSolver.SolveGroup(new List<CollisionObject>(), manifolds, manifolds.Count, new List<TypedConstraint>(), infoGlobal, _debugDrawer);
}
//integrate transforms
IntegrateTransforms(timeStep);
UpdateAabbs();
SynchronizeMotionStates();
}
public override void UpdateAabbs()
{
for (int i = 0; i < CollisionObjects.Count; i++)
{
CollisionObject colObj = CollisionObjects[i];
RigidBody body = RigidBody.Upcast(colObj);
if (body != null)
{
if (body.IsActive && (!body.IsStaticObject))
{
Vector3 minAabb, maxAabb;
colObj.CollisionShape.GetAabb(colObj.WorldTransform, out minAabb, out maxAabb);
IBroadphase bp = Broadphase;
bp.SetAabb(body.Broadphase, minAabb, maxAabb);
}
}
}
}
public override void AddRigidBody(RigidBody body)
{
body.Gravity = _gravity;
if (body.CollisionShape != null)
{
AddCollisionObject(body);
}
}
public override void RemoveRigidBody(RigidBody body)
{
RemoveCollisionObject(body);
}
public void SynchronizeMotionStates()
{
for (int i = 0; i < CollisionObjects.Count; i++)
{
CollisionObject colObj = CollisionObjects[i];
RigidBody body = RigidBody.Upcast(colObj);
if (body != null && body.MotionState != null)
{
if (body.ActivationState != ActivationState.IslandSleeping)
{
body.MotionState.SetWorldTransform(body.WorldTransform);
}
}
}
}
protected void PredictUnconstraintMotion(float timeStep)
{
for (int i = 0; i < CollisionObjects.Count; i++)
{
CollisionObject colObj = CollisionObjects[i];
RigidBody body = RigidBody.Upcast(colObj);
if (body != null)
{
if (!body.IsStaticObject)
{
if (body.IsActive)
{
body.ApplyForces(timeStep);
body.IntegrateVelocities(timeStep);
Matrix temp = body.InterpolationWorldTransform;
body.PredictIntegratedTransform(timeStep, ref temp);
body.InterpolationWorldTransform = temp;
}
}
}
}
}
protected void IntegrateTransforms(float timeStep)
{
Matrix predictedTrans = Matrix.Identity;
for (int i = 0; i < CollisionObjects.Count; i++)
{
CollisionObject colObj = CollisionObjects[i];
RigidBody body = RigidBody.Upcast(colObj);
if (body != null)
{
if (body.IsActive && (!body.IsStaticObject))
{
body.PredictIntegratedTransform(timeStep, ref predictedTrans);
body.ProceedToTransform(predictedTrans);
}
}
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Persistence.g.cs" company="Akka.NET Project">
// Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Persistence.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Akka.Persistence.Serialization.Proto.Msg {
/// <summary>Holder for reflection information generated from Persistence.proto</summary>
internal static partial class PersistenceReflection {
#region Descriptor
/// <summary>File descriptor for Persistence.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static PersistenceReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChFQZXJzaXN0ZW5jZS5wcm90bxIoQWtrYS5QZXJzaXN0ZW5jZS5TZXJpYWxp",
"emF0aW9uLlByb3RvLk1zZyLmAQoRUGVyc2lzdGVudE1lc3NhZ2USTAoHcGF5",
"bG9hZBgBIAEoCzI7LkFra2EuUGVyc2lzdGVuY2UuU2VyaWFsaXphdGlvbi5Q",
"cm90by5Nc2cuUGVyc2lzdGVudFBheWxvYWQSEgoKc2VxdWVuY2VOchgCIAEo",
"AxIVCg1wZXJzaXN0ZW5jZUlkGAMgASgJEg8KB2RlbGV0ZWQYBCABKAgSDgoG",
"c2VuZGVyGAsgASgJEhAKCG1hbmlmZXN0GAwgASgJEhIKCndyaXRlckd1aWQY",
"DSABKAkSEQoJdGltZXN0YW1wGA4gASgSIlMKEVBlcnNpc3RlbnRQYXlsb2Fk",
"EhQKDHNlcmlhbGl6ZXJJZBgBIAEoBRIPCgdwYXlsb2FkGAIgASgMEhcKD3Bh",
"eWxvYWRNYW5pZmVzdBgDIAEoDCJbCgtBdG9taWNXcml0ZRJMCgdwYXlsb2Fk",
"GAEgAygLMjsuQWtrYS5QZXJzaXN0ZW5jZS5TZXJpYWxpemF0aW9uLlByb3Rv",
"Lk1zZy5QZXJzaXN0ZW50TWVzc2FnZSKMAQoTVW5jb25maXJtZWREZWxpdmVy",
"eRISCgpkZWxpdmVyeUlkGAEgASgDEhMKC2Rlc3RpbmF0aW9uGAIgASgJEkwK",
"B3BheWxvYWQYAyABKAsyOy5Ba2thLlBlcnNpc3RlbmNlLlNlcmlhbGl6YXRp",
"b24uUHJvdG8uTXNnLlBlcnNpc3RlbnRQYXlsb2FkIpYBChtBdExlYXN0T25j",
"ZURlbGl2ZXJ5U25hcHNob3QSGQoRY3VycmVudERlbGl2ZXJ5SWQYASABKAMS",
"XAoVdW5jb25maXJtZWREZWxpdmVyaWVzGAIgAygLMj0uQWtrYS5QZXJzaXN0",
"ZW5jZS5TZXJpYWxpemF0aW9uLlByb3RvLk1zZy5VbmNvbmZpcm1lZERlbGl2",
"ZXJ5IkwKGlBlcnNpc3RlbnRTdGF0ZUNoYW5nZUV2ZW50EhcKD3N0YXRlSWRl",
"bnRpZmllchgBIAEoCRIVCg10aW1lb3V0TWlsbGlzGAIgASgDIpIBChVQZXJz",
"aXN0ZW50RlNNU25hcHNob3QSFwoPc3RhdGVJZGVudGlmaWVyGAEgASgJEkkK",
"BGRhdGEYAiABKAsyOy5Ba2thLlBlcnNpc3RlbmNlLlNlcmlhbGl6YXRpb24u",
"UHJvdG8uTXNnLlBlcnNpc3RlbnRQYXlsb2FkEhUKDXRpbWVvdXRNaWxsaXMY",
"AyABKANiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Persistence.Serialization.Proto.Msg.PersistentMessage), global::Akka.Persistence.Serialization.Proto.Msg.PersistentMessage.Parser, new[]{ "Payload", "SequenceNr", "PersistenceId", "Deleted", "Sender", "Manifest", "WriterGuid", "Timestamp" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Persistence.Serialization.Proto.Msg.PersistentPayload), global::Akka.Persistence.Serialization.Proto.Msg.PersistentPayload.Parser, new[]{ "SerializerId", "Payload", "PayloadManifest" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Persistence.Serialization.Proto.Msg.AtomicWrite), global::Akka.Persistence.Serialization.Proto.Msg.AtomicWrite.Parser, new[]{ "Payload" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Persistence.Serialization.Proto.Msg.UnconfirmedDelivery), global::Akka.Persistence.Serialization.Proto.Msg.UnconfirmedDelivery.Parser, new[]{ "DeliveryId", "Destination", "Payload" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Persistence.Serialization.Proto.Msg.AtLeastOnceDeliverySnapshot), global::Akka.Persistence.Serialization.Proto.Msg.AtLeastOnceDeliverySnapshot.Parser, new[]{ "CurrentDeliveryId", "UnconfirmedDeliveries" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Persistence.Serialization.Proto.Msg.PersistentStateChangeEvent), global::Akka.Persistence.Serialization.Proto.Msg.PersistentStateChangeEvent.Parser, new[]{ "StateIdentifier", "TimeoutMillis" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Persistence.Serialization.Proto.Msg.PersistentFSMSnapshot), global::Akka.Persistence.Serialization.Proto.Msg.PersistentFSMSnapshot.Parser, new[]{ "StateIdentifier", "Data", "TimeoutMillis" }, null, null, null)
}));
}
#endregion
}
#region Messages
internal sealed partial class PersistentMessage : pb::IMessage<PersistentMessage> {
private static readonly pb::MessageParser<PersistentMessage> _parser = new pb::MessageParser<PersistentMessage>(() => new PersistentMessage());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PersistentMessage> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Persistence.Serialization.Proto.Msg.PersistenceReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PersistentMessage() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PersistentMessage(PersistentMessage other) : this() {
Payload = other.payload_ != null ? other.Payload.Clone() : null;
sequenceNr_ = other.sequenceNr_;
persistenceId_ = other.persistenceId_;
deleted_ = other.deleted_;
sender_ = other.sender_;
manifest_ = other.manifest_;
writerGuid_ = other.writerGuid_;
timestamp_ = other.timestamp_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PersistentMessage Clone() {
return new PersistentMessage(this);
}
/// <summary>Field number for the "payload" field.</summary>
public const int PayloadFieldNumber = 1;
private global::Akka.Persistence.Serialization.Proto.Msg.PersistentPayload payload_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Akka.Persistence.Serialization.Proto.Msg.PersistentPayload Payload {
get { return payload_; }
set {
payload_ = value;
}
}
/// <summary>Field number for the "sequenceNr" field.</summary>
public const int SequenceNrFieldNumber = 2;
private long sequenceNr_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long SequenceNr {
get { return sequenceNr_; }
set {
sequenceNr_ = value;
}
}
/// <summary>Field number for the "persistenceId" field.</summary>
public const int PersistenceIdFieldNumber = 3;
private string persistenceId_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string PersistenceId {
get { return persistenceId_; }
set {
persistenceId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "deleted" field.</summary>
public const int DeletedFieldNumber = 4;
private bool deleted_;
/// <summary>
/// not used in new records from 2.4
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Deleted {
get { return deleted_; }
set {
deleted_ = value;
}
}
/// <summary>Field number for the "sender" field.</summary>
public const int SenderFieldNumber = 11;
private string sender_ = "";
/// <summary>
/// not stored in journal, needed for remote serialization
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Sender {
get { return sender_; }
set {
sender_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "manifest" field.</summary>
public const int ManifestFieldNumber = 12;
private string manifest_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Manifest {
get { return manifest_; }
set {
manifest_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "writerGuid" field.</summary>
public const int WriterGuidFieldNumber = 13;
private string writerGuid_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string WriterGuid {
get { return writerGuid_; }
set {
writerGuid_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "timestamp" field.</summary>
public const int TimestampFieldNumber = 14;
private long timestamp_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Timestamp {
get { return timestamp_; }
set {
timestamp_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PersistentMessage);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PersistentMessage other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Payload, other.Payload)) return false;
if (SequenceNr != other.SequenceNr) return false;
if (PersistenceId != other.PersistenceId) return false;
if (Deleted != other.Deleted) return false;
if (Sender != other.Sender) return false;
if (Manifest != other.Manifest) return false;
if (WriterGuid != other.WriterGuid) return false;
if (Timestamp != other.Timestamp) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (payload_ != null) hash ^= Payload.GetHashCode();
if (SequenceNr != 0L) hash ^= SequenceNr.GetHashCode();
if (PersistenceId.Length != 0) hash ^= PersistenceId.GetHashCode();
if (Deleted != false) hash ^= Deleted.GetHashCode();
if (Sender.Length != 0) hash ^= Sender.GetHashCode();
if (Manifest.Length != 0) hash ^= Manifest.GetHashCode();
if (WriterGuid.Length != 0) hash ^= WriterGuid.GetHashCode();
if (Timestamp != 0L) hash ^= Timestamp.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (payload_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Payload);
}
if (SequenceNr != 0L) {
output.WriteRawTag(16);
output.WriteInt64(SequenceNr);
}
if (PersistenceId.Length != 0) {
output.WriteRawTag(26);
output.WriteString(PersistenceId);
}
if (Deleted != false) {
output.WriteRawTag(32);
output.WriteBool(Deleted);
}
if (Sender.Length != 0) {
output.WriteRawTag(90);
output.WriteString(Sender);
}
if (Manifest.Length != 0) {
output.WriteRawTag(98);
output.WriteString(Manifest);
}
if (WriterGuid.Length != 0) {
output.WriteRawTag(106);
output.WriteString(WriterGuid);
}
if (Timestamp != 0L) {
output.WriteRawTag(112);
output.WriteSInt64(Timestamp);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (payload_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Payload);
}
if (SequenceNr != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(SequenceNr);
}
if (PersistenceId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(PersistenceId);
}
if (Deleted != false) {
size += 1 + 1;
}
if (Sender.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Sender);
}
if (Manifest.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Manifest);
}
if (WriterGuid.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(WriterGuid);
}
if (Timestamp != 0L) {
size += 1 + pb::CodedOutputStream.ComputeSInt64Size(Timestamp);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PersistentMessage other) {
if (other == null) {
return;
}
if (other.payload_ != null) {
if (payload_ == null) {
payload_ = new global::Akka.Persistence.Serialization.Proto.Msg.PersistentPayload();
}
Payload.MergeFrom(other.Payload);
}
if (other.SequenceNr != 0L) {
SequenceNr = other.SequenceNr;
}
if (other.PersistenceId.Length != 0) {
PersistenceId = other.PersistenceId;
}
if (other.Deleted != false) {
Deleted = other.Deleted;
}
if (other.Sender.Length != 0) {
Sender = other.Sender;
}
if (other.Manifest.Length != 0) {
Manifest = other.Manifest;
}
if (other.WriterGuid.Length != 0) {
WriterGuid = other.WriterGuid;
}
if (other.Timestamp != 0L) {
Timestamp = other.Timestamp;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (payload_ == null) {
payload_ = new global::Akka.Persistence.Serialization.Proto.Msg.PersistentPayload();
}
input.ReadMessage(payload_);
break;
}
case 16: {
SequenceNr = input.ReadInt64();
break;
}
case 26: {
PersistenceId = input.ReadString();
break;
}
case 32: {
Deleted = input.ReadBool();
break;
}
case 90: {
Sender = input.ReadString();
break;
}
case 98: {
Manifest = input.ReadString();
break;
}
case 106: {
WriterGuid = input.ReadString();
break;
}
case 112: {
Timestamp = input.ReadSInt64();
break;
}
}
}
}
}
internal sealed partial class PersistentPayload : pb::IMessage<PersistentPayload> {
private static readonly pb::MessageParser<PersistentPayload> _parser = new pb::MessageParser<PersistentPayload>(() => new PersistentPayload());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PersistentPayload> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Persistence.Serialization.Proto.Msg.PersistenceReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PersistentPayload() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PersistentPayload(PersistentPayload other) : this() {
serializerId_ = other.serializerId_;
payload_ = other.payload_;
payloadManifest_ = other.payloadManifest_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PersistentPayload Clone() {
return new PersistentPayload(this);
}
/// <summary>Field number for the "serializerId" field.</summary>
public const int SerializerIdFieldNumber = 1;
private int serializerId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int SerializerId {
get { return serializerId_; }
set {
serializerId_ = value;
}
}
/// <summary>Field number for the "payload" field.</summary>
public const int PayloadFieldNumber = 2;
private pb::ByteString payload_ = pb::ByteString.Empty;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString Payload {
get { return payload_; }
set {
payload_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "payloadManifest" field.</summary>
public const int PayloadManifestFieldNumber = 3;
private pb::ByteString payloadManifest_ = pb::ByteString.Empty;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString PayloadManifest {
get { return payloadManifest_; }
set {
payloadManifest_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PersistentPayload);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PersistentPayload other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (SerializerId != other.SerializerId) return false;
if (Payload != other.Payload) return false;
if (PayloadManifest != other.PayloadManifest) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (SerializerId != 0) hash ^= SerializerId.GetHashCode();
if (Payload.Length != 0) hash ^= Payload.GetHashCode();
if (PayloadManifest.Length != 0) hash ^= PayloadManifest.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (SerializerId != 0) {
output.WriteRawTag(8);
output.WriteInt32(SerializerId);
}
if (Payload.Length != 0) {
output.WriteRawTag(18);
output.WriteBytes(Payload);
}
if (PayloadManifest.Length != 0) {
output.WriteRawTag(26);
output.WriteBytes(PayloadManifest);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (SerializerId != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(SerializerId);
}
if (Payload.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Payload);
}
if (PayloadManifest.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(PayloadManifest);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PersistentPayload other) {
if (other == null) {
return;
}
if (other.SerializerId != 0) {
SerializerId = other.SerializerId;
}
if (other.Payload.Length != 0) {
Payload = other.Payload;
}
if (other.PayloadManifest.Length != 0) {
PayloadManifest = other.PayloadManifest;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
SerializerId = input.ReadInt32();
break;
}
case 18: {
Payload = input.ReadBytes();
break;
}
case 26: {
PayloadManifest = input.ReadBytes();
break;
}
}
}
}
}
internal sealed partial class AtomicWrite : pb::IMessage<AtomicWrite> {
private static readonly pb::MessageParser<AtomicWrite> _parser = new pb::MessageParser<AtomicWrite>(() => new AtomicWrite());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<AtomicWrite> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Persistence.Serialization.Proto.Msg.PersistenceReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AtomicWrite() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AtomicWrite(AtomicWrite other) : this() {
payload_ = other.payload_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AtomicWrite Clone() {
return new AtomicWrite(this);
}
/// <summary>Field number for the "payload" field.</summary>
public const int PayloadFieldNumber = 1;
private static readonly pb::FieldCodec<global::Akka.Persistence.Serialization.Proto.Msg.PersistentMessage> _repeated_payload_codec
= pb::FieldCodec.ForMessage(10, global::Akka.Persistence.Serialization.Proto.Msg.PersistentMessage.Parser);
private readonly pbc::RepeatedField<global::Akka.Persistence.Serialization.Proto.Msg.PersistentMessage> payload_ = new pbc::RepeatedField<global::Akka.Persistence.Serialization.Proto.Msg.PersistentMessage>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Akka.Persistence.Serialization.Proto.Msg.PersistentMessage> Payload {
get { return payload_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as AtomicWrite);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(AtomicWrite other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!payload_.Equals(other.payload_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= payload_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
payload_.WriteTo(output, _repeated_payload_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += payload_.CalculateSize(_repeated_payload_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(AtomicWrite other) {
if (other == null) {
return;
}
payload_.Add(other.payload_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
payload_.AddEntriesFrom(input, _repeated_payload_codec);
break;
}
}
}
}
}
internal sealed partial class UnconfirmedDelivery : pb::IMessage<UnconfirmedDelivery> {
private static readonly pb::MessageParser<UnconfirmedDelivery> _parser = new pb::MessageParser<UnconfirmedDelivery>(() => new UnconfirmedDelivery());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<UnconfirmedDelivery> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Persistence.Serialization.Proto.Msg.PersistenceReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UnconfirmedDelivery() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UnconfirmedDelivery(UnconfirmedDelivery other) : this() {
deliveryId_ = other.deliveryId_;
destination_ = other.destination_;
Payload = other.payload_ != null ? other.Payload.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UnconfirmedDelivery Clone() {
return new UnconfirmedDelivery(this);
}
/// <summary>Field number for the "deliveryId" field.</summary>
public const int DeliveryIdFieldNumber = 1;
private long deliveryId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long DeliveryId {
get { return deliveryId_; }
set {
deliveryId_ = value;
}
}
/// <summary>Field number for the "destination" field.</summary>
public const int DestinationFieldNumber = 2;
private string destination_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Destination {
get { return destination_; }
set {
destination_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "payload" field.</summary>
public const int PayloadFieldNumber = 3;
private global::Akka.Persistence.Serialization.Proto.Msg.PersistentPayload payload_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Akka.Persistence.Serialization.Proto.Msg.PersistentPayload Payload {
get { return payload_; }
set {
payload_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as UnconfirmedDelivery);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(UnconfirmedDelivery other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (DeliveryId != other.DeliveryId) return false;
if (Destination != other.Destination) return false;
if (!object.Equals(Payload, other.Payload)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (DeliveryId != 0L) hash ^= DeliveryId.GetHashCode();
if (Destination.Length != 0) hash ^= Destination.GetHashCode();
if (payload_ != null) hash ^= Payload.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (DeliveryId != 0L) {
output.WriteRawTag(8);
output.WriteInt64(DeliveryId);
}
if (Destination.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Destination);
}
if (payload_ != null) {
output.WriteRawTag(26);
output.WriteMessage(Payload);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (DeliveryId != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(DeliveryId);
}
if (Destination.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Destination);
}
if (payload_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Payload);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(UnconfirmedDelivery other) {
if (other == null) {
return;
}
if (other.DeliveryId != 0L) {
DeliveryId = other.DeliveryId;
}
if (other.Destination.Length != 0) {
Destination = other.Destination;
}
if (other.payload_ != null) {
if (payload_ == null) {
payload_ = new global::Akka.Persistence.Serialization.Proto.Msg.PersistentPayload();
}
Payload.MergeFrom(other.Payload);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
DeliveryId = input.ReadInt64();
break;
}
case 18: {
Destination = input.ReadString();
break;
}
case 26: {
if (payload_ == null) {
payload_ = new global::Akka.Persistence.Serialization.Proto.Msg.PersistentPayload();
}
input.ReadMessage(payload_);
break;
}
}
}
}
}
internal sealed partial class AtLeastOnceDeliverySnapshot : pb::IMessage<AtLeastOnceDeliverySnapshot> {
private static readonly pb::MessageParser<AtLeastOnceDeliverySnapshot> _parser = new pb::MessageParser<AtLeastOnceDeliverySnapshot>(() => new AtLeastOnceDeliverySnapshot());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<AtLeastOnceDeliverySnapshot> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Persistence.Serialization.Proto.Msg.PersistenceReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AtLeastOnceDeliverySnapshot() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AtLeastOnceDeliverySnapshot(AtLeastOnceDeliverySnapshot other) : this() {
currentDeliveryId_ = other.currentDeliveryId_;
unconfirmedDeliveries_ = other.unconfirmedDeliveries_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public AtLeastOnceDeliverySnapshot Clone() {
return new AtLeastOnceDeliverySnapshot(this);
}
/// <summary>Field number for the "currentDeliveryId" field.</summary>
public const int CurrentDeliveryIdFieldNumber = 1;
private long currentDeliveryId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long CurrentDeliveryId {
get { return currentDeliveryId_; }
set {
currentDeliveryId_ = value;
}
}
/// <summary>Field number for the "unconfirmedDeliveries" field.</summary>
public const int UnconfirmedDeliveriesFieldNumber = 2;
private static readonly pb::FieldCodec<global::Akka.Persistence.Serialization.Proto.Msg.UnconfirmedDelivery> _repeated_unconfirmedDeliveries_codec
= pb::FieldCodec.ForMessage(18, global::Akka.Persistence.Serialization.Proto.Msg.UnconfirmedDelivery.Parser);
private readonly pbc::RepeatedField<global::Akka.Persistence.Serialization.Proto.Msg.UnconfirmedDelivery> unconfirmedDeliveries_ = new pbc::RepeatedField<global::Akka.Persistence.Serialization.Proto.Msg.UnconfirmedDelivery>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Akka.Persistence.Serialization.Proto.Msg.UnconfirmedDelivery> UnconfirmedDeliveries {
get { return unconfirmedDeliveries_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as AtLeastOnceDeliverySnapshot);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(AtLeastOnceDeliverySnapshot other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (CurrentDeliveryId != other.CurrentDeliveryId) return false;
if(!unconfirmedDeliveries_.Equals(other.unconfirmedDeliveries_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (CurrentDeliveryId != 0L) hash ^= CurrentDeliveryId.GetHashCode();
hash ^= unconfirmedDeliveries_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (CurrentDeliveryId != 0L) {
output.WriteRawTag(8);
output.WriteInt64(CurrentDeliveryId);
}
unconfirmedDeliveries_.WriteTo(output, _repeated_unconfirmedDeliveries_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (CurrentDeliveryId != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(CurrentDeliveryId);
}
size += unconfirmedDeliveries_.CalculateSize(_repeated_unconfirmedDeliveries_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(AtLeastOnceDeliverySnapshot other) {
if (other == null) {
return;
}
if (other.CurrentDeliveryId != 0L) {
CurrentDeliveryId = other.CurrentDeliveryId;
}
unconfirmedDeliveries_.Add(other.unconfirmedDeliveries_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
CurrentDeliveryId = input.ReadInt64();
break;
}
case 18: {
unconfirmedDeliveries_.AddEntriesFrom(input, _repeated_unconfirmedDeliveries_codec);
break;
}
}
}
}
}
internal sealed partial class PersistentStateChangeEvent : pb::IMessage<PersistentStateChangeEvent> {
private static readonly pb::MessageParser<PersistentStateChangeEvent> _parser = new pb::MessageParser<PersistentStateChangeEvent>(() => new PersistentStateChangeEvent());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PersistentStateChangeEvent> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Persistence.Serialization.Proto.Msg.PersistenceReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PersistentStateChangeEvent() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PersistentStateChangeEvent(PersistentStateChangeEvent other) : this() {
stateIdentifier_ = other.stateIdentifier_;
timeoutMillis_ = other.timeoutMillis_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PersistentStateChangeEvent Clone() {
return new PersistentStateChangeEvent(this);
}
/// <summary>Field number for the "stateIdentifier" field.</summary>
public const int StateIdentifierFieldNumber = 1;
private string stateIdentifier_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string StateIdentifier {
get { return stateIdentifier_; }
set {
stateIdentifier_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "timeoutMillis" field.</summary>
public const int TimeoutMillisFieldNumber = 2;
private long timeoutMillis_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long TimeoutMillis {
get { return timeoutMillis_; }
set {
timeoutMillis_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PersistentStateChangeEvent);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PersistentStateChangeEvent other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (StateIdentifier != other.StateIdentifier) return false;
if (TimeoutMillis != other.TimeoutMillis) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (StateIdentifier.Length != 0) hash ^= StateIdentifier.GetHashCode();
if (TimeoutMillis != 0L) hash ^= TimeoutMillis.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (StateIdentifier.Length != 0) {
output.WriteRawTag(10);
output.WriteString(StateIdentifier);
}
if (TimeoutMillis != 0L) {
output.WriteRawTag(16);
output.WriteInt64(TimeoutMillis);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (StateIdentifier.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(StateIdentifier);
}
if (TimeoutMillis != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(TimeoutMillis);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PersistentStateChangeEvent other) {
if (other == null) {
return;
}
if (other.StateIdentifier.Length != 0) {
StateIdentifier = other.StateIdentifier;
}
if (other.TimeoutMillis != 0L) {
TimeoutMillis = other.TimeoutMillis;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
StateIdentifier = input.ReadString();
break;
}
case 16: {
TimeoutMillis = input.ReadInt64();
break;
}
}
}
}
}
internal sealed partial class PersistentFSMSnapshot : pb::IMessage<PersistentFSMSnapshot> {
private static readonly pb::MessageParser<PersistentFSMSnapshot> _parser = new pb::MessageParser<PersistentFSMSnapshot>(() => new PersistentFSMSnapshot());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PersistentFSMSnapshot> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Persistence.Serialization.Proto.Msg.PersistenceReflection.Descriptor.MessageTypes[6]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PersistentFSMSnapshot() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PersistentFSMSnapshot(PersistentFSMSnapshot other) : this() {
stateIdentifier_ = other.stateIdentifier_;
Data = other.data_ != null ? other.Data.Clone() : null;
timeoutMillis_ = other.timeoutMillis_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PersistentFSMSnapshot Clone() {
return new PersistentFSMSnapshot(this);
}
/// <summary>Field number for the "stateIdentifier" field.</summary>
public const int StateIdentifierFieldNumber = 1;
private string stateIdentifier_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string StateIdentifier {
get { return stateIdentifier_; }
set {
stateIdentifier_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "data" field.</summary>
public const int DataFieldNumber = 2;
private global::Akka.Persistence.Serialization.Proto.Msg.PersistentPayload data_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Akka.Persistence.Serialization.Proto.Msg.PersistentPayload Data {
get { return data_; }
set {
data_ = value;
}
}
/// <summary>Field number for the "timeoutMillis" field.</summary>
public const int TimeoutMillisFieldNumber = 3;
private long timeoutMillis_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long TimeoutMillis {
get { return timeoutMillis_; }
set {
timeoutMillis_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PersistentFSMSnapshot);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PersistentFSMSnapshot other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (StateIdentifier != other.StateIdentifier) return false;
if (!object.Equals(Data, other.Data)) return false;
if (TimeoutMillis != other.TimeoutMillis) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (StateIdentifier.Length != 0) hash ^= StateIdentifier.GetHashCode();
if (data_ != null) hash ^= Data.GetHashCode();
if (TimeoutMillis != 0L) hash ^= TimeoutMillis.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (StateIdentifier.Length != 0) {
output.WriteRawTag(10);
output.WriteString(StateIdentifier);
}
if (data_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Data);
}
if (TimeoutMillis != 0L) {
output.WriteRawTag(24);
output.WriteInt64(TimeoutMillis);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (StateIdentifier.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(StateIdentifier);
}
if (data_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Data);
}
if (TimeoutMillis != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(TimeoutMillis);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PersistentFSMSnapshot other) {
if (other == null) {
return;
}
if (other.StateIdentifier.Length != 0) {
StateIdentifier = other.StateIdentifier;
}
if (other.data_ != null) {
if (data_ == null) {
data_ = new global::Akka.Persistence.Serialization.Proto.Msg.PersistentPayload();
}
Data.MergeFrom(other.Data);
}
if (other.TimeoutMillis != 0L) {
TimeoutMillis = other.TimeoutMillis;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
StateIdentifier = input.ReadString();
break;
}
case 18: {
if (data_ == null) {
data_ = new global::Akka.Persistence.Serialization.Proto.Msg.PersistentPayload();
}
input.ReadMessage(data_);
break;
}
case 24: {
TimeoutMillis = input.ReadInt64();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.Test;
using NUnit.Framework;
namespace Org.BouncyCastle.Crypto.Tests
{
internal class DesParityTest
: SimpleTest
{
public override string Name
{
get { return "DESParityTest"; }
}
public override void PerformTest()
{
byte[] k1In = { (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff,
(byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff };
byte[] k1Out = { (byte)0xfe, (byte)0xfe, (byte)0xfe, (byte)0xfe,
(byte)0xfe, (byte)0xfe, (byte)0xfe, (byte)0xfe };
byte[] k2In = { (byte)0xef, (byte)0xcb, (byte)0xda, (byte)0x4f,
(byte)0xaa, (byte)0x99, (byte)0x7f, (byte)0x63 };
byte[] k2Out = { (byte)0xef, (byte)0xcb, (byte)0xda, (byte)0x4f,
(byte)0xab, (byte)0x98, (byte)0x7f, (byte)0x62 };
DesParameters.SetOddParity(k1In);
for (int i = 0; i != k1In.Length; i++)
{
if (k1In[i] != k1Out[i])
{
Fail("Failed "
+ "got " + Hex.ToHexString(k1In)
+ " expected " + Hex.ToHexString(k1Out));
}
}
DesParameters.SetOddParity(k2In);
for (int i = 0; i != k2In.Length; i++)
{
if (k2In[i] != k2Out[i])
{
Fail("Failed "
+ "got " + Hex.ToHexString(k2In)
+ " expected " + Hex.ToHexString(k2Out));
}
}
}
}
internal class KeyGenTest
: SimpleTest
{
public override string Name
{
get { return "KeyGenTest"; }
}
public override void PerformTest()
{
DesKeyGenerator keyGen = new DesKeyGenerator();
keyGen.Init(new KeyGenerationParameters(new SecureRandom(), 56));
byte[] kB = keyGen.GenerateKey();
if (kB.Length != 8)
{
Fail("DES bit key wrong length.");
}
}
}
internal class DesParametersTest
: SimpleTest
{
private static readonly byte[] weakKeys =
{
(byte)0x01,(byte)0x01,(byte)0x01,(byte)0x01, (byte)0x01,(byte)0x01,(byte)0x01,(byte)0x01,
(byte)0x1f,(byte)0x1f,(byte)0x1f,(byte)0x1f, (byte)0x0e,(byte)0x0e,(byte)0x0e,(byte)0x0e,
(byte)0xe0,(byte)0xe0,(byte)0xe0,(byte)0xe0, (byte)0xf1,(byte)0xf1,(byte)0xf1,(byte)0xf1,
(byte)0xfe,(byte)0xfe,(byte)0xfe,(byte)0xfe, (byte)0xfe,(byte)0xfe,(byte)0xfe,(byte)0xfe,
/* semi-weak keys */
(byte)0x01,(byte)0xfe,(byte)0x01,(byte)0xfe, (byte)0x01,(byte)0xfe,(byte)0x01,(byte)0xfe,
(byte)0x1f,(byte)0xe0,(byte)0x1f,(byte)0xe0, (byte)0x0e,(byte)0xf1,(byte)0x0e,(byte)0xf1,
(byte)0x01,(byte)0xe0,(byte)0x01,(byte)0xe0, (byte)0x01,(byte)0xf1,(byte)0x01,(byte)0xf1,
(byte)0x1f,(byte)0xfe,(byte)0x1f,(byte)0xfe, (byte)0x0e,(byte)0xfe,(byte)0x0e,(byte)0xfe,
(byte)0x01,(byte)0x1f,(byte)0x01,(byte)0x1f, (byte)0x01,(byte)0x0e,(byte)0x01,(byte)0x0e,
(byte)0xe0,(byte)0xfe,(byte)0xe0,(byte)0xfe, (byte)0xf1,(byte)0xfe,(byte)0xf1,(byte)0xfe,
(byte)0xfe,(byte)0x01,(byte)0xfe,(byte)0x01, (byte)0xfe,(byte)0x01,(byte)0xfe,(byte)0x01,
(byte)0xe0,(byte)0x1f,(byte)0xe0,(byte)0x1f, (byte)0xf1,(byte)0x0e,(byte)0xf1,(byte)0x0e,
(byte)0xe0,(byte)0x01,(byte)0xe0,(byte)0x01, (byte)0xf1,(byte)0x01,(byte)0xf1,(byte)0x01,
(byte)0xfe,(byte)0x1f,(byte)0xfe,(byte)0x1f, (byte)0xfe,(byte)0x0e,(byte)0xfe,(byte)0x0e,
(byte)0x1f,(byte)0x01,(byte)0x1f,(byte)0x01, (byte)0x0e,(byte)0x01,(byte)0x0e,(byte)0x01,
(byte)0xfe,(byte)0xe0,(byte)0xfe,(byte)0xe0, (byte)0xfe,(byte)0xf1,(byte)0xfe,(byte)0xf1
};
public override string Name
{
get { return "DesParameters"; }
}
public override void PerformTest()
{
try
{
DesParameters.IsWeakKey(new byte[4], 0);
Fail("no exception on small key");
}
catch (ArgumentException e)
{
if (!e.Message.Equals("key material too short."))
{
Fail("wrong exception");
}
}
try
{
new DesParameters(weakKeys);
Fail("no exception on weak key");
}
catch (ArgumentException e)
{
if (!e.Message.Equals("attempt to create weak DES key"))
{
Fail("wrong exception");
}
}
for (int i = 0; i != weakKeys.Length; i += 8)
{
if (!DesParameters.IsWeakKey(weakKeys, i))
{
Fail("weakKey test failed");
}
}
}
}
/**
* DES tester - vectors from <a href="http://www.itl.nist.gov/fipspubs/fip81.htm">FIPS 81</a>
*/
[TestFixture]
public class DesTest
: CipherTest
{
static string input1 = "4e6f77206973207468652074696d6520666f7220616c6c20";
static string input2 = "4e6f7720697320746865";
static string input3 = "4e6f7720697320746865aabbcc";
static SimpleTest[] tests =
{
new BlockCipherVectorTest(0, new DesEngine(),
new DesParameters(Hex.Decode("0123456789abcdef")),
input1, "3fa40e8a984d48156a271787ab8883f9893d51ec4b563b53"),
new BlockCipherVectorTest(1, new CbcBlockCipher(new DesEngine()),
new ParametersWithIV(new DesParameters(Hex.Decode("0123456789abcdef")), Hex.Decode("1234567890abcdef")),
input1, "e5c7cdde872bf27c43e934008c389c0f683788499a7c05f6"),
new BlockCipherVectorTest(2, new CfbBlockCipher(new DesEngine(), 8),
new ParametersWithIV(new DesParameters(Hex.Decode("0123456789abcdef")), Hex.Decode("1234567890abcdef")),
input2, "f31fda07011462ee187f"),
new BlockCipherVectorTest(3, new CfbBlockCipher(new DesEngine(), 64),
new ParametersWithIV(new DesParameters(Hex.Decode("0123456789abcdef")), Hex.Decode("1234567890abcdef")),
input1, "f3096249c7f46e51a69e839b1a92f78403467133898ea622"),
new BlockCipherVectorTest(4, new OfbBlockCipher(new DesEngine(), 8),
new ParametersWithIV(new DesParameters(Hex.Decode("0123456789abcdef")), Hex.Decode("1234567890abcdef")),
input2, "f34a2850c9c64985d684"),
new BlockCipherVectorTest(5, new CfbBlockCipher(new DesEngine(), 64),
new ParametersWithIV(new DesParameters(Hex.Decode("0123456789abcdef")), Hex.Decode("1234567890abcdef")),
input3, "f3096249c7f46e51a69e0954bf"),
new BlockCipherVectorTest(6, new OfbBlockCipher(new DesEngine(), 64),
new ParametersWithIV(new DesParameters(Hex.Decode("0123456789abcdef")), Hex.Decode("1234567890abcdef")),
input3, "f3096249c7f46e5135f2c0eb8b"),
new DesParityTest(),
new DesParametersTest(),
new KeyGenTest()
};
public DesTest()
: base(tests, new DesEngine(), new DesParameters(new byte[8]))
{
}
public override string Name
{
get { return "DES"; }
}
public static void Main(
string[] args)
{
RunTest(new DesTest());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using Microsoft.Extensions.Logging;
using Orleans.Messaging;
using Orleans.Serialization;
namespace Orleans.Runtime.Messaging
{
internal class IncomingMessageAcceptor : AsynchAgent
{
private readonly ConcurrentObjectPool<SaeaPoolWrapper> receiveEventArgsPool;
private const int SocketBufferSize = 1024 * 128; // 128 kb
private readonly IPEndPoint listenAddress;
private Action<Message> sniffIncomingMessageHandler;
private readonly LingerOption receiveLingerOption = new LingerOption(true, 0);
internal Socket AcceptingSocket;
protected MessageCenter MessageCenter;
protected HashSet<Socket> OpenReceiveSockets;
protected readonly MessageFactory MessageFactory;
private static readonly CounterStatistic allocatedSocketEventArgsCounter
= CounterStatistic.FindOrCreate(StatisticNames.MESSAGE_ACCEPTOR_ALLOCATED_SOCKET_EVENT_ARGS, false);
private readonly CounterStatistic checkedOutSocketEventArgsCounter;
private readonly CounterStatistic checkedInSocketEventArgsCounter;
private readonly SerializationManager serializationManager;
private readonly ILoggerFactory loggerFactory;
public Action<Message> SniffIncomingMessage
{
set
{
if (sniffIncomingMessageHandler != null)
throw new InvalidOperationException("IncomingMessageAcceptor SniffIncomingMessage already set");
sniffIncomingMessageHandler = value;
}
}
private const int LISTEN_BACKLOG_SIZE = 1024;
protected SocketDirection SocketDirection { get; private set; }
// Used for holding enough info to handle receive completion
internal IncomingMessageAcceptor(MessageCenter msgCtr, IPEndPoint here, SocketDirection socketDirection, MessageFactory messageFactory, SerializationManager serializationManager,
ILoggerFactory loggerFactory)
:base(loggerFactory)
{
this.loggerFactory = loggerFactory;
Log = new LoggerWrapper<IncomingMessageAcceptor>(loggerFactory);
MessageCenter = msgCtr;
listenAddress = here;
this.MessageFactory = messageFactory;
this.receiveEventArgsPool = new ConcurrentObjectPool<SaeaPoolWrapper>(() => this.CreateSocketReceiveAsyncEventArgsPoolWrapper());
this.serializationManager = serializationManager;
if (here == null)
listenAddress = MessageCenter.MyAddress.Endpoint;
AcceptingSocket = SocketManager.GetAcceptingSocketForEndpoint(listenAddress);
Log.Info(ErrorCode.Messaging_IMA_OpenedListeningSocket, "Opened a listening socket at address " + AcceptingSocket.LocalEndPoint);
OpenReceiveSockets = new HashSet<Socket>();
OnFault = FaultBehavior.CrashOnFault;
SocketDirection = socketDirection;
checkedOutSocketEventArgsCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGE_ACCEPTOR_CHECKED_OUT_SOCKET_EVENT_ARGS, false);
checkedInSocketEventArgsCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGE_ACCEPTOR_CHECKED_IN_SOCKET_EVENT_ARGS, false);
IntValueStatistic.FindOrCreate(StatisticNames.MESSAGE_ACCEPTOR_IN_USE_SOCKET_EVENT_ARGS,
() => checkedOutSocketEventArgsCounter.GetCurrentValue() - checkedInSocketEventArgsCounter.GetCurrentValue());
}
protected override void Run()
{
try
{
AcceptingSocket.Listen(LISTEN_BACKLOG_SIZE);
StartAccept(null);
}
catch (Exception ex)
{
Log.Error(ErrorCode.MessagingAcceptAsyncSocketException, "Exception beginning accept on listening socket", ex);
throw;
}
if (Log.IsVerbose3) Log.Verbose3("Started accepting connections.");
}
public override void Stop()
{
base.Stop();
if (Log.IsVerbose) Log.Verbose("Disconnecting the listening socket");
SocketManager.CloseSocket(AcceptingSocket);
Socket[] temp;
lock (Lockable)
{
temp = new Socket[OpenReceiveSockets.Count];
OpenReceiveSockets.CopyTo(temp);
}
foreach (var socket in temp)
{
SafeCloseSocket(socket);
}
lock (Lockable)
{
ClearSockets();
}
}
protected virtual bool RecordOpenedSocket(Socket sock)
{
GrainId client;
if (!ReceiveSocketPreample(sock, false, out client)) return false;
NetworkingStatisticsGroup.OnOpenedReceiveSocket();
return true;
}
protected bool ReceiveSocketPreample(Socket sock, bool expectProxiedConnection, out GrainId client)
{
client = null;
if (Cts.IsCancellationRequested) return false;
if (!ReadConnectionPreamble(sock, out client))
{
return false;
}
if (Log.IsVerbose2) Log.Verbose2(ErrorCode.MessageAcceptor_Connection, "Received connection from {0} at source address {1}", client, sock.RemoteEndPoint.ToString());
if (expectProxiedConnection)
{
// Proxied Gateway Connection - must have sender id
if (client.Equals(Constants.SiloDirectConnectionId))
{
Log.Error(ErrorCode.MessageAcceptor_NotAProxiedConnection, $"Gateway received unexpected non-proxied connection from {client} at source address {sock.RemoteEndPoint}");
return false;
}
}
else
{
// Direct connection - should not have sender id
if (!client.Equals(Constants.SiloDirectConnectionId))
{
Log.Error(ErrorCode.MessageAcceptor_UnexpectedProxiedConnection, $"Silo received unexpected proxied connection from {client} at source address {sock.RemoteEndPoint}");
return false;
}
}
lock (Lockable)
{
OpenReceiveSockets.Add(sock);
}
return true;
}
private bool ReadConnectionPreamble(Socket socket, out GrainId grainId)
{
grainId = null;
byte[] buffer = null;
try
{
buffer = ReadFromSocket(socket, sizeof(int)); // Read the size
if (buffer == null) return false;
Int32 size = BitConverter.ToInt32(buffer, 0);
if (size > 0)
{
buffer = ReadFromSocket(socket, size); // Receive the client ID
if (buffer == null) return false;
grainId = GrainIdExtensions.FromByteArray(buffer);
}
return true;
}
catch (Exception exc)
{
Log.Error(ErrorCode.GatewayFailedToParse,
$"Failed to convert the data that read from the socket. buffer = {Utils.EnumerableToString(buffer)}, from endpoint {socket.RemoteEndPoint}.", exc);
return false;
}
}
private byte[] ReadFromSocket(Socket sock, int expected)
{
var buffer = new byte[expected];
int offset = 0;
while (offset < buffer.Length)
{
try
{
int bytesRead = sock.Receive(buffer, offset, buffer.Length - offset, SocketFlags.None);
if (bytesRead == 0)
{
Log.Warn(ErrorCode.GatewayAcceptor_SocketClosed,
"Remote socket closed while receiving connection preamble data from endpoint {0}.", sock.RemoteEndPoint);
return null;
}
offset += bytesRead;
}
catch (Exception ex)
{
Log.Warn(ErrorCode.GatewayAcceptor_ExceptionReceiving,
"Exception receiving connection preamble data from endpoint " + sock.RemoteEndPoint, ex);
return null;
}
}
return buffer;
}
protected virtual void RecordClosedSocket(Socket sock)
{
if (TryRemoveClosedSocket(sock))
NetworkingStatisticsGroup.OnClosedReceivingSocket();
}
protected bool TryRemoveClosedSocket(Socket sock)
{
lock (Lockable)
{
return OpenReceiveSockets.Remove(sock);
}
}
protected virtual void ClearSockets()
{
lock (Lockable)
{
OpenReceiveSockets.Clear();
}
}
/// <summary>
/// Begins an operation to accept a connection request from the client.
/// </summary>
/// <param name="acceptEventArg">The context object to use when issuing
/// the accept operation on the server's listening socket.</param>
private void StartAccept(SocketAsyncEventArgs acceptEventArg)
{
if (acceptEventArg == null)
{
acceptEventArg = new SocketAsyncEventArgs();
acceptEventArg.UserToken = this;
acceptEventArg.Completed += OnAcceptCompleted;
}
else
{
// We have handed off the connection info from the
// accepting socket to the receiving socket. So, now we will clear
// the socket info from that object, so it will be
// ready for a new socket
acceptEventArg.AcceptSocket = null;
}
// Socket.AcceptAsync begins asynchronous operation to accept the connection.
// Note the listening socket will pass info to the SocketAsyncEventArgs
// object that has the Socket that does the accept operation.
// If you do not create a Socket object and put it in the SAEA object
// before calling AcceptAsync and use the AcceptSocket property to get it,
// then a new Socket object will be created by .NET.
try
{
// AcceptAsync returns true if the I / O operation is pending.The SocketAsyncEventArgs.Completed event
// on the e parameter will be raised upon completion of the operation.Returns false if the I/O operation
// completed synchronously. The SocketAsyncEventArgs.Completed event on the e parameter will not be raised
// and the e object passed as a parameter may be examined immediately after the method call returns to retrieve
// the result of the operation.
while (!AcceptingSocket.AcceptAsync(acceptEventArg))
{
ProcessAccept(acceptEventArg, true);
}
}
catch (SocketException ex)
{
Log.Warn(ErrorCode.MessagingAcceptAsyncSocketException, "Socket error on accepting socket during AcceptAsync {0}", ex.SocketErrorCode);
RestartAcceptingSocket();
}
catch (ObjectDisposedException)
{
// Socket was closed, but we're not shutting down; we need to open a new socket and start over...
// Close the old socket and open a new one
Log.Warn(ErrorCode.MessagingAcceptingSocketClosed, "Accepting socket was closed when not shutting down");
RestartAcceptingSocket();
}
catch (Exception ex)
{
// There was a network error. We need to get a new accepting socket and re-issue an accept before we continue.
// Close the old socket and open a new one
Log.Warn(ErrorCode.MessagingAcceptAsyncSocketException, "Exception on accepting socket during AcceptAsync", ex);
RestartAcceptingSocket();
}
}
private void OnAcceptCompleted(object sender, SocketAsyncEventArgs e)
{
((IncomingMessageAcceptor)e.UserToken).ProcessAccept(e, false);
}
/// <summary>
/// Process the accept for the socket listener.
/// </summary>
/// <param name="e">SocketAsyncEventArg associated with the completed accept operation.</param>
/// <param name="completedSynchronously">Shows whether AcceptAsync completed synchronously,
/// if true - the next accept operation woun't be started. Used for avoiding potential stack overflows.</param>
private void ProcessAccept(SocketAsyncEventArgs e, bool completedSynchronously)
{
var ima = e.UserToken as IncomingMessageAcceptor;
try
{
if (ima == null)
{
Log.Warn(ErrorCode.Messaging_IMA_AcceptCallbackUnexpectedState,
"AcceptCallback invoked with an unexpected async state of type {0}",
e.UserToken?.GetType().ToString() ?? "null");
return;
}
if (e.SocketError != SocketError.Success)
{
RestartAcceptingSocket();
return;
}
// First check to see if we're shutting down, in which case there's no point in doing anything other
// than closing the accepting socket and returning.
if (ima.Cts == null || ima.Cts.IsCancellationRequested)
{
SocketManager.CloseSocket(ima.AcceptingSocket);
ima.Log.Info(ErrorCode.Messaging_IMA_ClosingSocket, "Closing accepting socket during shutdown");
return;
}
Socket sock = e.AcceptSocket;
if (sock.Connected)
{
if (ima.Log.IsVerbose) ima.Log.Verbose("Received a connection from {0}", sock.RemoteEndPoint);
// Finally, process the incoming request:
// Prep the socket so it will reset on close
sock.LingerState = receiveLingerOption;
// Add the socket to the open socket collection
if (ima.RecordOpenedSocket(sock))
{
// Get the socket for the accepted client connection and put it into the
// ReadEventArg object user token.
var readEventArgs = GetSocketReceiveAsyncEventArgs(sock);
StartReceiveAsync(sock, readEventArgs, ima);
}
else
{
ima.SafeCloseSocket(sock);
}
}
// The next accept will be started in the caller method
if (completedSynchronously)
{
return;
}
// Start a new Accept
StartAccept(e);
}
catch (Exception ex)
{
var logger = ima?.Log ?? this.Log;
logger.Error(ErrorCode.Messaging_IMA_ExceptionAccepting, "Unexpected exception in IncomingMessageAccepter.AcceptCallback", ex);
RestartAcceptingSocket();
}
}
private void StartReceiveAsync(Socket sock, SocketAsyncEventArgs readEventArgs, IncomingMessageAcceptor ima)
{
try
{
// Set up the async receive
if (!sock.ReceiveAsync(readEventArgs))
{
ProcessReceive(readEventArgs);
}
}
catch (Exception exception)
{
var socketException = exception as SocketException;
var context = readEventArgs.UserToken as ReceiveCallbackContext;
ima.Log.Warn(ErrorCode.Messaging_IMA_NewBeginReceiveException,
$"Exception on new socket during ReceiveAsync with RemoteEndPoint " +
$"{socketException?.SocketErrorCode}: {context?.RemoteEndPoint}", exception);
ima.SafeCloseSocket(sock);
FreeSocketAsyncEventArgs(readEventArgs);
}
}
private SocketAsyncEventArgs GetSocketReceiveAsyncEventArgs(Socket sock)
{
var saea = receiveEventArgsPool.Allocate();
var token = ((ReceiveCallbackContext) saea.SocketAsyncEventArgs.UserToken);
token.IMA = this;
token.Socket = sock;
checkedOutSocketEventArgsCounter.Increment();
return saea.SocketAsyncEventArgs;
}
private SaeaPoolWrapper CreateSocketReceiveAsyncEventArgsPoolWrapper()
{
SocketAsyncEventArgs readEventArgs = new SocketAsyncEventArgs();
readEventArgs.Completed += OnReceiveCompleted;
var buffer = new byte[SocketBufferSize];
// SocketAsyncEventArgs and ReceiveCallbackContext's buffer shares the same buffer list with pinned arrays.
readEventArgs.SetBuffer(buffer, 0, buffer.Length);
var poolWrapper = new SaeaPoolWrapper(readEventArgs);
// Creates with incomplete state: IMA should be set before using
readEventArgs.UserToken = new ReceiveCallbackContext(poolWrapper, this.MessageFactory, this.serializationManager, this.loggerFactory);
allocatedSocketEventArgsCounter.Increment();
return poolWrapper;
}
private void FreeSocketAsyncEventArgs(SocketAsyncEventArgs args)
{
var receiveToken = (ReceiveCallbackContext) args.UserToken;
receiveToken.Reset();
args.AcceptSocket = null;
checkedInSocketEventArgsCounter.Increment();
receiveEventArgsPool.Free(receiveToken.SaeaPoolWrapper);
}
private static void OnReceiveCompleted(object sender, SocketAsyncEventArgs e)
{
if (e.LastOperation != SocketAsyncOperation.Receive)
{
throw new ArgumentException("The last operation completed on the socket was not a receive");
}
var rcc = e.UserToken as ReceiveCallbackContext;
if (rcc.IMA.Log.IsVerbose3) rcc.IMA.Log.Verbose("Socket receive completed from remote " + e.RemoteEndPoint);
rcc.IMA.ProcessReceive(e);
}
/// <summary>
/// This method is invoked when an asynchronous receive operation completes.
/// If the remote host closed the connection, then the socket is closed.
/// </summary>
/// <param name="e">SocketAsyncEventArg associated with the completed receive operation.</param>
private void ProcessReceive(SocketAsyncEventArgs e)
{
var rcc = e.UserToken as ReceiveCallbackContext;
// If no data was received, close the connection. This is a normal
// situation that shows when the remote host has finished sending data.
if (e.BytesTransferred <= 0)
{
if (Log.IsVerbose) Log.Verbose("Closing recieving socket: " + e.RemoteEndPoint);
rcc.IMA.SafeCloseSocket(rcc.Socket);
FreeSocketAsyncEventArgs(e);
return;
}
if (e.SocketError != SocketError.Success)
{
Log.Warn(ErrorCode.Messaging_IMA_NewBeginReceiveException,
$"Socket error on new socket during ReceiveAsync with RemoteEndPoint: {e.SocketError}");
rcc.IMA.SafeCloseSocket(rcc.Socket);
FreeSocketAsyncEventArgs(e);
return;
}
Socket sock = rcc.Socket;
try
{
rcc.ProcessReceived(e);
}
catch (Exception ex)
{
rcc.IMA.Log.Error(ErrorCode.Messaging_IMA_BadBufferReceived,
$"ProcessReceivedBuffer exception with RemoteEndPoint {rcc.RemoteEndPoint}: ", ex);
// There was a problem with the buffer, presumably data corruption, so give up
rcc.IMA.SafeCloseSocket(rcc.Socket);
FreeSocketAsyncEventArgs(e);
// And we're done
return;
}
StartReceiveAsync(sock, e, rcc.IMA);
}
protected virtual void HandleMessage(Message msg, Socket receivedOnSocket)
{
// See it's a Ping message, and if so, short-circuit it
object pingObj;
var requestContext = msg.RequestContextData;
if (requestContext != null &&
requestContext.TryGetValue(RequestContext.PING_APPLICATION_HEADER, out pingObj) &&
pingObj is bool &&
(bool)pingObj)
{
MessagingStatisticsGroup.OnPingReceive(msg.SendingSilo);
if (Log.IsVerbose2) Log.Verbose2("Responding to Ping from {0}", msg.SendingSilo);
if (!msg.TargetSilo.Equals(MessageCenter.MyAddress)) // got ping that is not destined to me. For example, got a ping to my older incarnation.
{
MessagingStatisticsGroup.OnRejectedMessage(msg);
Message rejection = this.MessageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable,
$"The target silo is no longer active: target was {msg.TargetSilo.ToLongString()}, but this silo is {MessageCenter.MyAddress.ToLongString()}. " +
$"The rejected ping message is {msg}.");
MessageCenter.OutboundQueue.SendMessage(rejection);
}
else
{
var response = this.MessageFactory.CreateResponseMessage(msg);
response.BodyObject = Response.Done;
MessageCenter.SendMessage(response);
}
return;
}
// sniff message headers for directory cache management
sniffIncomingMessageHandler?.Invoke(msg);
// Don't process messages that have already timed out
if (msg.IsExpired)
{
msg.DropExpiredMessage(MessagingStatisticsGroup.Phase.Receive);
return;
}
// If we've stopped application message processing, then filter those out now
// Note that if we identify or add other grains that are required for proper stopping, we will need to treat them as we do the membership table grain here.
if (MessageCenter.IsBlockingApplicationMessages && (msg.Category == Message.Categories.Application) && !Constants.SystemMembershipTableId.Equals(msg.SendingGrain))
{
// We reject new requests, and drop all other messages
if (msg.Direction != Message.Directions.Request) return;
MessagingStatisticsGroup.OnRejectedMessage(msg);
var reject = this.MessageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable, "Silo stopping");
MessageCenter.SendMessage(reject);
return;
}
// Make sure the message is for us. Note that some control messages may have no target
// information, so a null target silo is OK.
if ((msg.TargetSilo == null) || msg.TargetSilo.Matches(MessageCenter.MyAddress))
{
// See if it's a message for a client we're proxying.
if (MessageCenter.IsProxying && MessageCenter.TryDeliverToProxy(msg)) return;
// Nope, it's for us
MessageCenter.InboundQueue.PostMessage(msg);
return;
}
if (!msg.TargetSilo.Endpoint.Equals(MessageCenter.MyAddress.Endpoint))
{
// If the message is for some other silo altogether, then we need to forward it.
if (Log.IsVerbose2) Log.Verbose2("Forwarding message {0} from {1} to silo {2}", msg.Id, msg.SendingSilo, msg.TargetSilo);
MessageCenter.OutboundQueue.SendMessage(msg);
return;
}
// If the message was for this endpoint but an older epoch, then reject the message
// (if it was a request), or drop it on the floor if it was a response or one-way.
if (msg.Direction == Message.Directions.Request)
{
MessagingStatisticsGroup.OnRejectedMessage(msg);
Message rejection = this.MessageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Transient,
string.Format("The target silo is no longer active: target was {0}, but this silo is {1}. The rejected message is {2}.",
msg.TargetSilo.ToLongString(), MessageCenter.MyAddress.ToLongString(), msg));
MessageCenter.OutboundQueue.SendMessage(rejection);
if (Log.IsVerbose) Log.Verbose("Rejecting an obsolete request; target was {0}, but this silo is {1}. The rejected message is {2}.",
msg.TargetSilo.ToLongString(), MessageCenter.MyAddress.ToLongString(), msg);
}
}
private void RestartAcceptingSocket()
{
try
{
if (Log.IsVerbose) Log.Verbose("Restarting of the accepting socket");
SocketManager.CloseSocket(AcceptingSocket);
AcceptingSocket = SocketManager.GetAcceptingSocketForEndpoint(listenAddress);
AcceptingSocket.Listen(LISTEN_BACKLOG_SIZE);
StartAccept(null);
}
catch (Exception ex)
{
Log.Error(ErrorCode.Runtime_Error_100016, "Unable to create a new accepting socket", ex);
throw;
}
}
private void SafeCloseSocket(Socket sock)
{
RecordClosedSocket(sock);
SocketManager.CloseSocket(sock);
}
private class ReceiveCallbackContext
{
private readonly MessageFactory messageFactory;
private readonly IncomingMessageBuffer _buffer;
private Socket socket;
public Socket Socket {
get { return socket; }
internal set
{
socket = value;
RemoteEndPoint = socket.RemoteEndPoint;
}
}
public EndPoint RemoteEndPoint { get; private set; }
public IncomingMessageAcceptor IMA { get; internal set; }
public SaeaPoolWrapper SaeaPoolWrapper { get; }
public ReceiveCallbackContext(SaeaPoolWrapper poolWrapper, MessageFactory messageFactory, SerializationManager serializationManager, ILoggerFactory loggerFactory)
{
this.messageFactory = messageFactory;
SaeaPoolWrapper = poolWrapper;
_buffer = new IncomingMessageBuffer(loggerFactory, serializationManager);
}
public void ProcessReceived(SocketAsyncEventArgs e)
{
#if TRACK_DETAILED_STATS
ThreadTrackingStatistic tracker = null;
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
int id = System.Threading.Thread.CurrentThread.ManagedThreadId;
if (!trackers.TryGetValue(id, out tracker))
{
tracker = new ThreadTrackingStatistic("ThreadPoolThread." + System.Threading.Thread.CurrentThread.ManagedThreadId);
bool added = trackers.TryAdd(id, tracker);
if (added)
{
tracker.OnStartExecution();
}
}
tracker.OnStartProcessing();
}
#endif
try
{
_buffer.UpdateReceivedData(e.Buffer, e.BytesTransferred);
while (true)
{
Message msg = null;
try
{
if (!this._buffer.TryDecodeMessage(out msg)) break;
this.IMA.HandleMessage(msg, this.Socket);
}
catch (Exception exception)
{
// If deserialization completely failed or the message was one-way, rethrow the exception
// so that it can be handled at another level.
if (msg?.Headers == null || msg.Direction != Message.Directions.Request)
{
throw;
}
// The message body was not successfully decoded, but the headers were.
// Send a fast fail to the caller.
MessagingStatisticsGroup.OnRejectedMessage(msg);
var response = this.messageFactory.CreateResponseMessage(msg);
response.Result = Message.ResponseTypes.Error;
response.BodyObject = Response.ExceptionResponse(exception);
// Send the error response and continue processing the next message.
this.IMA.MessageCenter.SendMessage(response);
}
}
}
catch (Exception exc)
{
try
{
// Log details of receive state machine
IMA.Log.Error(ErrorCode.MessagingProcessReceiveBufferException,
$"Exception trying to process {e.BytesTransferred} bytes from endpoint {RemoteEndPoint}",
exc);
}
catch (Exception) { }
_buffer.Reset(); // Reset back to a hopefully good base state
throw;
}
#if TRACK_DETAILED_STATS
finally
{
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
tracker.IncrementNumberOfProcessed();
tracker.OnStopProcessing();
}
}
#endif
}
public void Reset()
{
_buffer.Reset();
}
}
private class SaeaPoolWrapper : PooledResource<SaeaPoolWrapper>
{
public SocketAsyncEventArgs SocketAsyncEventArgs { get; }
public SaeaPoolWrapper(SocketAsyncEventArgs socketAsyncEventArgs)
{
SocketAsyncEventArgs = socketAsyncEventArgs;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using Xunit;
namespace System.IO.Tests
{
public class FileStream_ctor_str_fm : FileSystemTest
{
protected virtual FileStream CreateFileStream(string path, FileMode mode)
{
return new FileStream(path, mode);
}
[Fact]
public void NullPathThrows()
{
Assert.Throws<ArgumentNullException>(() => CreateFileStream(null, FileMode.Open));
}
[Fact]
public void EmptyPathThrows()
{
Assert.Throws<ArgumentException>(() => CreateFileStream(String.Empty, FileMode.Open));
}
[Fact]
public void DirectoryThrows()
{
Assert.Throws<UnauthorizedAccessException>(() => CreateFileStream(".", FileMode.Open));
}
[Fact]
public void InvalidModeThrows()
{
Assert.Throws<ArgumentOutOfRangeException>("mode", () => CreateFileStream(GetTestFilePath(), ~FileMode.Open));
}
[Fact]
public void FileModeCreate()
{
using (CreateFileStream(GetTestFilePath(), FileMode.Create))
{ }
}
[Fact]
public void FileModeCreateExisting()
{
string fileName = GetTestFilePath();
using (FileStream fs = CreateFileStream(fileName, FileMode.Create))
{
fs.WriteByte(0);
}
using (FileStream fs = CreateFileStream(fileName, FileMode.Create))
{
// Ensure that the file was re-created
Assert.Equal(0L, fs.Length);
Assert.Equal(0L, fs.Position);
Assert.True(fs.CanRead);
Assert.True(fs.CanWrite);
}
}
[Fact]
public void FileModeCreateNew()
{
using (CreateFileStream(GetTestFilePath(), FileMode.CreateNew))
{ }
}
[Fact]
public void FileModeCreateNewExistingThrows()
{
string fileName = GetTestFilePath();
using (FileStream fs = CreateFileStream(fileName, FileMode.CreateNew))
{
fs.WriteByte(0);
Assert.True(fs.CanRead);
Assert.True(fs.CanWrite);
}
Assert.Throws<IOException>(() => CreateFileStream(fileName, FileMode.CreateNew));
}
[Fact]
public void FileModeOpenThrows()
{
string fileName = GetTestFilePath();
FileNotFoundException fnfe = Assert.Throws<FileNotFoundException>(() => CreateFileStream(fileName, FileMode.Open));
Assert.Equal(fileName, fnfe.FileName);
}
[Fact]
public void FileModeOpenExisting()
{
string fileName = GetTestFilePath();
using (FileStream fs = CreateFileStream(fileName, FileMode.Create))
{
fs.WriteByte(0);
}
using (FileStream fs = CreateFileStream(fileName, FileMode.Open))
{
// Ensure that the file was re-opened
Assert.Equal(1L, fs.Length);
Assert.Equal(0L, fs.Position);
Assert.True(fs.CanRead);
Assert.True(fs.CanWrite);
}
}
[Fact]
public void FileModeOpenOrCreate()
{
using (CreateFileStream(GetTestFilePath(), FileMode.OpenOrCreate))
{}
}
[Fact]
public void FileModeOpenOrCreateExisting()
{
string fileName = GetTestFilePath();
using (FileStream fs = CreateFileStream(fileName, FileMode.Create))
{
fs.WriteByte(0);
}
using (FileStream fs = CreateFileStream(fileName, FileMode.OpenOrCreate))
{
// Ensure that the file was re-opened
Assert.Equal(1L, fs.Length);
Assert.Equal(0L, fs.Position);
Assert.True(fs.CanRead);
Assert.True(fs.CanWrite);
}
}
[Fact]
public void FileModeTruncateThrows()
{
string fileName = GetTestFilePath();
FileNotFoundException fnfe = Assert.Throws<FileNotFoundException>(() => CreateFileStream(fileName, FileMode.Truncate));
Assert.Equal(fileName, fnfe.FileName);
}
[Fact]
public void FileModeTruncateExisting()
{
string fileName = GetTestFilePath();
using (FileStream fs = CreateFileStream(fileName, FileMode.Create))
{
fs.WriteByte(0);
}
using (FileStream fs = CreateFileStream(fileName, FileMode.Truncate))
{
// Ensure that the file was re-opened and truncated
Assert.Equal(0L, fs.Length);
Assert.Equal(0L, fs.Position);
Assert.True(fs.CanRead);
Assert.True(fs.CanWrite);
}
}
[Fact]
public void FileModeAppend()
{
using (FileStream fs = CreateFileStream(GetTestFilePath(), FileMode.Append))
{
Assert.Equal(false, fs.CanRead);
Assert.Equal(true, fs.CanWrite);
}
}
[Fact]
public void FileModeAppendExisting()
{
string fileName = GetTestFilePath();
using (FileStream fs = CreateFileStream(fileName, FileMode.Create))
{
fs.WriteByte(0);
}
using (FileStream fs = CreateFileStream(fileName, FileMode.Append))
{
// Ensure that the file was re-opened and position set to end
Assert.Equal(1L, fs.Length);
Assert.Equal(1L, fs.Position);
Assert.False(fs.CanRead);
Assert.True(fs.CanSeek);
Assert.True(fs.CanWrite);
Assert.Throws<IOException>(() => fs.Seek(-1, SeekOrigin.Current));
Assert.Throws<NotSupportedException>(() => fs.ReadByte());
}
}
}
}
| |
#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
// MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax
// .NET Compact Framework 1.0 has no support for Win32 Console API's
#if !NETCF
// .Mono 1.0 has no support for Win32 Console API's
#if !MONO
// SSCLI 1.0 has no support for Win32 Console API's
#if !SSCLI
// We don't want framework or platform specific code in the CLI version of log4net
#if !CLI_1_0
#if !NETMF
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using log4net.Layout;
using log4net.Util;
namespace log4net.Appender
{
/// <summary>
/// Appends logging events to the console.
/// </summary>
/// <remarks>
/// <para>
/// ColoredConsoleAppender 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 type of message to be set.
/// </para>
/// <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 directly to the application's attached console
/// not to the <c>System.Console.Out</c> or <c>System.Console.Error</c> <c>TextWriter</c>.
/// The <c>System.Console.Out</c> and <c>System.Console.Error</c> streams can be
/// programmatically redirected (for example NUnit does this to capture program output).
/// This appender will ignore these redirections because it needs to use Win32
/// API calls to colorize the output. To respect these redirections the <see cref="ConsoleAppender"/>
/// must be used.
/// </para>
/// <para>
/// When configuring the colored console appender, 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, HighIntensity" />
/// </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
/// combination 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>
/// <item><term>HighIntensity</term><description></description></item>
/// </list>
/// </para>
/// </remarks>
/// <author>Rick Hobbs</author>
/// <author>Nicko Cadell</author>
public class ColoredConsoleAppender : AppenderSkeleton
{
#region Colors Enum
/// <summary>
/// The enum of possible color values for use with the color mapping method
/// </summary>
/// <remarks>
/// <para>
/// The following flags can be combined together to
/// form the colors.
/// </para>
/// </remarks>
/// <seealso cref="ColoredConsoleAppender" />
[Flags]
public enum Colors : int
{
/// <summary>
/// color is blue
/// </summary>
Blue = 0x0001,
/// <summary>
/// color is green
/// </summary>
Green = 0x0002,
/// <summary>
/// color is red
/// </summary>
Red = 0x0004,
/// <summary>
/// color is white
/// </summary>
White = Blue | Green | Red,
/// <summary>
/// color is yellow
/// </summary>
Yellow = Red | Green,
/// <summary>
/// color is purple
/// </summary>
Purple = Red | Blue,
/// <summary>
/// color is cyan
/// </summary>
Cyan = Green | Blue,
/// <summary>
/// color is intensified
/// </summary>
HighIntensity = 0x0008,
}
#endregion // Colors Enum
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class.
/// </summary>
/// <remarks>
/// The instance of the <see cref="ColoredConsoleAppender" /> class is set up to write
/// to the standard output stream.
/// </remarks>
public ColoredConsoleAppender()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class
/// with the specified layout.
/// </summary>
/// <param name="layout">the layout to use for this appender</param>
/// <remarks>
/// The instance of the <see cref="ColoredConsoleAppender" /> class is set up to write
/// to the standard output stream.
/// </remarks>
[Obsolete("Instead use the default constructor and set the Layout property")]
public ColoredConsoleAppender(ILayout layout) : this(layout, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class
/// with the specified layout.
/// </summary>
/// <param name="layout">the layout to use for this appender</param>
/// <param name="writeToErrorStream">flag set to <c>true</c> to write to the console error stream</param>
/// <remarks>
/// When <paramref name="writeToErrorStream" /> is set to <c>true</c>, output is written to
/// the standard error output stream. Otherwise, output is written to the standard
/// output stream.
/// </remarks>
[Obsolete("Instead use the default constructor and set the Layout & Target properties")]
public ColoredConsoleAppender(ILayout layout, bool writeToErrorStream)
{
Layout = layout;
m_writeToErrorStream = writeToErrorStream;
}
#endregion // Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Target is the value of the console output stream.
/// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>.
/// </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 v = value.Trim();
if (string.Compare(ConsoleError, v, true, CultureInfo.InvariantCulture) == 0)
{
m_writeToErrorStream = true;
}
else
{
m_writeToErrorStream = false;
}
}
}
/// <summary>
/// Add a mapping of level to color - done by the config file
/// </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 colors
/// 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="M:AppenderSkeleton.DoAppend(log4net.Core.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>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#endif
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)]
override protected void Append(log4net.Core.LoggingEvent loggingEvent)
{
if (m_consoleOutputWriter != null)
{
IntPtr consoleHandle = IntPtr.Zero;
if (m_writeToErrorStream)
{
// Write to the error stream
consoleHandle = GetStdHandle(STD_ERROR_HANDLE);
}
else
{
// Write to the output stream
consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
}
// Default to white on black
ushort colorInfo = (ushort)Colors.White;
// see if there is a specified lookup
LevelColors levelColors = m_levelMapping.Lookup(loggingEvent.Level) as LevelColors;
if (levelColors != null)
{
colorInfo = levelColors.CombinedColor;
}
// Render the event to a string
string strLoggingMessage = RenderLoggingEvent(loggingEvent);
// get the current console color - to restore later
CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
GetConsoleScreenBufferInfo(consoleHandle, out bufferInfo);
// set the console colors
SetConsoleTextAttribute(consoleHandle, colorInfo);
// Using WriteConsoleW seems to be unreliable.
// If a large buffer is written, say 15,000 chars
// Followed by a larger buffer, say 20,000 chars
// then WriteConsoleW will fail, last error 8
// 'Not enough storage is available to process this command.'
//
// Although the documentation states that the buffer must
// be less that 64KB (i.e. 32,000 WCHARs) the longest string
// that I can write out a the first call to WriteConsoleW
// is only 30,704 chars.
//
// Unlike the WriteFile API the WriteConsoleW method does not
// seem to be able to partially write out from the input buffer.
// It does have a lpNumberOfCharsWritten parameter, but this is
// either the length of the input buffer if any output was written,
// or 0 when an error occurs.
//
// All results above were observed on Windows XP SP1 running
// .NET runtime 1.1 SP1.
//
// Old call to WriteConsoleW:
//
// WriteConsoleW(
// consoleHandle,
// strLoggingMessage,
// (UInt32)strLoggingMessage.Length,
// out (UInt32)ignoreWrittenCount,
// IntPtr.Zero);
//
// Instead of calling WriteConsoleW we use WriteFile which
// handles large buffers correctly. Because WriteFile does not
// handle the codepage conversion as WriteConsoleW does we
// need to use a System.IO.StreamWriter with the appropriate
// Encoding. The WriteFile calls are wrapped up in the
// System.IO.__ConsoleStream internal class obtained through
// the System.Console.OpenStandardOutput method.
//
// See the ActivateOptions method below for the code that
// retrieves and wraps the stream.
// The windows console uses ScrollConsoleScreenBuffer internally to
// scroll the console buffer when the display buffer of the console
// has been used up. ScrollConsoleScreenBuffer fills the area uncovered
// by moving the current content with the background color
// currently specified on the console. This means that it fills the
// whole line in front of the cursor position with the current
// background color.
// This causes an issue when writing out text with a non default
// background color. For example; We write a message with a Blue
// background color and the scrollable area of the console is full.
// When we write the newline at the end of the message the console
// needs to scroll the buffer to make space available for the new line.
// The ScrollConsoleScreenBuffer internals will fill the newly created
// space with the current background color: Blue.
// We then change the console color back to default (White text on a
// Black background). We write some text to the console, the text is
// written correctly in White with a Black background, however the
// remainder of the line still has a Blue background.
//
// This causes a disjointed appearance to the output where the background
// colors change.
//
// This can be remedied by restoring the console colors before causing
// the buffer to scroll, i.e. before writing the last newline. This does
// assume that the rendered message will end with a newline.
//
// Therefore we identify a trailing newline in the message and don't
// write this to the output, then we restore the console color and write
// a newline. Note that we must AutoFlush before we restore the console
// color otherwise we will have no effect.
//
// There will still be a slight artefact for the last line of the message
// will have the background extended to the end of the line, however this
// is unlikely to cause any user issues.
//
// Note that none of the above is visible while the console buffer is scrollable
// within the console window viewport, the effects only arise when the actual
// buffer is full and needs to be scrolled.
char[] messageCharArray = strLoggingMessage.ToCharArray();
int arrayLength = messageCharArray.Length;
bool appendNewline = false;
// Trim off last newline, if it exists
if (arrayLength > 1 && messageCharArray[arrayLength-2] == '\r' && messageCharArray[arrayLength-1] == '\n')
{
arrayLength -= 2;
appendNewline = true;
}
// Write to the output stream
m_consoleOutputWriter.Write(messageCharArray, 0, arrayLength);
// Restore the console back to its previous color scheme
SetConsoleTextAttribute(consoleHandle, bufferInfo.wAttributes);
if (appendNewline)
{
// Write the newline, after changing the color scheme
m_consoleOutputWriter.Write(s_windowsNewline, 0, 2);
}
}
}
private static readonly char[] s_windowsNewline = {'\r', '\n'};
/// <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>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#endif
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode=true)]
public override void ActivateOptions()
{
base.ActivateOptions();
m_levelMapping.ActivateOptions();
System.IO.Stream consoleOutputStream = null;
// Use the Console methods to open a Stream over the console std handle
if (m_writeToErrorStream)
{
// Write to the error stream
consoleOutputStream = Console.OpenStandardError();
}
else
{
// Write to the output stream
consoleOutputStream = Console.OpenStandardOutput();
}
// Lookup the codepage encoding for the console
System.Text.Encoding consoleEncoding = System.Text.Encoding.GetEncoding(GetConsoleOutputCP());
// Create a writer around the console stream
m_consoleOutputWriter = new System.IO.StreamWriter(consoleOutputStream, consoleEncoding, 0x100);
m_consoleOutputWriter.AutoFlush = true;
// SuppressFinalize on m_consoleOutputWriter because all it will do is flush
// and close the file handle. Because we have set AutoFlush the additional flush
// is not required. The console file handle should not be closed, so we don't call
// Dispose, Close or the finalizer.
GC.SuppressFinalize(m_consoleOutputWriter);
}
#endregion // Override implementation of AppenderSkeleton
#region Public Static Fields
/// <summary>
/// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console
/// standard output stream.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console
/// standard output stream.
/// </para>
/// </remarks>
public const string ConsoleOut = "Console.Out";
/// <summary>
/// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console
/// standard error output stream.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="ColoredConsoleAppender.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>
/// The console output stream writer to write to
/// </summary>
/// <remarks>
/// <para>
/// This writer is not thread safe.
/// </para>
/// </remarks>
private System.IO.StreamWriter m_consoleOutputWriter = null;
#endregion // Private Instances Fields
#region Win32 Methods
[DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern int GetConsoleOutputCP();
[DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern bool SetConsoleTextAttribute(
IntPtr consoleHandle,
ushort attributes);
[DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern bool GetConsoleScreenBufferInfo(
IntPtr consoleHandle,
out CONSOLE_SCREEN_BUFFER_INFO bufferInfo);
// [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
// private static extern bool WriteConsoleW(
// IntPtr hConsoleHandle,
// [MarshalAs(UnmanagedType.LPWStr)] string strBuffer,
// UInt32 bufferLen,
// out UInt32 written,
// IntPtr reserved);
//private const UInt32 STD_INPUT_HANDLE = unchecked((UInt32)(-10));
private const UInt32 STD_OUTPUT_HANDLE = unchecked((UInt32)(-11));
private const UInt32 STD_ERROR_HANDLE = unchecked((UInt32)(-12));
[DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern IntPtr GetStdHandle(
UInt32 type);
[StructLayout(LayoutKind.Sequential)]
private struct COORD
{
public UInt16 x;
public UInt16 y;
}
[StructLayout(LayoutKind.Sequential)]
private struct SMALL_RECT
{
public UInt16 Left;
public UInt16 Top;
public UInt16 Right;
public UInt16 Bottom;
}
[StructLayout(LayoutKind.Sequential)]
private struct CONSOLE_SCREEN_BUFFER_INFO
{
public COORD dwSize;
public COORD dwCursorPosition;
public ushort wAttributes;
public SMALL_RECT srWindow;
public COORD dwMaximumWindowSize;
}
#endregion // Win32 Methods
#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 Colors m_foreColor;
private Colors m_backColor;
private ushort m_combinedColor = 0;
/// <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 Colors 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 Colors BackColor
{
get { return m_backColor; }
set { m_backColor = value; }
}
/// <summary>
/// Initialize the options for the object
/// </summary>
/// <remarks>
/// <para>
/// Combine the <see cref="ForeColor"/> and <see cref="BackColor"/> together.
/// </para>
/// </remarks>
public override void ActivateOptions()
{
base.ActivateOptions();
m_combinedColor = (ushort)( (int)m_foreColor + (((int)m_backColor) << 4) );
}
/// <summary>
/// The combined <see cref="ForeColor"/> and <see cref="BackColor"/> suitable for
/// setting the console color.
/// </summary>
internal ushort CombinedColor
{
get { return m_combinedColor; }
}
}
#endregion // LevelColors LevelMapping Entry
}
}
#endif
#endif // !CLI_1_0
#endif // !SSCLI
#endif // !MONO
#endif // !NETCF
| |
using System;
using System.Collections;
using Cuyahoga.Core;
using Cuyahoga.Core.Domain;
using Cuyahoga.Core.Search;
using Cuyahoga.Core.Service;
using Cuyahoga.Core.Util;
using NHibernate;
using Cuyahoga.Modules.Flash.Domain;
using Cuyahoga.Core.DataAccess;
namespace Cuyahoga.Modules.Flash
{
/// <summary>
/// Summary description for FlashModule.
/// </summary>
public class FlashModule : ModuleBase, INHibernateModule, ISearchable
{
/// <summary>
/// Default constructor.
/// </summary>
public FlashModule()
{
}
/// <summary>
/// Get the content that belongs to the Section where the module is attached to.
/// </summary>
/// <returns></returns>
public AlternateContent GetContent()
{
if (base.Section != null)
{
string hql = "from AlternateContent s where s.Section.Id = :sectionId ";
IList results = base.NHSession.CreateQuery(hql).SetInt32("sectionId", this.Section.Id).List();
if (results.Count == 1)
{
return (AlternateContent)results[0];
}
else if (results.Count > 1)
{
throw new Exception("A request for AlternateContent should only return one item");
}
else
{
return null;
}
}
else
{
throw new Exception("Unable to get the AlternateContent when no Section is available");
}
}
/// <summary>
/// Save the content.
/// </summary>
/// <param name="content"></param>
public void SaveContent(AlternateContent content)
{
ITransaction tx = base.NHSession.BeginTransaction();
try
{
if (content.Id == -1)
{
content.UpdateTimestamp = DateTime.Now;
base.NHSession.Save(content);
OnContentCreated(new IndexEventArgs(AlternateContentToSearchContent(content)));
}
else
{
base.NHSession.Update(content);
OnContentUpdated(new IndexEventArgs(AlternateContentToSearchContent(content)));
}
tx.Commit();
}
catch (Exception ex)
{
tx.Rollback();
throw new Exception("Unable to save content: " + ex.Message, ex);
}
}
/// <summary>
/// Delete the content.
/// </summary>
/// <param name="content"></param>
public void DeleteContent(AlternateContent content)
{
ITransaction tx = base.NHSession.BeginTransaction();
try
{
base.NHSession.Delete(content);
tx.Commit();
OnContentDeleted(new IndexEventArgs(AlternateContentToSearchContent(content)));
}
catch (Exception ex)
{
tx.Rollback();
throw new Exception("Unable to delete content: " + ex.Message, ex);
}
}
public override void DeleteModuleContent()
{
// Delete the associated AlternateContent
AlternateContent content = this.GetContent();
if (content != null)
{
DeleteContent(content);
}
}
private SearchContent AlternateContentToSearchContent(AlternateContent shc)
{
SearchContent sc = new SearchContent();
sc.Title = shc.Section.Title;
sc.Summary = Text.TruncateText(shc.Content, 200); // trunctate the summary to 200 chars
sc.Contents = shc.Content;
sc.Author = shc.ModifiedBy.FullName;
sc.ModuleType = shc.Section.ModuleType.Name;
sc.Path = this.SectionUrl;
sc.Category = String.Empty;
sc.Site = shc.Section.Node.Site.Name;
sc.DateCreated = shc.UpdateTimestamp;
sc.DateModified = shc.UpdateTimestamp;
sc.SectionId = shc.Section.Id;
return sc;
}
#region ISearchable Members
public SearchContent[] GetAllSearchableContent()
{
AlternateContent shc = GetContent();
if (shc != null)
{
SearchContent[] searchContents = new SearchContent[1];
searchContents[0] = AlternateContentToSearchContent(shc);
return searchContents;
}
else
{
return new SearchContent[0];
}
}
public event IndexEventHandler ContentCreated;
protected void OnContentCreated(IndexEventArgs e)
{
if (ContentCreated != null)
{
ContentCreated(this, e);
}
}
public event IndexEventHandler ContentDeleted;
protected void OnContentDeleted(IndexEventArgs e)
{
if (ContentDeleted != null)
{
ContentDeleted(this, e);
}
}
public event IndexEventHandler ContentUpdated;
protected void OnContentUpdated(IndexEventArgs e)
{
if (ContentUpdated != null)
{
ContentUpdated(this, e);
}
}
#endregion
}
/// <summary>
/// The MovieQuality of the Flash
/// </summary>
public enum MovieQuality
{
high,
best,
medium,
low,
autolow,
autohigh
}
/// <summary>
/// The MovieAlign of the Flash
/// </summary>
public enum MovieAlign
{
left,
right,
top,
bottom,
middle
}
/// <summary>
/// The MovieScriptAccess of the Flash
/// </summary>
public enum MovieScriptAccess
{
sameDomain,
always,
never
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyComplex
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// Polymorphism operations.
/// </summary>
public partial class Polymorphism : IServiceOperations<AutoRestComplexTestService>, IPolymorphism
{
/// <summary>
/// Initializes a new instance of the Polymorphism class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Polymorphism(AutoRestComplexTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestComplexTestService
/// </summary>
public AutoRestComplexTestService Client { get; private set; }
/// <summary>
/// Get complex types that are polymorphic
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Fish>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/valid").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Fish>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Fish>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that are polymorphic
/// </summary>
/// <param name='complexBody'>
/// Please put a salmon that looks like this:
/// {
/// 'fishtype':'Salmon',
/// 'location':'alaska',
/// 'iswild':true,
/// 'species':'king',
/// 'length':1.0,
/// 'siblings':[
/// {
/// 'fishtype':'Shark',
/// 'age':6,
/// 'birthday': '2012-01-05T01:00:00Z',
/// 'length':20.0,
/// 'species':'predator',
/// },
/// {
/// 'fishtype':'Sawshark',
/// 'age':105,
/// 'birthday': '1900-01-05T01:00:00Z',
/// 'length':10.0,
/// 'picture': new Buffer([255, 255, 255, 255,
/// 254]).toString('base64'),
/// 'species':'dangerous',
/// },
/// {
/// 'fishtype': 'goblin',
/// 'age': 1,
/// 'birthday': '2015-08-08T00:00:00Z',
/// 'length': 30.0,
/// 'species': 'scary',
/// 'jawsize': 5
/// }
/// ]
/// };
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutValidWithHttpMessagesAsync(Fish complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (complexBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "complexBody");
}
if (complexBody != null)
{
complexBody.Validate();
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/valid").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that are polymorphic, attempting to omit required
/// 'birthday' field - the request should not be allowed from the client
/// </summary>
/// <param name='complexBody'>
/// Please attempt put a sawshark that looks like this, the client should not
/// allow this data to be sent:
/// {
/// "fishtype": "sawshark",
/// "species": "snaggle toothed",
/// "length": 18.5,
/// "age": 2,
/// "birthday": "2013-06-01T01:00:00Z",
/// "location": "alaska",
/// "picture": base64(FF FF FF FF FE),
/// "siblings": [
/// {
/// "fishtype": "shark",
/// "species": "predator",
/// "birthday": "2012-01-05T01:00:00Z",
/// "length": 20,
/// "age": 6
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "picture": base64(FF FF FF FF FE),
/// "length": 10,
/// "age": 105
/// }
/// ]
/// }
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutValidMissingRequiredWithHttpMessagesAsync(Fish complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (complexBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "complexBody");
}
if (complexBody != null)
{
complexBody.Validate();
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValidMissingRequired", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/missingrequired/invalid").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// 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.Reflection.Emit
{
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class GenericTypeParameterBuilder: TypeInfo
{
public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){
if(typeInfo==null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
#region Private Data Mebers
internal TypeBuilder m_type;
#endregion
#region Constructor
internal GenericTypeParameterBuilder(TypeBuilder type)
{
m_type = type;
}
#endregion
#region Object Overrides
public override String ToString()
{
return m_type.Name;
}
public override bool Equals(object o)
{
GenericTypeParameterBuilder g = o as GenericTypeParameterBuilder;
if (g == null)
return false;
return object.ReferenceEquals(g.m_type, m_type);
}
public override int GetHashCode() { return m_type.GetHashCode(); }
#endregion
#region MemberInfo Overrides
public override Type DeclaringType { get { return m_type.DeclaringType; } }
public override Type ReflectedType { get { return m_type.ReflectedType; } }
public override String Name { get { return m_type.Name; } }
public override Module Module { get { return m_type.Module; } }
internal int MetadataTokenInternal { get { return m_type.MetadataTokenInternal; } }
#endregion
#region Type Overrides
public override Type MakePointerType()
{
return SymbolType.FormCompoundType("*", this, 0);
}
public override Type MakeByRefType()
{
return SymbolType.FormCompoundType("&", this, 0);
}
public override Type MakeArrayType()
{
return SymbolType.FormCompoundType("[]", this, 0);
}
public override Type MakeArrayType(int rank)
{
if (rank <= 0)
throw new IndexOutOfRangeException();
Contract.EndContractBlock();
string szrank = "";
if (rank == 1)
{
szrank = "*";
}
else
{
for(int i = 1; i < rank; i++)
szrank += ",";
}
string s = String.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,]
SymbolType st = SymbolType.FormCompoundType(s, this, 0) as SymbolType;
return st;
}
public override Guid GUID { get { throw new NotSupportedException(); } }
public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) { throw new NotSupportedException(); }
public override Assembly Assembly { get { return m_type.Assembly; } }
public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } }
public override String FullName { get { return null; } }
public override String Namespace { get { return null; } }
public override String AssemblyQualifiedName { get { return null; } }
public override Type BaseType { get { return m_type.BaseType; } }
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
[System.Runtime.InteropServices.ComVisible(true)]
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo GetField(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type GetInterface(String name, bool ignoreCase) { throw new NotSupportedException(); }
public override Type[] GetInterfaces() { throw new NotSupportedException(); }
public override EventInfo GetEvent(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents() { throw new NotSupportedException(); }
protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type GetNestedType(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(); }
[System.Runtime.InteropServices.ComVisible(true)]
public override InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override TypeAttributes GetAttributeFlagsImpl() { return TypeAttributes.Public; }
protected override bool IsArrayImpl() { return false; }
protected override bool IsByRefImpl() { return false; }
protected override bool IsPointerImpl() { return false; }
protected override bool IsPrimitiveImpl() { return false; }
protected override bool IsCOMObjectImpl() { return false; }
public override Type GetElementType() { throw new NotSupportedException(); }
protected override bool HasElementTypeImpl() { return false; }
public override Type UnderlyingSystemType { get { return this; } }
public override Type[] GetGenericArguments() { throw new InvalidOperationException(); }
public override bool IsGenericTypeDefinition { get { return false; } }
public override bool IsGenericType { get { return false; } }
public override bool IsGenericParameter { get { return true; } }
public override bool IsConstructedGenericType { get { return false; } }
public override int GenericParameterPosition { get { return m_type.GenericParameterPosition; } }
public override bool ContainsGenericParameters { get { return m_type.ContainsGenericParameters; } }
public override GenericParameterAttributes GenericParameterAttributes { get { return m_type.GenericParameterAttributes; } }
public override MethodBase DeclaringMethod { get { return m_type.DeclaringMethod; } }
public override Type GetGenericTypeDefinition() { throw new InvalidOperationException(); }
public override Type MakeGenericType(params Type[] typeArguments) { throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericTypeDefinition")); }
protected override bool IsValueTypeImpl() { return false; }
public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); }
[System.Runtime.InteropServices.ComVisible(true)]
[Pure]
public override bool IsSubclassOf(Type c) { throw new NotSupportedException(); }
#endregion
#region ICustomAttributeProvider Implementation
public override Object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(); }
public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(); }
#endregion
#region Public Members
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
m_type.SetGenParamCustomAttribute(con, binaryAttribute);
}
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
m_type.SetGenParamCustomAttribute(customBuilder);
}
public void SetBaseTypeConstraint(Type baseTypeConstraint)
{
m_type.CheckContext(baseTypeConstraint);
m_type.SetParent(baseTypeConstraint);
}
[System.Runtime.InteropServices.ComVisible(true)]
public void SetInterfaceConstraints(params Type[] interfaceConstraints)
{
m_type.CheckContext(interfaceConstraints);
m_type.SetInterfaces(interfaceConstraints);
}
public void SetGenericParameterAttributes(GenericParameterAttributes genericParameterAttributes)
{
m_type.SetGenParamAttributes(genericParameterAttributes);
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedParameter.Global
// ReSharper disable UnusedAutoPropertyAccessor.Local
// ReSharper disable UnusedAutoPropertyAccessor.Global
#pragma warning disable 618
namespace Apache.Ignite.Core.Tests
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Events;
using Apache.Ignite.Core.Resource;
using Apache.Ignite.Core.Tests.Compute;
using NUnit.Framework;
using ImplCompute = Core.Impl.Compute.Compute;
/// <summary>
/// <see cref="IEvents"/> tests.
/// </summary>
public class EventsTest
{
/** */
public const string CacheName = "eventsTest";
/** */
private IIgnite _grid1;
/** */
private IIgnite _grid2;
/** */
private IIgnite _grid3;
/** */
private IIgnite[] _grids;
/// <summary>
/// Executes before each test.
/// </summary>
[SetUp]
public void SetUp()
{
StartGrids();
EventsTestHelper.ListenResult = true;
}
/// <summary>
/// Executes after each test.
/// </summary>
[TearDown]
public void TearDown()
{
try
{
TestUtils.AssertHandleRegistryIsEmpty(1000, _grid1, _grid2, _grid3);
}
catch (Exception)
{
// Restart grids to cleanup
StopGrids();
throw;
}
finally
{
EventsTestHelper.AssertFailures();
if (TestContext.CurrentContext.Test.Name.StartsWith("TestEventTypes"))
StopGrids(); // clean events for other tests
}
}
/// <summary>
/// Fixture tear down.
/// </summary>
[TestFixtureTearDown]
public void FixtureTearDown()
{
StopGrids();
}
/// <summary>
/// Tests enable/disable of event types.
/// </summary>
[Test]
public void TestEnableDisable()
{
var events = _grid1.GetEvents();
Assert.AreEqual(0, events.GetEnabledEvents().Count);
Assert.IsFalse(EventType.CacheAll.Any(events.IsEnabled));
events.EnableLocal(EventType.CacheAll);
Assert.AreEqual(EventType.CacheAll, events.GetEnabledEvents());
Assert.IsTrue(EventType.CacheAll.All(events.IsEnabled));
events.EnableLocal(EventType.TaskExecutionAll);
events.DisableLocal(EventType.CacheAll);
Assert.AreEqual(EventType.TaskExecutionAll, events.GetEnabledEvents());
}
/// <summary>
/// Tests LocalListen.
/// </summary>
[Test]
public void TestLocalListen()
{
var events = _grid1.GetEvents();
var listener = EventsTestHelper.GetListener();
var eventType = EventType.TaskExecutionAll;
events.EnableLocal(eventType);
events.LocalListen(listener, eventType);
CheckSend(3); // 3 events per task * 3 grids
// Check unsubscription for specific event
events.StopLocalListen(listener, EventType.TaskReduced);
CheckSend(2);
// Unsubscribe from all events
events.StopLocalListen(listener, Enumerable.Empty<int>());
CheckNoEvent();
// Check unsubscription by filter
events.LocalListen(listener, EventType.TaskReduced);
CheckSend();
EventsTestHelper.ListenResult = false;
CheckSend(); // one last event will be received for each listener
CheckNoEvent();
}
/// <summary>
/// Tests LocalListen.
/// </summary>
[Test]
[Ignore("IGNITE-879")]
public void TestLocalListenRepeatedSubscription()
{
var events = _grid1.GetEvents();
var listener = EventsTestHelper.GetListener();
var eventType = EventType.TaskExecutionAll;
events.EnableLocal(eventType);
events.LocalListen(listener, eventType);
CheckSend(3); // 3 events per task * 3 grids
events.LocalListen(listener, eventType);
events.LocalListen(listener, eventType);
CheckSend(9);
events.StopLocalListen(listener, eventType);
CheckSend(6);
events.StopLocalListen(listener, eventType);
CheckSend(3);
events.StopLocalListen(listener, eventType);
CheckNoEvent();
}
/// <summary>
/// Tests all available event types/classes.
/// </summary>
[Test, TestCaseSource("TestCases")]
public void TestEventTypes(EventTestCase testCase)
{
var events = _grid1.GetEvents();
events.EnableLocal(testCase.EventType);
var listener = EventsTestHelper.GetListener();
events.LocalListen(listener, testCase.EventType);
EventsTestHelper.ClearReceived(testCase.EventCount);
testCase.GenerateEvent(_grid1);
EventsTestHelper.VerifyReceive(testCase.EventCount, testCase.EventObjectType, testCase.EventType);
if (testCase.VerifyEvents != null)
testCase.VerifyEvents(EventsTestHelper.ReceivedEvents.Reverse(), _grid1);
// Check stop
events.StopLocalListen(listener);
EventsTestHelper.ClearReceived(0);
testCase.GenerateEvent(_grid1);
Thread.Sleep(EventsTestHelper.Timeout);
}
/// <summary>
/// Test cases for TestEventTypes: type id + type + event generator.
/// </summary>
public IEnumerable<EventTestCase> TestCases
{
get
{
yield return new EventTestCase
{
EventType = EventType.CacheAll,
EventObjectType = typeof (CacheEvent),
GenerateEvent = g => g.GetCache<int, int>(CacheName).Put(TestUtils.GetPrimaryKey(g, CacheName), 1),
VerifyEvents = (e, g) => VerifyCacheEvents(e, g),
EventCount = 3
};
yield return new EventTestCase
{
EventType = EventType.TaskExecutionAll,
EventObjectType = typeof (TaskEvent),
GenerateEvent = g => GenerateTaskEvent(g),
VerifyEvents = (e, g) => VerifyTaskEvents(e),
EventCount = 3
};
yield return new EventTestCase
{
EventType = EventType.JobExecutionAll,
EventObjectType = typeof (JobEvent),
GenerateEvent = g => GenerateTaskEvent(g),
EventCount = 7
};
yield return new EventTestCase
{
EventType = new[] {EventType.CacheQueryExecuted},
EventObjectType = typeof (CacheQueryExecutedEvent),
GenerateEvent = g => GenerateCacheQueryEvent(g),
EventCount = 1
};
yield return new EventTestCase
{
EventType = new[] { EventType.CacheQueryObjectRead },
EventObjectType = typeof (CacheQueryReadEvent),
GenerateEvent = g => GenerateCacheQueryEvent(g),
EventCount = 1
};
}
}
/// <summary>
/// Tests the LocalQuery.
/// </summary>
[Test]
public void TestLocalQuery()
{
var events = _grid1.GetEvents();
var eventType = EventType.TaskExecutionAll;
events.EnableLocal(eventType);
var oldEvents = events.LocalQuery();
GenerateTaskEvent();
// "Except" works because of overridden equality
var qryResult = events.LocalQuery(eventType).Except(oldEvents).ToList();
Assert.AreEqual(3, qryResult.Count);
}
/// <summary>
/// Tests the record local.
/// </summary>
[Test]
public void TestRecordLocal()
{
Assert.Throws<NotSupportedException>(() => _grid1.GetEvents().RecordLocal(new MyEvent()));
}
/// <summary>
/// Tests the WaitForLocal.
/// </summary>
[Test]
public void TestWaitForLocal()
{
var events = _grid1.GetEvents();
var timeout = TimeSpan.FromSeconds(3);
var eventType = EventType.TaskExecutionAll;
events.EnableLocal(eventType);
var taskFuncs = GetWaitTasks(events).Select(
func => (Func<IEventFilter<IEvent>, int[], Task<IEvent>>) (
(filter, types) =>
{
var task = func(filter, types);
Thread.Sleep(100); // allow task to start and begin waiting for events
GenerateTaskEvent();
return task;
})).ToArray();
for (int i = 0; i < taskFuncs.Length; i++)
{
var getWaitTask = taskFuncs[i];
// No params
var waitTask = getWaitTask(null, new int[0]);
waitTask.Wait(timeout);
// Event types
waitTask = getWaitTask(null, new[] {EventType.TaskReduced});
Assert.IsTrue(waitTask.Wait(timeout));
Assert.IsInstanceOf(typeof(TaskEvent), waitTask.Result);
Assert.AreEqual(EventType.TaskReduced, waitTask.Result.Type);
if (i > 3)
{
// Filter
waitTask = getWaitTask(new LocalEventFilter<IEvent>(e => e.Type == EventType.TaskReduced), new int[0]);
Assert.IsTrue(waitTask.Wait(timeout));
Assert.IsInstanceOf(typeof(TaskEvent), waitTask.Result);
Assert.AreEqual(EventType.TaskReduced, waitTask.Result.Type);
// Filter & types
waitTask = getWaitTask(new LocalEventFilter<IEvent>(e => e.Type == EventType.TaskReduced),
new[] {EventType.TaskReduced});
Assert.IsTrue(waitTask.Wait(timeout));
Assert.IsInstanceOf(typeof(TaskEvent), waitTask.Result);
Assert.AreEqual(EventType.TaskReduced, waitTask.Result.Type);
}
}
}
/// <summary>
/// Gets the wait tasks for different overloads of WaitForLocal.
/// </summary>
private static IEnumerable<Func<IEventFilter<IEvent>, int[], Task<IEvent>>> GetWaitTasks(IEvents events)
{
yield return (filter, types) => TaskRunner.Run(() => events.WaitForLocal(types));
yield return (filter, types) => TaskRunner.Run(() => events.WaitForLocal(types.ToList()));
yield return (filter, types) => events.WaitForLocalAsync(types);
yield return (filter, types) => events.WaitForLocalAsync(types.ToList());
yield return (filter, types) => TaskRunner.Run(() => events.WaitForLocal(filter, types));
yield return (filter, types) => TaskRunner.Run(() => events.WaitForLocal(filter, types.ToList()));
yield return (filter, types) => events.WaitForLocalAsync(filter, types);
yield return (filter, types) => events.WaitForLocalAsync(filter, types.ToList());
}
/// <summary>
/// Tests the wait for local overloads.
/// </summary>
[Test]
public void TestWaitForLocalOverloads()
{
}
/*
/// <summary>
/// Tests RemoteListen.
/// </summary>
[Test]
public void TestRemoteListen(
[Values(true, false)] bool async,
[Values(true, false)] bool binarizable,
[Values(true, false)] bool autoUnsubscribe)
{
foreach (var g in _grids)
{
g.GetEvents().EnableLocal(EventType.JobExecutionAll);
g.GetEvents().EnableLocal(EventType.TaskExecutionAll);
}
var events = _grid1.GetEvents();
var expectedType = EventType.JobStarted;
var remoteFilter = binary
? (IEventFilter<IEvent>) new RemoteEventBinarizableFilter(expectedType)
: new RemoteEventFilter(expectedType);
var localListener = EventsTestHelper.GetListener();
if (async)
events = events.WithAsync();
var listenId = events.RemoteListen(localListener: localListener, remoteFilter: remoteFilter,
autoUnsubscribe: autoUnsubscribe);
if (async)
listenId = events.GetFuture<Guid>().Get();
Assert.IsNotNull(listenId);
CheckSend(3, typeof(JobEvent), expectedType);
_grid3.GetEvents().DisableLocal(EventType.JobExecutionAll);
CheckSend(2, typeof(JobEvent), expectedType);
events.StopRemoteListen(listenId.Value);
if (async)
events.GetFuture().Get();
CheckNoEvent();
// Check unsubscription with listener
events.RemoteListen(localListener: localListener, remoteFilter: remoteFilter,
autoUnsubscribe: autoUnsubscribe);
if (async)
events.GetFuture<Guid>().Get();
CheckSend(2, typeof(JobEvent), expectedType);
EventsTestHelper.ListenResult = false;
CheckSend(1, typeof(JobEvent), expectedType); // one last event
CheckNoEvent();
}*/
/// <summary>
/// Tests RemoteQuery.
/// </summary>
[Test]
public void TestRemoteQuery([Values(true, false)] bool async)
{
foreach (var g in _grids)
g.GetEvents().EnableLocal(EventType.JobExecutionAll);
var events = _grid1.GetEvents();
var eventFilter = new RemoteEventFilter(EventType.JobStarted);
var oldEvents = events.RemoteQuery(eventFilter);
GenerateTaskEvent();
var remoteQuery = !async
? events.RemoteQuery(eventFilter, EventsTestHelper.Timeout, EventType.JobExecutionAll)
: events.RemoteQueryAsync(eventFilter, EventsTestHelper.Timeout, EventType.JobExecutionAll).Result;
var qryResult = remoteQuery.Except(oldEvents).Cast<JobEvent>().ToList();
Assert.AreEqual(_grids.Length - 1, qryResult.Count);
Assert.IsTrue(qryResult.All(x => x.Type == EventType.JobStarted));
}
/// <summary>
/// Tests serialization.
/// </summary>
[Test]
public void TestSerialization()
{
var grid = (Ignite) _grid1;
var comp = (ImplCompute) grid.GetCluster().ForLocal().GetCompute();
var locNode = grid.GetCluster().GetLocalNode();
var expectedGuid = Guid.Parse("00000000-0000-0001-0000-000000000002");
var expectedGridGuid = new IgniteGuid(expectedGuid, 3);
using (var inStream = IgniteManager.Memory.Allocate().GetStream())
{
var result = comp.ExecuteJavaTask<bool>("org.apache.ignite.platform.PlatformEventsWriteEventTask",
inStream.MemoryPointer);
Assert.IsTrue(result);
inStream.SynchronizeInput();
var reader = grid.Marshaller.StartUnmarshal(inStream);
var cacheEvent = EventReader.Read<CacheEvent>(reader);
CheckEventBase(cacheEvent);
Assert.AreEqual("cacheName", cacheEvent.CacheName);
Assert.AreEqual(locNode, cacheEvent.EventNode);
Assert.AreEqual(1, cacheEvent.Partition);
Assert.AreEqual(true, cacheEvent.IsNear);
Assert.AreEqual(2, cacheEvent.Key);
Assert.AreEqual(expectedGridGuid, cacheEvent.Xid);
Assert.AreEqual(4, cacheEvent.NewValue);
Assert.AreEqual(true, cacheEvent.HasNewValue);
Assert.AreEqual(5, cacheEvent.OldValue);
Assert.AreEqual(true, cacheEvent.HasOldValue);
Assert.AreEqual(expectedGuid, cacheEvent.SubjectId);
Assert.AreEqual("cloClsName", cacheEvent.ClosureClassName);
Assert.AreEqual("taskName", cacheEvent.TaskName);
Assert.IsTrue(cacheEvent.ToShortString().StartsWith("NODE_FAILED: IsNear="));
var qryExecEvent = EventReader.Read<CacheQueryExecutedEvent>(reader);
CheckEventBase(qryExecEvent);
Assert.AreEqual("qryType", qryExecEvent.QueryType);
Assert.AreEqual("cacheName", qryExecEvent.CacheName);
Assert.AreEqual("clsName", qryExecEvent.ClassName);
Assert.AreEqual("clause", qryExecEvent.Clause);
Assert.AreEqual(expectedGuid, qryExecEvent.SubjectId);
Assert.AreEqual("taskName", qryExecEvent.TaskName);
Assert.AreEqual(
"NODE_FAILED: QueryType=qryType, CacheName=cacheName, ClassName=clsName, Clause=clause, " +
"SubjectId=00000000-0000-0001-0000-000000000002, TaskName=taskName", qryExecEvent.ToShortString());
var qryReadEvent = EventReader.Read<CacheQueryReadEvent>(reader);
CheckEventBase(qryReadEvent);
Assert.AreEqual("qryType", qryReadEvent.QueryType);
Assert.AreEqual("cacheName", qryReadEvent.CacheName);
Assert.AreEqual("clsName", qryReadEvent.ClassName);
Assert.AreEqual("clause", qryReadEvent.Clause);
Assert.AreEqual(expectedGuid, qryReadEvent.SubjectId);
Assert.AreEqual("taskName", qryReadEvent.TaskName);
Assert.AreEqual(1, qryReadEvent.Key);
Assert.AreEqual(2, qryReadEvent.Value);
Assert.AreEqual(3, qryReadEvent.OldValue);
Assert.AreEqual(4, qryReadEvent.Row);
Assert.AreEqual(
"NODE_FAILED: QueryType=qryType, CacheName=cacheName, ClassName=clsName, Clause=clause, " +
"SubjectId=00000000-0000-0001-0000-000000000002, TaskName=taskName, Key=1, Value=2, " +
"OldValue=3, Row=4", qryReadEvent.ToShortString());
var cacheRebalancingEvent = EventReader.Read<CacheRebalancingEvent>(reader);
CheckEventBase(cacheRebalancingEvent);
Assert.AreEqual("cacheName", cacheRebalancingEvent.CacheName);
Assert.AreEqual(1, cacheRebalancingEvent.Partition);
Assert.AreEqual(locNode, cacheRebalancingEvent.DiscoveryNode);
Assert.AreEqual(2, cacheRebalancingEvent.DiscoveryEventType);
Assert.AreEqual(3, cacheRebalancingEvent.DiscoveryTimestamp);
Assert.IsTrue(cacheRebalancingEvent.ToShortString().StartsWith(
"NODE_FAILED: CacheName=cacheName, Partition=1, DiscoveryNode=GridNode"));
var checkpointEvent = EventReader.Read<CheckpointEvent>(reader);
CheckEventBase(checkpointEvent);
Assert.AreEqual("cpKey", checkpointEvent.Key);
Assert.AreEqual("NODE_FAILED: Key=cpKey", checkpointEvent.ToShortString());
var discoEvent = EventReader.Read<DiscoveryEvent>(reader);
CheckEventBase(discoEvent);
Assert.AreEqual(grid.TopologyVersion, discoEvent.TopologyVersion);
Assert.AreEqual(grid.GetNodes(), discoEvent.TopologyNodes);
Assert.IsTrue(discoEvent.ToShortString().StartsWith("NODE_FAILED: EventNode=GridNode"));
var jobEvent = EventReader.Read<JobEvent>(reader);
CheckEventBase(jobEvent);
Assert.AreEqual(expectedGridGuid, jobEvent.JobId);
Assert.AreEqual("taskClsName", jobEvent.TaskClassName);
Assert.AreEqual("taskName", jobEvent.TaskName);
Assert.AreEqual(locNode, jobEvent.TaskNode);
Assert.AreEqual(expectedGridGuid, jobEvent.TaskSessionId);
Assert.AreEqual(expectedGuid, jobEvent.TaskSubjectId);
Assert.IsTrue(jobEvent.ToShortString().StartsWith("NODE_FAILED: TaskName=taskName"));
var taskEvent = EventReader.Read<TaskEvent>(reader);
CheckEventBase(taskEvent);
Assert.AreEqual(true,taskEvent.Internal);
Assert.AreEqual(expectedGuid, taskEvent.SubjectId);
Assert.AreEqual("taskClsName", taskEvent.TaskClassName);
Assert.AreEqual("taskName", taskEvent.TaskName);
Assert.AreEqual(expectedGridGuid, taskEvent.TaskSessionId);
Assert.IsTrue(taskEvent.ToShortString().StartsWith("NODE_FAILED: TaskName=taskName"));
}
}
/// <summary>
/// Tests the event store configuration.
/// </summary>
[Test]
public void TestConfiguration()
{
var cfg = _grid1.GetConfiguration().EventStorageSpi as MemoryEventStorageSpi;
Assert.IsNotNull(cfg);
Assert.AreEqual(MemoryEventStorageSpi.DefaultExpirationTimeout, cfg.ExpirationTimeout);
Assert.AreEqual(MemoryEventStorageSpi.DefaultMaxEventCount, cfg.MaxEventCount);
// Test user-defined event storage.
var igniteCfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
IgniteInstanceName = "grid4",
EventStorageSpi = new MyEventStorage()
};
var ex = Assert.Throws<IgniteException>(() => Ignition.Start(igniteCfg));
Assert.AreEqual("Unsupported IgniteConfiguration.EventStorageSpi: " +
"'Apache.Ignite.Core.Tests.MyEventStorage'. Supported implementations: " +
"'Apache.Ignite.Core.Events.NoopEventStorageSpi', " +
"'Apache.Ignite.Core.Events.MemoryEventStorageSpi'.", ex.Message);
}
/// <summary>
/// Checks base event fields serialization.
/// </summary>
/// <param name="evt">The evt.</param>
private void CheckEventBase(IEvent evt)
{
var locNode = _grid1.GetCluster().GetLocalNode();
Assert.AreEqual(locNode, evt.Node);
Assert.AreEqual("msg", evt.Message);
Assert.AreEqual(EventType.NodeFailed, evt.Type);
Assert.IsNotNullOrEmpty(evt.Name);
Assert.AreNotEqual(Guid.Empty, evt.Id.GlobalId);
Assert.IsTrue(Math.Abs((evt.Timestamp - DateTime.UtcNow).TotalSeconds) < 20,
"Invalid event timestamp: '{0}', current time: '{1}'", evt.Timestamp, DateTime.Now);
Assert.Greater(evt.LocalOrder, 0);
Assert.IsTrue(evt.ToString().Contains("[Name=NODE_FAILED"));
Assert.IsTrue(evt.ToShortString().StartsWith("NODE_FAILED"));
}
/// <summary>
/// Sends events in various ways and verifies correct receive.
/// </summary>
/// <param name="repeat">Expected event count multiplier.</param>
/// <param name="eventObjectType">Expected event object type.</param>
/// <param name="eventType">Type of the event.</param>
private void CheckSend(int repeat = 1, Type eventObjectType = null, params int[] eventType)
{
EventsTestHelper.ClearReceived(repeat);
GenerateTaskEvent();
EventsTestHelper.VerifyReceive(repeat, eventObjectType ?? typeof (TaskEvent),
eventType.Any() ? eventType : EventType.TaskExecutionAll);
}
/// <summary>
/// Checks that no event has arrived.
/// </summary>
private void CheckNoEvent()
{
// this will result in an exception in case of a event
EventsTestHelper.ClearReceived(0);
GenerateTaskEvent();
Thread.Sleep(EventsTestHelper.Timeout);
EventsTestHelper.AssertFailures();
}
/// <summary>
/// Gets the Ignite configuration.
/// </summary>
private static IgniteConfiguration GetConfiguration(string name, bool client = false)
{
return new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
IgniteInstanceName = name,
EventStorageSpi = new MemoryEventStorageSpi(),
CacheConfiguration = new [] {new CacheConfiguration(CacheName) },
ClientMode = client
};
}
/// <summary>
/// Generates the task event.
/// </summary>
private void GenerateTaskEvent(IIgnite grid = null)
{
(grid ?? _grid1).GetCompute().Broadcast(new ComputeAction());
}
/// <summary>
/// Verifies the task events.
/// </summary>
private static void VerifyTaskEvents(IEnumerable<IEvent> events)
{
var e = events.Cast<TaskEvent>().ToArray();
// started, reduced, finished
Assert.AreEqual(
new[] {EventType.TaskStarted, EventType.TaskReduced, EventType.TaskFinished},
e.Select(x => x.Type).ToArray());
}
/// <summary>
/// Generates the cache query event.
/// </summary>
private static void GenerateCacheQueryEvent(IIgnite g)
{
var cache = g.GetCache<int, int>(CacheName);
cache.Clear();
cache.Put(TestUtils.GetPrimaryKey(g, CacheName), 1);
cache.Query(new ScanQuery<int, int>()).GetAll();
}
/// <summary>
/// Verifies the cache events.
/// </summary>
private static void VerifyCacheEvents(IEnumerable<IEvent> events, IIgnite grid)
{
var e = events.Cast<CacheEvent>().ToArray();
foreach (var cacheEvent in e)
{
Assert.AreEqual(CacheName, cacheEvent.CacheName);
Assert.AreEqual(null, cacheEvent.ClosureClassName);
Assert.AreEqual(null, cacheEvent.TaskName);
Assert.AreEqual(grid.GetCluster().GetLocalNode(), cacheEvent.EventNode);
Assert.AreEqual(grid.GetCluster().GetLocalNode(), cacheEvent.Node);
Assert.AreEqual(false, cacheEvent.HasOldValue);
Assert.AreEqual(null, cacheEvent.OldValue);
if (cacheEvent.Type == EventType.CacheObjectPut)
{
Assert.AreEqual(true, cacheEvent.HasNewValue);
Assert.AreEqual(1, cacheEvent.NewValue);
}
else if (cacheEvent.Type == EventType.CacheEntryCreated)
{
Assert.AreEqual(false, cacheEvent.HasNewValue);
Assert.AreEqual(null, cacheEvent.NewValue);
}
else if (cacheEvent.Type == EventType.CacheEntryDestroyed)
{
Assert.IsFalse(cacheEvent.HasNewValue);
Assert.IsFalse(cacheEvent.HasOldValue);
}
else
{
Assert.Fail("Unexpected event type");
}
}
}
/// <summary>
/// Starts the grids.
/// </summary>
private void StartGrids()
{
if (_grid1 != null)
return;
_grid1 = Ignition.Start(GetConfiguration("grid1"));
_grid2 = Ignition.Start(GetConfiguration("grid2"));
_grid3 = Ignition.Start(GetConfiguration("grid3", true));
_grids = new[] {_grid1, _grid2, _grid3};
}
/// <summary>
/// Stops the grids.
/// </summary>
private void StopGrids()
{
_grid1 = _grid2 = _grid3 = null;
_grids = null;
Ignition.StopAll(true);
}
}
/// <summary>
/// Event test helper class.
/// </summary>
[Serializable]
public static class EventsTestHelper
{
/** */
public static readonly ConcurrentStack<IEvent> ReceivedEvents = new ConcurrentStack<IEvent>();
/** */
public static readonly ConcurrentStack<string> Failures = new ConcurrentStack<string>();
/** */
public static readonly CountdownEvent ReceivedEvent = new CountdownEvent(0);
/** */
public static readonly ConcurrentStack<Guid?> LastNodeIds = new ConcurrentStack<Guid?>();
/** */
public static volatile bool ListenResult = true;
/** */
public static readonly TimeSpan Timeout = TimeSpan.FromMilliseconds(800);
/// <summary>
/// Clears received event information.
/// </summary>
/// <param name="expectedCount">The expected count of events to be received.</param>
public static void ClearReceived(int expectedCount)
{
ReceivedEvents.Clear();
ReceivedEvent.Reset(expectedCount);
LastNodeIds.Clear();
}
/// <summary>
/// Verifies received events against events events.
/// </summary>
public static void VerifyReceive(int count, Type eventObjectType, ICollection<int> eventTypes)
{
// check if expected event count has been received; Wait returns false if there were none.
Assert.IsTrue(ReceivedEvent.Wait(Timeout),
"Failed to receive expected number of events. Remaining count: " + ReceivedEvent.CurrentCount);
Assert.AreEqual(count, ReceivedEvents.Count);
Assert.IsTrue(ReceivedEvents.All(x => x.GetType() == eventObjectType));
Assert.IsTrue(ReceivedEvents.All(x => eventTypes.Contains(x.Type)));
AssertFailures();
}
/// <summary>
/// Gets the event listener.
/// </summary>
/// <returns>New instance of event listener.</returns>
public static IEventListener<IEvent> GetListener()
{
return new LocalEventFilter<IEvent>(Listen);
}
/// <summary>
/// Combines accumulated failures and throws an assertion, if there are any.
/// Clears accumulated failures.
/// </summary>
public static void AssertFailures()
{
try
{
if (Failures.Any())
Assert.Fail(Failures.Reverse().Aggregate((x, y) => string.Format("{0}\n{1}", x, y)));
}
finally
{
Failures.Clear();
}
}
/// <summary>
/// Listen method.
/// </summary>
/// <param name="evt">Event.</param>
private static bool Listen(IEvent evt)
{
try
{
LastNodeIds.Push(evt.Node.Id);
ReceivedEvents.Push(evt);
ReceivedEvent.Signal();
return ListenResult;
}
catch (Exception ex)
{
// When executed on remote nodes, these exceptions will not go to sender,
// so we have to accumulate them.
Failures.Push(string.Format("Exception in Listen (msg: {0}, id: {1}): {2}", evt, evt.Node.Id, ex));
throw;
}
}
}
/// <summary>
/// Test event filter.
/// </summary>
[Serializable]
public class LocalEventFilter<T> : IEventFilter<T>, IEventListener<T> where T : IEvent
{
/** */
private readonly Func<T, bool> _invoke;
/// <summary>
/// Initializes a new instance of the <see cref="RemoteListenEventFilter"/> class.
/// </summary>
/// <param name="invoke">The invoke delegate.</param>
public LocalEventFilter(Func<T, bool> invoke)
{
_invoke = invoke;
}
/** <inheritdoc /> */
bool IEventFilter<T>.Invoke(T evt)
{
return _invoke(evt);
}
/** <inheritdoc /> */
bool IEventListener<T>.Invoke(T evt)
{
return _invoke(evt);
}
/** <inheritdoc /> */
// ReSharper disable once UnusedMember.Global
public bool Invoke(T evt)
{
throw new Exception("Invalid method");
}
}
/// <summary>
/// Remote event filter.
/// </summary>
[Serializable]
public class RemoteEventFilter : IEventFilter<IEvent>
{
/** */
private readonly int _type;
/** */
[InstanceResource]
public IIgnite Ignite { get; set; }
public RemoteEventFilter(int type)
{
_type = type;
}
/** <inheritdoc /> */
public bool Invoke(IEvent evt)
{
Assert.IsNotNull(Ignite);
return evt.Type == _type;
}
}
/// <summary>
/// Event test case.
/// </summary>
public class EventTestCase
{
/// <summary>
/// Gets or sets the type of the event.
/// </summary>
public ICollection<int> EventType { get; set; }
/// <summary>
/// Gets or sets the type of the event object.
/// </summary>
public Type EventObjectType { get; set; }
/// <summary>
/// Gets or sets the generate event action.
/// </summary>
public Action<IIgnite> GenerateEvent { get; set; }
/// <summary>
/// Gets or sets the verify events action.
/// </summary>
public Action<IEnumerable<IEvent>, IIgnite> VerifyEvents { get; set; }
/// <summary>
/// Gets or sets the event count.
/// </summary>
public int EventCount { get; set; }
/** <inheritdoc /> */
public override string ToString()
{
return EventObjectType.ToString();
}
}
/// <summary>
/// Custom event.
/// </summary>
public class MyEvent : IEvent
{
/** <inheritdoc /> */
public IgniteGuid Id
{
get { throw new NotImplementedException(); }
}
/** <inheritdoc /> */
public long LocalOrder
{
get { throw new NotImplementedException(); }
}
/** <inheritdoc /> */
public IClusterNode Node
{
get { throw new NotImplementedException(); }
}
/** <inheritdoc /> */
public string Message
{
get { throw new NotImplementedException(); }
}
/** <inheritdoc /> */
public int Type
{
get { throw new NotImplementedException(); }
}
/** <inheritdoc /> */
public string Name
{
get { throw new NotImplementedException(); }
}
/** <inheritdoc /> */
public DateTime Timestamp
{
get { throw new NotImplementedException(); }
}
/** <inheritdoc /> */
public string ToShortString()
{
throw new NotImplementedException();
}
}
public class MyEventStorage : IEventStorageSpi
{
// No-op.
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Diagnostics
{
using System.Text;
using System.Threading;
using System;
////using System.Security;
////using System.Security.Permissions;
////using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
////using System.Globalization;
////using System.Runtime.Serialization;
////using System.Runtime.Versioning;
// READ ME:
// Modifying the order or fields of this object may require other changes
// to the unmanaged definition of the StackFrameHelper class, in
// VM\DebugDebugger.h. The binder will catch some of these layout problems.
[Serializable]
internal class StackFrameHelper
{
[NonSerialized]
private Thread targetThread;
private int[] rgiOffset;
private int[] rgiILOffset;
// this field is here only for backwards compatibility of serialization format
//////private MethodBase[] rgMethodBase;
////
////#pragma warning disable 414 // Field is not used from managed.
//// // dynamicMethods is an array of System.Resolver objects, used to keep
//// // DynamicMethodDescs alive for the lifetime of StackFrameHelper.
//// private Object dynamicMethods;
////#pragma warning restore 414
////
//// [NonSerialized]
private RuntimeMethodHandle[] rgMethodHandle;
private String[] rgFilename;
private int[] rgiLineNumber;
private int[] rgiColumnNumber;
private int iFrameCount;
private bool fNeedFileInfo;
public StackFrameHelper( bool fNeedFileLineColInfo, Thread target )
{
targetThread = target;
//////rgMethodBase = null;
rgMethodHandle = null;
rgiOffset = null;
rgiILOffset = null;
rgFilename = null;
rgiLineNumber = null;
rgiColumnNumber = null;
//////dynamicMethods = null;
// 0 means capture all frames. For StackTraces from an Exception, the EE always
// captures all frames. For other uses of StackTraces, we can abort stack walking after
// some limit if we want to by setting this to a non-zero value. In Whidbey this was
// hard-coded to 512, but some customers complained. There shouldn't be any need to limit
// this as memory/CPU is no longer allocated up front. If there is some reason to provide a
// limit in the future, then we should expose it in the managed API so applications can
// override it.
iFrameCount = 0;
fNeedFileInfo = fNeedFileLineColInfo;
}
public virtual MethodBase GetMethodBase( int i )
{
// There may be a better way to do this.
// we got RuntimeMethodHandles here and we need to go to MethodBase
// but we don't know whether the reflection info has been initialized
// or not. So we call GetMethods and GetConstructors on the type
// and then we fetch the proper MethodBase!!
RuntimeMethodHandle mh = rgMethodHandle[i];
if(mh.IsNullHandle( ))
return null;
//////mh = mh.GetTypicalMethodDefinition( );
//////return RuntimeType.GetMethodBase( mh );
return null; ;
}
public virtual int GetOffset( int i ) { return rgiOffset[ i ]; }
public virtual int GetILOffset( int i ) { return rgiILOffset[ i ]; }
public virtual String GetFilename( int i ) { return rgFilename[ i ]; }
public virtual int GetLineNumber( int i ) { return rgiLineNumber[ i ]; }
public virtual int GetColumnNumber( int i ) { return rgiColumnNumber[ i ]; }
public virtual int GetNumberOfFrames( ) { return iFrameCount; }
public virtual void SetNumberOfFrames( int i ) { iFrameCount = i; }
//// //
//// // serialization implementation
//// //
//// [OnSerializing]
//// void OnSerializing( StreamingContext context )
//// {
//// // this is called in the process of serializing this object.
//// // For compatibility with Everett we need to assign the rgMethodBase field as that is the field
//// // that will be serialized
//// rgMethodBase = (rgMethodHandle == null) ? null : new MethodBase[rgMethodHandle.Length];
//// if(rgMethodHandle != null)
//// {
//// for(int i = 0; i < rgMethodHandle.Length; i++)
//// {
//// if(!rgMethodHandle[i].IsNullHandle())
//// rgMethodBase[i] = RuntimeType.GetMethodBase( rgMethodHandle[i] );
//// }
//// }
//// }
////
//// [OnSerialized]
//// void OnSerialized( StreamingContext context )
//// {
//// // after we are done serializing null the rgMethodBase field
//// rgMethodBase = null;
//// }
////
//// [OnDeserialized]
//// void OnDeserialized( StreamingContext context )
//// {
//// // after we are done deserializing we need to transform the rgMethodBase in rgMethodHandle
//// rgMethodHandle = (rgMethodBase == null) ? null : new RuntimeMethodHandle[rgMethodBase.Length];
//// if(rgMethodBase != null)
//// {
//// for(int i = 0; i < rgMethodBase.Length; i++)
//// {
//// if(rgMethodBase[i] != null)
//// rgMethodHandle[i] = rgMethodBase[i].MethodHandle;
//// }
//// }
//// rgMethodBase = null;
//// }
}
// Class which represents a description of a stack trace
// There is no good reason for the methods of this class to be virtual.
// In order to ensure trusted code can trust the data it gets from a
// StackTrace, we use an InheritanceDemand to prevent partially-trusted
// subclasses.
////[SecurityPermission( SecurityAction.InheritanceDemand, UnmanagedCode = true )]
[Serializable]
public class StackTrace
{
public const int METHODS_TO_SKIP = 0;
private StackFrame[] frames;
private int m_iNumOfFrames;
private int m_iMethodsToSkip;
// Constructs a stack trace from the current location.
public StackTrace( )
{
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace( METHODS_TO_SKIP, false, null, null );
}
// Constructs a stack trace from the current location.
//
public StackTrace( bool fNeedFileInfo )
{
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace( METHODS_TO_SKIP, fNeedFileInfo, null, null );
}
// Constructs a stack trace from the current location, in a caller's
// frame
//
public StackTrace( int skipFrames )
{
if(skipFrames < 0)
{
throw new ArgumentOutOfRangeException( "skipFrames", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) );
}
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace( skipFrames + METHODS_TO_SKIP, false, null, null );
}
// Constructs a stack trace from the current location, in a caller's
// frame
//
public StackTrace( int skipFrames, bool fNeedFileInfo )
{
if(skipFrames < 0)
{
throw new ArgumentOutOfRangeException( "skipFrames", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) );
}
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace( skipFrames + METHODS_TO_SKIP, fNeedFileInfo, null, null );
}
// Constructs a stack trace from the current location.
public StackTrace( Exception e )
{
if(e == null)
{
throw new ArgumentNullException( "e" );
}
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace( METHODS_TO_SKIP, false, null, e );
}
// Constructs a stack trace from the current location.
//
public StackTrace( Exception e, bool fNeedFileInfo )
{
if(e == null)
{
throw new ArgumentNullException( "e" );
}
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace( METHODS_TO_SKIP, fNeedFileInfo, null, e );
}
// Constructs a stack trace from the current location, in a caller's
// frame
//
public StackTrace( Exception e, int skipFrames )
{
if(e == null)
{
throw new ArgumentNullException( "e" );
}
if(skipFrames < 0)
{
throw new ArgumentOutOfRangeException( "skipFrames", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) );
}
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace( skipFrames + METHODS_TO_SKIP, false, null, e );
}
// Constructs a stack trace from the current location, in a caller's
// frame
//
public StackTrace( Exception e, int skipFrames, bool fNeedFileInfo )
{
if(e == null)
{
throw new ArgumentNullException( "e" );
}
if(skipFrames < 0)
{
throw new ArgumentOutOfRangeException( "skipFrames", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) );
}
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace( skipFrames + METHODS_TO_SKIP, fNeedFileInfo, null, e );
}
// Constructs a "fake" stack trace, just containing a single frame.
// Does not have the overhead of a full stack trace.
//
public StackTrace( StackFrame frame )
{
frames = new StackFrame[ 1 ];
frames[ 0 ] = frame;
m_iMethodsToSkip = 0;
m_iNumOfFrames = 1;
}
// Constructs a stack trace for the given thread
//
public StackTrace( Thread targetThread, bool needFileInfo )
{
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
CaptureStackTrace( METHODS_TO_SKIP, needFileInfo, targetThread, null );
}
//////[ResourceExposure( ResourceScope.None )]
[MethodImplAttribute( MethodImplOptions.InternalCall )]
internal static extern void GetStackFramesInternal( StackFrameHelper sfh, int iSkip, Exception e );
internal static int CalculateFramesToSkip( StackFrameHelper StackF, int iNumFrames )
{
int iRetVal = 0;
String PackageName = "System.Diagnostics";
// Check if this method is part of the System.Diagnostics
// package. If so, increment counter keeping track of
// System.Diagnostics functions
for(int i = 0; i < iNumFrames; i++)
{
MethodBase mb = StackF.GetMethodBase( i );
if(mb != null)
{
Type t = mb.DeclaringType;
if(t == null)
break;
String ns = t.Namespace;
if(ns == null)
break;
if(String.Compare( ns, PackageName, StringComparison.Ordinal ) != 0)
break;
}
iRetVal++;
}
return iRetVal;
}
// Retrieves an object with stack trace information encoded.
// It leaves out the first "iSkip" lines of the stacktrace.
//
private void CaptureStackTrace( int iSkip, bool fNeedFileInfo, Thread targetThread,
Exception e )
{
m_iMethodsToSkip += iSkip;
StackFrameHelper StackF = new StackFrameHelper( fNeedFileInfo, targetThread );
GetStackFramesInternal( StackF, 0, e );
m_iNumOfFrames = StackF.GetNumberOfFrames( );
if(m_iMethodsToSkip > m_iNumOfFrames)
m_iMethodsToSkip = m_iNumOfFrames;
if(m_iNumOfFrames != 0)
{
frames = new StackFrame[ m_iNumOfFrames ];
for(int i = 0; i < m_iNumOfFrames; i++)
{
bool fDummy1 = true;
bool fDummy2 = true;
StackFrame sfTemp = new StackFrame( fDummy1, fDummy2 );
sfTemp.SetMethodBase( StackF.GetMethodBase( i ) );
sfTemp.SetOffset( StackF.GetOffset( i ) );
sfTemp.SetILOffset( StackF.GetILOffset( i ) );
if(fNeedFileInfo)
{
sfTemp.SetFileName( StackF.GetFilename( i ) );
sfTemp.SetLineNumber( StackF.GetLineNumber( i ) );
sfTemp.SetColumnNumber( StackF.GetColumnNumber( i ) );
}
frames[ i ] = sfTemp;
}
// CalculateFramesToSkip skips all frames in the System.Diagnostics namespace,
// but this is not desired if building a stack trace from an exception.
if(e == null)
m_iMethodsToSkip += CalculateFramesToSkip( StackF, m_iNumOfFrames );
m_iNumOfFrames -= m_iMethodsToSkip;
if(m_iNumOfFrames < 0)
{
m_iNumOfFrames = 0;
}
}
// In case this is the same object being re-used, set frames to null
else
frames = null;
}
// Property to get the number of frames in the stack trace
//
public virtual int FrameCount
{
get
{
return m_iNumOfFrames;
}
}
// Returns a given stack frame. Stack frames are numbered starting at
// zero, which is the last stack frame pushed.
//
public virtual StackFrame GetFrame( int index )
{
throw new NotImplementedException();
//// if((frames != null) && (index < m_iNumOfFrames) && (index >= 0))
//// {
//// return frames[index + m_iMethodsToSkip];
//// }
////
//// return null;
}
// Returns an array of all stack frames for this stacktrace.
// The array is ordered and sized such that GetFrames()[i] == GetFrame(i)
// The nth element of this array is the same as GetFrame(n).
// The length of the array is the same as FrameCount.
//
public virtual StackFrame[ ] GetFrames( )
{
if(frames == null || m_iNumOfFrames <= 0)
{
return null;
}
// We have to return a subset of the array. Unfortunately this
// means we have to allocate a new array and copy over.
StackFrame[] array = new StackFrame[m_iNumOfFrames];
Array.Copy( frames, m_iMethodsToSkip, array, 0, m_iNumOfFrames );
return array;
}
// Builds a readable representation of the stack trace
//
public override String ToString( )
{
// Include a trailing newline for backwards compatibility
return ToString( TraceFormat.TrailingNewLine );
}
// TraceFormat is Used to specify options for how the
// string-representation of a StackTrace should be generated.
internal enum TraceFormat
{
Normal,
TrailingNewLine, // include a trailing new line character
NoResourceLookup // to prevent infinite resource recusion
}
// Builds a readable representation of the stack trace, specifying
// the format for backwards compatibility.
internal String ToString( TraceFormat traceFormat )
{
String word_At = "at";
String inFileLineNum = "in {0}:line {1}";
if(traceFormat != TraceFormat.NoResourceLookup)
{
word_At = Environment.GetResourceString( "Word_At" );
inFileLineNum = Environment.GetResourceString( "StackTrace_InFileLineNumber" );
}
bool fFirstFrame = true;
StringBuilder sb = new StringBuilder( 255 );
for(int iFrameIndex = 0; iFrameIndex < m_iNumOfFrames; iFrameIndex++)
{
StackFrame sf = GetFrame( iFrameIndex );
MethodBase mb = sf.GetMethod();
if(mb != null)
{
// We want a newline at the end of every line except for the last
if(fFirstFrame)
fFirstFrame = false;
else
sb.Append( Environment.NewLine );
sb.AppendFormat( /*CultureInfo.InvariantCulture,*/ " {0} ", word_At );
Type t = mb.DeclaringType;
// if there is a type (non global method) print it
if(t != null)
{
sb.Append( t.FullName.Replace( '+', '.' ) );
sb.Append( "." );
}
sb.Append( mb.Name );
// deal with the generic portion of the method
if(mb is MethodInfo && ( (MethodInfo)mb ).IsGenericMethod)
{
Type[] typars = ((MethodInfo)mb).GetGenericArguments();
sb.Append( "[" );
int k = 0;
bool fFirstTyParam = true;
while(k < typars.Length)
{
if(fFirstTyParam == false)
sb.Append( "," );
else
fFirstTyParam = false;
sb.Append( typars[ k ].Name );
k++;
}
sb.Append( "]" );
}
// arguments printing
sb.Append( "(" );
ParameterInfo[] pi = mb.GetParameters();
bool fFirstParam = true;
for(int j = 0; j < pi.Length; j++)
{
if(fFirstParam == false)
sb.Append( ", " );
else
fFirstParam = false;
String typeName = "<UnknownType>";
if(pi[ j ].ParameterType != null)
typeName = pi[ j ].ParameterType.Name;
sb.Append( typeName + " " + pi[ j ].Name );
}
sb.Append( ")" );
// source location printing
if(sf.GetILOffset( ) != -1)
{
// It's possible we have a debug version of an executable but no PDB. In
// this case, the file name will be null.
String fileName = null;
try
{
fileName = sf.GetFileName( );
}
catch/*(SecurityException)*/
{
}
if(fileName != null)
{
// tack on " in c:\tmp\MyFile.cs:line 5"
sb.Append( ' ' );
sb.AppendFormat( /*CultureInfo.InvariantCulture,*/ inFileLineNum, fileName, sf.GetFileLineNumber( ) );
}
}
}
}
if(traceFormat == TraceFormat.TrailingNewLine)
{
sb.Append( Environment.NewLine );
}
return sb.ToString( );
}
// This helper is called from within the EE to construct a string representation
// of the current stack trace.
private static String GetManagedStackTraceStringHelper( bool fNeedFileInfo )
{
// Note all the frames in System.Diagnostics will be skipped when capturing
// a normal stack trace (not from an exception) so we don't need to explicitly
// skip the GetManagedStackTraceStringHelper frame.
StackTrace st = new StackTrace( 0, fNeedFileInfo );
return st.ToString( );
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System.Globalization
{
// This abstract class represents a calendar. A calendar reckons time in
// divisions such as weeks, months and years. The number, length and start of
// the divisions vary in each calendar.
//
// Any instant in time can be represented as an n-tuple of numeric values using
// a particular calendar. For example, the next vernal equinox occurs at (0.0, 0
// , 46, 8, 20, 3, 1999) in the Gregorian calendar. An implementation of
// Calendar can map any DateTime value to such an n-tuple and vice versa. The
// DateTimeFormat class can map between such n-tuples and a textual
// representation such as "8:46 AM March 20th 1999 AD".
//
// Most calendars identify a year which begins the current era. There may be any
// number of previous eras. The Calendar class identifies the eras as enumerated
// integers where the current era (CurrentEra) has the value zero.
//
// For consistency, the first unit in each interval, e.g. the first month, is
// assigned the value one.
// The calculation of hour/minute/second is moved to Calendar from GregorianCalendar,
// since most of the calendars (or all?) have the same way of calcuating hour/minute/second.
[Serializable]
public abstract partial class Calendar : ICloneable
{
// Number of 100ns (10E-7 second) ticks per time unit
internal const long TicksPerMillisecond = 10000;
internal const long TicksPerSecond = TicksPerMillisecond * 1000;
internal const long TicksPerMinute = TicksPerSecond * 60;
internal const long TicksPerHour = TicksPerMinute * 60;
internal const long TicksPerDay = TicksPerHour * 24;
// Number of milliseconds per time unit
internal const int MillisPerSecond = 1000;
internal const int MillisPerMinute = MillisPerSecond * 60;
internal const int MillisPerHour = MillisPerMinute * 60;
internal const int MillisPerDay = MillisPerHour * 24;
// Number of days in a non-leap year
internal const int DaysPerYear = 365;
// Number of days in 4 years
internal const int DaysPer4Years = DaysPerYear * 4 + 1;
// Number of days in 100 years
internal const int DaysPer100Years = DaysPer4Years * 25 - 1;
// Number of days in 400 years
internal const int DaysPer400Years = DaysPer100Years * 4 + 1;
// Number of days from 1/1/0001 to 1/1/10000
internal const int DaysTo10000 = DaysPer400Years * 25 - 366;
internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
private int _currentEraValue = -1;
[OptionalField(VersionAdded = 2)]
private bool _isReadOnly = false;
#if CORECLR
internal const CalendarId CAL_HEBREW = CalendarId.HEBREW;
internal const CalendarId CAL_HIJRI = CalendarId.HIJRI;
internal const CalendarId CAL_JAPAN = CalendarId.JAPAN;
internal const CalendarId CAL_JULIAN = CalendarId.JULIAN;
internal const CalendarId CAL_TAIWAN = CalendarId.TAIWAN;
internal const CalendarId CAL_UMALQURA = CalendarId.UMALQURA;
internal const CalendarId CAL_PERSIAN = CalendarId.PERSIAN;
#endif
// The minimum supported DateTime range for the calendar.
public virtual DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
// The maximum supported DateTime range for the calendar.
public virtual DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
public virtual CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.Unknown;
}
}
protected Calendar()
{
//Do-nothing constructor.
}
///
// This can not be abstract, otherwise no one can create a subclass of Calendar.
//
internal virtual CalendarId ID
{
get
{
return CalendarId.UNINITIALIZED_VALUE;
}
}
///
// Return the Base calendar ID for calendars that didn't have defined data in calendarData
//
internal virtual CalendarId BaseCalendarID
{
get { return ID; }
}
////////////////////////////////////////////////////////////////////////
//
// IsReadOnly
//
// Detect if the object is readonly.
//
////////////////////////////////////////////////////////////////////////
public bool IsReadOnly
{
get { return (_isReadOnly); }
}
////////////////////////////////////////////////////////////////////////
//
// Clone
//
// Is the implementation of ICloneable.
//
////////////////////////////////////////////////////////////////////////
public virtual object Clone()
{
object o = MemberwiseClone();
((Calendar)o).SetReadOnlyState(false);
return (o);
}
////////////////////////////////////////////////////////////////////////
//
// ReadOnly
//
// Create a cloned readonly instance or return the input one if it is
// readonly.
//
////////////////////////////////////////////////////////////////////////
public static Calendar ReadOnly(Calendar calendar)
{
if (calendar == null) { throw new ArgumentNullException(nameof(calendar)); }
Contract.EndContractBlock();
if (calendar.IsReadOnly) { return (calendar); }
Calendar clonedCalendar = (Calendar)(calendar.MemberwiseClone());
clonedCalendar.SetReadOnlyState(true);
return (clonedCalendar);
}
internal void VerifyWritable()
{
if (_isReadOnly)
{
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
}
internal void SetReadOnlyState(bool readOnly)
{
_isReadOnly = readOnly;
}
/*=================================CurrentEraValue==========================
**Action: This is used to convert CurretEra(0) to an appropriate era value.
**Returns:
**Arguments:
**Exceptions:
**Notes:
** The value is from calendar.nlp.
============================================================================*/
internal virtual int CurrentEraValue
{
get
{
// The following code assumes that the current era value can not be -1.
if (_currentEraValue == -1)
{
Debug.Assert(BaseCalendarID != CalendarId.UNINITIALIZED_VALUE, "[Calendar.CurrentEraValue] Expected a real calendar ID");
_currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra;
}
return (_currentEraValue);
}
}
// The current era for a calendar.
public const int CurrentEra = 0;
internal int twoDigitYearMax = -1;
internal static void CheckAddResult(long ticks, DateTime minValue, DateTime maxValue)
{
if (ticks < minValue.Ticks || ticks > maxValue.Ticks)
{
throw new ArgumentException(
String.Format(CultureInfo.InvariantCulture, SR.Format(SR.Argument_ResultCalendarRange,
minValue, maxValue)));
}
Contract.EndContractBlock();
}
internal DateTime Add(DateTime time, double value, int scale)
{
// From ECMA CLI spec, Partition III, section 3.27:
//
// If overflow occurs converting a floating-point type to an integer, or if the floating-point value
// being converted to an integer is a NaN, the value returned is unspecified.
//
// Based upon this, this method should be performing the comparison against the double
// before attempting a cast. Otherwise, the result is undefined.
double tempMillis = (value * scale + (value >= 0 ? 0.5 : -0.5));
if (!((tempMillis > -(double)MaxMillis) && (tempMillis < (double)MaxMillis)))
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_AddValue);
}
long millis = (long)tempMillis;
long ticks = time.Ticks + millis * TicksPerMillisecond;
CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the DateTime resulting from adding the given number of
// milliseconds to the specified DateTime. The result is computed by rounding
// the number of milliseconds given by value to the nearest integer,
// and adding that interval to the specified DateTime. The value
// argument is permitted to be negative.
//
public virtual DateTime AddMilliseconds(DateTime time, double milliseconds)
{
return (Add(time, milliseconds, 1));
}
// Returns the DateTime resulting from adding a fractional number of
// days to the specified DateTime. The result is computed by rounding the
// fractional number of days given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddDays(DateTime time, int days)
{
return (Add(time, days, MillisPerDay));
}
// Returns the DateTime resulting from adding a fractional number of
// hours to the specified DateTime. The result is computed by rounding the
// fractional number of hours given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddHours(DateTime time, int hours)
{
return (Add(time, hours, MillisPerHour));
}
// Returns the DateTime resulting from adding a fractional number of
// minutes to the specified DateTime. The result is computed by rounding the
// fractional number of minutes given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddMinutes(DateTime time, int minutes)
{
return (Add(time, minutes, MillisPerMinute));
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public abstract DateTime AddMonths(DateTime time, int months);
// Returns the DateTime resulting from adding a number of
// seconds to the specified DateTime. The result is computed by rounding the
// fractional number of seconds given by value to the nearest
// millisecond, and adding that interval to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddSeconds(DateTime time, int seconds)
{
return Add(time, seconds, MillisPerSecond);
}
// Returns the DateTime resulting from adding a number of
// weeks to the specified DateTime. The
// value argument is permitted to be negative.
//
public virtual DateTime AddWeeks(DateTime time, int weeks)
{
return (AddDays(time, weeks * 7));
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public abstract DateTime AddYears(DateTime time, int years);
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public abstract int GetDayOfMonth(DateTime time);
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public abstract DayOfWeek GetDayOfWeek(DateTime time);
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public abstract int GetDayOfYear(DateTime time);
// Returns the number of days in the month given by the year and
// month arguments.
//
public virtual int GetDaysInMonth(int year, int month)
{
return (GetDaysInMonth(year, month, CurrentEra));
}
// Returns the number of days in the month given by the year and
// month arguments for the specified era.
//
public abstract int GetDaysInMonth(int year, int month, int era);
// Returns the number of days in the year given by the year argument for the current era.
//
public virtual int GetDaysInYear(int year)
{
return (GetDaysInYear(year, CurrentEra));
}
// Returns the number of days in the year given by the year argument for the current era.
//
public abstract int GetDaysInYear(int year, int era);
// Returns the era for the specified DateTime value.
public abstract int GetEra(DateTime time);
/*=================================Eras==========================
**Action: Get the list of era values.
**Returns: The int array of the era names supported in this calendar.
** null if era is not used.
**Arguments: None.
**Exceptions: None.
============================================================================*/
public abstract int[] Eras
{
get;
}
// Returns the hour part of the specified DateTime. The returned value is an
// integer between 0 and 23.
//
public virtual int GetHour(DateTime time)
{
return ((int)((time.Ticks / TicksPerHour) % 24));
}
// Returns the millisecond part of the specified DateTime. The returned value
// is an integer between 0 and 999.
//
public virtual double GetMilliseconds(DateTime time)
{
return (double)((time.Ticks / TicksPerMillisecond) % 1000);
}
// Returns the minute part of the specified DateTime. The returned value is
// an integer between 0 and 59.
//
public virtual int GetMinute(DateTime time)
{
return ((int)((time.Ticks / TicksPerMinute) % 60));
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public abstract int GetMonth(DateTime time);
// Returns the number of months in the specified year in the current era.
public virtual int GetMonthsInYear(int year)
{
return (GetMonthsInYear(year, CurrentEra));
}
// Returns the number of months in the specified year and era.
public abstract int GetMonthsInYear(int year, int era);
// Returns the second part of the specified DateTime. The returned value is
// an integer between 0 and 59.
//
public virtual int GetSecond(DateTime time)
{
return ((int)((time.Ticks / TicksPerSecond) % 60));
}
/*=================================GetFirstDayWeekOfYear==========================
**Action: Get the week of year using the FirstDay rule.
**Returns: the week of year.
**Arguments:
** time
** firstDayOfWeek the first day of week (0=Sunday, 1=Monday, ... 6=Saturday)
**Notes:
** The CalendarWeekRule.FirstDay rule: Week 1 begins on the first day of the year.
** Assume f is the specifed firstDayOfWeek,
** and n is the day of week for January 1 of the specified year.
** Assign offset = n - f;
** Case 1: offset = 0
** E.g.
** f=1
** weekday 0 1 2 3 4 5 6 0 1
** date 1/1
** week# 1 2
** then week of year = (GetDayOfYear(time) - 1) / 7 + 1
**
** Case 2: offset < 0
** e.g.
** n=1 f=3
** weekday 0 1 2 3 4 5 6 0
** date 1/1
** week# 1 2
** This means that the first week actually starts 5 days before 1/1.
** So week of year = (GetDayOfYear(time) + (7 + offset) - 1) / 7 + 1
** Case 3: offset > 0
** e.g.
** f=0 n=2
** weekday 0 1 2 3 4 5 6 0 1 2
** date 1/1
** week# 1 2
** This means that the first week actually starts 2 days before 1/1.
** So Week of year = (GetDayOfYear(time) + offset - 1) / 7 + 1
============================================================================*/
internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek)
{
int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
// Calculate the day of week for the first day of the year.
// dayOfWeek - (dayOfYear % 7) is the day of week for the first day of this year. Note that
// this value can be less than 0. It's fine since we are making it positive again in calculating offset.
int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
int offset = (dayForJan1 - firstDayOfWeek + 14) % 7;
Debug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0");
return ((dayOfYear + offset) / 7 + 1);
}
private int GetWeekOfYearFullDays(DateTime time, int firstDayOfWeek, int fullDays)
{
int dayForJan1;
int offset;
int day;
int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
//
// Calculate the number of days between the first day of year (1/1) and the first day of the week.
// This value will be a positive value from 0 ~ 6. We call this value as "offset".
//
// If offset is 0, it means that the 1/1 is the start of the first week.
// Assume the first day of the week is Monday, it will look like this:
// Sun Mon Tue Wed Thu Fri Sat
// 12/31 1/1 1/2 1/3 1/4 1/5 1/6
// +--> First week starts here.
//
// If offset is 1, it means that the first day of the week is 1 day ahead of 1/1.
// Assume the first day of the week is Monday, it will look like this:
// Sun Mon Tue Wed Thu Fri Sat
// 1/1 1/2 1/3 1/4 1/5 1/6 1/7
// +--> First week starts here.
//
// If offset is 2, it means that the first day of the week is 2 days ahead of 1/1.
// Assume the first day of the week is Monday, it will look like this:
// Sat Sun Mon Tue Wed Thu Fri Sat
// 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8
// +--> First week starts here.
// Day of week is 0-based.
// Get the day of week for 1/1. This can be derived from the day of week of the target day.
// Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset.
dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7);
// Now, calculate the offset. Subtract the first day of week from the dayForJan1. And make it a positive value.
offset = (firstDayOfWeek - dayForJan1 + 14) % 7;
if (offset != 0 && offset >= fullDays)
{
//
// If the offset is greater than the value of fullDays, it means that
// the first week of the year starts on the week where Jan/1 falls on.
//
offset -= 7;
}
//
// Calculate the day of year for specified time by taking offset into account.
//
day = dayOfYear - offset;
if (day >= 0)
{
//
// If the day of year value is greater than zero, get the week of year.
//
return (day / 7 + 1);
}
//
// Otherwise, the specified time falls on the week of previous year.
// Call this method again by passing the last day of previous year.
//
// the last day of the previous year may "underflow" to no longer be a valid date time for
// this calendar if we just subtract so we need the subclass to provide us with
// that information
if (time <= MinSupportedDateTime.AddDays(dayOfYear))
{
return GetWeekOfYearOfMinSupportedDateTime(firstDayOfWeek, fullDays);
}
return (GetWeekOfYearFullDays(time.AddDays(-(dayOfYear + 1)), firstDayOfWeek, fullDays));
}
private int GetWeekOfYearOfMinSupportedDateTime(int firstDayOfWeek, int minimumDaysInFirstWeek)
{
int dayOfYear = GetDayOfYear(MinSupportedDateTime) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
int dayOfWeekOfFirstOfYear = (int)GetDayOfWeek(MinSupportedDateTime) - dayOfYear % 7;
// Calculate the offset (how many days from the start of the year to the start of the week)
int offset = (firstDayOfWeek + 7 - dayOfWeekOfFirstOfYear) % 7;
if (offset == 0 || offset >= minimumDaysInFirstWeek)
{
// First of year falls in the first week of the year
return 1;
}
int daysInYearBeforeMinSupportedYear = DaysInYearBeforeMinSupportedYear - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
int dayOfWeekOfFirstOfPreviousYear = dayOfWeekOfFirstOfYear - 1 - (daysInYearBeforeMinSupportedYear % 7);
// starting from first day of the year, how many days do you have to go forward
// before getting to the first day of the week?
int daysInInitialPartialWeek = (firstDayOfWeek - dayOfWeekOfFirstOfPreviousYear + 14) % 7;
int day = daysInYearBeforeMinSupportedYear - daysInInitialPartialWeek;
if (daysInInitialPartialWeek >= minimumDaysInFirstWeek)
{
// If the offset is greater than the minimum Days in the first week, it means that
// First of year is part of the first week of the year even though it is only a partial week
// add another week
day += 7;
}
return (day / 7 + 1);
}
// it would be nice to make this abstract but we can't since that would break previous implementations
protected virtual int DaysInYearBeforeMinSupportedYear
{
get
{
return 365;
}
}
// Returns the week of year for the specified DateTime. The returned value is an
// integer between 1 and 53.
//
public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6)
{
throw new ArgumentOutOfRangeException(
nameof(firstDayOfWeek), SR.Format(SR.ArgumentOutOfRange_Range,
DayOfWeek.Sunday, DayOfWeek.Saturday));
}
Contract.EndContractBlock();
switch (rule)
{
case CalendarWeekRule.FirstDay:
return (GetFirstDayWeekOfYear(time, (int)firstDayOfWeek));
case CalendarWeekRule.FirstFullWeek:
return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 7));
case CalendarWeekRule.FirstFourDayWeek:
return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4));
}
throw new ArgumentOutOfRangeException(
nameof(rule), SR.Format(SR.ArgumentOutOfRange_Range,
CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek));
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and 9999.
//
public abstract int GetYear(DateTime time);
// Checks whether a given day in the current era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public virtual bool IsLeapDay(int year, int month, int day)
{
return (IsLeapDay(year, month, day, CurrentEra));
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public abstract bool IsLeapDay(int year, int month, int day, int era);
// Checks whether a given month in the current era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public virtual bool IsLeapMonth(int year, int month)
{
return (IsLeapMonth(year, month, CurrentEra));
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public abstract bool IsLeapMonth(int year, int month, int era);
// Returns the leap month in a calendar year of the current era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public virtual int GetLeapMonth(int year)
{
return (GetLeapMonth(year, CurrentEra));
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public virtual int GetLeapMonth(int year, int era)
{
if (!IsLeapYear(year, era))
return 0;
int monthsCount = GetMonthsInYear(year, era);
for (int month = 1; month <= monthsCount; month++)
{
if (IsLeapMonth(year, month, era))
return month;
}
return 0;
}
// Checks whether a given year in the current era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public virtual bool IsLeapYear(int year)
{
return (IsLeapYear(year, CurrentEra));
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public abstract bool IsLeapYear(int year, int era);
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public virtual DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond)
{
return (ToDateTime(year, month, day, hour, minute, second, millisecond, CurrentEra));
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public abstract DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era);
internal virtual Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result)
{
result = DateTime.MinValue;
try
{
result = ToDateTime(year, month, day, hour, minute, second, millisecond, era);
return true;
}
catch (ArgumentException)
{
return false;
}
}
internal virtual bool IsValidYear(int year, int era)
{
return (year >= GetYear(MinSupportedDateTime) && year <= GetYear(MaxSupportedDateTime));
}
internal virtual bool IsValidMonth(int year, int month, int era)
{
return (IsValidYear(year, era) && month >= 1 && month <= GetMonthsInYear(year, era));
}
internal virtual bool IsValidDay(int year, int month, int day, int era)
{
return (IsValidMonth(year, month, era) && day >= 1 && day <= GetDaysInMonth(year, month, era));
}
// Returns and assigns the maximum value to represent a two digit year. This
// value is the upper boundary of a 100 year range that allows a two digit year
// to be properly translated to a four digit year. For example, if 2029 is the
// upper boundary, then a two digit value of 30 should be interpreted as 1930
// while a two digit value of 29 should be interpreted as 2029. In this example
// , the 100 year range would be from 1930-2029. See ToFourDigitYear().
public virtual int TwoDigitYearMax
{
get
{
return (twoDigitYearMax);
}
set
{
VerifyWritable();
twoDigitYearMax = value;
}
}
// Converts the year value to the appropriate century by using the
// TwoDigitYearMax property. For example, if the TwoDigitYearMax value is 2029,
// then a two digit value of 30 will get converted to 1930 while a two digit
// value of 29 will get converted to 2029.
public virtual int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year),
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
if (year < 100)
{
return ((TwoDigitYearMax / 100 - (year > TwoDigitYearMax % 100 ? 1 : 0)) * 100 + year);
}
// If the year value is above 100, just return the year value. Don't have to do
// the TwoDigitYearMax comparison.
return (year);
}
// Return the tick count corresponding to the given hour, minute, second.
// Will check the if the parameters are valid.
internal static long TimeToTicks(int hour, int minute, int second, int millisecond)
{
if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
{
if (millisecond < 0 || millisecond >= MillisPerSecond)
{
throw new ArgumentOutOfRangeException(
nameof(millisecond),
String.Format(
CultureInfo.InvariantCulture,
SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1)));
}
return InternalGlobalizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond;
}
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
}
internal static int GetSystemTwoDigitYearSetting(CalendarId CalID, int defaultYearValue)
{
int twoDigitYearMax = CalendarData.GetTwoDigitYearMax(CalID);
if (twoDigitYearMax < 0)
{
twoDigitYearMax = defaultYearValue;
}
return (twoDigitYearMax);
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using ASC.Core.Common.Settings;
namespace ASC.Web.Studio.UserControls.Management.SingleSignOnSettings
{
[Serializable]
[DataContract]
public class SsoSettingsV2 : BaseSettings<SsoSettingsV2>
{
public override Guid ID
{
get { return new Guid("{1500187F-B8AB-406F-97B8-04BFE8261DBE}"); }
}
public const string SSO_SP_LOGIN_LABEL = "Single Sign-on";
public override ISettings GetDefault()
{
return new SsoSettingsV2
{
EnableSso = false,
IdpSettings = new SsoIdpSettings
{
EntityId = string.Empty,
SsoUrl = string.Empty,
SsoBinding = SsoBindingType.Saml20HttpPost,
SloUrl = string.Empty,
SloBinding = SsoBindingType.Saml20HttpPost,
NameIdFormat = SsoNameIdFormatType.Saml20Transient
},
IdpCertificates = new List<SsoCertificate>(),
IdpCertificateAdvanced = new SsoIdpCertificateAdvanced
{
DecryptAlgorithm = SsoEncryptAlgorithmType.AES_128,
DecryptAssertions = false,
VerifyAlgorithm = SsoSigningAlgorithmType.RSA_SHA1,
VerifyAuthResponsesSign = false,
VerifyLogoutRequestsSign = false,
VerifyLogoutResponsesSign = false
},
SpCertificates = new List<SsoCertificate>(),
SpCertificateAdvanced = new SsoSpCertificateAdvanced
{
DecryptAlgorithm = SsoEncryptAlgorithmType.AES_128,
EncryptAlgorithm = SsoEncryptAlgorithmType.AES_128,
EncryptAssertions = false,
SigningAlgorithm = SsoSigningAlgorithmType.RSA_SHA1,
SignAuthRequests = false,
SignLogoutRequests = false,
SignLogoutResponses = false
},
FieldMapping = new SsoFieldMapping
{
FirstName = "givenName",
LastName = "sn",
Email = "mail",
Title = "title",
Location = "l",
Phone = "mobile"
},
SpLoginLabel = SSO_SP_LOGIN_LABEL,
HideAuthPage = false
};
}
[DataMember]
public bool EnableSso { get; set; }
[DataMember]
public SsoIdpSettings IdpSettings { get; set; }
[DataMember]
public List<SsoCertificate> IdpCertificates { get; set; }
[DataMember]
public SsoIdpCertificateAdvanced IdpCertificateAdvanced { get; set; }
[DataMember]
public string SpLoginLabel { get; set; }
[DataMember]
public List<SsoCertificate> SpCertificates { get; set; }
[DataMember]
public SsoSpCertificateAdvanced SpCertificateAdvanced { get; set; }
[DataMember]
public SsoFieldMapping FieldMapping { get; set; }
[DataMember]
public bool HideAuthPage { get; set; }
}
#region SpSettings
[Serializable]
[DataContract]
public class SsoIdpSettings
{
[DataMember]
public string EntityId { get; set; }
[DataMember]
public string SsoUrl { get; set; }
[DataMember]
public string SsoBinding { get; set; }
[DataMember]
public string SloUrl { get; set; }
[DataMember]
public string SloBinding { get; set; }
[DataMember]
public string NameIdFormat { get; set; }
}
#endregion
#region FieldsMapping
[Serializable]
[DataContract]
public class SsoFieldMapping
{
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
[DataMember]
public string Email { get; set; }
[DataMember]
public string Title { get; set; }
[DataMember]
public string Location { get; set; }
[DataMember]
public string Phone { get; set; }
}
#endregion
#region Certificates
[Serializable]
[DataContract]
public class SsoCertificate
{
[DataMember]
public bool SelfSigned { get; set; }
[DataMember]
public string Crt { get; set; }
[DataMember]
public string Key { get; set; }
[DataMember]
public string Action { get; set; }
[DataMember]
public string DomainName { get; set; }
[DataMember]
public DateTime StartDate { get; set; }
[DataMember]
public DateTime ExpiredDate { get; set; }
}
[Serializable]
[DataContract]
public class SsoIdpCertificateAdvanced
{
[DataMember]
public string VerifyAlgorithm { get; set; }
[DataMember]
public bool VerifyAuthResponsesSign { get; set; }
[DataMember]
public bool VerifyLogoutRequestsSign { get; set; }
[DataMember]
public bool VerifyLogoutResponsesSign { get; set; }
[DataMember]
public string DecryptAlgorithm { get; set; }
[DataMember]
public bool DecryptAssertions { get; set; }
}
[Serializable]
[DataContract]
public class SsoSpCertificateAdvanced
{
[DataMember]
public string SigningAlgorithm { get; set; }
[DataMember]
public bool SignAuthRequests { get; set; }
[DataMember]
public bool SignLogoutRequests { get; set; }
[DataMember]
public bool SignLogoutResponses { get; set; }
[DataMember]
public string EncryptAlgorithm { get; set; }
[DataMember]
public string DecryptAlgorithm { get; set; }
[DataMember]
public bool EncryptAssertions { get; set; }
}
#endregion
#region Types
[Serializable]
[DataContract]
public class SsoNameIdFormatType
{
[DataMember]
public const string Saml11Unspecified = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified";
[DataMember]
public const string Saml11EmailAddress = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress";
[DataMember]
public const string Saml20Entity = "urn:oasis:names:tc:SAML:2.0:nameid-format:entity";
[DataMember]
public const string Saml20Transient = "urn:oasis:names:tc:SAML:2.0:nameid-format:transient";
[DataMember]
public const string Saml20Persistent = "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent";
[DataMember]
public const string Saml20Encrypted = "urn:oasis:names:tc:SAML:2.0:nameid-format:encrypted";
[DataMember]
public const string Saml20Unspecified = "urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified";
[DataMember]
public const string Saml11X509SubjectName = "urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName";
[DataMember]
public const string Saml11WindowsDomainQualifiedName = "urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName";
[DataMember]
public const string Saml20Kerberos = "urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos";
}
[Serializable]
[DataContract]
public class SsoBindingType
{
[DataMember]
public const string Saml20HttpPost = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST";
[DataMember]
public const string Saml20HttpRedirect = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect";
}
[Serializable]
[DataContract]
public class SsoMetadata
{
[DataMember]
public const string BaseUrl = "";
[DataMember]
public const string MetadataUrl = "/sso/metadata";
[DataMember]
public const string EntityId = "/sso/metadata";
[DataMember]
public const string ConsumerUrl = "/sso/acs";
[DataMember]
public const string LogoutUrl = "/sso/slo/callback";
}
[Serializable]
[DataContract]
public class SsoSigningAlgorithmType
{
[DataMember]
public const string RSA_SHA1 = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
[DataMember]
public const string RSA_SHA256 = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
[DataMember]
public const string RSA_SHA512 = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512";
}
[Serializable]
[DataContract]
public class SsoEncryptAlgorithmType
{
[DataMember]
public const string AES_128 = "http://www.w3.org/2001/04/xmlenc#aes128-cbc";
[DataMember]
public const string AES_256 = "http://www.w3.org/2001/04/xmlenc#aes256-cbc";
[DataMember]
public const string TRI_DEC = "http://www.w3.org/2001/04/xmlenc#tripledes-cbc";
}
[Serializable]
[DataContract]
public class SsoSpCertificateActionType
{
[DataMember]
public const string Signing = "signing";
[DataMember]
public const string Encrypt = "encrypt";
[DataMember]
public const string SigningAndEncrypt = "signing and encrypt";
}
[Serializable]
[DataContract]
public class SsoIdpCertificateActionType
{
[DataMember]
public const string Verification = "verification";
[DataMember]
public const string Decrypt = "decrypt";
[DataMember]
public const string VerificationAndDecrypt = "verification and decrypt";
}
#endregion
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.DDF
{
using System;
using System.Text;
using System.Collections.Generic;
using System.IO;
using NUnit.Framework;
using NPOI.DDF;
using NPOI.Util;
using System.Configuration;
[TestFixture]
public class TestEscherContainerRecord
{
private String ESCHER_DATA_PATH;
public TestEscherContainerRecord()
{
ESCHER_DATA_PATH = ConfigurationManager.AppSettings["escher.data.path"];
}
[Test]
public void TestFillFields()
{
IEscherRecordFactory f = new DefaultEscherRecordFactory();
byte[] data = HexRead.ReadFromString("0F 02 11 F1 00 00 00 00");
EscherRecord r = f.CreateRecord(data, 0);
r.FillFields(data, 0, f);
Assert.IsTrue(r is EscherContainerRecord);
Assert.AreEqual((short)0x020F, r.Options);
Assert.AreEqual(unchecked((short)0xF111), r.RecordId);
data = HexRead.ReadFromString("0F 02 11 F1 08 00 00 00" +
" 02 00 22 F2 00 00 00 00");
r = f.CreateRecord(data, 0);
r.FillFields(data, 0, f);
EscherRecord c = r.GetChild(0);
Assert.IsFalse(c is EscherContainerRecord);
Assert.AreEqual(unchecked((short)0x0002), c.Options);
Assert.AreEqual(unchecked((short)0xF222), c.RecordId);
}
[Test]
public void TestSerialize()
{
UnknownEscherRecord r = new UnknownEscherRecord();
r.Options=(short)0x123F;
r.RecordId=unchecked((short)0xF112);
byte[] data = new byte[8];
r.Serialize(0, data);
Assert.AreEqual("[3F, 12, 12, F1, 00, 00, 00, 00, ]", HexDump.ToHex(data));
EscherRecord childRecord = new UnknownEscherRecord();
childRecord.Options=unchecked((short)0x9999);
childRecord.RecordId=unchecked((short)0xFF01);
r.AddChildRecord(childRecord);
data = new byte[16];
r.Serialize(0, data);
Assert.AreEqual("[3F, 12, 12, F1, 08, 00, 00, 00, 99, 99, 01, FF, 00, 00, 00, 00, ]", HexDump.ToHex(data));
}
[Test]
public void TestToString()
{
EscherContainerRecord r = new EscherContainerRecord();
r.RecordId=EscherContainerRecord.SP_CONTAINER;
r.Options=(short)0x000F;
String nl = Environment.NewLine;
Assert.AreEqual("EscherContainerRecord (SpContainer):" + nl +
" isContainer: True" + nl +
" version: 0x000F" + nl +
" instance: 0x0000" + nl +
" recordId: 0xF004" + nl +
" numchildren: 0" + nl
, r.ToString());
EscherOptRecord r2 = new EscherOptRecord();
// don't try to shoot in foot, please -- vlsergey
// r2.setOptions((short) 0x9876);
r2.RecordId=EscherOptRecord.RECORD_ID;
String expected;
r.AddChildRecord(r2);
expected = "EscherContainerRecord (SpContainer):" + nl +
" isContainer: True" + nl +
" version: 0x000F" + nl +
" instance: 0x0000" + nl +
" recordId: 0xF004" + nl +
" numchildren: 1" + nl +
" children: " + nl +
" Child 0:" + nl +
" EscherOptRecord:" + nl +
" isContainer: False" + nl +
" version: 0x0003" + nl +
" instance: 0x0000" + nl +
" recordId: 0xF00B" + nl +
" numchildren: 0" + nl +
" properties:" + nl +
" " + nl;
Assert.AreEqual(expected, r.ToString());
r.AddChildRecord(r2);
expected = "EscherContainerRecord (SpContainer):" + nl +
" isContainer: True" + nl +
" version: 0x000F" + nl +
" instance: 0x0000" + nl +
" recordId: 0xF004" + nl +
" numchildren: 2" + nl +
" children: " + nl +
" Child 0:" + nl +
" EscherOptRecord:" + nl +
" isContainer: False" + nl +
" version: 0x0003" + nl +
" instance: 0x0000" + nl +
" recordId: 0xF00B" + nl +
" numchildren: 0" + nl +
" properties:" + nl +
" " + nl +
" Child 1:" + nl +
" EscherOptRecord:" + nl +
" isContainer: False" + nl +
" version: 0x0003" + nl +
" instance: 0x0000" + nl +
" recordId: 0xF00B" + nl +
" numchildren: 0" + nl +
" properties:" + nl +
" " + nl;
Assert.AreEqual(expected, r.ToString());
}
private class DummyEscherRecord : EscherRecord
{
public DummyEscherRecord() { }
public override int FillFields(byte[] data, int offset, IEscherRecordFactory recordFactory)
{ return 0; }
public override int Serialize(int offset, byte[] data, EscherSerializationListener listener)
{ return 0; }
public override int RecordSize { get { return 10; } }
public override String RecordName { get { return ""; } }
}
[Test]
public void TestRecordSize()
{
EscherContainerRecord r = new EscherContainerRecord();
r.AddChildRecord(new DummyEscherRecord());
Assert.AreEqual(18, r.RecordSize);
}
/**
* We were having problems with Reading too much data on an UnknownEscherRecord,
* but hopefully we now Read the correct size.
*/
[Test]
public void TestBug44857()
{
//File f = new File(ESCHER_DATA_PATH, "Container.dat");
Assert.IsTrue(File.Exists(ESCHER_DATA_PATH+"Container.dat"));
using (FileStream finp = new FileStream(ESCHER_DATA_PATH + "Container.dat", FileMode.Open, FileAccess.Read))
{
byte[] data = IOUtils.ToByteArray(finp);
finp.Close();
// This used to fail with an OutOfMemory
EscherContainerRecord record = new EscherContainerRecord();
record.FillFields(data, 0, new DefaultEscherRecordFactory());
}
}
/**
* Ensure {@link EscherContainerRecord} doesn't spill its guts everywhere
*/
[Test]
public void TestChildren()
{
EscherContainerRecord ecr = new EscherContainerRecord();
List<EscherRecord> children0 = ecr.ChildRecords;
Assert.AreEqual(0, children0.Count);
EscherRecord chA = new DummyEscherRecord();
EscherRecord chB = new DummyEscherRecord();
EscherRecord chC = new DummyEscherRecord();
ecr.AddChildRecord(chA);
ecr.AddChildRecord(chB);
children0.Add(chC);
List<EscherRecord> children1 = ecr.ChildRecords;
Assert.IsTrue(children0 != children1);
Assert.AreEqual(2, children1.Count);
Assert.AreEqual(chA, children1[0]);
Assert.AreEqual(chB, children1[1]);
Assert.AreEqual(1, children0.Count); // first copy unchanged
ecr.ChildRecords=(children0);
ecr.AddChildRecord(chA);
List<EscherRecord> children2 = ecr.ChildRecords;
Assert.AreEqual(2, children2.Count);
Assert.AreEqual(chC, children2[0]);
Assert.AreEqual(chA, children2[1]);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file.
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SharePoint_Add_in_CSOM_BasicDataOperationsWeb
{
public partial class Default : System.Web.UI.Page
{
SharePointContextToken contextToken;
string accessToken;
Uri sharepointUrl;
protected void Page_PreInit(object sender, EventArgs e)
{
Uri redirectUrl;
switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl))
{
case RedirectionStatus.Ok:
return;
case RedirectionStatus.ShouldRedirect:
Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true);
break;
case RedirectionStatus.CanNotRedirect:
Response.Write("An error occurred while processing your request.");
Response.End();
break;
}
}
// The Page_load method fetches the context token and the access token. The access token is used by all of the data retrieval methods.
protected void Page_Load(object sender, EventArgs e)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);
if (contextTokenString != null)
{
contextToken =
TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);
sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
accessToken =
TokenHelper.GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
// In a production add-in, you should cache the access token somewhere, such as in a database
// or ASP.NET Session Cache. (Do not put it in a cookie.) Your code should also check to see
// if it is expired before using it (and use the refresh token to get a new one when needed).
// For more information, see the MSDN topic at https://msdn.microsoft.com/library/office/dn762763.aspx
// For simplicity, this sample does not follow these practices.
AddListButton.CommandArgument = accessToken;
RefreshListButton.CommandArgument = accessToken;
RetrieveListButton.CommandArgument = accessToken;
AddItemButton.CommandArgument = accessToken;
DeleteListButton.CommandArgument = accessToken;
ChangeListTitleButton.CommandArgument = accessToken;
RetrieveLists(accessToken);
}
else if (!IsPostBack)
{
Response.Write("Could not find a context token.");
}
}
//This method retrieves all of the lists on the host Web.
private void RetrieveLists(string accessToken)
{
if (IsPostBack)
{
sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
}
AddItemButton.Visible = false;
AddListItemBox.Visible = false;
RetrieveListNameBox.Enabled = true;
DeleteListButton.Visible = false;
ChangeListTitleButton.Visible = false;
ChangeListTitleBox.Visible = false;
ListTable.Rows[0].Cells[1].Text = "List ID";
//Execute a request for all of the site's lists.
ClientContext clientContext =
TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
Web web = clientContext.Web;
ListCollection lists = web.Lists;
clientContext.Load<ListCollection>(lists);
clientContext.ExecuteQuery();
foreach (List list in lists)
{
TableRow tableRow = new TableRow();
TableCell tableCell1 = new TableCell();
tableCell1.Controls.Add(new LiteralControl(list.Title));
LiteralControl idClick = new LiteralControl();
//Use Javascript to populate the RetrieveListNameBox control with the list id.
string clickScript = "<a onclick=\"document.getElementById(\'RetrieveListNameBox\').value = '" + list.Id.ToString() + "';\" href=\"#\">" + list.Id.ToString() + "</a>";
idClick.Text = clickScript;
TableCell tableCell2 = new TableCell();
tableCell2.Controls.Add(idClick);
tableRow.Cells.Add(tableCell1);
tableRow.Cells.Add(tableCell2);
ListTable.Rows.Add(tableRow);
}
}
//This method retrieves all items from a specified list.
private void RetrieveListItems(string accessToken, Guid listId)
{
if (IsPostBack)
{
sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
}
//Adjust the visibility of controls on the page in light of the list-specific context.
AddItemButton.Visible = true;
AddListItemBox.Visible = true;
RetrieveListNameBox.Enabled = false;
DeleteListButton.Visible = true;
ChangeListTitleButton.Visible = true;
ChangeListTitleBox.Visible = true;
ListTable.Rows[0].Cells[1].Text = "List Items";
//Execute a request to get the first 100 of the list's items.
ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
Web web = clientContext.Web;
ListCollection lists = web.Lists;
List selectedList = lists.GetById(listId);
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<View><RowLimit>100</RowLimit></View>";
//Use the fully qualified name to disambiguate the ListItemCollection type.
Microsoft.SharePoint.Client.ListItemCollection listItems = selectedList.GetItems(camlQuery);
clientContext.Load<ListCollection>(lists);
clientContext.Load<List>(selectedList);
clientContext.Load<Microsoft.SharePoint.Client.ListItemCollection>(listItems);
clientContext.ExecuteQuery();
TableRow tableRow = new TableRow();
TableCell tableCell1 = new TableCell();
tableCell1.Controls.Add(new LiteralControl(selectedList.Title));
TableCell tableCell2 = new TableCell();
foreach (Microsoft.SharePoint.Client.ListItem item in listItems)
{
tableCell2.Text += item.FieldValues["Title"] + "<br>";
}
tableRow.Cells.Add(tableCell1);
tableRow.Cells.Add(tableCell2);
ListTable.Rows.Add(tableRow);
}
//This method adds a list with the specified title.
private void AddList(string accessToken, string newListName)
{
if (IsPostBack)
{
sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
}
//Execute a request to add a list that has the user-supplied name.
ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
Web web = clientContext.Web;
ListCollection lists = web.Lists;
ListCreationInformation listCreationInfo = new ListCreationInformation();
listCreationInfo.Title = newListName;
listCreationInfo.TemplateType = (int)ListTemplateType.GenericList;
lists.Add(listCreationInfo);
clientContext.Load<ListCollection>(lists);
try
{
clientContext.ExecuteQuery();
}
catch (Exception e)
{
AddListNameBox.Text = e.Message;
}
RetrieveLists(accessToken);
}
//This method adds a list item to the specified list.
private void AddListItem(string accessToken, Guid listId, string newItemName)
{
if (IsPostBack)
{
sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
}
//Execute a request to add a list item.
ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
Web web = clientContext.Web;
ListCollection lists = web.Lists;
List selectedList = lists.GetById(listId);
clientContext.Load<ListCollection>(lists);
clientContext.Load<List>(selectedList);
ListItemCreationInformation listItemCreationInfo = new ListItemCreationInformation();
var listItem = selectedList.AddItem(listItemCreationInfo);
listItem["Title"] = newItemName;
listItem.Update();
clientContext.ExecuteQuery();
RetrieveListItems(accessToken, listId);
}
private void ChangeListTitle(string accessToken, Guid listId, string newListTitle)
{
if (IsPostBack)
{
sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
}
//Execute a request to change the title of the specified list.
ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
Web web = clientContext.Web;
ListCollection lists = web.Lists;
List selectedList = lists.GetById(listId);
clientContext.Load<ListCollection>(lists);
clientContext.Load<List>(selectedList);
selectedList.Title = newListTitle;
selectedList.Update();
clientContext.ExecuteQuery();
RetrieveListItems(accessToken, listId);
}
private void DeleteList(string accessToken, Guid listId)
{
if (IsPostBack)
{
sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
}
//Execute a request to delete the specified list.
ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
Web web = clientContext.Web;
ListCollection lists = web.Lists;
List selectedList = lists.GetById(listId);
clientContext.Load<ListCollection>(lists);
clientContext.Load<List>(selectedList);
selectedList.DeleteObject();
clientContext.ExecuteQuery();
RetrieveListNameBox.Text = "";
RetrieveLists(accessToken);
}
protected void AddList_Click(object sender, EventArgs e)
{
string commandAccessToken = ((Button)sender).CommandArgument;
if (AddListNameBox.Text != "")
{
AddList(commandAccessToken, AddListNameBox.Text);
}
else
{
AddListNameBox.Text = "Enter a list title";
}
}
protected void RefreshList_Click(object sender, EventArgs e)
{
string commandAccessToken = ((Button)sender).CommandArgument;
RetrieveLists(commandAccessToken);
}
protected void RetrieveListButton_Click(object sender, EventArgs e)
{
string commandAccessToken = ((Button)sender).CommandArgument;
Guid listId = new Guid();
if (Guid.TryParse(RetrieveListNameBox.Text, out listId))
{
RetrieveListItems(commandAccessToken, listId);
}
else
{
RetrieveListNameBox.Text = "Enter a List GUID";
}
}
protected void AddItemButton_Click(object sender, EventArgs e)
{
string commandAccessToken = ((Button)sender).CommandArgument;
Guid listId = new Guid(RetrieveListNameBox.Text);
if (AddListItemBox.Text != "")
{
AddListItem(commandAccessToken, listId, AddListItemBox.Text);
}
else
{
AddListItemBox.Text = "Enter an item title";
}
}
protected void DeleteListButton_Click(object sender, EventArgs e)
{
string commandAccessToken = ((Button)sender).CommandArgument;
Guid listId = new Guid(RetrieveListNameBox.Text);
DeleteList(commandAccessToken, listId);
}
protected void ChangeListTitleButton_Click(object sender, EventArgs e)
{
string commandAccessToken = ((Button)sender).CommandArgument;
Guid listId = new Guid(RetrieveListNameBox.Text);
if (ChangeListTitleBox.Text != null)
{
ChangeListTitle(commandAccessToken, listId, ChangeListTitleBox.Text);
}
else
{
ChangeListTitleBox.Text = "Enter a new list title";
}
}
}
}
/*
SharePoint-Add-in-CSOM-BasicDataOperations, http://github/officedev/SharePoint-Add-in-CSOM-BasicDataOperations
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License:
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
| |
// 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Common;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Versions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.TodoComments
{
internal partial class TodoCommentIncrementalAnalyzer : IIncrementalAnalyzer
{
public const string Name = "Todo Comment Document Worker";
private readonly TodoCommentIncrementalAnalyzerProvider _owner;
private readonly Workspace _workspace;
private readonly TodoCommentTokens _todoCommentTokens;
private readonly TodoCommentState _state;
public TodoCommentIncrementalAnalyzer(Workspace workspace, TodoCommentIncrementalAnalyzerProvider owner, TodoCommentTokens todoCommentTokens)
{
_workspace = workspace;
_owner = owner;
_todoCommentTokens = todoCommentTokens;
_state = new TodoCommentState();
}
public Task DocumentResetAsync(Document document, CancellationToken cancellationToken)
{
// remove cache
_state.Remove(document.Id);
return _state.PersistAsync(document, new Data(VersionStamp.Default, VersionStamp.Default, ImmutableArray<TodoItem>.Empty), cancellationToken);
}
public async Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken)
{
// it has an assumption that this will not be called concurrently for same document.
// in fact, in current design, it won't be even called concurrently for different documents.
// but, can be called concurrently for different documents in future if we choose to.
Contract.ThrowIfFalse(document.IsFromPrimaryBranch());
if (!document.Options.GetOption(InternalFeatureOnOffOptions.TodoComments))
{
return;
}
// use tree version so that things like compiler option changes are considered
var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
var syntaxVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false);
var existingData = await _state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false);
if (existingData != null)
{
// check whether we can use the data as it is (can happen when re-using persisted data from previous VS session)
if (CheckVersions(document, textVersion, syntaxVersion, existingData))
{
Contract.Requires(_workspace == document.Project.Solution.Workspace);
RaiseTaskListUpdated(_workspace, document.Project.Solution, document.Id, existingData.Items);
return;
}
}
var service = document.GetLanguageService<ITodoCommentService>();
if (service == null)
{
return;
}
var comments = await service.GetTodoCommentsAsync(document, _todoCommentTokens.GetTokens(document), cancellationToken).ConfigureAwait(false);
var items = await CreateItemsAsync(document, comments, cancellationToken).ConfigureAwait(false);
var data = new Data(textVersion, syntaxVersion, items);
await _state.PersistAsync(document, data, cancellationToken).ConfigureAwait(false);
// * NOTE * cancellation can't throw after this point.
if (existingData == null || existingData.Items.Length > 0 || data.Items.Length > 0)
{
Contract.Requires(_workspace == document.Project.Solution.Workspace);
RaiseTaskListUpdated(_workspace, document.Project.Solution, document.Id, data.Items);
}
}
private async Task<ImmutableArray<TodoItem>> CreateItemsAsync(Document document, IList<TodoComment> comments, CancellationToken cancellationToken)
{
var items = ImmutableArray.CreateBuilder<TodoItem>();
if (comments != null)
{
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var syntaxTree = document.SupportsSyntaxTree ? await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false) : null;
foreach (var comment in comments)
{
items.Add(CreateItem(document, text, syntaxTree, comment));
}
}
return items.ToImmutable();
}
private TodoItem CreateItem(Document document, SourceText text, SyntaxTree tree, TodoComment comment)
{
// make sure given position is within valid text range.
var textSpan = new TextSpan(Math.Min(text.Length, Math.Max(0, comment.Position)), 0);
var location = tree == null ? Location.Create(document.FilePath, textSpan, text.Lines.GetLinePositionSpan(textSpan)) : tree.GetLocation(textSpan);
var originalLineInfo = location.GetLineSpan();
var mappedLineInfo = location.GetMappedLineSpan();
return new TodoItem(
comment.Descriptor.Priority,
comment.Message,
document.Project.Solution.Workspace,
document.Id,
mappedLine: mappedLineInfo.StartLinePosition.Line,
originalLine: originalLineInfo.StartLinePosition.Line,
mappedColumn: mappedLineInfo.StartLinePosition.Character,
originalColumn: originalLineInfo.StartLinePosition.Character,
mappedFilePath: mappedLineInfo.GetMappedFilePathIfExist(),
originalFilePath: document.FilePath);
}
public ImmutableArray<TodoItem> GetTodoItems(Workspace workspace, DocumentId id, CancellationToken cancellationToken)
{
var document = workspace.CurrentSolution.GetDocument(id);
if (document == null)
{
return ImmutableArray<TodoItem>.Empty;
}
// TODO let's think about what to do here. for now, let call it synchronously. also, there is no actual async-ness for the
// TryGetExistingDataAsync, API just happen to be async since our persistent API is async API. but both caller and implementor are
// actually not async.
var existingData = _state.TryGetExistingDataAsync(document, cancellationToken).WaitAndGetResult(cancellationToken);
if (existingData == null)
{
return ImmutableArray<TodoItem>.Empty;
}
return existingData.Items;
}
public IEnumerable<UpdatedEventArgs> GetTodoItemsUpdatedEventArgs(Workspace workspace, CancellationToken cancellationToken)
{
foreach (var documentId in _state.GetDocumentIds())
{
yield return new UpdatedEventArgs(Tuple.Create(this, documentId), workspace, documentId.ProjectId, documentId);
}
}
private static bool CheckVersions(Document document, VersionStamp textVersion, VersionStamp syntaxVersion, Data existingData)
{
// first check full version to see whether we can reuse data in same session, if we can't, check timestamp only version to see whether
// we can use it cross-session.
return document.CanReusePersistedTextVersion(textVersion, existingData.TextVersion) &&
document.CanReusePersistedSyntaxTreeVersion(syntaxVersion, existingData.SyntaxVersion);
}
internal ImmutableArray<TodoItem> GetItems_TestingOnly(DocumentId documentId)
{
return _state.GetItems_TestingOnly(documentId);
}
private void RaiseTaskListUpdated(Workspace workspace, Solution solution, DocumentId documentId, ImmutableArray<TodoItem> items)
{
if (_owner != null)
{
_owner.RaiseTaskListUpdated(documentId, workspace, solution, documentId.ProjectId, documentId, items);
}
}
public void RemoveDocument(DocumentId documentId)
{
_state.Remove(documentId);
RaiseTaskListUpdated(_workspace, null, documentId, ImmutableArray<TodoItem>.Empty);
}
public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e)
{
return e.Option == TodoCommentOptions.TokenList;
}
private class Data
{
public readonly VersionStamp TextVersion;
public readonly VersionStamp SyntaxVersion;
public readonly ImmutableArray<TodoItem> Items;
public Data(VersionStamp textVersion, VersionStamp syntaxVersion, ImmutableArray<TodoItem> items)
{
this.TextVersion = textVersion;
this.SyntaxVersion = syntaxVersion;
this.Items = items;
}
}
#region not used
public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public void RemoveProject(ProjectId projectId)
{
}
#endregion
}
}
| |
//-----------------------------------------------------------------------------
//
// <copyright file="AnnotationResource.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description:
// Resource represents a portion of content. It can refer to the content
// or directly contain the content, or both. They are used to model anchors
// and cargos of annotations.
//
// Spec: http://team/sites/ag/Specifications/Simplifying%20Store%20Cache%20Model.doc
//
// History:
// 10/04/2002: rruiz: Added header comment to ObjectModel.cs
// 07/03/2003: magedz: Renamed Link, LinkSequence to LocatorPart and Locator
// respectively.
// 05/31/2003: LGolding: Ported to WCP tree.
// 07/15/2003: rruiz: Rewrote implementations to extend abstract classes
// instead of implement interfaces; got rid of obsolete
// classes; put each class in separate file.
// 12/09/2003: ssimova: Added ResourceId
// 6/30/2004: rruiz: Made the class concrete, updated the APIs to be more type
// safe, made the class Xml serializable.
//
//-----------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Windows.Annotations.Storage;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using MS.Internal;
using MS.Internal.Annotations;
namespace System.Windows.Annotations
{
/// <summary>
/// Resource represents a portion of content. It can refer to the content
/// or directly contain the content, or both. They are used to model anchors
/// and cargos of annotations.
/// </summary>
[XmlRoot(Namespace = AnnotationXmlConstants.Namespaces.CoreSchemaNamespace, ElementName = AnnotationXmlConstants.Elements.Resource)]
public sealed class AnnotationResource : IXmlSerializable, INotifyPropertyChanged2, IOwnedObject
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// Creates an instance of Resource.
/// </summary>
public AnnotationResource()
{
_id = Guid.NewGuid();
}
/// <summary>
/// Creates an instance of Resource with specified name.
/// </summary>
/// <param name="name">name used to distinguish this Resource
/// from others in the same annotation; no validation is performed on the name</param>
/// <exception cref="ArgumentNullException">name is null</exception>
public AnnotationResource(string name)
: this()
{
if (name == null)
{
throw new ArgumentNullException("name");
}
_name = name;
_id = Guid.NewGuid();
}
/// <summary>
/// Creates an instance of Resource with the specified Guid as its Id.
/// This constructor is for store implementations that use their own
/// method of serialization and need a way to create a Resource with
/// the correct read-only data.
/// </summary>
/// <param name="id">the new Resource's id</param>
/// <exception cref="ArgumentException">id is equal to Guid.Empty</exception>
public AnnotationResource(Guid id)
{
if (Guid.Empty.Equals(id))
throw new ArgumentException(SR.Get(SRID.InvalidGuid), "id");
// Guid is a struct and cannot be null
_id = id;
}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
#region IXmlSerializable Implementation
/// <summary>
/// Returns the null. The annotations schema can be found at
/// http://schemas.microsoft.com/windows/annotations/2003/11/core.
/// </summary>
public XmlSchema GetSchema()
{
return null;
}
/// <summary>
/// Serializes this Resource to XML with the passed in XmlWriter.
/// </summary>
/// <param name="writer">the writer to serialize the Resource to</param>
/// <exception cref="ArgumentNullException">writer is null</exception>
public void WriteXml(XmlWriter writer)
{
if (writer == null)
{
throw new ArgumentNullException("writer");
}
if (String.IsNullOrEmpty(writer.LookupPrefix(AnnotationXmlConstants.Namespaces.CoreSchemaNamespace)))
{
writer.WriteAttributeString(AnnotationXmlConstants.Prefixes.XmlnsPrefix, AnnotationXmlConstants.Prefixes.CoreSchemaPrefix, null, AnnotationXmlConstants.Namespaces.CoreSchemaNamespace);
}
writer.WriteAttributeString(AnnotationXmlConstants.Attributes.Id, XmlConvert.ToString(_id));
if (_name != null)
{
writer.WriteAttributeString(AnnotationXmlConstants.Attributes.ResourceName, _name);
}
// Use the actual field here to avoid creating the collection for no reason
if (_locators != null)
{
foreach (ContentLocatorBase locator in _locators)
{
if (locator != null)
{
if (locator is ContentLocatorGroup)
{
LocatorGroupSerializer.Serialize(writer, locator);
}
else
{
ListSerializer.Serialize(writer, locator);
}
}
}
}
// Use the actual field here to avoid creating the collection for no reason
if (_contents != null)
{
foreach (XmlElement content in _contents)
{
if (content != null)
{
content.WriteTo(writer);
}
}
}
}
/// <summary>
/// Deserializes an Resource from the XmlReader passed in.
/// </summary>
/// <param name="reader">reader to deserialize from</param>
/// <exception cref="ArgumentNullException">reader is null</exception>
public void ReadXml(XmlReader reader)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
XmlDocument doc = new XmlDocument();
ReadAttributes(reader);
if (!reader.IsEmptyElement)
{
reader.Read(); // Reads the remainder of "Resource" start tag
while (!(AnnotationXmlConstants.Elements.Resource == reader.LocalName && XmlNodeType.EndElement == reader.NodeType))
{
if (AnnotationXmlConstants.Elements.ContentLocatorGroup == reader.LocalName)
{
ContentLocatorBase locator = (ContentLocatorBase)LocatorGroupSerializer.Deserialize(reader);
InternalLocators.Add(locator);
}
else if (AnnotationXmlConstants.Elements.ContentLocator == reader.LocalName)
{
ContentLocatorBase locator = (ContentLocatorBase)ListSerializer.Deserialize(reader);
InternalLocators.Add(locator);
}
else if (XmlNodeType.Element == reader.NodeType)
{
XmlElement element = doc.ReadNode(reader) as XmlElement;
InternalContents.Add(element);
}
else
{
// The resource must contain a non-XmlElement child such as plain
// text which is not part of the schema.
throw new XmlException(SR.Get(SRID.InvalidXmlContent, AnnotationXmlConstants.Elements.Resource));
}
}
}
reader.Read(); // Reads the end of the "Resource" element (or whole element if empty)
}
#endregion IXmlSerializable Implementation
#endregion Public Methods
//------------------------------------------------------
//
// Public Operators
//
//------------------------------------------------------
//------------------------------------------------------
//
// Public Events
//
//------------------------------------------------------
#region Public Events
/// <summary>
///
/// </summary>
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
{
add{ _propertyChanged += value; }
remove{ _propertyChanged -= value; }
}
#endregion Public Events
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
/// <summary>
/// A Resource is given a unique Guid when it is first instantiated.
/// </summary>
/// <returns>the unique id of this Resource; this property will return an
/// invalid Guid if the Resource was instantied with the default constructor -
/// which should not be used directly</returns>
public Guid Id
{
get
{
return _id;
}
}
/// <summary>
/// The name given this Resource to distinguish it from other anchors or
/// cargos in an annotation.
/// </summary>
/// <value>the name of this resource; can be null</value>
public string Name
{
get
{
return _name;
}
set
{
bool changed = false;
if (_name == null)
{
if (value != null)
{
changed = true;
}
}
else if (!_name.Equals(value))
{
changed = true;
}
_name = value;
if (changed)
{
FireResourceChanged("Name");
}
}
}
/// <summary>
/// Collection of zero or more Locators in this Resource.
/// </summary>
/// <returns>collection of Locators; never returns null</returns>
public Collection<ContentLocatorBase> ContentLocators
{
get
{
return InternalLocators;
}
}
/// <summary>
/// Collection of zero or more XmlElements representing the
/// contents of this Resource.
/// </summary>
/// <returns>collection of XmlElements which are the contents of
/// this resource; never returns null</returns>
public Collection<XmlElement> Contents
{
get
{
return InternalContents;
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
bool IOwnedObject.Owned
{
get
{
return _owned;
}
set
{
_owned = value;
}
}
/// <summary>
/// Returns serializer for ContentLocator objects. Lazily
/// creates the serializer for cases where its not needed.
/// The property is internal so that other classes (ContentLocatorGroup)
/// has access to the same serializer.
/// </summary>
internal static Serializer ListSerializer
{
get
{
if (s_ListSerializer == null)
{
s_ListSerializer = new Serializer(typeof(ContentLocator));
}
return s_ListSerializer;
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Private Properties
//
//------------------------------------------------------
#region Private Properties
/// <summary>
/// Returns the list of locators - used internally to
/// lazily create the list when its needed.
/// </summary>
private AnnotationObservableCollection<ContentLocatorBase> InternalLocators
{
get
{
if (_locators == null)
{
_locators = new AnnotationObservableCollection<ContentLocatorBase>();
_locators.CollectionChanged += OnLocatorsChanged;
}
return _locators;
}
}
/// <summary>
/// Returns the list of contents - used internally to
/// lazily create the list when its needed.
/// </summary>
private XmlElementCollection InternalContents
{
get
{
if (_contents == null)
{
_contents = new XmlElementCollection();
_contents.CollectionChanged += OnContentsChanged;
}
return _contents;
}
}
/// <summary>
/// Returns serializer for ContentLocatorGroup objects. Lazily creates
/// the serializer for cases where its not needed.
/// </summary>
private static Serializer LocatorGroupSerializer
{
get
{
if (s_LocatorGroupSerializer == null)
{
s_LocatorGroupSerializer = new Serializer(typeof(ContentLocatorGroup));
}
return s_LocatorGroupSerializer;
}
}
#endregion Private Properties
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
/// <summary>
/// Reads all attributes for the "Resource" element and throws
/// appropriate exceptions if any required attributes are missing
/// or unexpected attributes are found
/// </summary>
private void ReadAttributes(XmlReader reader)
{
Invariant.Assert(reader != null, "No reader passed in.");
// Use a temporary variable to determine if a Guid value
// was actually provided. The member variable is set in
// the default ctor and can't be relied on for this.
Guid tempId = Guid.Empty;
// Read all the attributes
while (reader.MoveToNextAttribute())
{
string value = reader.Value;
// Skip null values - they will be treated the same as if
// they weren't specified at all
if (value == null)
continue;
switch (reader.LocalName)
{
case AnnotationXmlConstants.Attributes.Id:
tempId = XmlConvert.ToGuid(value);
break;
case AnnotationXmlConstants.Attributes.ResourceName:
_name = value;
break;
default:
if (!Annotation.IsNamespaceDeclaration(reader))
throw new XmlException(SR.Get(SRID.UnexpectedAttribute, reader.LocalName, AnnotationXmlConstants.Elements.Resource));
break;
}
}
if (Guid.Empty.Equals(tempId))
{
throw new XmlException(SR.Get(SRID.RequiredAttributeMissing, AnnotationXmlConstants.Attributes.Id, AnnotationXmlConstants.Elements.Resource));
}
_id = tempId;
// Name attribute is optional, so no need to check it
// Move back to the parent "Resource" element
reader.MoveToContent();
}
/// <summary>
/// Listens for change events from the list of locators. Fires a change event
/// for this resource when an event is received.
/// </summary>
private void OnLocatorsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
FireResourceChanged("Locators");
}
/// <summary>
/// Listens for change events from the list of contents. Fires a change event
/// for this resource when an event is received.
/// </summary>
private void OnContentsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
FireResourceChanged("Contents");
}
/// <summary>
/// Fires a change notification to the Annotation that contains
/// this Resource.
/// </summary>
private void FireResourceChanged(string name)
{
if (_propertyChanged != null)
{
_propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(name));
}
}
#endregion Private Methods
//------------------------------------------------------
//
// 2Private Fields
//
//------------------------------------------------------
#region Private Fields
/// <summary>
/// Unique ID for this resource
/// </summary>
private Guid _id;
/// <summary>
/// Name given this resource by the developer. Used to differentiate
/// between multiple resources on an annotation.
/// </summary>
private string _name;
/// <summary>
/// List of locators that refer to the data of this resource
/// </summary>
private AnnotationObservableCollection<ContentLocatorBase> _locators;
/// <summary>
/// List of instances of the data for this resource
/// </summary>
private XmlElementCollection _contents;
/// <summary>
/// Serializer we use for serializing and deserializing Locators.
/// </summary>
private static Serializer s_ListSerializer;
/// <summary>
/// Serializer we use for serializing and deserializing LocatorGroups.
/// </summary>
private static Serializer s_LocatorGroupSerializer;
/// <summary>
///
/// </summary>
private bool _owned;
/// <summary>
///
/// </summary>
private PropertyChangedEventHandler _propertyChanged;
#endregion Private Fields
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
namespace Internal.Cryptography.Pal
{
internal sealed class OpenSslX509Encoder : IX509Pal
{
public AsymmetricAlgorithm DecodePublicKey(Oid oid, byte[] encodedKeyValue, byte[] encodedParameters, ICertificatePal certificatePal)
{
if (oid.Value == Oids.Ecc && certificatePal != null)
{
return ((OpenSslX509CertificateReader)certificatePal).GetECDsaPublicKey();
}
switch (oid.Value)
{
case Oids.RsaRsa:
return BuildRsaPublicKey(encodedKeyValue);
}
// NotSupportedException is what desktop and CoreFx-Windows throw in this situation.
throw new NotSupportedException(SR.NotSupported_KeyAlgorithm);
}
public string X500DistinguishedNameDecode(byte[] encodedDistinguishedName, X500DistinguishedNameFlags flags)
{
return X500NameEncoder.X500DistinguishedNameDecode(encodedDistinguishedName, true, flags);
}
public byte[] X500DistinguishedNameEncode(string distinguishedName, X500DistinguishedNameFlags flag)
{
return X500NameEncoder.X500DistinguishedNameEncode(distinguishedName, flag);
}
public string X500DistinguishedNameFormat(byte[] encodedDistinguishedName, bool multiLine)
{
return X500NameEncoder.X500DistinguishedNameDecode(
encodedDistinguishedName,
true,
multiLine ? X500DistinguishedNameFlags.UseNewLines : X500DistinguishedNameFlags.None,
multiLine);
}
public X509ContentType GetCertContentType(byte[] rawData)
{
{
ICertificatePal certPal;
if (CertificatePal.TryReadX509Der(rawData, out certPal) ||
CertificatePal.TryReadX509Pem(rawData, out certPal))
{
certPal.Dispose();
return X509ContentType.Cert;
}
}
if (PkcsFormatReader.IsPkcs7(rawData))
{
return X509ContentType.Pkcs7;
}
{
OpenSslPkcs12Reader pfx;
if (OpenSslPkcs12Reader.TryRead(rawData, out pfx))
{
pfx.Dispose();
return X509ContentType.Pkcs12;
}
}
// Unsupported format.
// Windows throws new CryptographicException(CRYPT_E_NO_MATCH)
throw new CryptographicException();
}
public X509ContentType GetCertContentType(string fileName)
{
// If we can't open the file, fail right away.
using (SafeBioHandle fileBio = Interop.Crypto.BioNewFile(fileName, "rb"))
{
Interop.Crypto.CheckValidOpenSslHandle(fileBio);
int bioPosition = Interop.Crypto.BioTell(fileBio);
Debug.Assert(bioPosition >= 0);
// X509ContentType.Cert
{
ICertificatePal certPal;
if (CertificatePal.TryReadX509Der(fileBio, out certPal))
{
certPal.Dispose();
return X509ContentType.Cert;
}
CertificatePal.RewindBio(fileBio, bioPosition);
if (CertificatePal.TryReadX509Pem(fileBio, out certPal))
{
certPal.Dispose();
return X509ContentType.Cert;
}
CertificatePal.RewindBio(fileBio, bioPosition);
}
// X509ContentType.Pkcs7
{
if (PkcsFormatReader.IsPkcs7Der(fileBio))
{
return X509ContentType.Pkcs7;
}
CertificatePal.RewindBio(fileBio, bioPosition);
if (PkcsFormatReader.IsPkcs7Pem(fileBio))
{
return X509ContentType.Pkcs7;
}
CertificatePal.RewindBio(fileBio, bioPosition);
}
// X509ContentType.Pkcs12 (aka PFX)
{
OpenSslPkcs12Reader pkcs12Reader;
if (OpenSslPkcs12Reader.TryRead(fileBio, out pkcs12Reader))
{
pkcs12Reader.Dispose();
return X509ContentType.Pkcs12;
}
CertificatePal.RewindBio(fileBio, bioPosition);
}
}
// Unsupported format.
// Windows throws new CryptographicException(CRYPT_E_NO_MATCH)
throw new CryptographicException();
}
public byte[] EncodeX509KeyUsageExtension(X509KeyUsageFlags keyUsages)
{
// The numeric values of X509KeyUsageFlags mean that if we interpret it as a little-endian
// ushort it will line up with the flags in the spec.
ushort ushortValue = unchecked((ushort)(int)keyUsages);
byte[] data = BitConverter.GetBytes(ushortValue);
// RFC 3280 section 4.2.1.3 (https://tools.ietf.org/html/rfc3280#section-4.2.1.3) defines
// digitalSignature (0) through decipherOnly (8), making 9 named bits.
const int namedBitsCount = 9;
// The expected output of this method isn't the SEQUENCE value, but just the payload bytes.
byte[][] segments = DerEncoder.SegmentedEncodeNamedBitList(data, namedBitsCount);
Debug.Assert(segments.Length == 3);
return ConcatenateArrays(segments);
}
public void DecodeX509KeyUsageExtension(byte[] encoded, out X509KeyUsageFlags keyUsages)
{
using (SafeAsn1BitStringHandle bitString = Interop.Crypto.DecodeAsn1BitString(encoded, encoded.Length))
{
Interop.Crypto.CheckValidOpenSslHandle(bitString);
byte[] decoded = Interop.Crypto.GetAsn1StringBytes(bitString.DangerousGetHandle());
// Only 9 bits are defined.
if (decoded.Length > 2)
{
throw new CryptographicException();
}
// DER encodings of BIT_STRING values number the bits as
// 01234567 89 (big endian), plus a number saying how many bits of the last byte were padding.
//
// So digitalSignature (0) doesn't mean 2^0 (0x01), it means the most significant bit
// is set in this byte stream.
//
// BIT_STRING values are compact. So a value of cRLSign (6) | keyEncipherment (2), which
// is 0b0010001 => 0b0010 0010 (1 bit padding) => 0x22 encoded is therefore
// 0x02 (length remaining) 0x01 (1 bit padding) 0x22.
//
// OpenSSL's d2i_ASN1_BIT_STRING is going to take that, and return 0x22. 0x22 lines up
// exactly with X509KeyUsageFlags.CrlSign (0x20) | X509KeyUsageFlags.KeyEncipherment (0x02)
//
// Once the decipherOnly (8) bit is added to the mix, the values become:
// 0b001000101 => 0b0010 0010 1000 0000 (7 bits padding)
// { 0x03 0x07 0x22 0x80 }
// And OpenSSL returns new byte[] { 0x22 0x80 }
//
// The value of X509KeyUsageFlags.DecipherOnly is 0x8000. 0x8000 in a little endian
// representation is { 0x00 0x80 }. This means that the DER storage mechanism has effectively
// ended up being little-endian for BIT_STRING values. Untwist the bytes, and now the bits all
// line up with the existing X509KeyUsageFlags.
int value = 0;
if (decoded.Length > 0)
{
value = decoded[0];
}
if (decoded.Length > 1)
{
value |= decoded[1] << 8;
}
keyUsages = (X509KeyUsageFlags)value;
}
}
public bool SupportsLegacyBasicConstraintsExtension
{
get { return false; }
}
public byte[] EncodeX509BasicConstraints2Extension(
bool certificateAuthority,
bool hasPathLengthConstraint,
int pathLengthConstraint)
{
//BasicConstraintsSyntax::= SEQUENCE {
// cA BOOLEAN DEFAULT FALSE,
// pathLenConstraint INTEGER(0..MAX) OPTIONAL,
// ... }
List<byte[][]> segments = new List<byte[][]>(2);
if (certificateAuthority)
{
segments.Add(DerEncoder.SegmentedEncodeBoolean(true));
}
if (hasPathLengthConstraint)
{
byte[] pathLengthBytes = BitConverter.GetBytes(pathLengthConstraint);
// Little-Endian => Big-Endian
Array.Reverse(pathLengthBytes);
segments.Add(DerEncoder.SegmentedEncodeUnsignedInteger(pathLengthBytes));
}
return DerEncoder.ConstructSequence(segments);
}
public void DecodeX509BasicConstraintsExtension(
byte[] encoded,
out bool certificateAuthority,
out bool hasPathLengthConstraint,
out int pathLengthConstraint)
{
// No RFC nor ITU document describes the layout of the 2.5.29.10 structure,
// and OpenSSL doesn't have a decoder for it, either.
//
// Since it was never published as a standard (2.5.29.19 replaced it before publication)
// there shouldn't be too many people upset that we can't decode it for them on Unix.
throw new PlatformNotSupportedException(SR.NotSupported_LegacyBasicConstraints);
}
public void DecodeX509BasicConstraints2Extension(
byte[] encoded,
out bool certificateAuthority,
out bool hasPathLengthConstraint,
out int pathLengthConstraint)
{
if (!Interop.Crypto.DecodeX509BasicConstraints2Extension(
encoded,
encoded.Length,
out certificateAuthority,
out hasPathLengthConstraint,
out pathLengthConstraint))
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
}
public byte[] EncodeX509EnhancedKeyUsageExtension(OidCollection usages)
{
//extKeyUsage EXTENSION ::= {
// SYNTAX SEQUENCE SIZE(1..MAX) OF KeyPurposeId
// IDENTIFIED BY id - ce - extKeyUsage }
//
//KeyPurposeId::= OBJECT IDENTIFIER
List<byte[][]> segments = new List<byte[][]>(usages.Count);
foreach (Oid usage in usages)
{
segments.Add(DerEncoder.SegmentedEncodeOid(usage));
}
return DerEncoder.ConstructSequence(segments);
}
public void DecodeX509EnhancedKeyUsageExtension(byte[] encoded, out OidCollection usages)
{
OidCollection oids = new OidCollection();
using (SafeEkuExtensionHandle eku = Interop.Crypto.DecodeExtendedKeyUsage(encoded, encoded.Length))
{
Interop.Crypto.CheckValidOpenSslHandle(eku);
int count = Interop.Crypto.GetX509EkuFieldCount(eku);
for (int i = 0; i < count; i++)
{
IntPtr oidPtr = Interop.Crypto.GetX509EkuField(eku, i);
if (oidPtr == IntPtr.Zero)
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
string oidValue = Interop.Crypto.GetOidValue(oidPtr);
oids.Add(new Oid(oidValue));
}
}
usages = oids;
}
public byte[] EncodeX509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier)
{
//subjectKeyIdentifier EXTENSION ::= {
// SYNTAX SubjectKeyIdentifier
// IDENTIFIED BY id - ce - subjectKeyIdentifier }
//
//SubjectKeyIdentifier::= KeyIdentifier
//
//KeyIdentifier ::= OCTET STRING
byte[][] segments = DerEncoder.SegmentedEncodeOctetString(subjectKeyIdentifier);
// The extension is not a sequence, just the octet string
return ConcatenateArrays(segments);
}
public void DecodeX509SubjectKeyIdentifierExtension(byte[] encoded, out byte[] subjectKeyIdentifier)
{
subjectKeyIdentifier = DecodeX509SubjectKeyIdentifierExtension(encoded);
}
internal static byte[] DecodeX509SubjectKeyIdentifierExtension(byte[] encoded)
{
DerSequenceReader reader = DerSequenceReader.CreateForPayload(encoded);
return reader.ReadOctetString();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "SHA1 is required for Compat")]
public byte[] ComputeCapiSha1OfPublicKey(PublicKey key)
{
// The CapiSha1 value is the SHA-1 of the SubjectPublicKeyInfo field, inclusive
// of the DER structural bytes.
//SubjectPublicKeyInfo::= SEQUENCE {
// algorithm AlgorithmIdentifier{ { SupportedAlgorithms} },
// subjectPublicKey BIT STRING,
// ... }
//
//AlgorithmIdentifier{ ALGORITHM: SupportedAlgorithms} ::= SEQUENCE {
// algorithm ALGORITHM.&id({ SupportedAlgorithms}),
// parameters ALGORITHM.&Type({ SupportedAlgorithms}
// { @algorithm}) OPTIONAL,
// ... }
//
//ALGORITHM::= CLASS {
// &Type OPTIONAL,
// &id OBJECT IDENTIFIER UNIQUE }
//WITH SYNTAX {
// [&Type]
//IDENTIFIED BY &id }
// key.EncodedKeyValue corresponds to SubjectPublicKeyInfo.subjectPublicKey, except it
// has had the BIT STRING envelope removed.
//
// key.EncodedParameters corresponds to AlgorithmIdentifier.Parameters precisely
// (DER NULL for RSA, DER Constructed SEQUENCE for DSA)
byte[] empty = Array.Empty<byte>();
byte[][] algorithmOid = DerEncoder.SegmentedEncodeOid(key.Oid);
// Because ConstructSegmentedSequence doesn't look to see that it really is tag+length+value (but does check
// that the array has length 3), just hide the joined TLV triplet in the last element.
byte[][] segmentedParameters = { empty, empty, key.EncodedParameters.RawData };
byte[][] algorithmIdentifier = DerEncoder.ConstructSegmentedSequence(algorithmOid, segmentedParameters);
byte[][] subjectPublicKey = DerEncoder.SegmentedEncodeBitString(key.EncodedKeyValue.RawData);
using (SHA1 hash = SHA1.Create())
{
return hash.ComputeHash(
DerEncoder.ConstructSequence(
algorithmIdentifier,
subjectPublicKey));
}
}
private static RSA BuildRsaPublicKey(byte[] encodedData)
{
using (SafeRsaHandle rsaHandle = Interop.Crypto.DecodeRsaPublicKey(encodedData, encodedData.Length))
{
Interop.Crypto.CheckValidOpenSslHandle(rsaHandle);
RSAParameters rsaParameters = Interop.Crypto.ExportRsaParameters(rsaHandle, false);
RSA rsa = new RSAOpenSsl();
rsa.ImportParameters(rsaParameters);
return rsa;
}
}
private static byte[] ConcatenateArrays(byte[][] segments)
{
int length = 0;
foreach (byte[] segment in segments)
{
length += segment.Length;
}
byte[] concatenated = new byte[length];
int offset = 0;
foreach (byte[] segment in segments)
{
Buffer.BlockCopy(segment, 0, concatenated, offset, segment.Length);
offset += segment.Length;
}
return concatenated;
}
}
}
| |
/****************************************************************************
Tilde
Copyright (c) 2008 Tantalus Media Pty
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
namespace Tilde.Framework.Controls
{
public class TreeTableSubItem
{
private TreeTableNode m_owner;
private string m_text = "";
private Color m_foreColor;
private Font m_font;
public TreeTableSubItem()
{
}
public TreeTableSubItem(string label)
{
m_text = label;
}
public string Text
{
get { return m_text; }
set
{
if (m_text != value)
{
m_text = value;
if (m_owner != null && m_owner.Owner != null)
m_owner.Owner.NodeChangedSubItem(m_owner);
}
}
}
public Color ForeColor
{
get { return m_foreColor; }
set { m_foreColor = value; }
}
public Font Font
{
get { return m_font; }
set { m_font = value; }
}
internal TreeTableNode Owner
{
get { return m_owner; }
set { m_owner = value; }
}
}
public class TreeTableSubItemCollection : IList<TreeTableSubItem>
{
private TreeTableNode m_owner;
private List<TreeTableSubItem> m_list;
public TreeTableSubItemCollection(TreeTableNode owner)
{
m_owner = owner;
m_list = new List<TreeTableSubItem>();
}
private void OnRemove(TreeTableSubItem item)
{
item.Owner = null;
if (m_owner.Owner != null)
m_owner.Owner.NodeChangedSubItem(m_owner);
}
private void OnAdd(TreeTableSubItem item)
{
item.Owner = m_owner;
if (m_owner.Owner != null)
m_owner.Owner.NodeChangedSubItem(m_owner);
}
#region IList<TreeTableSubItemCollection> Members
public int IndexOf(TreeTableSubItem item)
{
return m_list.IndexOf(item);
}
public void Insert(int index, TreeTableSubItem item)
{
m_list.Insert(index, item);
OnAdd(item);
}
public void RemoveAt(int index)
{
TreeTableSubItem item = m_list[index];
m_list.RemoveAt(index);
OnRemove(item);
}
public TreeTableSubItem this[int index]
{
get
{
return m_list[index];
}
set
{
RemoveAt(index);
Insert(index, value);
}
}
#endregion
#region ICollection<TreeTableSubItemCollection> Members
public void Add(TreeTableSubItem item)
{
Insert(m_list.Count, item);
}
public void Add(string label)
{
Insert(m_list.Count, new TreeTableSubItem(label));
}
public void Clear()
{
foreach (TreeTableSubItem item in m_list)
{
OnRemove(item);
}
m_list.Clear();
}
public bool Contains(TreeTableSubItem item)
{
return m_list.Contains(item);
}
public void CopyTo(TreeTableSubItem[] array, int arrayIndex)
{
m_list.CopyTo(array, arrayIndex);
}
public int Count
{
get { return m_list.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(TreeTableSubItem item)
{
bool result = m_list.Remove(item);
if (result)
OnRemove(item);
return result;
}
#endregion
#region IEnumerable<TreeTableSubItemCollection> Members
public IEnumerator<TreeTableSubItem> GetEnumerator()
{
return m_list.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return m_list.GetEnumerator();
}
#endregion
}
}
| |
using System;
using System.IO;
using System.Security.Cryptography;
using ExcelDataReader.Core.OfficeCrypto;
using ExcelDataReader.Exceptions;
namespace ExcelDataReader.Core.BinaryFormat
{
/// <summary>
/// Represents a BIFF stream
/// </summary>
internal class XlsBiffStream : IDisposable
{
public XlsBiffStream(Stream baseStream, int offset = 0, int explicitVersion = 0, string password = null, byte[] secretKey = null, EncryptionInfo encryption = null)
{
BaseStream = baseStream;
Position = offset;
var bof = Read() as XlsBiffBOF;
if (bof != null)
{
BiffVersion = explicitVersion == 0 ? GetBiffVersion(bof) : explicitVersion;
BiffType = bof.Type;
}
CipherBlock = -1;
if (secretKey != null)
{
SecretKey = secretKey;
Encryption = encryption;
Cipher = Encryption.CreateCipher();
}
else
{
var filePass = Read() as XlsBiffFilePass;
if (filePass == null)
filePass = Read() as XlsBiffFilePass;
if (filePass != null)
{
Encryption = filePass.EncryptionInfo;
if (Encryption.VerifyPassword("VelvetSweatshop"))
{
// Magic password used for write-protected workbooks
password = "VelvetSweatshop";
}
else if (password == null || !Encryption.VerifyPassword(password))
{
throw new InvalidPasswordException(Errors.ErrorInvalidPassword);
}
SecretKey = Encryption.GenerateSecretKey(password);
Cipher = Encryption.CreateCipher();
}
}
Position = offset;
}
public int BiffVersion { get; }
public BIFFTYPE BiffType { get; }
/// <summary>
/// Gets the size of BIFF stream in bytes
/// </summary>
public int Size => (int)BaseStream.Length;
/// <summary>
/// Gets or sets the current position in BIFF stream
/// </summary>
public int Position { get => (int)BaseStream.Position; set => Seek(value, SeekOrigin.Begin); }
public Stream BaseStream { get; }
public byte[] SecretKey { get; }
public EncryptionInfo Encryption { get; }
public SymmetricAlgorithm Cipher { get; }
/// <summary>
/// Gets or sets the ICryptoTransform instance used to decrypt the current block
/// </summary>
public ICryptoTransform CipherTransform { get; set; }
/// <summary>
/// Gets or sets the current block number being decrypted with CipherTransform
/// </summary>
public int CipherBlock { get; set; }
/// <summary>
/// Sets stream pointer to the specified offset
/// </summary>
/// <param name="offset">Offset value</param>
/// <param name="origin">Offset origin</param>
public void Seek(int offset, SeekOrigin origin)
{
BaseStream.Seek(offset, origin);
if (Position < 0)
throw new ArgumentOutOfRangeException(string.Format("{0} On offset={1}", Errors.ErrorBiffIlegalBefore, offset));
if (Position > Size)
throw new ArgumentOutOfRangeException(string.Format("{0} On offset={1}", Errors.ErrorBiffIlegalAfter, offset));
if (SecretKey != null)
{
CreateBlockDecryptor(offset / 1024);
AlignBlockDecryptor(offset % 1024);
}
}
/// <summary>
/// Reads record under cursor and advances cursor position to next record
/// </summary>
/// <returns>The record -or- null.</returns>
public XlsBiffRecord Read()
{
// Minimum record size is 4
if ((uint)Position + 4 >= Size)
return null;
var record = GetRecord(BaseStream);
if (Position > Size)
{
record = null;
}
return record;
}
/// <summary>
/// Returns record at specified offset
/// </summary>
/// <param name="stream">The stream</param>
/// <returns>The record -or- null.</returns>
public XlsBiffRecord GetRecord(Stream stream)
{
var recordOffset = (int)stream.Position;
var header = new byte[4];
stream.Read(header, 0, 4);
var id = (BIFFRECORDTYPE)BitConverter.ToUInt16(header, 0);
int recordSize = BitConverter.ToUInt16(header, 2);
var bytes = new byte[4 + recordSize];
Array.Copy(header, bytes, 4);
stream.Read(bytes, 4, recordSize);
if (SecretKey != null)
DecryptRecord(recordOffset, id, bytes);
uint offset = 0;
int biffVersion = BiffVersion;
switch ((BIFFRECORDTYPE)id)
{
case BIFFRECORDTYPE.BOF_V2:
case BIFFRECORDTYPE.BOF_V3:
case BIFFRECORDTYPE.BOF_V4:
case BIFFRECORDTYPE.BOF:
return new XlsBiffBOF(bytes, offset);
case BIFFRECORDTYPE.EOF:
return new XlsBiffEof(bytes, offset);
case BIFFRECORDTYPE.INTERFACEHDR:
return new XlsBiffInterfaceHdr(bytes, offset);
case BIFFRECORDTYPE.SST:
return new XlsBiffSST(bytes, offset);
case BIFFRECORDTYPE.INDEX:
return new XlsBiffIndex(bytes, offset, biffVersion == 8);
case BIFFRECORDTYPE.DEFAULTROWHEIGHT_V2:
case BIFFRECORDTYPE.DEFAULTROWHEIGHT:
return new XlsBiffDefaultRowHeight(bytes, offset, biffVersion);
case BIFFRECORDTYPE.ROW_V2:
case BIFFRECORDTYPE.ROW:
return new XlsBiffRow(bytes, offset);
case BIFFRECORDTYPE.DBCELL:
return new XlsBiffDbCell(bytes, offset);
case BIFFRECORDTYPE.BOOLERR:
case BIFFRECORDTYPE.BOOLERR_OLD:
case BIFFRECORDTYPE.BLANK:
case BIFFRECORDTYPE.BLANK_OLD:
return new XlsBiffBlankCell(bytes, offset, biffVersion);
case BIFFRECORDTYPE.MULBLANK:
return new XlsBiffMulBlankCell(bytes, offset, biffVersion);
case BIFFRECORDTYPE.LABEL_OLD:
case BIFFRECORDTYPE.LABEL:
case BIFFRECORDTYPE.RSTRING:
return new XlsBiffLabelCell(bytes, offset, biffVersion);
case BIFFRECORDTYPE.LABELSST:
return new XlsBiffLabelSSTCell(bytes, offset, biffVersion);
case BIFFRECORDTYPE.INTEGER:
case BIFFRECORDTYPE.INTEGER_OLD:
return new XlsBiffIntegerCell(bytes, offset, biffVersion);
case BIFFRECORDTYPE.NUMBER:
case BIFFRECORDTYPE.NUMBER_OLD:
return new XlsBiffNumberCell(bytes, offset, biffVersion);
case BIFFRECORDTYPE.RK:
return new XlsBiffRKCell(bytes, offset, biffVersion);
case BIFFRECORDTYPE.MULRK:
return new XlsBiffMulRKCell(bytes, offset, biffVersion);
case BIFFRECORDTYPE.FORMULA:
case BIFFRECORDTYPE.FORMULA_V3:
case BIFFRECORDTYPE.FORMULA_V4:
return new XlsBiffFormulaCell(bytes, offset, biffVersion);
case BIFFRECORDTYPE.FORMAT_V23:
case BIFFRECORDTYPE.FORMAT:
return new XlsBiffFormatString(bytes, offset, biffVersion);
case BIFFRECORDTYPE.STRING:
case BIFFRECORDTYPE.STRING_OLD:
return new XlsBiffFormulaString(bytes, offset, biffVersion);
case BIFFRECORDTYPE.CONTINUE:
return new XlsBiffContinue(bytes, offset);
case BIFFRECORDTYPE.DIMENSIONS:
case BIFFRECORDTYPE.DIMENSIONS_V2:
return new XlsBiffDimensions(bytes, offset, biffVersion);
case BIFFRECORDTYPE.BOUNDSHEET:
return new XlsBiffBoundSheet(bytes, offset, biffVersion);
case BIFFRECORDTYPE.WINDOW1:
return new XlsBiffWindow1(bytes, offset);
case BIFFRECORDTYPE.CODEPAGE:
return new XlsBiffSimpleValueRecord(bytes, offset);
case BIFFRECORDTYPE.FNGROUPCOUNT:
return new XlsBiffSimpleValueRecord(bytes, offset);
case BIFFRECORDTYPE.RECORD1904:
return new XlsBiffSimpleValueRecord(bytes, offset);
case BIFFRECORDTYPE.BOOKBOOL:
return new XlsBiffSimpleValueRecord(bytes, offset);
case BIFFRECORDTYPE.BACKUP:
return new XlsBiffSimpleValueRecord(bytes, offset);
case BIFFRECORDTYPE.HIDEOBJ:
return new XlsBiffSimpleValueRecord(bytes, offset);
case BIFFRECORDTYPE.USESELFS:
return new XlsBiffSimpleValueRecord(bytes, offset);
case BIFFRECORDTYPE.UNCALCED:
return new XlsBiffUncalced(bytes, offset);
case BIFFRECORDTYPE.QUICKTIP:
return new XlsBiffQuickTip(bytes, offset);
case BIFFRECORDTYPE.MSODRAWING:
return new XlsBiffMSODrawing(bytes, offset);
case BIFFRECORDTYPE.FILEPASS:
return new XlsBiffFilePass(bytes, offset, biffVersion);
case BIFFRECORDTYPE.HEADER:
case BIFFRECORDTYPE.FOOTER:
return new XlsBiffHeaderFooterString(bytes, offset, biffVersion);
case BIFFRECORDTYPE.CODENAME:
return new XlsBiffCodeName(bytes, offset);
case BIFFRECORDTYPE.XF:
case BIFFRECORDTYPE.XF_V2:
case BIFFRECORDTYPE.XF_V3:
case BIFFRECORDTYPE.XF_V4:
return new XlsBiffXF(bytes, offset, biffVersion);
case BIFFRECORDTYPE.FONT:
return new XlsBiffFont(bytes, offset, biffVersion);
case BIFFRECORDTYPE.MERGECELLS:
return new XlsBiffMergeCells(bytes, offset);
case BIFFRECORDTYPE.COLINFO:
return new XlsBiffColInfo(bytes, offset);
default:
return new XlsBiffRecord(bytes, offset);
}
}
public void Dispose()
{
CipherTransform?.Dispose();
((IDisposable)Cipher)?.Dispose();
}
private int GetBiffVersion(XlsBiffBOF bof)
{
switch (bof.Id)
{
case BIFFRECORDTYPE.BOF_V2:
return 2;
case BIFFRECORDTYPE.BOF_V3:
return 3;
case BIFFRECORDTYPE.BOF_V4:
return 4;
case BIFFRECORDTYPE.BOF:
if (bof.Version == 0x200)
return 2;
else if (bof.Version == 0x300)
return 3;
else if (bof.Version == 0x400)
return 4;
else if (bof.Version == 0x500 || bof.Version == 0)
return 5;
if (bof.Version == 0x600)
return 8;
break;
}
return 0;
}
/// <summary>
/// Create an ICryptoTransform instance to decrypt a 1024-byte block
/// </summary>
private void CreateBlockDecryptor(int blockNumber)
{
CipherTransform?.Dispose();
var blockKey = Encryption.GenerateBlockKey(blockNumber, SecretKey);
CipherTransform = Cipher.CreateDecryptor(blockKey, null);
CipherBlock = blockNumber;
}
/// <summary>
/// Decrypt some dummy bytes to align the decryptor with the position in the current 1024-byte block
/// </summary>
private void AlignBlockDecryptor(int blockOffset)
{
var bytes = new byte[blockOffset];
CryptoHelpers.DecryptBytes(CipherTransform, bytes);
}
private void DecryptRecord(int startPosition, BIFFRECORDTYPE id, byte[] bytes)
{
// Decrypt the last read record, find it's start offset relative to the current stream position
int startDecrypt = 4;
int recordSize = bytes.Length;
switch (id)
{
case BIFFRECORDTYPE.BOF:
case BIFFRECORDTYPE.FILEPASS:
case BIFFRECORDTYPE.INTERFACEHDR:
startDecrypt = recordSize;
break;
case BIFFRECORDTYPE.BOUNDSHEET:
startDecrypt += 4; // For some reason the sheet offset is not encrypted
break;
}
var position = 0;
while (position < recordSize)
{
var offset = startPosition + position;
int blockNumber = offset / 1024;
var blockOffset = offset % 1024;
if (blockNumber != CipherBlock)
{
CreateBlockDecryptor(blockNumber);
}
if (Encryption.IsXor)
{
// Bypass everything and hook into the XorTransform instance to set the XorArrayIndex pr record.
// This is a hack to use the XorTransform otherwise transparently to the other encryption methods.
var xorTransform = (XorManaged.XorTransform)CipherTransform;
xorTransform.XorArrayIndex = offset + recordSize - 4;
}
// Decrypt at most up to the next 1024 byte boundary
var chunkSize = (int)Math.Min(recordSize - position, 1024 - blockOffset);
var block = new byte[chunkSize];
Array.Copy(bytes, position, block, 0, chunkSize);
var decryptedblock = CryptoHelpers.DecryptBytes(CipherTransform, block);
for (var i = 0; i < decryptedblock.Length; i++)
{
if (position >= startDecrypt)
bytes[position] = decryptedblock[i];
position++;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using Xunit;
public class ValueTupleTests
{
private class ValueTupleTestDriver<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>
{
private int _nItems;
private readonly object valueTuple;
private readonly ValueTuple valueTuple0;
private readonly ValueTuple<T1> valueTuple1;
private readonly ValueTuple<T1, T2> valueTuple2;
private readonly ValueTuple<T1, T2, T3> valueTuple3;
private readonly ValueTuple<T1, T2, T3, T4> valueTuple4;
private readonly ValueTuple<T1, T2, T3, T4, T5> valueTuple5;
private readonly ValueTuple<T1, T2, T3, T4, T5, T6> valueTuple6;
private readonly ValueTuple<T1, T2, T3, T4, T5, T6, T7> valueTuple7;
private readonly ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> valueTuple8;
private readonly ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9>> valueTuple9;
private readonly ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10>> valueTuple10;
internal ValueTupleTestDriver(params object[] values)
{
if (values.Length > 10)
throw new ArgumentOutOfRangeException(nameof(values), "You must provide at most 10 values");
_nItems = values.Length;
switch (_nItems)
{
case 0:
valueTuple0 = ValueTuple.Create();
valueTuple = valueTuple0;
break;
case 1:
valueTuple1 = ValueTuple.Create((T1)values[0]);
valueTuple = valueTuple1;
break;
case 2:
valueTuple2 = ValueTuple.Create((T1)values[0], (T2)values[1]);
valueTuple = valueTuple2;
break;
case 3:
valueTuple3 = ValueTuple.Create((T1)values[0], (T2)values[1], (T3)values[2]);
valueTuple = valueTuple3;
break;
case 4:
valueTuple4 = ValueTuple.Create((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3]);
valueTuple = valueTuple4;
break;
case 5:
valueTuple5 = ValueTuple.Create((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3], (T5)values[4]);
valueTuple = valueTuple5;
break;
case 6:
valueTuple6 = ValueTuple.Create((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3],
(T5)values[4], (T6)values[5]);
valueTuple = valueTuple6;
break;
case 7:
valueTuple7 = ValueTuple.Create((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3],
(T5)values[4], (T6)values[5], (T7)values[6]);
valueTuple = valueTuple7;
break;
case 8:
valueTuple8 = ValueTuple.Create((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3],
(T5)values[4], (T6)values[5], (T7)values[6], ValueTuple.Create((T8)values[7]));
valueTuple = valueTuple8;
break;
case 9:
valueTuple9 = ValueTuple.Create((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3],
(T5)values[4], (T6)values[5], (T7)values[6], ValueTuple.Create((T8)values[7], (T9)values[8]));
valueTuple = valueTuple9;
break;
case 10:
valueTuple10 = ValueTuple.Create((T1)values[0], (T2)values[1], (T3)values[2], (T4)values[3],
(T5)values[4], (T6)values[5], (T7)values[6], ValueTuple.Create((T8)values[7], (T9)values[8], (T10)values[9]));
valueTuple = valueTuple10;
break;
}
}
private void VerifyItem(int itemPos, object Item1, object Item2)
{
Assert.True(object.Equals(Item1, Item2));
}
public void TestConstructor(params object[] expectedValue)
{
if (expectedValue.Length != _nItems)
throw new ArgumentOutOfRangeException("expectedValues", "You must provide " + _nItems + " expectedvalues");
switch (_nItems)
{
case 0:
break;
case 1:
VerifyItem(1, valueTuple1.Item1, expectedValue[0]);
break;
case 2:
VerifyItem(1, valueTuple2.Item1, expectedValue[0]);
VerifyItem(2, valueTuple2.Item2, expectedValue[1]);
break;
case 3:
VerifyItem(1, valueTuple3.Item1, expectedValue[0]);
VerifyItem(2, valueTuple3.Item2, expectedValue[1]);
VerifyItem(3, valueTuple3.Item3, expectedValue[2]);
break;
case 4:
VerifyItem(1, valueTuple4.Item1, expectedValue[0]);
VerifyItem(2, valueTuple4.Item2, expectedValue[1]);
VerifyItem(3, valueTuple4.Item3, expectedValue[2]);
VerifyItem(4, valueTuple4.Item4, expectedValue[3]);
break;
case 5:
VerifyItem(1, valueTuple5.Item1, expectedValue[0]);
VerifyItem(2, valueTuple5.Item2, expectedValue[1]);
VerifyItem(3, valueTuple5.Item3, expectedValue[2]);
VerifyItem(4, valueTuple5.Item4, expectedValue[3]);
VerifyItem(5, valueTuple5.Item5, expectedValue[4]);
break;
case 6:
VerifyItem(1, valueTuple6.Item1, expectedValue[0]);
VerifyItem(2, valueTuple6.Item2, expectedValue[1]);
VerifyItem(3, valueTuple6.Item3, expectedValue[2]);
VerifyItem(4, valueTuple6.Item4, expectedValue[3]);
VerifyItem(5, valueTuple6.Item5, expectedValue[4]);
VerifyItem(6, valueTuple6.Item6, expectedValue[5]);
break;
case 7:
VerifyItem(1, valueTuple7.Item1, expectedValue[0]);
VerifyItem(2, valueTuple7.Item2, expectedValue[1]);
VerifyItem(3, valueTuple7.Item3, expectedValue[2]);
VerifyItem(4, valueTuple7.Item4, expectedValue[3]);
VerifyItem(5, valueTuple7.Item5, expectedValue[4]);
VerifyItem(6, valueTuple7.Item6, expectedValue[5]);
VerifyItem(7, valueTuple7.Item7, expectedValue[6]);
break;
case 8: // Extended ValueTuple
VerifyItem(1, valueTuple8.Item1, expectedValue[0]);
VerifyItem(2, valueTuple8.Item2, expectedValue[1]);
VerifyItem(3, valueTuple8.Item3, expectedValue[2]);
VerifyItem(4, valueTuple8.Item4, expectedValue[3]);
VerifyItem(5, valueTuple8.Item5, expectedValue[4]);
VerifyItem(6, valueTuple8.Item6, expectedValue[5]);
VerifyItem(7, valueTuple8.Item7, expectedValue[6]);
VerifyItem(8, valueTuple8.Rest.Item1, expectedValue[7]);
break;
case 9: // Extended ValueTuple
VerifyItem(1, valueTuple9.Item1, expectedValue[0]);
VerifyItem(2, valueTuple9.Item2, expectedValue[1]);
VerifyItem(3, valueTuple9.Item3, expectedValue[2]);
VerifyItem(4, valueTuple9.Item4, expectedValue[3]);
VerifyItem(5, valueTuple9.Item5, expectedValue[4]);
VerifyItem(6, valueTuple9.Item6, expectedValue[5]);
VerifyItem(7, valueTuple9.Item7, expectedValue[6]);
VerifyItem(8, valueTuple9.Rest.Item1, expectedValue[7]);
VerifyItem(9, valueTuple9.Rest.Item2, expectedValue[8]);
break;
case 10: // Extended ValueTuple
VerifyItem(1, valueTuple10.Item1, expectedValue[0]);
VerifyItem(2, valueTuple10.Item2, expectedValue[1]);
VerifyItem(3, valueTuple10.Item3, expectedValue[2]);
VerifyItem(4, valueTuple10.Item4, expectedValue[3]);
VerifyItem(5, valueTuple10.Item5, expectedValue[4]);
VerifyItem(6, valueTuple10.Item6, expectedValue[5]);
VerifyItem(7, valueTuple10.Item7, expectedValue[6]);
VerifyItem(8, valueTuple10.Rest.Item1, expectedValue[7]);
VerifyItem(9, valueTuple10.Rest.Item2, expectedValue[8]);
VerifyItem(10, valueTuple10.Rest.Item3, expectedValue[9]);
break;
default:
throw new ArgumentException("Must specify between 0 and 10 expected values (inclusive).");
}
}
public void TestToString(string expected)
{
Assert.Equal(expected, valueTuple.ToString());
}
public void TestEquals_GetHashCode(ValueTupleTestDriver<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> other, bool expectEqual, bool expectStructuallyEqual)
{
if (expectEqual)
{
Assert.True(valueTuple.Equals(other.valueTuple));
Assert.Equal(valueTuple.GetHashCode(), other.valueTuple.GetHashCode());
}
else
{
Assert.False(valueTuple.Equals(other.valueTuple));
Assert.NotEqual(valueTuple.GetHashCode(), other.valueTuple.GetHashCode());
}
if (expectStructuallyEqual)
{
var equatable = ((IStructuralEquatable)valueTuple);
var otherEquatable = ((IStructuralEquatable)other.valueTuple);
Assert.True(equatable.Equals(other.valueTuple, TestEqualityComparer.Instance));
Assert.Equal(equatable.GetHashCode(TestEqualityComparer.Instance), otherEquatable.GetHashCode(TestEqualityComparer.Instance));
}
else
{
var equatable = ((IStructuralEquatable)valueTuple);
var otherEquatable = ((IStructuralEquatable)other.valueTuple);
Assert.False(equatable.Equals(other.valueTuple, TestEqualityComparer.Instance));
Assert.NotEqual(equatable.GetHashCode(TestEqualityComparer.Instance), otherEquatable.GetHashCode(TestEqualityComparer.Instance));
}
Assert.False(valueTuple.Equals(null));
Assert.False(((IStructuralEquatable)valueTuple).Equals(null));
}
public void TestCompareTo(ValueTupleTestDriver<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> other, int expectedResult, int expectedStructuralResult)
{
Assert.Equal(expectedResult, ((IComparable)valueTuple).CompareTo(other.valueTuple));
Assert.Equal(expectedStructuralResult, ((IStructuralComparable)valueTuple).CompareTo(other.valueTuple, DummyTestComparer.Instance));
Assert.Equal(1, ((IComparable)valueTuple).CompareTo(null));
}
public void TestNotEqual()
{
ValueTuple<int> ValueTupleB = new ValueTuple<int>((int)10000);
Assert.NotEqual(valueTuple, ValueTupleB);
}
internal void TestCompareToThrows()
{
ValueTuple<int> ValueTupleB = new ValueTuple<int>((int)10000);
Assert.Throws<ArgumentException>(() => ((IComparable)valueTuple).CompareTo(ValueTupleB));
}
}
[Fact]
public static void TestConstructor()
{
ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan> ValueTupleDriverA;
//ValueTuple-0
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>();
ValueTupleDriverA.TestConstructor();
//ValueTuple-1
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue);
ValueTupleDriverA.TestConstructor(short.MaxValue);
//ValueTuple-2
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue);
ValueTupleDriverA.TestConstructor(short.MinValue, int.MaxValue);
//ValueTuple-3
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue);
ValueTupleDriverA.TestConstructor((short)0, (int)0, long.MaxValue);
//ValueTuple-4
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This");
ValueTupleDriverA.TestConstructor((short)1, (int)1, long.MinValue, "This");
//ValueTuple-5
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A');
ValueTupleDriverA.TestConstructor((short)(-1), (int)(-1), (long)0, "is", 'A');
//ValueTuple-6
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MaxValue);
ValueTupleDriverA.TestConstructor((short)10, (int)100, (long)1, "testing", 'Z', Single.MaxValue);
//ValueTuple-7
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', Single.MinValue, Double.MaxValue);
ValueTupleDriverA.TestConstructor((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', Single.MinValue, Double.MaxValue);
object myObj = new object();
//ValueTuple-10
DateTime now = DateTime.Now;
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (Single)0.0001, (Double)0.0000001, now, ValueTuple.Create(false, myObj), TimeSpan.Zero);
ValueTupleDriverA.TestConstructor((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (Single)0.0001, (Double)0.0000001, now, ValueTuple.Create(false, myObj), TimeSpan.Zero);
Assert.Throws<ArgumentException>(() => ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, "not a tuple"));
}
[Fact]
public static void TestToString()
{
ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan> ValueTupleDriverA;
//ValueTuple-0
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>();
ValueTupleDriverA.TestToString("()");
//ValueTuple-1
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue);
ValueTupleDriverA.TestToString("(" + short.MaxValue + ")");
//ValueTuple-2
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue);
ValueTupleDriverA.TestToString("(" + short.MinValue + ", " + int.MaxValue + ")");
//ValueTuple-3
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue);
ValueTupleDriverA.TestToString("(" + ((short)0) + ", " + ((int)0) + ", " + long.MaxValue + ")");
//ValueTuple-4
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This");
ValueTupleDriverA.TestConstructor((short)1, (int)1, long.MinValue, "This");
ValueTupleDriverA.TestToString("(" + ((short)1) + ", " + ((int)1) + ", " + long.MinValue + ", This)");
//ValueTuple-5
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A');
ValueTupleDriverA.TestToString("(" + ((short)(-1)) + ", " + ((int)(-1)) + ", " + ((long)0) + ", is, A)");
//ValueTuple-6
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MaxValue);
ValueTupleDriverA.TestToString("(" + ((short)10) + ", " + ((int)100) + ", " + ((long)1) + ", testing, Z, " + Single.MaxValue + ")");
//ValueTuple-7
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', Single.MinValue, Double.MaxValue);
ValueTupleDriverA.TestToString("(" + ((short)(-100)) + ", " + ((int)(-1000)) + ", " + ((long)(-1)) + ", ValueTuples, , " + Single.MinValue + ", " + Double.MaxValue + ")");
object myObj = new object();
//ValueTuple-10
DateTime now = DateTime.Now;
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (Single)0.0001, (Double)0.0000001, now, ValueTuple.Create(false, myObj), TimeSpan.Zero);
// .NET Native bug 438149 - object.ToString in incorrect
ValueTupleDriverA.TestToString("(" + ((short)10000) + ", " + ((int)1000000) + ", " + ((long)10000000) + ", 2008?7?2?, 0, " + ((Single)0.0001) + ", " + ((Double)0.0000001) + ", (" + now + ", (False, System.Object), " + TimeSpan.Zero + "))");
}
[Fact]
public static void TestEquals_GetHashCode()
{
ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan> ValueTupleDriverA, ValueTupleDriverB, ValueTupleDriverC, ValueTupleDriverD;
//ValueTuple-0
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>();
ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>();
ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue, int.MaxValue);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false);
//ValueTuple-1
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue);
ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue);
ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue);
ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue, int.MaxValue);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false);
//ValueTuple-2
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue);
ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue);
ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MinValue);
ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), long.MinValue);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false);
//ValueTuple-3
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue);
ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue);
ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), long.MinValue);
ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "this");
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false);
//ValueTuple-4
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This");
ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This");
ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "this");
ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, (long)1, "IS", 'a');
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false);
//ValueTuple-5
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A');
ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A');
ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, (long)1, "IS", 'a');
ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MinValue);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false);
//ValueTuple-6
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MaxValue);
ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MaxValue);
ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MinValue);
ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-101), (int)(-1001), (long)(-2), "ValueTuples", ' ', Single.MinValue, (Double)0.0);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false);
//ValueTuple-7
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', Single.MinValue, Double.MaxValue);
ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', Single.MinValue, Double.MaxValue);
ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-101), (int)(-1001), (long)(-2), "ValueTuples", ' ', Single.MinValue, (Double)0.0);
ValueTupleDriverD = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10001, (int)1000001, (long)10000001, "2008?7?3?", '1', (Single)0.0002, (Double)0.0000002, DateTime.Now.AddMilliseconds(1));
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverD, false, false);
//ValueTuple-8
DateTime now = DateTime.Now;
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', Single.MinValue, Double.MaxValue, now);
ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', Single.MinValue, Double.MaxValue, now);
ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-101), (int)(-1001), (long)(-2), "ValueTuples", ' ', Single.MinValue, (Double)0.0, now.AddMilliseconds(1));
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false);
object myObj = new object();
//ValueTuple-10
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (Single)0.0001, (Double)0.0000001, now, ValueTuple.Create(false, myObj), TimeSpan.Zero);
ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (Single)0.0001, (Double)0.0000001, now, ValueTuple.Create(false, myObj), TimeSpan.Zero);
ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10001, (int)1000001, (long)10000001, "2008?7?3?", '1', (Single)0.0002, (Double)0.0000002, now.AddMilliseconds(1), ValueTuple.Create(true, myObj), TimeSpan.MaxValue);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverB, true, true);
ValueTupleDriverA.TestEquals_GetHashCode(ValueTupleDriverC, false, false);
}
[Fact]
public static void TestCompareTo()
{
ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan> ValueTupleDriverA, ValueTupleDriverB, ValueTupleDriverC;
//ValueTuple-0
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>();
ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>();
ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 0);
//ValueTuple-1
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue);
ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MaxValue);
ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue);
ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5);
ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, 65535, 5);
//ValueTuple-2
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue);
ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MaxValue);
ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>(short.MinValue, int.MinValue);
ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5);
ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, 1, 5);
//ValueTuple-3
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue);
ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, long.MaxValue);
ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), long.MinValue);
ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5);
ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, 1, 5);
//ValueTuple-4
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This");
ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "This");
ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)1, (int)1, long.MinValue, "this");
ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5);
ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, 1, 5);
//ValueTuple-5
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A');
ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-1), (int)(-1), (long)0, "is", 'A');
ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)0, (int)0, (long)1, "IS", 'a');
ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5);
ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, -1, 5);
//ValueTuple-6
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MaxValue);
ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MaxValue);
ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10, (int)100, (long)1, "testing", 'Z', Single.MinValue);
ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5);
ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, 1, 5);
//ValueTuple-7
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', Single.MinValue, Double.MaxValue);
ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-100), (int)(-1000), (long)(-1), "ValueTuples", ' ', Single.MinValue, Double.MaxValue);
ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)(-101), (int)(-1001), (long)(-2), "ValueTuples", ' ', Single.MinValue, (Double)0.0);
ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5);
ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, 1, 5);
object myObj = new object();
//ValueTuple-10
DateTime now = DateTime.Now;
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (Single)0.0001, (Double)0.0000001, now, ValueTuple.Create(false, myObj), TimeSpan.Zero);
ValueTupleDriverB = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', (Single)0.0001, (Double)0.0000001, now, ValueTuple.Create(false, myObj), TimeSpan.Zero);
ValueTupleDriverC = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, ValueTuple<bool, object>, TimeSpan>((short)10001, (int)1000001, (long)10000001, "2008?7?3?", '1', (Single)0.0002, (Double)0.0000002, now.AddMilliseconds(1), ValueTuple.Create(true, myObj), TimeSpan.MaxValue);
ValueTupleDriverA.TestCompareTo(ValueTupleDriverB, 0, 5);
ValueTupleDriverA.TestCompareTo(ValueTupleDriverC, -1, 5);
}
[Fact]
public static void TestNotEqual()
{
ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan> ValueTupleDriverA;
//ValueTuple-0
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>();
ValueTupleDriverA.TestNotEqual();
//ValueTuple-1
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000);
ValueTupleDriverA.TestNotEqual();
// This is for code coverage purposes
//ValueTuple-2
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000);
ValueTupleDriverA.TestNotEqual();
//ValueTuple-3
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000);
ValueTupleDriverA.TestNotEqual();
//ValueTuple-4
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?");
ValueTupleDriverA.TestNotEqual();
//ValueTuple-5
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0');
ValueTupleDriverA.TestNotEqual();
//ValueTuple-6
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', Single.NaN);
ValueTupleDriverA.TestNotEqual();
//ValueTuple-7
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', Single.NaN, Double.NegativeInfinity);
ValueTupleDriverA.TestNotEqual();
//ValueTuple-8, extended ValueTuple
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', Single.NaN, Double.NegativeInfinity, DateTime.Now);
ValueTupleDriverA.TestNotEqual();
//ValueTuple-9 and ValueTuple-10 are not necessary because they use the same code path as ValueTuple-8
}
[Fact]
public static void IncomparableTypes()
{
ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan> ValueTupleDriverA;
//ValueTuple-0
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>();
ValueTupleDriverA.TestCompareToThrows();
//ValueTuple-1
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000);
ValueTupleDriverA.TestCompareToThrows();
// This is for code coverage purposes
//ValueTuple-2
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000);
ValueTupleDriverA.TestCompareToThrows();
//ValueTuple-3
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000);
ValueTupleDriverA.TestCompareToThrows();
//ValueTuple-4
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?");
ValueTupleDriverA.TestCompareToThrows();
//ValueTuple-5
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0');
ValueTupleDriverA.TestCompareToThrows();
//ValueTuple-6
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', Single.NaN);
ValueTupleDriverA.TestCompareToThrows();
//ValueTuple-7
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', Single.NaN, Double.NegativeInfinity);
ValueTupleDriverA.TestCompareToThrows();
//ValueTuple-8, extended ValueTuple
ValueTupleDriverA = new ValueTupleTestDriver<short, int, long, string, Char, Single, Double, DateTime, bool, TimeSpan>((short)10000, (int)1000000, (long)10000000, "2008?7?2?", '0', Single.NaN, Double.NegativeInfinity, DateTime.Now);
ValueTupleDriverA.TestCompareToThrows();
//ValueTuple-9 and ValueTuple-10 are not necessary because they use the same code path as ValueTuple-8
}
[Fact]
public static void FloatingPointNaNCases()
{
var a = ValueTuple.Create(Double.MinValue, Double.NaN, Single.MinValue, Single.NaN);
var b = ValueTuple.Create(Double.MinValue, Double.NaN, Single.MinValue, Single.NaN);
Assert.True(a.Equals(b));
Assert.Equal(0, ((IComparable)a).CompareTo(b));
Assert.Equal(a.GetHashCode(), b.GetHashCode());
Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance));
Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance));
Assert.Equal(
((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance),
((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance));
}
[Fact]
public static void TestCustomTypeParameter1()
{
// Special case of ValueTuple<T1> where T1 is a custom type
var testClass = new TestClass();
var a = ValueTuple.Create(testClass);
var b = ValueTuple.Create(testClass);
Assert.True(a.Equals(b));
Assert.Equal(0, ((IComparable)a).CompareTo(b));
Assert.Equal(a.GetHashCode(), b.GetHashCode());
Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance));
Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance));
Assert.Equal(
((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance),
((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance));
}
[Fact]
public static void TestCustomTypeParameter2()
{
// Special case of ValueTuple<T1, T2> where T2 is a custom type
var testClass = new TestClass(1);
var a = ValueTuple.Create(1, testClass);
var b = ValueTuple.Create(1, testClass);
Assert.True(a.Equals(b));
Assert.Equal(0, ((IComparable)a).CompareTo(b));
Assert.Equal(a.GetHashCode(), b.GetHashCode());
Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance));
Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance));
Assert.Equal(
((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance),
((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance));
}
[Fact]
public static void TestCustomTypeParameter3()
{
// Special case of ValueTuple<T1, T2> where T1 and T2 are custom types
var testClassA = new TestClass(100);
var testClassB = new TestClass(101);
var a = ValueTuple.Create(testClassA, testClassB);
var b = ValueTuple.Create(testClassB, testClassA);
Assert.False(a.Equals(b));
Assert.Equal(-1, ((IComparable)a).CompareTo(b));
Assert.False(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance));
Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance));
// Equals(IEqualityComparer) is false, ignore hash code
}
[Fact]
public static void TestCustomTypeParameter4()
{
// Special case of ValueTuple<T1, T2> where T1 and T2 are custom types
var testClassA = new TestClass(100);
var testClassB = new TestClass(101);
var a = ValueTuple.Create(testClassA, testClassB);
var b = ValueTuple.Create(testClassA, testClassA);
Assert.False(a.Equals(b));
Assert.Equal(1, ((IComparable)a).CompareTo(b));
Assert.False(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance));
Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance));
// Equals(IEqualityComparer) is false, ignore hash code
}
[Fact]
public static void NestedValueTuples1()
{
var a = ValueTuple.Create(1, 2, ValueTuple.Create(31, 32), 4, 5, 6, 7, ValueTuple.Create(8, 9));
var b = ValueTuple.Create(1, 2, ValueTuple.Create(31, 32), 4, 5, 6, 7, ValueTuple.Create(8, 9));
Assert.True(a.Equals(b));
Assert.Equal(0, ((IComparable)a).CompareTo(b));
Assert.Equal(a.GetHashCode(), b.GetHashCode());
Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance));
Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance));
Assert.Equal(
((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance),
((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance));
Assert.Equal("(1, 2, (31, 32), 4, 5, 6, 7, (8, 9))", a.ToString());
Assert.Equal("(31, 32)", a.Item3.ToString());
Assert.Equal("(8, 9)", a.Rest.ToString());
}
[Fact]
public static void NestedValueTuples2()
{
var a = ValueTuple.Create(0, 1, 2, 3, 4, 5, 6, ValueTuple.Create(7, 8, 9, 10, 11, 12, 13, ValueTuple.Create(14, 15)));
var b = ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8, 9, 10, 11, 12, 13, 14, ValueTuple.Create(15, 16)));
Assert.False(a.Equals(b));
Assert.Equal(-1, ((IComparable)a).CompareTo(b));
Assert.False(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance));
Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance));
Assert.Equal("(0, 1, 2, 3, 4, 5, 6, (7, 8, 9, 10, 11, 12, 13, (14, 15)))", a.ToString());
Assert.Equal("(1, 2, 3, 4, 5, 6, 7, (8, 9, 10, 11, 12, 13, 14, (15, 16)))", b.ToString());
Assert.Equal("(7, 8, 9, 10, 11, 12, 13, (14, 15))", a.Rest.ToString());
}
[Fact]
public static void IncomparableTypesSpecialCase()
{
// Special case when T does not implement IComparable
var testClassA = new TestClass2(100);
var testClassB = new TestClass2(100);
var a = ValueTuple.Create(testClassA);
var b = ValueTuple.Create(testClassB);
Assert.True(a.Equals(b));
Assert.Throws<ArgumentException>(() => ((IComparable)a).CompareTo(b));
Assert.Equal(a.GetHashCode(), b.GetHashCode());
Assert.True(((IStructuralEquatable)a).Equals(b, TestEqualityComparer.Instance));
Assert.Equal(5, ((IStructuralComparable)a).CompareTo(b, DummyTestComparer.Instance));
Assert.Equal(
((IStructuralEquatable)a).GetHashCode(TestEqualityComparer.Instance),
((IStructuralEquatable)b).GetHashCode(TestEqualityComparer.Instance));
Assert.Equal("([100])", a.ToString());
}
[Fact]
public static void ZeroTuples()
{
var a = ValueTuple.Create();
Assert.True(a.Equals(new ValueTuple()));
Assert.Equal(1, ((IStructuralComparable)a).CompareTo(null, DummyTestComparer.Instance));
Assert.Throws<ArgumentException>(() => ((IStructuralComparable)a).CompareTo("string", DummyTestComparer.Instance));
}
[Fact]
public static void OneTuples()
{
IComparable c = ValueTuple.Create(1);
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3)));
IStructuralComparable sc = (IStructuralComparable)c;
Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance));
Assert.Throws<ArgumentException>(() => ((IStructuralComparable)sc).CompareTo("string", DummyTestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(3), TestComparer.Instance));
Assert.False(((IStructuralEquatable)sc).Equals(sc, DummyTestEqualityComparer.Instance));
}
[Fact]
public static void TwoTuples()
{
IComparable c = ValueTuple.Create(1, 1);
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3, 1)));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 3)));
IStructuralComparable sc = (IStructuralComparable)c;
Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance));
Assert.Throws<ArgumentException>(() => ((IStructuralComparable)sc).CompareTo("string", DummyTestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 3), TestComparer.Instance));
Assert.False(((IStructuralEquatable)sc).Equals(sc, DummyTestEqualityComparer.Instance));
}
[Fact]
public static void ThreeTuples()
{
IComparable c = ValueTuple.Create(1, 1, 1);
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3, 1, 1)));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 3, 1)));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 3)));
IStructuralComparable sc = (IStructuralComparable)c;
Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance));
Assert.Throws<ArgumentException>(() => ((IStructuralComparable)sc).CompareTo("string", DummyTestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 3, 1), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 3), TestComparer.Instance));
Assert.False(((IStructuralEquatable)sc).Equals(sc, DummyTestEqualityComparer.Instance));
}
[Fact]
public static void FourTuples()
{
IComparable c = ValueTuple.Create(1, 1, 1, 1);
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3, 1, 1, 1)));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 3, 1, 1)));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 3, 1)));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 3)));
IStructuralComparable sc = (IStructuralComparable)c;
Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance));
Assert.Throws<ArgumentException>(() => ((IStructuralComparable)sc).CompareTo("string", DummyTestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(3, 1, 1, 1), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 3, 1, 1), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 3, 1), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 3), TestComparer.Instance));
Assert.False(((IStructuralEquatable)sc).Equals(sc, DummyTestEqualityComparer.Instance));
}
[Fact]
public static void FiveTuples()
{
IComparable c = ValueTuple.Create(1, 1, 1, 1, 1);
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3, 1, 1, 1, 1)));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 3, 1, 1, 1)));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 3, 1, 1)));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 3, 1)));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 1, 3)));
IStructuralComparable sc = (IStructuralComparable)c;
Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance));
Assert.Throws<ArgumentException>(() => ((IStructuralComparable)sc).CompareTo("string", DummyTestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(3, 1, 1, 1, 1), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 3, 1, 1, 1), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 3, 1, 1), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 3, 1), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 3), TestComparer.Instance));
Assert.False(((IStructuralEquatable)sc).Equals(sc, DummyTestEqualityComparer.Instance));
}
[Fact]
public static void SixTuples()
{
IComparable c = ValueTuple.Create(1, 1, 1, 1, 1, 1);
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3, 1, 1, 1, 1, 1)));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 3, 1, 1, 1, 1)));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 3, 1, 1, 1)));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 3, 1, 1)));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 1, 3, 1)));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 3)));
IStructuralComparable sc = (IStructuralComparable)c;
Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance));
Assert.Throws<ArgumentException>(() => ((IStructuralComparable)sc).CompareTo("string", DummyTestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(3, 1, 1, 1, 1, 1), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 3, 1, 1, 1, 1), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 3, 1, 1, 1), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 3, 1, 1), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 3, 1), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 3), TestComparer.Instance));
Assert.False(((IStructuralEquatable)sc).Equals(sc, DummyTestEqualityComparer.Instance));
}
[Fact]
public static void SevenTuples()
{
IComparable c = ValueTuple.Create(1, 1, 1, 1, 1, 1, 1);
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3, 1, 1, 1, 1, 1, 1)));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 3, 1, 1, 1, 1, 1)));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 3, 1, 1, 1, 1)));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 3, 1, 1, 1)));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 1, 3, 1, 1)));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 3, 1)));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 1, 3)));
IStructuralComparable sc = (IStructuralComparable)c;
Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance));
Assert.Throws<ArgumentException>(() => ((IStructuralComparable)sc).CompareTo("string", DummyTestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(3, 1, 1, 1, 1, 1, 1), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 3, 1, 1, 1, 1, 1), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 3, 1, 1, 1, 1), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 3, 1, 1, 1), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 3, 1, 1), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 3, 1), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 1, 3), TestComparer.Instance));
Assert.False(((IStructuralEquatable)sc).Equals(sc, DummyTestEqualityComparer.Instance));
}
[Fact]
public static void EightTuples()
{
var t = ValueTuple.Create(1, 1, 1, 1, 1, 1, 1, ValueTuple.Create(1));
IStructuralEquatable se = t;
Assert.False(se.Equals(null, TestEqualityComparer.Instance));
Assert.False(se.Equals("string", TestEqualityComparer.Instance));
Assert.False(se.Equals(new ValueTuple(), TestEqualityComparer.Instance));
IComparable c = t;
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(3, 1, 1, 1, 1, 1, 1, ValueTuple.Create(1))));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 3, 1, 1, 1, 1, 1, ValueTuple.Create(1))));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 3, 1, 1, 1, 1, ValueTuple.Create(1))));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 3, 1, 1, 1, ValueTuple.Create(1))));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 1, 3, 1, 1, ValueTuple.Create(1))));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 3, 1, ValueTuple.Create(1))));
Assert.Equal(-1, c.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 1, 3, ValueTuple.Create(1))));
IStructuralComparable sc = t;
Assert.Equal(1, sc.CompareTo(null, DummyTestComparer.Instance));
Assert.Throws<ArgumentException>(() => sc.CompareTo("string", DummyTestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(3, 1, 1, 1, 1, 1, 1, ValueTuple.Create(1)), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 3, 1, 1, 1, 1, 1, ValueTuple.Create(1)), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 3, 1, 1, 1, 1, ValueTuple.Create(1)), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 3, 1, 1, 1, ValueTuple.Create(1)), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 3, 1, 1, ValueTuple.Create(1)), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 3, 1, ValueTuple.Create(1)), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 1, 3, ValueTuple.Create(1)), TestComparer.Instance));
Assert.Equal(1, sc.CompareTo(ValueTuple.Create(1, 1, 1, 1, 1, 1, 1, ValueTuple.Create(3)), TestComparer.Instance));
Assert.Equal(46208, ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create()).GetHashCode());
Assert.Equal(46216, ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8)).GetHashCode());
Assert.Equal(81152, ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8, 9)).GetHashCode());
Assert.Equal(125864, ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8, 9, 10)).GetHashCode());
Assert.Equal(146432, ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8, 9, 10, 11)).GetHashCode());
Assert.Equal(276872, ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8, 9, 10, 11, 12)).GetHashCode());
Assert.Equal(275712, ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8, 9, 10, 11, 12, 13)).GetHashCode());
Assert.Equal(269608, ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8, 9, 10, 11, 12, 13, 14)).GetHashCode());
Assert.Equal(269544, ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8, 9, 10, 11, 12, 13, 14, ValueTuple.Create())).GetHashCode());
Assert.Equal(269312, ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8, 9, 10, 11, 12, 13, 14, ValueTuple.Create(15))).GetHashCode());
Assert.Equal(46208, ((IStructuralEquatable)ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create())).GetHashCode(TestEqualityComparer.Instance));
Assert.Equal(46216, ((IStructuralEquatable)ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8))).GetHashCode(TestEqualityComparer.Instance));
Assert.Equal(81152, ((IStructuralEquatable)ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8, 9))).GetHashCode(TestEqualityComparer.Instance));
Assert.Equal(125864, ((IStructuralEquatable)ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8, 9, 10))).GetHashCode(TestEqualityComparer.Instance));
Assert.Equal(146432, ((IStructuralEquatable)ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8, 9, 10, 11))).GetHashCode(TestEqualityComparer.Instance));
Assert.Equal(276872, ((IStructuralEquatable)ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8, 9, 10, 11, 12))).GetHashCode(TestEqualityComparer.Instance));
Assert.Equal(275712, ((IStructuralEquatable)ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8, 9, 10, 11, 12, 13))).GetHashCode(TestEqualityComparer.Instance));
Assert.Equal(269608, ((IStructuralEquatable)ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8, 9, 10, 11, 12, 13, 14))).GetHashCode(TestEqualityComparer.Instance));
Assert.Equal(269544, ((IStructuralEquatable)ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8, 9, 10, 11, 12, 13, 14, ValueTuple.Create()))).GetHashCode(TestEqualityComparer.Instance));
Assert.Equal(269312, ((IStructuralEquatable)ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, ValueTuple.Create(8, 9, 10, 11, 12, 13, 14, ValueTuple.Create(15)))).GetHashCode(TestEqualityComparer.Instance));
var d = default(ValueTuple<int, int, int, int, int, int, int, int>);
d.Item1 = 1;
d.Rest = 42;
Assert.Equal(35937, d.GetHashCode());
Assert.Equal(35937, ((IStructuralEquatable)d).GetHashCode());
Assert.False(se.Equals(t, DummyTestEqualityComparer.Instance));
}
private class TestClass : IComparable
{
private readonly int _value;
internal TestClass()
: this(0)
{ }
internal TestClass(int value)
{
this._value = value;
}
public override string ToString()
{
return "{" + _value.ToString() + "}";
}
public int CompareTo(object x)
{
TestClass tmp = x as TestClass;
if (tmp != null)
return this._value.CompareTo(tmp._value);
else
return 1;
}
}
private class TestClass2
{
private readonly int _value;
internal TestClass2()
: this(0)
{ }
internal TestClass2(int value)
{
this._value = value;
}
public override string ToString()
{
return "[" + _value.ToString() + "]";
}
public override bool Equals(object x)
{
TestClass2 tmp = x as TestClass2;
if (tmp != null)
return _value.Equals(tmp._value);
else
return false;
}
public override int GetHashCode()
{
return _value.GetHashCode();
}
}
private class DummyTestComparer : IComparer
{
public static readonly DummyTestComparer Instance = new DummyTestComparer();
public int Compare(object x, object y)
{
return 5;
}
}
private class TestComparer : IComparer
{
public static readonly TestComparer Instance = new TestComparer();
public int Compare(object x, object y)
{
return x.Equals(y) ? 0 : 1;
}
}
private class DummyTestEqualityComparer : IEqualityComparer
{
public static readonly DummyTestEqualityComparer Instance = new DummyTestEqualityComparer();
public new bool Equals(object x, object y)
{
return false;
}
public int GetHashCode(object x)
{
return x.GetHashCode();
}
}
private class TestEqualityComparer : IEqualityComparer
{
public static readonly TestEqualityComparer Instance = new TestEqualityComparer();
public new bool Equals(object x, object y)
{
return x.Equals(y);
}
public int GetHashCode(object x)
{
return x.GetHashCode();
}
}
}
| |
//
// Authors:
// Marek Habersack grendel@twistedcode.net
//
// Copyright (c) 2010, Novell, Inc (http://novell.com/)
//
// 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 Novell, Inc nor names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Mail;
using System.Text;
using CaptainHook.Base;
using CaptainHook.GitHub;
using CaptainHook.Utils;
namespace CaptainHook.Mail
{
public class Template <TData> : CommonBase, ITemplate
{
string templateName;
string basePath;
string commitSourceID;
string fullTemplatePath;
string fullPrefixedTemplatePath;
List <TemplateElement> compiled;
TemplateElementFactory <TData> factory;
public string TemplateName {
get {
if (String.IsNullOrEmpty (templateName))
templateName = typeof (TData).Name.ToLower ();
return templateName;
}
set {
templateName = value;
fullTemplatePath = null;
}
}
public string FullTemplatePath {
get {
if (String.IsNullOrEmpty (fullTemplatePath))
fullTemplatePath = Path.Combine (basePath, TemplateName + ".txt");
return fullTemplatePath;
}
}
public string FullPrefixedTemplatePath {
get {
if (String.IsNullOrEmpty (fullPrefixedTemplatePath))
fullPrefixedTemplatePath = Path.Combine (basePath, commitSourceID + "." + TemplateName + ".txt");
return fullPrefixedTemplatePath;
}
}
public Template (string basePath, string commitSourceID)
{
if (String.IsNullOrEmpty (basePath))
throw new ArgumentNullException ("basePath");
if (String.IsNullOrEmpty (commitSourceID))
throw new ArgumentNullException ("commitSourceID");
this.basePath = basePath;
this.commitSourceID = commitSourceID;
}
public bool Compile ()
{
if (compiled != null)
return true;
string path = FullPrefixedTemplatePath;
if (!File.Exists (path)) {
path = FullTemplatePath;
if (!File.Exists (path))
throw new InvalidOperationException (String.Format ("Template '{0}' does not exist in directory '{1}'.", TemplateName, basePath));
}
compiled = new List <TemplateElement> ();
factory = new TemplateElementFactory <TData> (basePath, commitSourceID);
try {
var parser = new TemplateParser (path);
parser.FragmentParsed += new EventHandler<FragmentParsedEventArguments> (OnFragmentParsed);
parser.Parse ();
} catch (Exception ex) {
Log (ex);
return false;
} finally {
factory = null;
}
return compiled != null;
}
void OnFragmentParsed (object sender, FragmentParsedEventArguments args)
{
compiled.Add (factory.GetElement (args.Fragment));
}
public MailMessage ComposeMail (object item)
{
if (item == null)
throw new ArgumentNullException ("item");
if (!(item is TData))
throw new ArgumentException (String.Format ("Must be an instance of the '{0}' type", typeof(TData).FullName), "item");
return ComposeMail ((TData)item);
}
public MailMessage ComposeMail (TData item)
{
if (item == null)
throw new ArgumentNullException ("item");
if (!Compile ())
return null;
var ret = new MailMessage ();
ret.Body = ComposeMailBody (item, ret);
CommitSource cs;
if (!Config.Instance.CommitSources.TryGetValue (commitSourceID, out cs) || cs == null)
throw new InvalidOperationException (String.Format ("Missing configuration for commit source with ID '{0}'", commitSourceID));
AddAddresses (ret.CC, cs.CCRecipients);
AddAddresses (ret.Bcc, cs.BCCRecipients);
AddAddresses (ret.To, cs.TORecipients);
var push = item as Push;
Author committer = GetCommitterAddress (push);
Author author;
if (cs.SendAsCommitter && typeof(TData) == typeof(Push)) {
if (committer == null) {
Log (LogSeverity.Error, "Unable to determine From address for the mail - no commits and SendAsCommiter is true");
return null;
}
ret.From = new MailAddress (committer.Email, committer.Name);
author = cs.From;
if (author != null)
ret.Sender = new MailAddress (author.Email, author.Name);
else
ret.Sender = ret.From;
Author replyTo = cs.ReplyTo;
if (replyTo == null)
ret.ReplyTo = new MailAddress (author.Email, author.Name);
else
ret.ReplyTo = new MailAddress (replyTo.Email, replyTo.Name);
} else {
author = cs.From;
string authorName;
if (cs.UseCommitterAsSenderName && committer != null)
authorName = String.Format ("{0} ({1})", committer.Name, committer.Email);
else
authorName = author.Name;
ret.From = new MailAddress (author.Email, authorName);
ret.Sender = ret.From;
author = cs.ReplyTo;
ret.ReplyTo = new MailAddress (author.Email, author.Name);
}
return ret;
}
Author GetCommitterAddress (Push push)
{
List<Commit> commits = push.Commits;
if (commits == null || commits.Count == 0)
return null;
return commits[0].Author;
}
void AddAddresses (MailAddressCollection coll, List<Author> list)
{
if (coll == null || list == null || list.Count == 0)
return;
string name;
MailAddress address;
foreach (var author in list) {
name = author.Name;
if (String.IsNullOrEmpty (name))
address = new MailAddress (author.Email);
else
address = new MailAddress (author.Email, name);
coll.Add (address);
}
}
public string ComposeMailBody (object item)
{
return ComposeMailBody ((TData)item);
}
public string ComposeMailBody (TData item)
{
if (item == null)
throw new ArgumentNullException ("item");
if (!Compile ())
return null;
return ComposeMailBody (item, null);
}
string ComposeMailBody (TData item, MailMessage message)
{
var sb = new StringBuilder ();
string data;
bool skipNewlineIfEmpty = false;
bool dataEmpty;
foreach (TemplateElement element in compiled) {
if (element is TemplateElementMailHeader) {
if (message != null) {
SetMessageHeader (element as TemplateElementMailHeader, message, item);
skipNewlineIfEmpty = true;
}
continue;
}
data = element.Generate (item);
dataEmpty = String.IsNullOrEmpty (data);
if (skipNewlineIfEmpty && !dataEmpty && element is TemplateElementText) {
int newline = data.IndexOf ('\n');
bool skip = true;
if (newline == -1)
skip = false;
else {
for (int i = 0; i < newline; i++) {
if (!Char.IsWhiteSpace (data[i])) {
skip = false;
break;
}
}
}
if (skip) {
if (newline < data.Length - 1)
data = data.Substring (newline + 1);
else
continue;
dataEmpty = String.IsNullOrEmpty (data);
}
}
if (dataEmpty)
skipNewlineIfEmpty = element.SkipNewlineIfLineEmpty;
else {
skipNewlineIfEmpty = false;
sb.Append (data);
}
}
return sb.ToString ();
}
void SetMessageHeader (TemplateElementMailHeader element, MailMessage message, TData item)
{
var headerList = element as TemplateElementListMailHeader<TData>;
if (headerList != null) {
headerList.Generate (item);
List<string> values = headerList.Values;
if (values == null || values.Count == 0)
return;
string headerName = element.Name;
foreach (string v in values)
message.Headers.Add (headerName, v);
}
string val = element.Generate (item);
if (String.Compare ("subject", element.Name, StringComparison.OrdinalIgnoreCase) == 0) {
message.Subject = val;
return;
}
message.Headers.Add (element.Name, val);
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A web page. Every web page is implicitly assumed to be declared to be of type WebPage, so the various properties about that webpage, such as <code>breadcrumb</code> may be used. We recommend explicit declaration if these properties are specified, but if they are found outside of an itemscope, they will be assumed to be about the page
/// </summary>
public class WebPage_Core : TypeCore, ICreativeWork
{
public WebPage_Core()
{
this._TypeId = 293;
this._Id = "WebPage";
this._Schema_Org_Url = "http://schema.org/WebPage";
string label = "";
GetLabel(out label, "WebPage", typeof(WebPage_Core));
this._Label = label;
this._Ancestors = new int[]{266,78};
this._SubTypes = new int[]{8,56,64,69,142,217,237};
this._SuperTypes = new int[]{78};
this._Properties = new int[]{67,108,143,229,0,2,10,12,18,20,24,26,21,50,51,54,57,58,59,61,62,64,70,72,81,97,100,110,115,116,126,138,151,178,179,180,199,211,219,230,231,38,117,133,169,208};
}
/// <summary>
/// The subject matter of the content.
/// </summary>
private About_Core about;
public About_Core About
{
get
{
return about;
}
set
{
about = value;
SetPropertyInstance(about);
}
}
/// <summary>
/// Specifies the Person that is legally accountable for the CreativeWork.
/// </summary>
private AccountablePerson_Core accountablePerson;
public AccountablePerson_Core AccountablePerson
{
get
{
return accountablePerson;
}
set
{
accountablePerson = value;
SetPropertyInstance(accountablePerson);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// A secondary title of the CreativeWork.
/// </summary>
private AlternativeHeadline_Core alternativeHeadline;
public AlternativeHeadline_Core AlternativeHeadline
{
get
{
return alternativeHeadline;
}
set
{
alternativeHeadline = value;
SetPropertyInstance(alternativeHeadline);
}
}
/// <summary>
/// The media objects that encode this creative work. This property is a synonym for encodings.
/// </summary>
private AssociatedMedia_Core associatedMedia;
public AssociatedMedia_Core AssociatedMedia
{
get
{
return associatedMedia;
}
set
{
associatedMedia = value;
SetPropertyInstance(associatedMedia);
}
}
/// <summary>
/// An embedded audio object.
/// </summary>
private Audio_Core audio;
public Audio_Core Audio
{
get
{
return audio;
}
set
{
audio = value;
SetPropertyInstance(audio);
}
}
/// <summary>
/// The author of this content. Please note that author is special in that HTML 5 provides a special mechanism for indicating authorship via the rel tag. That is equivalent to this and may be used interchangabely.
/// </summary>
private Author_Core author;
public Author_Core Author
{
get
{
return author;
}
set
{
author = value;
SetPropertyInstance(author);
}
}
/// <summary>
/// Awards won by this person or for this creative work.
/// </summary>
private Awards_Core awards;
public Awards_Core Awards
{
get
{
return awards;
}
set
{
awards = value;
SetPropertyInstance(awards);
}
}
/// <summary>
/// A set of links that can help a user understand and navigate a website hierarchy.
/// </summary>
private Breadcrumb_Core breadcrumb;
public Breadcrumb_Core Breadcrumb
{
get
{
return breadcrumb;
}
set
{
breadcrumb = value;
SetPropertyInstance(breadcrumb);
}
}
/// <summary>
/// Comments, typically from users, on this CreativeWork.
/// </summary>
private Comment_Core comment;
public Comment_Core Comment
{
get
{
return comment;
}
set
{
comment = value;
SetPropertyInstance(comment);
}
}
/// <summary>
/// The location of the content.
/// </summary>
private ContentLocation_Core contentLocation;
public ContentLocation_Core ContentLocation
{
get
{
return contentLocation;
}
set
{
contentLocation = value;
SetPropertyInstance(contentLocation);
}
}
/// <summary>
/// Official rating of a piece of content\u2014for example,'MPAA PG-13'.
/// </summary>
private ContentRating_Core contentRating;
public ContentRating_Core ContentRating
{
get
{
return contentRating;
}
set
{
contentRating = value;
SetPropertyInstance(contentRating);
}
}
/// <summary>
/// A secondary contributor to the CreativeWork.
/// </summary>
private Contributor_Core contributor;
public Contributor_Core Contributor
{
get
{
return contributor;
}
set
{
contributor = value;
SetPropertyInstance(contributor);
}
}
/// <summary>
/// The party holding the legal copyright to the CreativeWork.
/// </summary>
private CopyrightHolder_Core copyrightHolder;
public CopyrightHolder_Core CopyrightHolder
{
get
{
return copyrightHolder;
}
set
{
copyrightHolder = value;
SetPropertyInstance(copyrightHolder);
}
}
/// <summary>
/// The year during which the claimed copyright for the CreativeWork was first asserted.
/// </summary>
private CopyrightYear_Core copyrightYear;
public CopyrightYear_Core CopyrightYear
{
get
{
return copyrightYear;
}
set
{
copyrightYear = value;
SetPropertyInstance(copyrightYear);
}
}
/// <summary>
/// The creator/author of this CreativeWork or UserComments. This is the same as the Author property for CreativeWork.
/// </summary>
private Creator_Core creator;
public Creator_Core Creator
{
get
{
return creator;
}
set
{
creator = value;
SetPropertyInstance(creator);
}
}
/// <summary>
/// The date on which the CreativeWork was created.
/// </summary>
private DateCreated_Core dateCreated;
public DateCreated_Core DateCreated
{
get
{
return dateCreated;
}
set
{
dateCreated = value;
SetPropertyInstance(dateCreated);
}
}
/// <summary>
/// The date on which the CreativeWork was most recently modified.
/// </summary>
private DateModified_Core dateModified;
public DateModified_Core DateModified
{
get
{
return dateModified;
}
set
{
dateModified = value;
SetPropertyInstance(dateModified);
}
}
/// <summary>
/// Date of first broadcast/publication.
/// </summary>
private DatePublished_Core datePublished;
public DatePublished_Core DatePublished
{
get
{
return datePublished;
}
set
{
datePublished = value;
SetPropertyInstance(datePublished);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// A link to the page containing the comments of the CreativeWork.
/// </summary>
private DiscussionURL_Core discussionURL;
public DiscussionURL_Core DiscussionURL
{
get
{
return discussionURL;
}
set
{
discussionURL = value;
SetPropertyInstance(discussionURL);
}
}
/// <summary>
/// Specifies the Person who edited the CreativeWork.
/// </summary>
private Editor_Core editor;
public Editor_Core Editor
{
get
{
return editor;
}
set
{
editor = value;
SetPropertyInstance(editor);
}
}
/// <summary>
/// The media objects that encode this creative work
/// </summary>
private Encodings_Core encodings;
public Encodings_Core Encodings
{
get
{
return encodings;
}
set
{
encodings = value;
SetPropertyInstance(encodings);
}
}
/// <summary>
/// Genre of the creative work
/// </summary>
private Genre_Core genre;
public Genre_Core Genre
{
get
{
return genre;
}
set
{
genre = value;
SetPropertyInstance(genre);
}
}
/// <summary>
/// Headline of the article
/// </summary>
private Headline_Core headline;
public Headline_Core Headline
{
get
{
return headline;
}
set
{
headline = value;
SetPropertyInstance(headline);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// The language of the content. please use one of the language codes from the <a href=\http://tools.ietf.org/html/bcp47\>IETF BCP 47 standard.</a>
/// </summary>
private InLanguage_Core inLanguage;
public InLanguage_Core InLanguage
{
get
{
return inLanguage;
}
set
{
inLanguage = value;
SetPropertyInstance(inLanguage);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// Indicates whether this content is family friendly.
/// </summary>
private IsFamilyFriendly_Core isFamilyFriendly;
public IsFamilyFriendly_Core IsFamilyFriendly
{
get
{
return isFamilyFriendly;
}
set
{
isFamilyFriendly = value;
SetPropertyInstance(isFamilyFriendly);
}
}
/// <summary>
/// Indicates the collection or gallery to which the item belongs.
/// </summary>
private IsPartOf_Core isPartOf;
public IsPartOf_Core IsPartOf
{
get
{
return isPartOf;
}
set
{
isPartOf = value;
SetPropertyInstance(isPartOf);
}
}
/// <summary>
/// The keywords/tags used to describe this content.
/// </summary>
private Keywords_Core keywords;
public Keywords_Core Keywords
{
get
{
return keywords;
}
set
{
keywords = value;
SetPropertyInstance(keywords);
}
}
/// <summary>
/// Indicates if this web page element is the main subject of the page.
/// </summary>
private MainContentOfPage_Core mainContentOfPage;
public MainContentOfPage_Core MainContentOfPage
{
get
{
return mainContentOfPage;
}
set
{
mainContentOfPage = value;
SetPropertyInstance(mainContentOfPage);
}
}
/// <summary>
/// Indicates that the CreativeWork contains a reference to, but is not necessarily about a concept.
/// </summary>
private Mentions_Core mentions;
public Mentions_Core Mentions
{
get
{
return mentions;
}
set
{
mentions = value;
SetPropertyInstance(mentions);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event.
/// </summary>
private Offers_Core offers;
public Offers_Core Offers
{
get
{
return offers;
}
set
{
offers = value;
SetPropertyInstance(offers);
}
}
/// <summary>
/// Indicates the main image on the page
/// </summary>
private PrimaryImageOfPage_Core primaryImageOfPage;
public PrimaryImageOfPage_Core PrimaryImageOfPage
{
get
{
return primaryImageOfPage;
}
set
{
primaryImageOfPage = value;
SetPropertyInstance(primaryImageOfPage);
}
}
/// <summary>
/// Specifies the Person or Organization that distributed the CreativeWork.
/// </summary>
private Provider_Core provider;
public Provider_Core Provider
{
get
{
return provider;
}
set
{
provider = value;
SetPropertyInstance(provider);
}
}
/// <summary>
/// The publisher of the creative work.
/// </summary>
private Publisher_Core publisher;
public Publisher_Core Publisher
{
get
{
return publisher;
}
set
{
publisher = value;
SetPropertyInstance(publisher);
}
}
/// <summary>
/// Link to page describing the editorial principles of the organization primarily responsible for the creation of the CreativeWork.
/// </summary>
private PublishingPrinciples_Core publishingPrinciples;
public PublishingPrinciples_Core PublishingPrinciples
{
get
{
return publishingPrinciples;
}
set
{
publishingPrinciples = value;
SetPropertyInstance(publishingPrinciples);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The most significant URLs on the page. Typically, these are the non-navigation links that are clicked on the most
/// </summary>
private SignificantLinks_Core significantLinks;
public SignificantLinks_Core SignificantLinks
{
get
{
return significantLinks;
}
set
{
significantLinks = value;
SetPropertyInstance(significantLinks);
}
}
/// <summary>
/// The Organization on whose behalf the creator was working.
/// </summary>
private SourceOrganization_Core sourceOrganization;
public SourceOrganization_Core SourceOrganization
{
get
{
return sourceOrganization;
}
set
{
sourceOrganization = value;
SetPropertyInstance(sourceOrganization);
}
}
/// <summary>
/// A thumbnail image relevant to the Thing.
/// </summary>
private ThumbnailURL_Core thumbnailURL;
public ThumbnailURL_Core ThumbnailURL
{
get
{
return thumbnailURL;
}
set
{
thumbnailURL = value;
SetPropertyInstance(thumbnailURL);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
/// <summary>
/// The version of the CreativeWork embodied by a specified resource.
/// </summary>
private Version_Core version;
public Version_Core Version
{
get
{
return version;
}
set
{
version = value;
SetPropertyInstance(version);
}
}
/// <summary>
/// An embedded video object.
/// </summary>
private Video_Core video;
public Video_Core Video
{
get
{
return video;
}
set
{
video = value;
SetPropertyInstance(video);
}
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
#region Imports
using System;
using System.Collections;
#if !NET_1_1
using System.Collections.Generic;
#endif
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Text;
using Spring.Collections;
using Spring.Context;
using Spring.Objects.Factory;
#endregion
namespace Spring.Objects
{
/// <summary>
/// Simple test object used for testing object factories, AOP framework etc.
/// </summary>
/// <author>Rod Johnson</author>
/// <author>Mark Pollack (.NET)</author>
public class TestObject : MarshalByRefObject, ITestObject, IObjectFactoryAware, IComparable, IOther, IApplicationContextAware, IObjectNameAware, IInitializingObject, ISharedStateAware
{
#region Event testing members
public event EventHandler Click;
public static event EventHandler StaticClick;
/// <summary>
/// Public method to programmatically raise the <event>Click</event> event
/// while testing.
/// </summary>
public void OnClick()
{
if (Click != null)
{
Click(this, EventArgs.Empty);
}
}
/// <summary>
/// Public method to programmatically raise the <b>static</b>
/// <event>Click</event> event while testing.
/// </summary>
public static void OnStaticClick()
{
if (TestObject.StaticClick != null)
{
TestObject.StaticClick(typeof (TestObject), EventArgs.Empty);
}
}
#endregion
#region Properties
public int ObjectNumber
{
get { return objectNumber; }
set { objectNumber = value; }
}
// for use in ObjectWrapperTests.SetPropertyValuesFailsWhenSettingReadOnlyProperty
public int ReadOnlyObjectNumber
{
get { return objectNumber; }
}
public IndexedTestObject NestedIndexedObject
{
get { return nestedIndexedObject; }
set { nestedIndexedObject = value; }
}
/// <summary>
/// Public Enumeration Property for FileMode.
/// </summary>
public FileMode FileMode
{
get { return FileModeEnum; }
set { FileModeEnum = value; }
}
public IObjectFactory ObjectFactory
{
get { return objectFactory; }
set { objectFactory = value; }
}
public CultureInfo MyCulture
{
get { return myCulture; }
set { myCulture = value; }
}
public string Touchy
{
get { return touchy; }
set
{
if (value.IndexOf('.') != - 1)
{
throw new Exception("Can't contain a .");
}
if (value.IndexOf(',') != - 1)
{
throw new FormatException("Number format exception: contains a ,");
}
this.touchy = value;
}
}
public bool PostProcessed
{
get { return postProcessed; }
set { this.postProcessed = value; }
}
public string Name
{
get { return name; }
set { this.name = value; }
}
public string Nickname
{
get { return nickname; }
set { this.nickname = value; }
}
public virtual int Age
{
get { return age; }
set { this.age = value; }
}
public virtual DateTime Date
{
get { return date; }
set { this.date = value; }
}
public virtual Single MyFloat
{
get { return myFloat; }
set { this.myFloat = value; }
}
public virtual ITestObject Spouse
{
get { return spouse; }
set { this.spouse = value; }
}
public virtual ITestObject Sibling
{
get { return sibling; }
set { this.sibling = value; }
}
public virtual INestedTestObject Doctor
{
get { return doctor; }
set { this.doctor = value; }
}
public virtual INestedTestObject Lawyer
{
get { return lawyer; }
set { this.lawyer = value; }
}
public virtual NestedTestObject RealLawyer
{
get { return myRealLawyer; }
set { this.myRealLawyer = value; }
}
/// <summary>
/// A collection of friends.
/// </summary>
public virtual ICollection Friends
{
get { return friends; }
set { this.friends = value; }
}
/// <summary>
/// A read-only collection of pets.
/// </summary>
public virtual ICollection Pets
{
get { return pets; }
}
public virtual TestObjectList TypedFriends
{
get { return typedFriends; }
set { typedFriends = value; }
}
/// <summary>
/// A read-only map of periodic table values.
/// </summary>
public virtual IDictionary PeriodicTable
{
get { return periodicTable; }
}
/// <summary>
/// A read-only set of computer names
/// </summary>
public virtual ISet Computers
{
get { return computers; }
}
public virtual ISet SomeSet
{
get { return someSet; }
set { this.someSet = value; }
}
public virtual string[] Hats
{
get { return hats; }
set { hats = value; }
}
public virtual IDictionary SomeMap
{
get { return someMap; }
set { this.someMap = value; }
}
public virtual IList SomeList
{
get { return someList; }
set { this.someList = value;}
}
#if !NET_1_1
public virtual List<string> SomeGenericStringList
{
get { return someGenericStringList; }
set { this.someGenericStringList = value; }
}
#endif
public virtual NameValueCollection SomeNameValueCollection
{
get { return someNameValueCollection; }
set { this.someNameValueCollection = value;}
}
protected virtual string HappyPlace
{
get { return _happyPlace; }
set { _happyPlace = value; }
}
// used in reflective tests, so don't remove this property...
private string[] SamsoniteSuitcase
{
get { return _samsoniteSuitcase; }
set { _samsoniteSuitcase = value; }
}
public Type ClassProperty
{
get { return classProperty; }
set { classProperty = value; }
}
public IApplicationContext ApplicationContext
{
get { return applicationContext; }
set { applicationContext = value; }
}
public string ObjectName
{
get { return objectName; }
set { objectName = value; }
}
public int ExceptionMethodCallCount
{
get { return exceptionMethodCallCount; }
}
public bool InitCompleted
{
get { return initCompleted; }
set { initCompleted = value; }
}
public Size Size
{
get { return size; }
set { size = value;}
}
#endregion
#region Indexers
public string this[int index]
{
get
{
if (index < 0 || index >= favoriteQuotes.Length)
{
throw new ArgumentException("Index out of range");
}
return favoriteQuotes[index];
}
set
{
if (index < 0 || index >= favoriteQuotes.Length)
{
throw new ArgumentException("index is out of range.");
}
favoriteQuotes[index] = value;
}
}
#endregion
#region Fields
private int exceptionMethodCallCount;
private int objectNumber = 0;
public FileMode FileModeEnum;
private IObjectFactory objectFactory;
private bool postProcessed;
private int age;
private string name;
private string nickname;
private ITestObject spouse;
private ITestObject sibling;
private string touchy;
private ICollection friends = new LinkedList();
private TestObjectList typedFriends = new TestObjectList();
private ICollection pets = new LinkedList();
private IDictionary periodicTable = new Hashtable();
private string[] favoriteQuotes = new string[]
{
"He who ha-ha ho-ho",
"The quick brown fox jumped over the lazy dogs."
};
private Type classProperty;
private ISet computers = new HybridSet();
private ISet someSet = new HybridSet();
private IDictionary someMap = new Hashtable();
private IList someList = new ArrayList();
private DateTime date = DateTime.Now;
private Single myFloat = (float) 0.0;
private CultureInfo myCulture = CultureInfo.InvariantCulture;
private string[] hats = null;
private INestedTestObject doctor = new NestedTestObject();
private INestedTestObject lawyer = new NestedTestObject();
private NestedTestObject myRealLawyer = new NestedTestObject();
private IndexedTestObject nestedIndexedObject;
private string _happyPlace = DefaultHappyPlace;
private string[] _samsoniteSuitcase = DefaultContentsOfTheSuitcase;
public const string DefaultHappyPlace = "The_SeaBass_Diner";
public static readonly string[] DefaultContentsOfTheSuitcase
= new string[] {"John Pryor's 'Leaving On A Jet Plane' LP"};
private IApplicationContext applicationContext;
private string objectName;
private Size size;
private bool initCompleted;
private IDictionary sharedState;
private NameValueCollection someNameValueCollection;
#if !NET_1_1
private List<string> someGenericStringList;
#endif
#endregion
#region Constructor (s) / Destructor
public TestObject()
{
}
public TestObject(string name, int age)
{
this.name = name;
this.age = age;
}
public TestObject(string name, int age, INestedTestObject doctor)
{
this.name = name;
this.age = age;
this.doctor = doctor;
}
public TestObject(string name, int age, INestedTestObject doctor, INestedTestObject lawyer)
{
this.name = name;
this.age = age;
this.doctor = doctor;
this.lawyer = lawyer;
}
public TestObject(ITestObject spouse)
{
this.spouse = spouse;
}
public TestObject(IList someList)
{
this.someList = someList;
}
public TestObject(ISet someSet)
{
this.someSet = someSet;
}
public TestObject(IDictionary someMap)
{
this.someMap = someMap;
}
public TestObject(NameValueCollection someProps)
{
this.someNameValueCollection = someProps;
}
#endregion
#region Static Methods
public static TestObject Create(string name)
{
return new TestObject(name, 30);
}
#endregion
#region Methods
public void AfterPropertiesSet()
{
initCompleted = true;
}
public void AddComputerName(string name)
{
if (computers == null)
{
computers = new HybridSet();
}
computers.Add(name);
}
public void AddPeriodicElement(string name, string element)
{
if (periodicTable == null)
{
periodicTable = new Hashtable();
}
periodicTable.Add(name, element);
}
public string GetNameWithHonorific(bool isFemale, params string[] lettersAfterName)
{
StringBuilder buffer = new StringBuilder();
buffer.Append(isFemale ? "Ms " : "Mr ");
buffer.Append(Name);
buffer.Append(" ");
foreach (string letters in lettersAfterName)
{
buffer.Append(letters);
}
return buffer.ToString();
}
public override bool Equals(object other)
{
return Equals(this, other);
}
new public static bool Equals(object @this, object other)
{
if (other == null || !(other is ITestObject))
{
return false;
}
ITestObject tb2 = (ITestObject) other;
ITestObject tb1 = (ITestObject) @this;
if (tb2.Age != tb1.Age)
{
return false;
}
if ((object) tb1.Name == null)
{
return (object) tb2.Name == null;
}
if (!tb2.Name.Equals(tb1.Name))
{
return false;
}
return true;
}
public override int GetHashCode()
{
return (name != null ? name.GetHashCode() : base.GetHashCode());
}
public virtual int CompareTo(object other)
{
if ((object) this.name != null && other is TestObject)
{
return String.CompareOrdinal(this.name, ((TestObject) other).name);
}
else
{
return 1;
}
}
public virtual string GetDescription()
{
string s = "name=" + name + "; age=" + age + "; touchy=" + touchy;
s += ("; spouse={" + (spouse != null ? spouse.Name : null) + "}");
return s;
}
public override string ToString()
{
string s = "name=" + name + "; age=" + age + "; touchy=" + touchy;
s += ("; spouse={" + (spouse != null ? spouse.Name : null) + "}");
return s;
}
//Used in testing messaging
public void SetName(string name)
{
this.name = name;
}
/// <summary>
/// Throw the given exception
/// </summary>
/// <param name="t">An exception to throw.</param>
public virtual void Exceptional(Exception t)
{
exceptionMethodCallCount++;
if (t != null)
{
throw t;
}
}
/// <summary>
/// Throw the given exception
/// </summary>
/// <param name="t">An exception to throw.</param>
/// <returns>314 if exception is null</returns>
public virtual int ExceptionalWithReturnValue(Exception t)
{
exceptionMethodCallCount++;
if (t != null)
{
throw t;
}
return 314;
}
/// <summary>
/// Return a reference to the object itself. 'Return this'
/// </summary>
/// <returns>a reference to the object itse.f</returns>
public virtual object ReturnsThis()
{
return this;
}
#endregion
#region IOther Implementation
/// <summary>
/// Funny Named method.
/// </summary>
public virtual void Absquatulate()
{
}
#endregion
public IDictionary SharedState
{
get { return sharedState; }
set { sharedState = value; }
}
}
#region Inner Class : TestObjectConverter
public class TestObjectConverter : TypeConverter
{
public override bool CanConvertTo(
ITypeDescriptorContext context, Type destinationType)
{
if ((destinationType == typeof (TestObjectConverter))
|| (destinationType == typeof (InstanceDescriptor)))
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
public override bool CanConvertFrom
(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof (string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom
(ITypeDescriptorContext context, CultureInfo culture, object text_obj)
{
if (text_obj is string)
{
string text = (string) text_obj;
TestObject tb = new TestObject();
string[] split = text.Split(new char[] {'_'});
tb.Name = split[0];
tb.Age = int.Parse(split[1]);
return tb;
}
return base.ConvertFrom(context, culture, text_obj);
}
public override object ConvertTo(
ITypeDescriptorContext context, CultureInfo culture, object param, Type destinationType)
{
return base.ConvertTo(context, culture, param, destinationType);
}
}
#endregion
}
| |
#define COUNT_ACTIVATE_DEACTIVATE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Orleans;
using Orleans.Runtime;
using Orleans.Runtime.Providers;
using Orleans.Streams;
using UnitTests.GrainInterfaces;
namespace UnitTests.Grains
{
[Serializable]
public class StreamLifecycleTestGrainState
{
// For producer and consumer
// -- only need to store this because of how we run our unit tests against multiple providers
public string StreamProviderName { get; set; }
// For producer only.
public IAsyncStream<int> Stream { get; set; }
public bool IsProducer { get; set; }
public int NumMessagesSent { get; set; }
public int NumErrors { get; set; }
// For consumer only.
public HashSet<StreamSubscriptionHandle<int>> ConsumerSubscriptionHandles { get; set; }
public StreamLifecycleTestGrainState()
{
ConsumerSubscriptionHandles = new HashSet<StreamSubscriptionHandle<int>>();
}
}
public class GenericArg
{
public string A { get; private set; }
public int B { get; private set; }
public GenericArg(string a, int b)
{
A = a;
B = b;
}
public override bool Equals(object obj)
{
var item = obj as GenericArg;
if (item == null)
{
return false;
}
return A.Equals(item.A) && B.Equals(item.B);
}
public override int GetHashCode()
{
return (B * 397) ^ (A != null ? A.GetHashCode() : 0);
}
}
public class AsyncObserverArg : GenericArg
{
public AsyncObserverArg(string a, int b) : base(a, b) { }
}
public class AsyncObservableArg : GenericArg
{
public AsyncObservableArg(string a, int b) : base(a, b) { }
}
public class AsyncStreamArg : GenericArg
{
public AsyncStreamArg(string a, int b) : base(a, b) { }
}
public class StreamSubscriptionHandleArg : GenericArg
{
public StreamSubscriptionHandleArg(string a, int b) : base(a, b) { }
}
public class StreamLifecycleTestGrainBase : Grain<StreamLifecycleTestGrainState>
{
protected Logger logger;
protected string _lastProviderName;
protected IStreamProvider _streamProvider;
#if COUNT_ACTIVATE_DEACTIVATE
private IActivateDeactivateWatcherGrain watcher;
#endif
protected Task RecordActivate()
{
#if COUNT_ACTIVATE_DEACTIVATE
watcher = GrainFactory.GetGrain<IActivateDeactivateWatcherGrain>(0);
return watcher.RecordActivateCall(IdentityString);
#else
return Task.CompletedTask;
#endif
}
protected Task RecordDeactivate()
{
#if COUNT_ACTIVATE_DEACTIVATE
return watcher.RecordDeactivateCall(IdentityString);
#else
return Task.CompletedTask;
#endif
}
protected void InitStream(Guid streamId, string streamNamespace, string providerToUse)
{
if (streamId == null) throw new ArgumentNullException("streamId", "Can't have null stream id");
if (streamNamespace == null) throw new ArgumentNullException("streamNamespace", "Can't have null stream namespace values");
if (providerToUse == null) throw new ArgumentNullException("providerToUse", "Can't have null stream provider name");
if (State.Stream != null && State.Stream.Guid != streamId)
{
if (logger.IsVerbose) logger.Verbose("Stream already exists for StreamId={0} StreamProvider={1} - Resetting", State.Stream, providerToUse);
// Note: in this test, we are deliberately not doing Unsubscribe consumers, just discard old stream and let auto-cleanup functions do their thing.
State.ConsumerSubscriptionHandles.Clear();
State.IsProducer = false;
State.NumMessagesSent = 0;
State.NumErrors = 0;
State.Stream = null;
}
if (logger.IsVerbose) logger.Verbose("InitStream StreamId={0} StreamProvider={1}", streamId, providerToUse);
if (providerToUse != _lastProviderName)
{
_streamProvider = GetStreamProvider(providerToUse);
_lastProviderName = providerToUse;
}
IAsyncStream<int> stream = _streamProvider.GetStream<int>(streamId, streamNamespace);
State.Stream = stream;
State.StreamProviderName = providerToUse;
if (logger.IsVerbose) logger.Verbose("InitStream returning with Stream={0} with ref type = {1}", State.Stream, State.Stream.GetType().FullName);
}
}
[Orleans.Providers.StorageProvider(ProviderName = "MemoryStore")]
internal class StreamLifecycleConsumerGrain : StreamLifecycleTestGrainBase, IStreamLifecycleConsumerGrain
{
protected readonly ISiloRuntimeClient runtimeClient;
protected readonly IStreamProviderRuntime streamProviderRuntime;
public StreamLifecycleConsumerGrain(ISiloRuntimeClient runtimeClient, IStreamProviderRuntime streamProviderRuntime)
{
this.runtimeClient = runtimeClient;
this.streamProviderRuntime = streamProviderRuntime;
}
protected IDictionary<StreamSubscriptionHandle<int>, MyStreamObserver<int>> Observers { get; set; }
public override async Task OnActivateAsync()
{
logger = this.GetLogger(GetType().Name + "-" + IdentityString);
if (logger.IsVerbose) logger.Verbose("OnActivateAsync");
await RecordActivate();
if (Observers == null)
{
Observers = new Dictionary<StreamSubscriptionHandle<int>, MyStreamObserver<int>>();
}
if (State.Stream != null && State.StreamProviderName != null)
{
if (State.ConsumerSubscriptionHandles.Count > 0)
{
var handles = State.ConsumerSubscriptionHandles.ToArray();
logger.Info("ReconnectConsumerHandles SubscriptionHandles={0} Grain={1}", Utils.EnumerableToString(handles), this.AsReference<IStreamLifecycleConsumerGrain>());
foreach (var handle in handles)
{
var observer = new MyStreamObserver<int>(logger);
StreamSubscriptionHandle<int> subsHandle = await handle.ResumeAsync(observer);
Observers.Add(subsHandle, observer);
}
}
}
else
{
if (logger.IsVerbose) logger.Verbose("Not conected to stream yet.");
}
}
public override async Task OnDeactivateAsync()
{
if (logger.IsVerbose) logger.Verbose("OnDeactivateAsync");
await RecordDeactivate();
}
public Task<int> GetReceivedCount()
{
int numReceived = Observers.Sum(o => o.Value.NumItems);
if (logger.IsVerbose) logger.Verbose("ReceivedCount={0}", numReceived);
return Task.FromResult(numReceived);
}
public Task<int> GetErrorsCount()
{
int numErrors = Observers.Sum(o => o.Value.NumErrors);
if (logger.IsVerbose) logger.Verbose("ErrorsCount={0}", numErrors);
return Task.FromResult(numErrors);
}
public Task Ping()
{
logger.Info("Ping");
return Task.CompletedTask;
}
public virtual async Task BecomeConsumer(Guid streamId, string streamNamespace, string providerToUse)
{
if (logger.IsVerbose) logger.Verbose("BecomeConsumer StreamId={0} StreamProvider={1} Grain={2}", streamId, providerToUse, this.AsReference<IStreamLifecycleConsumerGrain>());
InitStream(streamId, streamNamespace, providerToUse);
var observer = new MyStreamObserver<int>(logger);
var subsHandle = await State.Stream.SubscribeAsync(observer);
State.ConsumerSubscriptionHandles.Add(subsHandle);
Observers.Add(subsHandle, observer);
await WriteStateAsync();
}
public virtual async Task TestBecomeConsumerSlim(Guid streamIdGuid, string streamNamespace, string providerName)
{
InitStream(streamIdGuid, streamNamespace, providerName);
var observer = new MyStreamObserver<int>(logger);
//var subsHandle = await State.Stream.SubscribeAsync(observer);
IStreamConsumerExtension myExtensionReference;
#if USE_CAST
myExtensionReference = StreamConsumerExtensionFactory.Cast(this.AsReference());
#else
var tup = await runtimeClient.BindExtension<StreamConsumerExtension, IStreamConsumerExtension>(
() => new StreamConsumerExtension(streamProviderRuntime));
StreamConsumerExtension myExtension = tup.Item1;
myExtensionReference = tup.Item2;
#endif
string extKey = providerName + "_" + State.Stream.Namespace;
IPubSubRendezvousGrain pubsub = GrainFactory.GetGrain<IPubSubRendezvousGrain>(streamIdGuid, extKey, null);
GuidId subscriptionId = GuidId.GetNewGuidId();
await pubsub.RegisterConsumer(subscriptionId, ((StreamImpl<int>)State.Stream).StreamId, myExtensionReference, null);
myExtension.SetObserver(subscriptionId, ((StreamImpl<int>)State.Stream), observer, null, null, null);
}
public async Task RemoveConsumer(Guid streamId, string streamNamespace, string providerName, StreamSubscriptionHandle<int> subsHandle)
{
if (logger.IsVerbose) logger.Verbose("RemoveConsumer StreamId={0} StreamProvider={1}", streamId, providerName);
if (State.ConsumerSubscriptionHandles.Count == 0) throw new InvalidOperationException("Not a Consumer");
await subsHandle.UnsubscribeAsync();
Observers.Remove(subsHandle);
State.ConsumerSubscriptionHandles.Remove(subsHandle);
await WriteStateAsync();
}
public async Task ClearGrain()
{
logger.Info("ClearGrain");
var subsHandles = State.ConsumerSubscriptionHandles.ToArray();
foreach (var handle in subsHandles)
{
await handle.UnsubscribeAsync();
}
State.ConsumerSubscriptionHandles.Clear();
State.Stream = null;
State.IsProducer = false;
Observers.Clear();
await ClearStateAsync();
}
}
[Orleans.Providers.StorageProvider(ProviderName = "MemoryStore")]
internal class FilteredStreamConsumerGrain : StreamLifecycleConsumerGrain, IFilteredStreamConsumerGrain
{
private static Logger _logger;
private const int FilterDataOdd = 1;
private const int FilterDataEven = 2;
public FilteredStreamConsumerGrain(ISiloRuntimeClient runtimeClient, IStreamProviderRuntime streamProviderRuntime)
: base(runtimeClient, streamProviderRuntime)
{
}
public override Task BecomeConsumer(Guid streamId, string streamNamespace, string providerName)
{
throw new InvalidOperationException("Should not be calling unfiltered BecomeConsumer method on " + GetType());
}
public async Task BecomeConsumer(Guid streamId, string streamNamespace, string providerName, bool sendEvensOnly)
{
_logger = logger;
if (logger.IsVerbose)
logger.Verbose("BecomeConsumer StreamId={0} StreamProvider={1} Filter={2} Grain={3}",
streamId, providerName, sendEvensOnly, this.AsReference<IFilteredStreamConsumerGrain>());
InitStream(streamId, streamNamespace, providerName);
var observer = new MyStreamObserver<int>(logger);
StreamFilterPredicate filterFunc;
object filterData;
if (sendEvensOnly)
{
filterFunc = FilterIsEven;
filterData = FilterDataEven;
}
else
{
filterFunc = FilterIsOdd;
filterData = FilterDataOdd;
}
var subsHandle = await State.Stream.SubscribeAsync(observer, null, filterFunc, filterData);
State.ConsumerSubscriptionHandles.Add(subsHandle);
Observers.Add(subsHandle, observer);
await WriteStateAsync();
}
public async Task SubscribeWithBadFunc(Guid streamId, string streamNamespace, string providerName)
{
logger.Info("SubscribeWithBadFunc StreamId={0} StreamProvider={1}Grain={2}",
streamId, providerName, this.AsReference<IFilteredStreamConsumerGrain>());
InitStream(streamId, streamNamespace, providerName);
var observer = new MyStreamObserver<int>(logger);
StreamFilterPredicate filterFunc = BadFunc;
// This next call should fail because func is not static
await State.Stream.SubscribeAsync(observer, null, filterFunc);
}
public static bool FilterIsEven(IStreamIdentity stream, object filterData, object item)
{
if (!FilterDataEven.Equals(filterData))
{
throw new Exception("Should have got the correct filter data passed in, but got: " + filterData);
}
int val = (int) item;
bool result = val % 2 == 0;
if (_logger != null) _logger.Info("FilterIsEven(Stream={0},FilterData={1},Item={2}) Filter = {3}", stream, filterData, item, result);
return result;
}
public static bool FilterIsOdd(IStreamIdentity stream, object filterData, object item)
{
if (!FilterDataOdd.Equals(filterData))
{
throw new Exception("Should have got the correct filter data passed in, but got: " + filterData);
}
int val = (int) item;
bool result = val % 2 == 1;
if (_logger != null) _logger.Info("FilterIsOdd(Stream={0},FilterData={1},Item={2}) Filter = {3}", stream, filterData, item, result);
return result;
}
// Function is not static, so cannot be used as a filter predicate function.
public bool BadFunc(IStreamIdentity stream, object filterData, object item)
{
return true;
}
}
[Orleans.Providers.StorageProvider(ProviderName = "MemoryStore")]
public class StreamLifecycleProducerGrain : StreamLifecycleTestGrainBase, IStreamLifecycleProducerGrain
{
public override async Task OnActivateAsync()
{
logger = this.GetLogger(GetType().Name + "-" + IdentityString);
if (logger.IsVerbose) logger.Verbose("OnActivateAsync");
await RecordActivate();
if (State.Stream != null && State.StreamProviderName != null)
{
if (logger.IsVerbose) logger.Verbose("Reconnected to stream {0}", State.Stream);
}
else
{
if (logger.IsVerbose) logger.Verbose("Not connected to stream yet.");
}
}
public override async Task OnDeactivateAsync()
{
if (logger.IsVerbose) logger.Verbose("OnDeactivateAsync");
await RecordDeactivate();
}
public Task<int> GetSendCount()
{
int result = State.NumMessagesSent;
if (logger.IsVerbose) logger.Verbose("GetSendCount={0}", result);
return Task.FromResult(result);
}
public Task<int> GetErrorsCount()
{
int result = State.NumErrors;
if (logger.IsVerbose) logger.Verbose("GetErrorsCount={0}", result);
return Task.FromResult(result);
}
public Task Ping()
{
logger.Info("Ping");
return Task.CompletedTask;
}
public async Task SendItem(int item)
{
if (!State.IsProducer || State.Stream == null) throw new InvalidOperationException("Not a Producer");
if (logger.IsVerbose) logger.Verbose("SendItem Item={0}", item);
Exception error = null;
try
{
await State.Stream.OnNextAsync(item);
if (logger.IsVerbose) logger.Verbose("Successful SendItem " + item);
State.NumMessagesSent++;
}
catch (Exception exc)
{
logger.Error(0, "Error from SendItem " + item, exc);
State.NumErrors++;
error = exc;
}
await WriteStateAsync(); // Update counts in persisted state
if (error != null)
{
throw new AggregateException(error);
}
if (logger.IsVerbose) logger.Verbose("Finished SendItem for Item={0}", item);
}
public async Task BecomeProducer(Guid streamId, string streamNamespace, string providerName)
{
if (logger.IsVerbose) logger.Verbose("BecomeProducer StreamId={0} StreamProvider={1}", streamId, providerName);
InitStream(streamId, streamNamespace, providerName);
State.IsProducer = true;
// Send an initial message to ensure we are properly initialized as a Producer.
await State.Stream.OnNextAsync(0);
State.NumMessagesSent++;
await WriteStateAsync();
if (logger.IsVerbose) logger.Verbose("Finished BecomeProducer for StreamId={0} StreamProvider={1}", streamId, providerName);
}
public async Task ClearGrain()
{
logger.Info("ClearGrain");
State.IsProducer = false;
State.Stream = null;
await ClearStateAsync();
}
public async Task DoDeactivateNoClose()
{
if (logger.IsVerbose) logger.Verbose("DoDeactivateNoClose");
State.IsProducer = false;
State.Stream = null;
await WriteStateAsync();
if (logger.IsVerbose) logger.Verbose("Calling DeactivateOnIdle");
DeactivateOnIdle();
}
}
[Serializable]
public class MyStreamObserver<T> : IAsyncObserver<T>
{
internal int NumItems { get; private set; }
internal int NumErrors { get; private set; }
private readonly Logger logger;
internal MyStreamObserver(Logger logger)
{
this.logger = logger;
}
public Task OnNextAsync(T item, StreamSequenceToken token)
{
NumItems++;
if (logger != null && logger.IsVerbose)
{
logger.Verbose("Received OnNextAsync - Item={0} - Total Items={1} Errors={2}", item, NumItems, NumErrors);
}
return Task.CompletedTask;
}
public Task OnCompletedAsync()
{
if (logger != null)
{
logger.Info("Receive OnCompletedAsync - Total Items={0} Errors={1}", NumItems, NumErrors);
}
return Task.CompletedTask;
}
public Task OnErrorAsync(Exception ex)
{
NumErrors++;
if (logger != null)
{
logger.Warn(1, "Received OnErrorAsync - Exception={0} - Total Items={1} Errors={2}", ex, NumItems, NumErrors);
}
return Task.CompletedTask;
}
}
public class ClosedTypeStreamObserver : MyStreamObserver<AsyncObserverArg>
{
public ClosedTypeStreamObserver(Logger logger) : base(logger)
{
}
}
public interface IClosedTypeAsyncObservable : IAsyncObservable<AsyncObservableArg> { }
public interface IClosedTypeAsyncStream : IAsyncStream<AsyncStreamArg> { }
internal class ClosedTypeStreamSubscriptionHandle : StreamSubscriptionHandleImpl<StreamSubscriptionHandleArg>
{
public ClosedTypeStreamSubscriptionHandle() : base(null, null) { /* not a subject to the creation */ }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
namespace System.Xml.Xsl.Qil
{
/// <summary>A base internal class for QIL visitors.</summary>
/// <remarks>
/// <p>QilVisitor is a base internal class for traversing QIL graphs. Override individual Visit methods to change
/// behavior for only certain node types; override Visit() to change behavior for all node types at once; override
/// VisitChildren() to change the algorithm for iterating and visiting children.</p>
/// <p>Subclasses may also find it useful to annotate the tree during visitation.</p>
/// </remarks>
internal abstract class QilVisitor
{
//-----------------------------------------------
// QilVisitor methods (manually generated)
//-----------------------------------------------
/// <summary>
/// If a reference is passed to the Visit() method, it is assumed to be the definition.
/// This method assumes it is a reference to a definition.
/// For example, if a Let node is visited, is it the Let definition or a reference to the
/// the Let definition? Without context, it is ambiguous. This method allows a caller
/// to disambiguate.
/// </summary>
protected virtual QilNode VisitAssumeReference(QilNode expr)
{
if (expr is QilReference)
return VisitReference(expr);
return Visit(expr);
}
/// <summary>
/// Visit all children of "parent". By default, take care to avoid circular visits.
/// </summary>
protected virtual QilNode VisitChildren(QilNode parent)
{
for (int i = 0; i < parent.Count; i++)
{
// If child is a reference, then call VisitReference instead of Visit in order to avoid circular visits.
if (IsReference(parent, i))
VisitReference(parent[i]);
else
Visit(parent[i]);
}
return parent;
}
/// <summary>
/// Visit all children of "parent". Take care to avoid circular visits.
/// </summary>
protected virtual bool IsReference(QilNode parent, int childNum)
{
QilNode child = parent[childNum];
if (child != null)
{
switch (child.NodeType)
{
case QilNodeType.For:
case QilNodeType.Let:
case QilNodeType.Parameter:
// Is this a reference or a definition?
switch (parent.NodeType)
{
case QilNodeType.Loop:
case QilNodeType.Filter:
case QilNodeType.Sort:
// Second child of these node types is a reference; first child is a definition
return childNum == 1;
case QilNodeType.GlobalVariableList:
case QilNodeType.GlobalParameterList:
case QilNodeType.FormalParameterList:
// All children of definition lists are definitions
return false;
}
// All other cases are references
return true;
case QilNodeType.Function:
// If parent is an Invoke node, then visit a reference to the function
return parent.NodeType == QilNodeType.Invoke;
}
}
return false;
}
//-----------------------------------------------
// QilVisitor methods (auto-generated)
//-----------------------------------------------
// Do not edit this region
#region AUTOGENERATED
protected virtual QilNode Visit(QilNode n)
{
if (n == null)
return VisitNull();
switch (n.NodeType)
{
case QilNodeType.QilExpression: return VisitQilExpression((QilExpression)n);
case QilNodeType.FunctionList: return VisitFunctionList((QilList)n);
case QilNodeType.GlobalVariableList: return VisitGlobalVariableList((QilList)n);
case QilNodeType.GlobalParameterList: return VisitGlobalParameterList((QilList)n);
case QilNodeType.ActualParameterList: return VisitActualParameterList((QilList)n);
case QilNodeType.FormalParameterList: return VisitFormalParameterList((QilList)n);
case QilNodeType.SortKeyList: return VisitSortKeyList((QilList)n);
case QilNodeType.BranchList: return VisitBranchList((QilList)n);
case QilNodeType.OptimizeBarrier: return VisitOptimizeBarrier((QilUnary)n);
case QilNodeType.Unknown: return VisitUnknown(n);
case QilNodeType.DataSource: return VisitDataSource((QilDataSource)n);
case QilNodeType.Nop: return VisitNop((QilUnary)n);
case QilNodeType.Error: return VisitError((QilUnary)n);
case QilNodeType.Warning: return VisitWarning((QilUnary)n);
case QilNodeType.For: return VisitFor((QilIterator)n);
case QilNodeType.Let: return VisitLet((QilIterator)n);
case QilNodeType.Parameter: return VisitParameter((QilParameter)n);
case QilNodeType.PositionOf: return VisitPositionOf((QilUnary)n);
case QilNodeType.True: return VisitTrue(n);
case QilNodeType.False: return VisitFalse(n);
case QilNodeType.LiteralString: return VisitLiteralString((QilLiteral)n);
case QilNodeType.LiteralInt32: return VisitLiteralInt32((QilLiteral)n);
case QilNodeType.LiteralInt64: return VisitLiteralInt64((QilLiteral)n);
case QilNodeType.LiteralDouble: return VisitLiteralDouble((QilLiteral)n);
case QilNodeType.LiteralDecimal: return VisitLiteralDecimal((QilLiteral)n);
case QilNodeType.LiteralQName: return VisitLiteralQName((QilName)n);
case QilNodeType.LiteralType: return VisitLiteralType((QilLiteral)n);
case QilNodeType.LiteralObject: return VisitLiteralObject((QilLiteral)n);
case QilNodeType.And: return VisitAnd((QilBinary)n);
case QilNodeType.Or: return VisitOr((QilBinary)n);
case QilNodeType.Not: return VisitNot((QilUnary)n);
case QilNodeType.Conditional: return VisitConditional((QilTernary)n);
case QilNodeType.Choice: return VisitChoice((QilChoice)n);
case QilNodeType.Length: return VisitLength((QilUnary)n);
case QilNodeType.Sequence: return VisitSequence((QilList)n);
case QilNodeType.Union: return VisitUnion((QilBinary)n);
case QilNodeType.Intersection: return VisitIntersection((QilBinary)n);
case QilNodeType.Difference: return VisitDifference((QilBinary)n);
case QilNodeType.Average: return VisitAverage((QilUnary)n);
case QilNodeType.Sum: return VisitSum((QilUnary)n);
case QilNodeType.Minimum: return VisitMinimum((QilUnary)n);
case QilNodeType.Maximum: return VisitMaximum((QilUnary)n);
case QilNodeType.Negate: return VisitNegate((QilUnary)n);
case QilNodeType.Add: return VisitAdd((QilBinary)n);
case QilNodeType.Subtract: return VisitSubtract((QilBinary)n);
case QilNodeType.Multiply: return VisitMultiply((QilBinary)n);
case QilNodeType.Divide: return VisitDivide((QilBinary)n);
case QilNodeType.Modulo: return VisitModulo((QilBinary)n);
case QilNodeType.StrLength: return VisitStrLength((QilUnary)n);
case QilNodeType.StrConcat: return VisitStrConcat((QilStrConcat)n);
case QilNodeType.StrParseQName: return VisitStrParseQName((QilBinary)n);
case QilNodeType.Ne: return VisitNe((QilBinary)n);
case QilNodeType.Eq: return VisitEq((QilBinary)n);
case QilNodeType.Gt: return VisitGt((QilBinary)n);
case QilNodeType.Ge: return VisitGe((QilBinary)n);
case QilNodeType.Lt: return VisitLt((QilBinary)n);
case QilNodeType.Le: return VisitLe((QilBinary)n);
case QilNodeType.Is: return VisitIs((QilBinary)n);
case QilNodeType.After: return VisitAfter((QilBinary)n);
case QilNodeType.Before: return VisitBefore((QilBinary)n);
case QilNodeType.Loop: return VisitLoop((QilLoop)n);
case QilNodeType.Filter: return VisitFilter((QilLoop)n);
case QilNodeType.Sort: return VisitSort((QilLoop)n);
case QilNodeType.SortKey: return VisitSortKey((QilSortKey)n);
case QilNodeType.DocOrderDistinct: return VisitDocOrderDistinct((QilUnary)n);
case QilNodeType.Function: return VisitFunction((QilFunction)n);
case QilNodeType.Invoke: return VisitInvoke((QilInvoke)n);
case QilNodeType.Content: return VisitContent((QilUnary)n);
case QilNodeType.Attribute: return VisitAttribute((QilBinary)n);
case QilNodeType.Parent: return VisitParent((QilUnary)n);
case QilNodeType.Root: return VisitRoot((QilUnary)n);
case QilNodeType.XmlContext: return VisitXmlContext(n);
case QilNodeType.Descendant: return VisitDescendant((QilUnary)n);
case QilNodeType.DescendantOrSelf: return VisitDescendantOrSelf((QilUnary)n);
case QilNodeType.Ancestor: return VisitAncestor((QilUnary)n);
case QilNodeType.AncestorOrSelf: return VisitAncestorOrSelf((QilUnary)n);
case QilNodeType.Preceding: return VisitPreceding((QilUnary)n);
case QilNodeType.FollowingSibling: return VisitFollowingSibling((QilUnary)n);
case QilNodeType.PrecedingSibling: return VisitPrecedingSibling((QilUnary)n);
case QilNodeType.NodeRange: return VisitNodeRange((QilBinary)n);
case QilNodeType.Deref: return VisitDeref((QilBinary)n);
case QilNodeType.ElementCtor: return VisitElementCtor((QilBinary)n);
case QilNodeType.AttributeCtor: return VisitAttributeCtor((QilBinary)n);
case QilNodeType.CommentCtor: return VisitCommentCtor((QilUnary)n);
case QilNodeType.PICtor: return VisitPICtor((QilBinary)n);
case QilNodeType.TextCtor: return VisitTextCtor((QilUnary)n);
case QilNodeType.RawTextCtor: return VisitRawTextCtor((QilUnary)n);
case QilNodeType.DocumentCtor: return VisitDocumentCtor((QilUnary)n);
case QilNodeType.NamespaceDecl: return VisitNamespaceDecl((QilBinary)n);
case QilNodeType.RtfCtor: return VisitRtfCtor((QilBinary)n);
case QilNodeType.NameOf: return VisitNameOf((QilUnary)n);
case QilNodeType.LocalNameOf: return VisitLocalNameOf((QilUnary)n);
case QilNodeType.NamespaceUriOf: return VisitNamespaceUriOf((QilUnary)n);
case QilNodeType.PrefixOf: return VisitPrefixOf((QilUnary)n);
case QilNodeType.TypeAssert: return VisitTypeAssert((QilTargetType)n);
case QilNodeType.IsType: return VisitIsType((QilTargetType)n);
case QilNodeType.IsEmpty: return VisitIsEmpty((QilUnary)n);
case QilNodeType.XPathNodeValue: return VisitXPathNodeValue((QilUnary)n);
case QilNodeType.XPathFollowing: return VisitXPathFollowing((QilUnary)n);
case QilNodeType.XPathPreceding: return VisitXPathPreceding((QilUnary)n);
case QilNodeType.XPathNamespace: return VisitXPathNamespace((QilUnary)n);
case QilNodeType.XsltGenerateId: return VisitXsltGenerateId((QilUnary)n);
case QilNodeType.XsltInvokeLateBound: return VisitXsltInvokeLateBound((QilInvokeLateBound)n);
case QilNodeType.XsltInvokeEarlyBound: return VisitXsltInvokeEarlyBound((QilInvokeEarlyBound)n);
case QilNodeType.XsltCopy: return VisitXsltCopy((QilBinary)n);
case QilNodeType.XsltCopyOf: return VisitXsltCopyOf((QilUnary)n);
case QilNodeType.XsltConvert: return VisitXsltConvert((QilTargetType)n);
default: return VisitUnknown(n);
}
}
protected virtual QilNode VisitReference(QilNode n)
{
if (n == null)
return VisitNull();
switch (n.NodeType)
{
case QilNodeType.For: return VisitForReference((QilIterator)n);
case QilNodeType.Let: return VisitLetReference((QilIterator)n);
case QilNodeType.Parameter: return VisitParameterReference((QilParameter)n);
case QilNodeType.Function: return VisitFunctionReference((QilFunction)n);
default: return VisitUnknown(n);
}
}
protected virtual QilNode VisitNull() { return null; }
#region meta
protected virtual QilNode VisitQilExpression(QilExpression n) { return VisitChildren(n); }
protected virtual QilNode VisitFunctionList(QilList n) { return VisitChildren(n); }
protected virtual QilNode VisitGlobalVariableList(QilList n) { return VisitChildren(n); }
protected virtual QilNode VisitGlobalParameterList(QilList n) { return VisitChildren(n); }
protected virtual QilNode VisitActualParameterList(QilList n) { return VisitChildren(n); }
protected virtual QilNode VisitFormalParameterList(QilList n) { return VisitChildren(n); }
protected virtual QilNode VisitSortKeyList(QilList n) { return VisitChildren(n); }
protected virtual QilNode VisitBranchList(QilList n) { return VisitChildren(n); }
protected virtual QilNode VisitOptimizeBarrier(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitUnknown(QilNode n) { return VisitChildren(n); }
#endregion
#region specials
protected virtual QilNode VisitDataSource(QilDataSource n) { return VisitChildren(n); }
protected virtual QilNode VisitNop(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitError(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitWarning(QilUnary n) { return VisitChildren(n); }
#endregion
#region variables
protected virtual QilNode VisitFor(QilIterator n) { return VisitChildren(n); }
protected virtual QilNode VisitForReference(QilIterator n) { return n; }
protected virtual QilNode VisitLet(QilIterator n) { return VisitChildren(n); }
protected virtual QilNode VisitLetReference(QilIterator n) { return n; }
protected virtual QilNode VisitParameter(QilParameter n) { return VisitChildren(n); }
protected virtual QilNode VisitParameterReference(QilParameter n) { return n; }
protected virtual QilNode VisitPositionOf(QilUnary n) { return VisitChildren(n); }
#endregion
#region literals
protected virtual QilNode VisitTrue(QilNode n) { return VisitChildren(n); }
protected virtual QilNode VisitFalse(QilNode n) { return VisitChildren(n); }
protected virtual QilNode VisitLiteralString(QilLiteral n) { return VisitChildren(n); }
protected virtual QilNode VisitLiteralInt32(QilLiteral n) { return VisitChildren(n); }
protected virtual QilNode VisitLiteralInt64(QilLiteral n) { return VisitChildren(n); }
protected virtual QilNode VisitLiteralDouble(QilLiteral n) { return VisitChildren(n); }
protected virtual QilNode VisitLiteralDecimal(QilLiteral n) { return VisitChildren(n); }
protected virtual QilNode VisitLiteralQName(QilName n) { return VisitChildren(n); }
protected virtual QilNode VisitLiteralType(QilLiteral n) { return VisitChildren(n); }
protected virtual QilNode VisitLiteralObject(QilLiteral n) { return VisitChildren(n); }
#endregion
#region boolean operators
protected virtual QilNode VisitAnd(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitOr(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitNot(QilUnary n) { return VisitChildren(n); }
#endregion
#region choice
protected virtual QilNode VisitConditional(QilTernary n) { return VisitChildren(n); }
protected virtual QilNode VisitChoice(QilChoice n) { return VisitChildren(n); }
#endregion
#region collection operators
protected virtual QilNode VisitLength(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitSequence(QilList n) { return VisitChildren(n); }
protected virtual QilNode VisitUnion(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitIntersection(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitDifference(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitAverage(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitSum(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitMinimum(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitMaximum(QilUnary n) { return VisitChildren(n); }
#endregion
#region arithmetic operators
protected virtual QilNode VisitNegate(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitAdd(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitSubtract(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitMultiply(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitDivide(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitModulo(QilBinary n) { return VisitChildren(n); }
#endregion
#region string operators
protected virtual QilNode VisitStrLength(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitStrConcat(QilStrConcat n) { return VisitChildren(n); }
protected virtual QilNode VisitStrParseQName(QilBinary n) { return VisitChildren(n); }
#endregion
#region value comparison operators
protected virtual QilNode VisitNe(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitEq(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitGt(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitGe(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitLt(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitLe(QilBinary n) { return VisitChildren(n); }
#endregion
#region node comparison operators
protected virtual QilNode VisitIs(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitAfter(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitBefore(QilBinary n) { return VisitChildren(n); }
#endregion
#region loops
protected virtual QilNode VisitLoop(QilLoop n) { return VisitChildren(n); }
protected virtual QilNode VisitFilter(QilLoop n) { return VisitChildren(n); }
#endregion
#region sorting
protected virtual QilNode VisitSort(QilLoop n) { return VisitChildren(n); }
protected virtual QilNode VisitSortKey(QilSortKey n) { return VisitChildren(n); }
protected virtual QilNode VisitDocOrderDistinct(QilUnary n) { return VisitChildren(n); }
#endregion
#region function definition and invocation
protected virtual QilNode VisitFunction(QilFunction n) { return VisitChildren(n); }
protected virtual QilNode VisitFunctionReference(QilFunction n) { return n; }
protected virtual QilNode VisitInvoke(QilInvoke n) { return VisitChildren(n); }
#endregion
#region XML navigation
protected virtual QilNode VisitContent(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitAttribute(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitParent(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitRoot(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitXmlContext(QilNode n) { return VisitChildren(n); }
protected virtual QilNode VisitDescendant(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitDescendantOrSelf(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitAncestor(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitAncestorOrSelf(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitPreceding(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitFollowingSibling(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitPrecedingSibling(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitNodeRange(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitDeref(QilBinary n) { return VisitChildren(n); }
#endregion
#region XML construction
protected virtual QilNode VisitElementCtor(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitAttributeCtor(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitCommentCtor(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitPICtor(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitTextCtor(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitRawTextCtor(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitDocumentCtor(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitNamespaceDecl(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitRtfCtor(QilBinary n) { return VisitChildren(n); }
#endregion
#region Node properties
protected virtual QilNode VisitNameOf(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitLocalNameOf(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitNamespaceUriOf(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitPrefixOf(QilUnary n) { return VisitChildren(n); }
#endregion
#region Type operators
protected virtual QilNode VisitTypeAssert(QilTargetType n) { return VisitChildren(n); }
protected virtual QilNode VisitIsType(QilTargetType n) { return VisitChildren(n); }
protected virtual QilNode VisitIsEmpty(QilUnary n) { return VisitChildren(n); }
#endregion
#region XPath operators
protected virtual QilNode VisitXPathNodeValue(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitXPathFollowing(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitXPathPreceding(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitXPathNamespace(QilUnary n) { return VisitChildren(n); }
#endregion
#region XSLT
protected virtual QilNode VisitXsltGenerateId(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitXsltInvokeLateBound(QilInvokeLateBound n) { return VisitChildren(n); }
protected virtual QilNode VisitXsltInvokeEarlyBound(QilInvokeEarlyBound n) { return VisitChildren(n); }
protected virtual QilNode VisitXsltCopy(QilBinary n) { return VisitChildren(n); }
protected virtual QilNode VisitXsltCopyOf(QilUnary n) { return VisitChildren(n); }
protected virtual QilNode VisitXsltConvert(QilTargetType n) { return VisitChildren(n); }
#endregion
#endregion // AUTOGENERATED
}
//for checking the depth of QilNode to avoid StackOverflow in visit stage
internal class QilDepthChecker
{
private const int MAX_QIL_DEPTH = 800;
private Dictionary<QilNode, bool> _visitedRef = new Dictionary<QilNode, bool>();
public static void Check(QilNode input)
{
if (LocalAppContextSwitches.LimitXPathComplexity)
{
new QilDepthChecker().Check(input, 0);
}
}
private void Check(QilNode input, int depth)
{
if (depth > MAX_QIL_DEPTH)
{
throw XsltException.Create(SR.Xslt_InputTooComplex);
}
//QilReference node may duplicate, the first one is definition and should expand, others are reference.
if (input is QilReference)
{
if (_visitedRef.ContainsKey(input))
return;
_visitedRef[input] = true;
}
int nextDepth = depth + 1;
for (int i = 0; i < input.Count; i++)
{
QilNode child = input[i];
if (child != null)
{
Check(child, nextDepth);
}
}
}
}
}
| |
using Skybrud.Social.Facebook.Fields;
using Skybrud.Social.Facebook.Models.Photos;
namespace Skybrud.Social.Facebook.Constants {
/// <summary>
/// Static class with constants for the fields available for a Facebook post (<see cref="FacebookPhoto" />).
///
/// The class is auto-generated and based on the fields listed in the Facebook Graph API documentation. Not all
/// fields may have been mapped for the implementation in Skybrud.Social.
/// </summary>
/// <see>
/// <cref>https://developers.facebook.com/docs/graph-api/reference/v2.12/post</cref>
/// </see>
public static class FacebookPostFields {
#region Individial fields
/// <summary>
/// The post ID.
/// </summary>
public static readonly FacebookField Id = new FacebookField("id");
/// <summary>
/// The admin creator of a Page post. If the Page has only one admin, no data will be returned. Requires a Page
/// Access Token and the.
/// </summary>
public static readonly FacebookField AdminCreator = new FacebookField("admin_creator");
/// <summary>
/// Information about the app this post was published by.
/// </summary>
public static readonly FacebookField Application = new FacebookField("application");
/// <summary>
/// The call to action type used in any Page posts for.
/// </summary>
public static readonly FacebookField CallToAction = new FacebookField("call_to_action");
/// <summary>
/// Whether the Page viewer can send a private reply to this Post. Requires the <c>read_page_mailboxes</c>
/// permission.
/// </summary>
public static readonly FacebookField CanReplyPrivately = new FacebookField("can_reply_privately");
/// <summary>
/// Link caption in post that appears below name. The caption must be an actual URLs and should accurately
/// reflect the URL and associated advertiser or business someone visits when they click on it.
/// </summary>
public static readonly FacebookField Caption = new FacebookField("caption");
/// <summary>
/// The time the post was initially published. For a post about a life event, this will be the date and time of
/// the life event.
/// </summary>
public static readonly FacebookField CreatedTime = new FacebookField("created_time");
/// <summary>
/// A description of a link in the post (appears beneath the.
/// </summary>
public static readonly FacebookField Description = new FacebookField("description");
/// <summary>
/// Object that controls.
/// </summary>
public static readonly FacebookField FeedTargeting = new FacebookField("feed_targeting");
/// <summary>
/// Information (<c>name</c> and <c>id</c>) about the <a
/// href="https://developers.facebook.com/docs/graph-api/reference/profile" target="_blank">Profile</a> that
/// created the Post.
/// </summary>
public static readonly FacebookField From = new FacebookField("from");
/// <summary>
/// URL to a full-sized version of the Photo published in the Post or scraped from a <c>link</c> in the Post. If
/// the photo's largest dimension exceeds 720 pixels, it will be resized, with the largest dimension set to 720.
/// </summary>
public static readonly FacebookField FullPicture = new FacebookField("full_picture");
/// <summary>
/// A link to an icon representing the type of this post.
/// </summary>
public static readonly FacebookField Icon = new FacebookField("icon");
/// <summary>
/// Whether the post can be promoted on Instagram. It returns the enum "eligible" if it can be promoted.
/// Otherwise it returns an enum for why it cannot be promoted.
/// </summary>
public static readonly FacebookField InstagramEligibility = new FacebookField("instagram_eligibility");
/// <summary>
/// If this post is marked as hidden (Applies to Pages only).
/// </summary>
public static readonly FacebookField IsHidden = new FacebookField("is_hidden");
/// <summary>
/// Whether this post can be promoted in Instagram.
/// </summary>
public static readonly FacebookField IsInstagramEligible = new FacebookField("is_instagram_eligible");
/// <summary>
/// Indicates whether a scheduled post was published (applies to scheduled Page Post only, for users post and
/// instantly published posts this value is always.
/// </summary>
public static readonly FacebookField IsPublished = new FacebookField("is_published");
/// <summary>
/// The link attached to this post.
/// </summary>
public static readonly FacebookField Link = new FacebookField("link");
/// <summary>
/// The status message in the post.
/// </summary>
public static readonly FacebookField Message = new FacebookField("message");
/// <summary>
/// An array of profiles tagged in the.
/// </summary>
public static readonly FacebookField MessageTags = new FacebookField("message_tags");
/// <summary>
/// The name of the.
/// </summary>
public static readonly FacebookField Name = new FacebookField("name");
/// <summary>
/// The ID of any uploaded photo or video attached to the post.
/// </summary>
public static readonly FacebookField ObjectId = new FacebookField("object_id");
/// <summary>
/// The ID of a parent post for this post, if it exists. For example, if this story is a 'Your Page was
/// mentioned in a post' story, the.
/// </summary>
public static readonly FacebookField ParentId = new FacebookField("parent_id");
/// <summary>
/// URL to the permalink page of the post.
/// </summary>
public static readonly FacebookField PermalinkUrl = new FacebookField("permalink_url");
/// <summary>
/// URL to a resized version of the Photo published in the Post or scraped from a <c>link</c> in the Post. If
/// the photo's largest dimension exceeds 130 pixels, it will be resized, with the largest dimension set to 130.
/// </summary>
public static readonly FacebookField Picture = new FacebookField("picture");
/// <summary>
/// Any location information attached to the post.
/// </summary>
public static readonly FacebookField Place = new FacebookField("place");
/// <summary>
/// The privacy settings of the post.
/// </summary>
public static readonly FacebookField Privacy = new FacebookField("privacy");
/// <summary>
/// ID of post to use for promotion for stories that cannot be promoted directly.
/// </summary>
public static readonly FacebookField PromotableId = new FacebookField("promotable_id");
/// <summary>
/// Status of the promotion. Requires Page admin privileges. Possible values:.
/// </summary>
public static readonly FacebookField PromotionStatus = new FacebookField("promotion_status");
/// <summary>
/// A list of properties for any attached video, for example, the length of the video.
/// </summary>
public static readonly FacebookField Properties = new FacebookField("properties");
/// <summary>
/// The shares count of this post. The share count may include deleted posts and posts you cannot see for
/// privacy reasons.
/// </summary>
public static readonly FacebookField Shares = new FacebookField("shares");
/// <summary>
/// A URL to any Flash movie or video file attached to the post.
/// </summary>
public static readonly FacebookField Source = new FacebookField("source");
/// <summary>
/// Description of the type of a status update.
/// </summary>
public static readonly FacebookField StatusType = new FacebookField("status_type");
/// <summary>
/// Text from stories not intentionally generated by users, such as those generated when two people become
/// friends, or when someone else posts on the person's wall.
/// </summary>
public static readonly FacebookField Story = new FacebookField("story");
/// <summary>
/// Deprecated field, same as.
/// </summary>
public static readonly FacebookField StoryTags = new FacebookField("story_tags");
/// <summary>
/// Object that.
/// </summary>
public static readonly FacebookField Targeting = new FacebookField("targeting");
/// <summary>
/// Profiles mentioned or targeted in this post.
/// </summary>
public static readonly FacebookField To = new FacebookField("to");
/// <summary>
/// A string indicating the object type of this post.
/// </summary>
public static readonly FacebookField Type = new FacebookField("type");
/// <summary>
/// This field's behavior depends on the type of object the Post is on:.
/// </summary>
public static readonly FacebookField UpdatedTime = new FacebookField("updated_time");
/// <summary>
/// Profiles tagged as being 'with' the publisher of the post.
/// </summary>
public static readonly FacebookField WithTags = new FacebookField("with_tags");
#endregion
/// <summary>
/// Gets an array of all known fields available for a Facebook post.
/// </summary>
public static readonly FacebookField[] All = {
Id, AdminCreator, Application, CallToAction, CanReplyPrivately, Caption, CreatedTime, Description, FeedTargeting,
From, FullPicture, Icon, InstagramEligibility, IsHidden, IsInstagramEligible, IsPublished, Link, Message, MessageTags,
Name, ObjectId, ParentId, PermalinkUrl, Picture, Place, Privacy, PromotableId, PromotionStatus, Properties, Shares,
Source, StatusType, Story, StoryTags, Targeting, To, Type, UpdatedTime, WithTags
};
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>CustomerFeed</c> resource.</summary>
public sealed partial class CustomerFeedName : gax::IResourceName, sys::IEquatable<CustomerFeedName>
{
/// <summary>The possible contents of <see cref="CustomerFeedName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>customers/{customer_id}/customerFeeds/{feed_id}</c>.</summary>
CustomerFeed = 1,
}
private static gax::PathTemplate s_customerFeed = new gax::PathTemplate("customers/{customer_id}/customerFeeds/{feed_id}");
/// <summary>Creates a <see cref="CustomerFeedName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="CustomerFeedName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static CustomerFeedName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CustomerFeedName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CustomerFeedName"/> with the pattern <c>customers/{customer_id}/customerFeeds/{feed_id}</c>
/// .
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="CustomerFeedName"/> constructed from the provided ids.</returns>
public static CustomerFeedName FromCustomerFeed(string customerId, string feedId) =>
new CustomerFeedName(ResourceNameType.CustomerFeed, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomerFeedName"/> with pattern
/// <c>customers/{customer_id}/customerFeeds/{feed_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CustomerFeedName"/> with pattern
/// <c>customers/{customer_id}/customerFeeds/{feed_id}</c>.
/// </returns>
public static string Format(string customerId, string feedId) => FormatCustomerFeed(customerId, feedId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomerFeedName"/> with pattern
/// <c>customers/{customer_id}/customerFeeds/{feed_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CustomerFeedName"/> with pattern
/// <c>customers/{customer_id}/customerFeeds/{feed_id}</c>.
/// </returns>
public static string FormatCustomerFeed(string customerId, string feedId) =>
s_customerFeed.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)));
/// <summary>Parses the given resource name string into a new <see cref="CustomerFeedName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/customerFeeds/{feed_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="customerFeedName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CustomerFeedName"/> if successful.</returns>
public static CustomerFeedName Parse(string customerFeedName) => Parse(customerFeedName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CustomerFeedName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/customerFeeds/{feed_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customerFeedName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="CustomerFeedName"/> if successful.</returns>
public static CustomerFeedName Parse(string customerFeedName, bool allowUnparsed) =>
TryParse(customerFeedName, allowUnparsed, out CustomerFeedName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CustomerFeedName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/customerFeeds/{feed_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="customerFeedName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CustomerFeedName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string customerFeedName, out CustomerFeedName result) =>
TryParse(customerFeedName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CustomerFeedName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/customerFeeds/{feed_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customerFeedName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CustomerFeedName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string customerFeedName, bool allowUnparsed, out CustomerFeedName result)
{
gax::GaxPreconditions.CheckNotNull(customerFeedName, nameof(customerFeedName));
gax::TemplatedResourceName resourceName;
if (s_customerFeed.TryParseName(customerFeedName, out resourceName))
{
result = FromCustomerFeed(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(customerFeedName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private CustomerFeedName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string feedId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
FeedId = feedId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CustomerFeedName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/customerFeeds/{feed_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
public CustomerFeedName(string customerId, string feedId) : this(ResourceNameType.CustomerFeed, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>Feed</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string FeedId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerFeed: return s_customerFeed.Expand(CustomerId, FeedId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as CustomerFeedName);
/// <inheritdoc/>
public bool Equals(CustomerFeedName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CustomerFeedName a, CustomerFeedName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CustomerFeedName a, CustomerFeedName b) => !(a == b);
}
public partial class CustomerFeed
{
/// <summary>
/// <see cref="CustomerFeedName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal CustomerFeedName ResourceNameAsCustomerFeedName
{
get => string.IsNullOrEmpty(ResourceName) ? null : CustomerFeedName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary><see cref="FeedName"/>-typed view over the <see cref="Feed"/> resource name property.</summary>
internal FeedName FeedAsFeedName
{
get => string.IsNullOrEmpty(Feed) ? null : FeedName.Parse(Feed, allowUnparsed: true);
set => Feed = value?.ToString() ?? "";
}
}
}
| |
#region [Copyright (c) 2015 Cristian Alexandru Geambasu]
// Distributed under the terms of an MIT-style license:
//
// The MIT License
//
// Copyright (c) 2015 Cristian Alexandru Geambasu
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial
// portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion
using UnityEngine;
using UnityEditor;
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using TeamUtility.IO;
using TeamUtilityEditor.IO.InputManager;
using _InputManager = TeamUtility.IO.InputManager;
namespace TeamUtilityEditor.IO
{
public sealed class AdvancedInputEditor : EditorWindow
{
#region [Menu Options]
public enum FileMenuOptions
{
OverriteInputSettings = 0, CreateSnapshot, LoadSnapshot, Export, Import, ImportJoystickMapping, ConfigureForInputAdapter, CreateDefaultInputConfig
}
public enum EditMenuOptions
{
NewInputConfiguration = 0, NewAxisConfiguration, Duplicate, Delete, DeleteAll, SelectTarget, IgnoreTimescale, DontDestroyOnLoad, Copy, Paste
}
#endregion
#region [SearchResult]
[Serializable]
private class SearchResult
{
public int configuration;
public List<int> axes;
public SearchResult()
{
configuration = 0;
axes = new List<int>();
}
public SearchResult(int configuration, IEnumerable<int> axes)
{
this.configuration = configuration;
this.axes = new List<int>(axes);
}
}
#endregion
#region [Fields]
[SerializeField] private _InputManager _inputManager;
[SerializeField] private List<SearchResult> _searchResults;
[SerializeField] private List<int> _selectionPath;
[SerializeField] private Vector2 _hierarchyScrollPos = Vector2.zero;
[SerializeField] private Vector2 _mainPanelScrollPos = Vector2.zero;
[SerializeField] private float _hierarchyPanelWidth = _menuWidth * 2;
[SerializeField] private Texture2D _highlightTexture;
[SerializeField] private string _searchString = "";
[SerializeField] private string _keyString = string.Empty;
private AxisConfiguration _copySource;
private GUIStyle _whiteLabel;
private GUIStyle _whiteFoldout;
private GUIStyle _warningLabel;
private float _minCursorRectWidth = 10.0f;
private float _maxCursorRectWidth = 50.0f;
private float _toolbarHeight = 18.0f;
private float _hierarchyItemHeight = 18.0f;
private bool _isResizingHierarchy = false;
private bool _editingPositiveKey = false;
private bool _editingAltPositiveKey = false;
private bool _editingNegativeKey = false;
private bool _editingAltNegativeKey = false;
private bool _tryedToFindInputManagerInScene = false;
private bool _isDisposed = false;
private string[] _axisOptions = new string[] { "X", "Y", "3rd(Scrollwheel)", "4th", "5th", "6th", "7th", "8th", "9th", "10th" };
private string[] _joystickOptions = new string[] { "Joystick 1", "Joystick 2", "Joystick 3", "Joystick 4" };
private const float _menuWidth = 100.0f;
private const float _minHierarchyPanelWidth = 150.0f;
#endregion
private void OnEnable()
{
EditorToolbox.ShowStartupWarning();
IsOpen = true;
_tryedToFindInputManagerInScene = false;
if(_inputManager == null)
_inputManager = UnityEngine.Object.FindObjectOfType(typeof(_InputManager)) as _InputManager;
if(_selectionPath == null)
_selectionPath = new List<int>();
if(_searchResults == null)
_searchResults = new List<SearchResult>();
if(_highlightTexture == null)
CreateHighlightTexture();
EditorApplication.playmodeStateChanged += HandlePlayModeChanged;
_isDisposed = false;
}
private void OnDisable()
{
Dispose();
}
private void OnDestroy()
{
Dispose();
}
private void Dispose()
{
if(!_isDisposed)
{
IsOpen = false;
Texture2D.DestroyImmediate(_highlightTexture);
_highlightTexture = null;
_copySource = null;
EditorApplication.playmodeStateChanged -= HandlePlayModeChanged;
_isDisposed = true;
}
}
private void CreateHighlightTexture()
{
_highlightTexture = new Texture2D(1, 1);
_highlightTexture.SetPixel(0, 0, new Color32(50, 125, 255, 255));
_highlightTexture.Apply();
}
private void ValidateGUIStyles()
{
if(_whiteLabel == null)
{
_whiteLabel = new GUIStyle(EditorStyles.label);
_whiteLabel.normal.textColor = Color.white;
}
if(_whiteFoldout == null)
{
_whiteFoldout = new GUIStyle(EditorStyles.foldout);
_whiteFoldout.normal.textColor = Color.white;
_whiteFoldout.onNormal.textColor = Color.white;
_whiteFoldout.active.textColor = Color.white;
_whiteFoldout.onActive.textColor = Color.white;
_whiteFoldout.focused.textColor = Color.white;
_whiteFoldout.onFocused.textColor = Color.white;
}
if(_warningLabel == null)
{
_warningLabel = new GUIStyle(EditorStyles.largeLabel);
_warningLabel.alignment = TextAnchor.MiddleCenter;
_warningLabel.fontStyle = FontStyle.Bold;
_warningLabel.fontSize = 14;
}
}
public void AddInputConfiguration(InputConfiguration configuration)
{
_inputManager.inputConfigurations.Add(configuration);
_selectionPath.Clear();
_selectionPath.Add(_inputManager.inputConfigurations.Count - 1);
Repaint();
}
private void ExportInputConfigurations()
{
string file = EditorUtility.SaveFilePanel("Export input profile", "", "profile.xml", "xml");
if(string.IsNullOrEmpty(file))
return;
InputSaverXML inputSaver = new InputSaverXML(file);
inputSaver.Save(_inputManager.GetSaveParameters());
if(file.StartsWith(Application.dataPath))
AssetDatabase.Refresh();
}
private void ImportInputConfigurations()
{
string file = EditorUtility.OpenFilePanel("Import input profile", "", "xml");
if(string.IsNullOrEmpty(file))
return;
bool replace = EditorUtility.DisplayDialog("Replace or Append", "Do you want to replace the current input configrations?", "Replace", "Append");
if(replace)
{
InputLoaderXML inputLoader = new InputLoaderXML(file);
_inputManager.Load(inputLoader.Load());
_selectionPath.Clear();
}
else
{
InputLoaderXML inputLoader = new InputLoaderXML(file);
var parameters = inputLoader.Load();
if(parameters.inputConfigurations != null && parameters.inputConfigurations.Count > 0)
{
foreach(var config in parameters.inputConfigurations)
{
_inputManager.inputConfigurations.Add(config);
}
}
}
if(_searchString.Length > 0)
{
UpdateSearchResults();
}
Repaint();
}
private void LoadInputConfigurationsFromResource(string resourcePath)
{
if(_inputManager.inputConfigurations.Count > 0)
{
bool cont = EditorUtility.DisplayDialog("Warning", "This operation will replace the current input configrations!\nDo you want to continue?", "Yes", "No");
if(!cont) return;
}
TextAsset textAsset = Resources.Load<TextAsset>(resourcePath);
if(textAsset != null)
{
using(System.IO.StringReader reader = new System.IO.StringReader(textAsset.text))
{
InputLoaderXML inputLoader = new InputLoaderXML(reader);
_inputManager.Load(inputLoader.Load());
_selectionPath.Clear();
}
}
else
{
EditorUtility.DisplayDialog("Error", "Failed to load input configurations. The resource file might have been deleted or renamed.", "OK");
}
}
private void TryToFindInputManagerInScene()
{
_inputManager = UnityEngine.Object.FindObjectOfType(typeof(_InputManager)) as _InputManager;
_tryedToFindInputManagerInScene = true;
}
private void HandlePlayModeChanged()
{
if(_inputManager == null)
TryToFindInputManagerInScene();
}
#region [Menus]
private void CreateFileMenu(Rect position)
{
GenericMenu fileMenu = new GenericMenu();
fileMenu.AddItem(new GUIContent("Overwrite Input Settings"), false, HandleFileMenuOption, FileMenuOptions.OverriteInputSettings);
fileMenu.AddItem(new GUIContent("Default Input Configuration"), false, HandleFileMenuOption, FileMenuOptions.CreateDefaultInputConfig);
if(EditorToolbox.HasInputAdapterAddon())
fileMenu.AddItem(new GUIContent("Configure For Input Adapter"), false, HandleFileMenuOption, FileMenuOptions.ConfigureForInputAdapter);
fileMenu.AddSeparator("");
if(_inputManager.inputConfigurations.Count > 0)
fileMenu.AddItem(new GUIContent("Create Snapshot"), false, HandleFileMenuOption, FileMenuOptions.CreateSnapshot);
else
fileMenu.AddDisabledItem(new GUIContent("Create Snapshot"));
if(EditorToolbox.CanLoadSnapshot())
fileMenu.AddItem(new GUIContent("Restore Snapshot"), false, HandleFileMenuOption, FileMenuOptions.LoadSnapshot);
else
fileMenu.AddDisabledItem(new GUIContent("Restore Snapshot"));
fileMenu.AddSeparator("");
if(_inputManager.inputConfigurations.Count > 0)
fileMenu.AddItem(new GUIContent("Export"), false, HandleFileMenuOption, FileMenuOptions.Export);
else
fileMenu.AddDisabledItem(new GUIContent("Export"));
fileMenu.AddItem(new GUIContent("Import"), false, HandleFileMenuOption, FileMenuOptions.Import);
if(EditorToolbox.HasJoystickMappingAddon())
fileMenu.AddItem(new GUIContent("Import Joystick Mapping"), false, HandleFileMenuOption, FileMenuOptions.ImportJoystickMapping);
fileMenu.DropDown(position);
}
private void HandleFileMenuOption(object arg)
{
FileMenuOptions option = (FileMenuOptions)arg;
switch(option)
{
case FileMenuOptions.OverriteInputSettings:
EditorToolbox.OverwriteInputSettings();
break;
case FileMenuOptions.CreateSnapshot:
EditorToolbox.CreateSnapshot(_inputManager);
break;
case FileMenuOptions.LoadSnapshot:
EditorToolbox.LoadSnapshot(_inputManager);
break;
case FileMenuOptions.Export:
ExportInputConfigurations();
break;
case FileMenuOptions.Import:
ImportInputConfigurations();
break;
case FileMenuOptions.ImportJoystickMapping:
EditorToolbox.OpenImportJoystickMappingWindow(this);
break;
case FileMenuOptions.ConfigureForInputAdapter:
LoadInputConfigurationsFromResource(ResourcePaths.INPUT_ADAPTER_DEFAULT_CONFIG);
break;
case FileMenuOptions.CreateDefaultInputConfig:
LoadInputConfigurationsFromResource(ResourcePaths.INPUT_MANAGER_DEFAULT_CONFIG);
break;
}
}
private void CreateEditMenu(Rect position)
{
GenericMenu editMenu = new GenericMenu();
editMenu.AddItem(new GUIContent("New Configuration"), false, HandleEditMenuOption, EditMenuOptions.NewInputConfiguration);
if(_selectionPath.Count >= 1)
editMenu.AddItem(new GUIContent("New Axis"), false, HandleEditMenuOption, EditMenuOptions.NewAxisConfiguration);
else
editMenu.AddDisabledItem(new GUIContent("New Axis"));
editMenu.AddSeparator("");
if(_selectionPath.Count > 0)
editMenu.AddItem(new GUIContent("Duplicate Shift+D"), false, HandleEditMenuOption, EditMenuOptions.Duplicate);
else
editMenu.AddDisabledItem(new GUIContent("Duplicate Shift+D"));
if(_selectionPath.Count > 0)
editMenu.AddItem(new GUIContent("Delete Del"), false, HandleEditMenuOption, EditMenuOptions.Delete);
else
editMenu.AddDisabledItem(new GUIContent("Delete Del"));
if(_inputManager.inputConfigurations.Count > 0)
editMenu.AddItem(new GUIContent("Delete All"), false, HandleEditMenuOption, EditMenuOptions.DeleteAll);
else
editMenu.AddDisabledItem(new GUIContent("Delete All"));
if(_selectionPath.Count >= 2)
editMenu.AddItem(new GUIContent("Copy"), false, HandleEditMenuOption, EditMenuOptions.Copy);
else
editMenu.AddDisabledItem(new GUIContent("Copy"));
if(_copySource != null && _selectionPath.Count >= 2)
editMenu.AddItem(new GUIContent("Paste"), false, HandleEditMenuOption, EditMenuOptions.Paste);
else
editMenu.AddDisabledItem(new GUIContent("Paste"));
editMenu.AddSeparator("");
editMenu.AddItem(new GUIContent("Select Target"), false, HandleEditMenuOption, EditMenuOptions.SelectTarget);
editMenu.AddItem(new GUIContent("Ignore Timescale"), _inputManager.ignoreTimescale, HandleEditMenuOption, EditMenuOptions.IgnoreTimescale);
editMenu.AddItem(new GUIContent("Dont Destroy On Load"), _inputManager.dontDestroyOnLoad, HandleEditMenuOption, EditMenuOptions.DontDestroyOnLoad);
editMenu.DropDown(position);
}
private void HandleEditMenuOption(object arg)
{
EditMenuOptions option = (EditMenuOptions)arg;
switch(option)
{
case EditMenuOptions.NewInputConfiguration:
CreateNewInputConfiguration();
break;
case EditMenuOptions.NewAxisConfiguration:
CreateNewAxisConfiguration();
break;
case EditMenuOptions.Duplicate:
Duplicate();
break;
case EditMenuOptions.Delete:
Delete();
break;
case EditMenuOptions.DeleteAll:
DeleteAll();
break;
case EditMenuOptions.SelectTarget:
Selection.activeGameObject = _inputManager.gameObject;
break;
case EditMenuOptions.IgnoreTimescale:
_inputManager.ignoreTimescale = !_inputManager.ignoreTimescale;
break;
case EditMenuOptions.DontDestroyOnLoad:
_inputManager.dontDestroyOnLoad = !_inputManager.dontDestroyOnLoad;
break;
case EditMenuOptions.Copy:
CopySelectedAxisConfig();
break;
case EditMenuOptions.Paste:
PasteAxisConfig();
break;
}
}
private void CreateNewInputConfiguration()
{
_inputManager.inputConfigurations.Add(new InputConfiguration());
_selectionPath.Clear();
_selectionPath.Add(_inputManager.inputConfigurations.Count - 1);
Repaint();
}
private void CreateNewAxisConfiguration()
{
if(_selectionPath.Count >= 1)
{
InputConfiguration inputConfig = _inputManager.inputConfigurations[_selectionPath[0]];
inputConfig.axes.Add(new AxisConfiguration());
inputConfig.isExpanded = true;
if(_selectionPath.Count == 2) {
_selectionPath[1] = inputConfig.axes.Count - 1;
}
else {
_selectionPath.Add(inputConfig.axes.Count - 1);
}
Repaint();
}
}
private void Duplicate()
{
if(_selectionPath.Count == 1) {
DuplicateInputConfiguration();
}
else if(_selectionPath.Count == 2) {
DuplicateAxisConfiguration();
}
}
private void DuplicateAxisConfiguration()
{
InputConfiguration inputConfig = _inputManager.inputConfigurations[_selectionPath[0]];
AxisConfiguration source = inputConfig.axes[_selectionPath[1]];
AxisConfiguration axisConfig = AxisConfiguration.Duplicate(source);
if(_selectionPath[1] < inputConfig.axes.Count - 1)
{
inputConfig.axes.Insert(_selectionPath[1], axisConfig);
_selectionPath[1]++;
}
else
{
inputConfig.axes.Add(axisConfig);
_selectionPath[1] = inputConfig.axes.Count - 1;
}
if(_searchString.Length > 0)
{
UpdateSearchResults();
}
Repaint();
}
private void DuplicateInputConfiguration()
{
InputConfiguration source = _inputManager.inputConfigurations[_selectionPath[0]];
InputConfiguration inputConfig = InputConfiguration.Duplicate(source);
if(_selectionPath[0] < _inputManager.inputConfigurations.Count - 1)
{
_inputManager.inputConfigurations.Insert(_selectionPath[0] + 1, inputConfig);
_selectionPath[0]++;
}
else
{
_inputManager.inputConfigurations.Add(inputConfig);
_selectionPath[0] = _inputManager.inputConfigurations.Count - 1;
}
if(_searchString.Length > 0)
{
UpdateSearchResults();
}
Repaint();
}
private void Delete()
{
if(_selectionPath.Count == 1)
{
_inputManager.inputConfigurations.RemoveAt(_selectionPath[0]);
Repaint();
}
else if(_selectionPath.Count == 2)
{
_inputManager.inputConfigurations[_selectionPath[0]].axes.RemoveAt(_selectionPath[1]);
Repaint();
}
_selectionPath.Clear();
if(_searchString.Length > 0)
{
UpdateSearchResults();
}
}
private void DeleteAll()
{
_inputManager.inputConfigurations.Clear();
_inputManager.playerOneDefault = string.Empty;
_inputManager.playerTwoDefault = string.Empty;
_inputManager.playerThreeDefault = string.Empty;
_inputManager.playerFourDefault = string.Empty;
_selectionPath.Clear();
if(_searchString.Length > 0)
{
UpdateSearchResults();
}
Repaint();
}
private void CopySelectedAxisConfig()
{
if(_copySource == null)
_copySource = new AxisConfiguration();
InputConfiguration inputConfig = _inputManager.inputConfigurations[_selectionPath[0]];
AxisConfiguration axisConfig = inputConfig.axes[_selectionPath[1]];
_copySource.Copy(axisConfig);
}
private void PasteAxisConfig()
{
InputConfiguration inputConfig = _inputManager.inputConfigurations[_selectionPath[0]];
AxisConfiguration axisConfig = inputConfig.axes[_selectionPath[1]];
axisConfig.Copy(_copySource);
}
private void UpdateSearchResults()
{
_searchResults.Clear();
for(int i = 0; i < _inputManager.inputConfigurations.Count; i++)
{
IEnumerable<int> axes = from a in _inputManager.inputConfigurations[i].axes
where (a.name.IndexOf(_searchString, System.StringComparison.InvariantCultureIgnoreCase) >= 0)
select _inputManager.inputConfigurations[i].axes.IndexOf(a);
if(axes.Count() > 0)
{
_searchResults.Add(new SearchResult(i, axes));
}
}
}
#endregion
#region [OnGUI]
private void OnGUI()
{
ValidateGUIStyles();
if(_inputManager == null && !_tryedToFindInputManagerInScene)
TryToFindInputManagerInScene();
if(_inputManager == null)
{
DisplayMissingInputManagerWarning();
return;
}
Undo.RecordObject(_inputManager, "InputManager");
UpdateHierarchyPanelWidth();
if(_searchString.Length > 0)
{
DisplaySearchResults();
}
else
{
DisplayHierarchyPanel();
}
if(_selectionPath.Count >= 1)
{
DisplayMainPanel();
}
DisplayMainToolbar();
if(GUI.changed)
EditorUtility.SetDirty(_inputManager);
}
private void DisplayMissingInputManagerWarning()
{
Rect warningRect = new Rect(0.0f, 20.0f, position.width, 40.0f);
Rect buttonRect = new Rect(position.width / 2 - 100.0f, warningRect.yMax, 200.0f, 25.0f);
EditorGUI.LabelField(warningRect, "Could not find an input manager instance in the scene!", _warningLabel);
if(GUI.Button(buttonRect, "Try Again"))
{
TryToFindInputManagerInScene();
}
}
private void DisplayMainToolbar()
{
Rect screenRect = new Rect(0.0f, 0.0f, position.width, _toolbarHeight);
Rect fileMenuRect = new Rect(0.0f, 0.0f, _menuWidth, screenRect.height);
Rect editMenuRect = new Rect(fileMenuRect.xMax, 0.0f, _menuWidth, screenRect.height);
Rect paddingLabelRect = new Rect(editMenuRect.xMax, 0.0f, screenRect.width - _menuWidth * 2, screenRect.height);
Rect searchFieldRect = new Rect(screenRect.width - (_menuWidth * 1.5f + 5.0f), 2.0f, _menuWidth * 1.5f, screenRect.height - 2.0f);
int lastSearchStringLength = _searchString.Length;
GUI.BeginGroup(screenRect);
DisplayFileMenu(fileMenuRect);
DisplayEditMenu(editMenuRect);
EditorGUI.LabelField(paddingLabelRect, "", EditorStyles.toolbarButton);
GUILayout.BeginArea(searchFieldRect);
_searchString = EditorToolbox.SearchField(_searchString);
GUILayout.EndArea();
GUI.EndGroup();
if(lastSearchStringLength != _searchString.Length)
{
UpdateSearchResults();
}
}
private void DisplayFileMenu(Rect screenRect)
{
EditorGUI.LabelField(screenRect, "File", EditorStyles.toolbarDropDown);
if(Event.current.type == EventType.MouseDown && Event.current.button == 0 &&
screenRect.Contains(Event.current.mousePosition))
{
CreateFileMenu(new Rect(screenRect.x, screenRect.yMax, 0.0f, 0.0f));
}
if(Event.current.type == EventType.KeyDown)
{
if(Event.current.keyCode == KeyCode.Q && (Event.current.control || Event.current.command))
{
Close();
Event.current.Use();
}
}
}
private void DisplayEditMenu(Rect screenRect)
{
EditorGUI.LabelField(screenRect, "Edit", EditorStyles.toolbarDropDown);
if(Event.current.type == EventType.MouseDown && Event.current.button == 0 &&
screenRect.Contains(Event.current.mousePosition))
{
CreateEditMenu(new Rect(screenRect.x, screenRect.yMax, 0.0f, 0.0f));
}
if(Event.current.type == EventType.KeyDown)
{
if(Event.current.keyCode == KeyCode.D && Event.current.shift)
{
Duplicate();
Event.current.Use();
}
if(Event.current.keyCode == KeyCode.Delete)
{
Delete();
Event.current.Use();
}
}
}
private void UpdateHierarchyPanelWidth()
{
float cursorRectWidth = _isResizingHierarchy ? _maxCursorRectWidth : _minCursorRectWidth;
Rect cursorRect = new Rect(_hierarchyPanelWidth - cursorRectWidth / 2, _toolbarHeight, cursorRectWidth,
position.height - _toolbarHeight);
Rect resizeRect = new Rect(_hierarchyPanelWidth - _minCursorRectWidth / 2, 0.0f,
_minCursorRectWidth, position.height);
EditorGUIUtility.AddCursorRect(cursorRect, MouseCursor.ResizeHorizontal);
switch(Event.current.type)
{
case EventType.MouseDown:
if(Event.current.button == 0 && resizeRect.Contains(Event.current.mousePosition))
{
_isResizingHierarchy = true;
Event.current.Use();
}
break;
case EventType.MouseUp:
if(Event.current.button == 0 && _isResizingHierarchy)
{
_isResizingHierarchy = false;
Event.current.Use();
}
break;
case EventType.MouseDrag:
if(_isResizingHierarchy)
{
_hierarchyPanelWidth = Mathf.Clamp(_hierarchyPanelWidth + Event.current.delta.x,
_minHierarchyPanelWidth, position.width / 2);
Event.current.Use();
Repaint();
}
break;
default:
break;
}
}
private void DisplaySearchResults()
{
Rect screenRect = new Rect(0.0f, _toolbarHeight - 5.0f, _hierarchyPanelWidth, position.height - _toolbarHeight + 10.0f);
GUI.Box(screenRect, "");
if(_searchResults.Count > 0)
{
Rect scrollView = new Rect(screenRect.x, screenRect.y + 5.0f, screenRect.width, position.height - screenRect.y);
GUILayout.BeginArea(scrollView);
_hierarchyScrollPos = EditorGUILayout.BeginScrollView(_hierarchyScrollPos);
GUILayout.Space(5.0f);
for(int i = 0; i < _searchResults.Count; i++)
{
DisplaySearchResult(screenRect, _searchResults[i]);
}
GUILayout.Space(5.0f);
EditorGUILayout.EndScrollView();
GUILayout.EndArea();
}
}
private void DisplaySearchResult(Rect screenRect, SearchResult result)
{
DisplayHierarchyInputConfigItem(screenRect, result.configuration,
_inputManager.inputConfigurations[result.configuration].name);
if(_inputManager.inputConfigurations[result.configuration].isExpanded)
{
for(int i = 0; i < result.axes.Count; i++)
{
DisplayHierarchiAxisConfigItem(screenRect, result.configuration, result.axes[i],
_inputManager.inputConfigurations[result.configuration].axes[result.axes[i]].name);
}
}
}
private void DisplayHierarchyPanel()
{
Rect screenRect = new Rect(0.0f, _toolbarHeight - 5.0f, _hierarchyPanelWidth, position.height - _toolbarHeight + 10.0f);
Rect scrollView = new Rect(screenRect.x, screenRect.y + 5.0f, screenRect.width, position.height - screenRect.y);
GUI.Box(screenRect, "");
GUILayout.BeginArea(scrollView);
_hierarchyScrollPos = EditorGUILayout.BeginScrollView(_hierarchyScrollPos);
GUILayout.Space(5.0f);
for(int i = 0; i < _inputManager.inputConfigurations.Count; i++)
{
DisplayHierarchyInputConfigItem(screenRect, i, _inputManager.inputConfigurations[i].name);
if(_inputManager.inputConfigurations[i].isExpanded)
{
for(int j = 0; j < _inputManager.inputConfigurations[i].axes.Count; j++)
{
DisplayHierarchiAxisConfigItem(screenRect, i, j, _inputManager.inputConfigurations[i].axes[j].name);
}
}
}
GUILayout.Space(5.0f);
EditorGUILayout.EndScrollView();
GUILayout.EndArea();
}
private void DisplayHierarchyInputConfigItem(Rect screenRect, int index, string name)
{
Rect configPos = GUILayoutUtility.GetRect(new GUIContent(name), EditorStyles.foldout, GUILayout.Height(_hierarchyItemHeight));
if(Event.current.type == EventType.MouseDown && Event.current.button == 0)
{
if(configPos.Contains(Event.current.mousePosition))
{
_selectionPath.Clear();
_selectionPath.Add(index);
GUI.FocusControl(null);
Repaint();
}
else if(screenRect.Contains(Event.current.mousePosition))
{
_selectionPath.Clear();
GUI.FocusControl(null);
Repaint();
}
}
if(_selectionPath.Count == 1 && _selectionPath[0] == index)
{
if(_highlightTexture == null) {
CreateHighlightTexture();
}
GUI.DrawTexture(configPos, _highlightTexture, ScaleMode.StretchToFill);
_inputManager.inputConfigurations[index].isExpanded = EditorGUI.Foldout(configPos, _inputManager.inputConfigurations[index].isExpanded, name, _whiteFoldout);
}
else
{
_inputManager.inputConfigurations[index].isExpanded = EditorGUI.Foldout(configPos, _inputManager.inputConfigurations[index].isExpanded, name);
}
}
private void DisplayHierarchiAxisConfigItem(Rect screenRect, int inputConfigIndex, int index, string name)
{
Rect configPos = GUILayoutUtility.GetRect(new GUIContent(name), EditorStyles.label, GUILayout.Height(_hierarchyItemHeight));
if(Event.current.type == EventType.MouseDown && Event.current.button == 0)
{
if(configPos.Contains(Event.current.mousePosition))
{
_editingPositiveKey = false;
_editingPositiveKey = false;
_editingAltPositiveKey = false;
_editingAltNegativeKey = false;
_keyString = string.Empty;
_selectionPath.Clear();
_selectionPath.Add(inputConfigIndex);
_selectionPath.Add(index);
GUI.FocusControl(null);
Event.current.Use();
Repaint();
}
else if(screenRect.Contains(Event.current.mousePosition))
{
_selectionPath.Clear();
GUI.FocusControl(null);
Repaint();
}
}
if(_selectionPath.Count == 2 && _selectionPath[0] == inputConfigIndex &&
_selectionPath[1] == index)
{
if(_highlightTexture == null) {
CreateHighlightTexture();
}
GUI.DrawTexture(configPos, _highlightTexture, ScaleMode.StretchToFill);
configPos.x += 20.0f;
EditorGUI.LabelField(configPos, name, _whiteLabel);
}
else
{
configPos.x += 20.0f;
EditorGUI.LabelField(configPos, name);
}
}
private void DisplayMainPanel()
{
Rect screenRect = new Rect(_hierarchyPanelWidth + 5.0f, _toolbarHeight + 5,
position.width - (_hierarchyPanelWidth + 5.0f),
position.height - _toolbarHeight - 5.0f);
InputConfiguration inputConfig = _inputManager.inputConfigurations[_selectionPath[0]];
if(_selectionPath.Count < 2)
{
DisplayInputConfigurationFields(inputConfig, screenRect);
}
else
{
AxisConfiguration axisConfig = inputConfig.axes[_selectionPath[1]];
DisplayAxisConfigurationFields(inputConfig, axisConfig, screenRect);
}
}
private void DisplayInputConfigurationFields(InputConfiguration inputConfig, Rect screenRect)
{
GUILayout.BeginArea(screenRect);
_mainPanelScrollPos = EditorGUILayout.BeginScrollView(_mainPanelScrollPos);
inputConfig.name = EditorGUILayout.TextField("Name", inputConfig.name);
EditorGUILayout.Space();
GUI.enabled = (!EditorApplication.isPlaying && _inputManager.playerOneDefault != inputConfig.name);
if(GUILayout.Button("Make Player One Default", GUILayout.Width(200.0f), GUILayout.Height(25.0f)))
{
_inputManager.playerOneDefault = inputConfig.name;
}
GUI.enabled = (!EditorApplication.isPlaying && _inputManager.playerTwoDefault != inputConfig.name);
if (GUILayout.Button("Make Player Two Default", GUILayout.Width(200.0f), GUILayout.Height(25.0f)))
{
_inputManager.playerTwoDefault = inputConfig.name;
}
GUI.enabled = (!EditorApplication.isPlaying && _inputManager.playerThreeDefault != inputConfig.name);
if (GUILayout.Button("Make Player Three Default", GUILayout.Width(200.0f), GUILayout.Height(25.0f)))
{
_inputManager.playerThreeDefault = inputConfig.name;
}
GUI.enabled = (!EditorApplication.isPlaying && _inputManager.playerFourDefault != inputConfig.name);
if (GUILayout.Button("Make Player Four Default", GUILayout.Width(200.0f), GUILayout.Height(25.0f)))
{
_inputManager.playerFourDefault = inputConfig.name;
}
//GUI.enabled = (EditorApplication.isPlaying && _InputManager.PlayerOneConfiguration.name != inputConfig.name);
//if(GUILayout.Button("Switch To", GUILayout.Width(135.0f), GUILayout.Height(20.0f)))
//{
// _InputManager.SetInputConfiguration(inputConfig.name, PlayerID.One);
//}
GUI.enabled = true;
EditorGUILayout.EndScrollView();
GUILayout.EndArea();
}
private void DisplayAxisConfigurationFields(InputConfiguration inputConfigx, AxisConfiguration axisConfig, Rect screenRect)
{
GUIContent gravityInfo = new GUIContent("Gravity", "The speed(in units/sec) at which a digital axis falls towards neutral.");
GUIContent sensitivityInfo = new GUIContent("Sensitivity", "The speed(in units/sec) at which an axis moves towards the target value.");
GUIContent snapInfo = new GUIContent("Snap", "If input switches direction, do we snap to neutral and continue from there? For digital axes only.");
GUIContent deadZoneInfo = new GUIContent("Dead Zone", "Size of analog dead zone. Values within this range map to neutral.");
GUILayout.BeginArea(screenRect);
_mainPanelScrollPos = GUILayout.BeginScrollView(_mainPanelScrollPos);
axisConfig.name = EditorGUILayout.TextField("Name", axisConfig.name);
axisConfig.description = EditorGUILayout.TextField("Description", axisConfig.description);
// Positive Key
EditorToolbox.KeyCodeField(ref _keyString, ref _editingPositiveKey, "Positive",
"editor_positive_key", axisConfig.positive);
ProcessKeyString(ref axisConfig.positive, ref _editingPositiveKey);
// Negative Key
EditorToolbox.KeyCodeField(ref _keyString, ref _editingNegativeKey, "Negative",
"editor_negative_key", axisConfig.negative);
ProcessKeyString(ref axisConfig.negative, ref _editingNegativeKey);
// Alt Positive Key
EditorToolbox.KeyCodeField(ref _keyString, ref _editingAltPositiveKey, "Alt Positive",
"editor_alt_positive_key", axisConfig.altPositive);
ProcessKeyString(ref axisConfig.altPositive, ref _editingAltPositiveKey);
// Alt Negative key
EditorToolbox.KeyCodeField(ref _keyString, ref _editingAltNegativeKey, "Alt Negative",
"editor_alt_negative_key", axisConfig.altNegative);
ProcessKeyString(ref axisConfig.altNegative, ref _editingAltNegativeKey);
axisConfig.gravity = EditorGUILayout.FloatField(gravityInfo, axisConfig.gravity);
axisConfig.deadZone = EditorGUILayout.FloatField(deadZoneInfo, axisConfig.deadZone);
axisConfig.sensitivity = EditorGUILayout.FloatField(sensitivityInfo, axisConfig.sensitivity);
axisConfig.snap = EditorGUILayout.Toggle(snapInfo, axisConfig.snap);
axisConfig.invert = EditorGUILayout.Toggle("Invert", axisConfig.invert);
axisConfig.type = (InputType)EditorGUILayout.EnumPopup("Type", axisConfig.type);
axisConfig.axis = EditorGUILayout.Popup("Axis", axisConfig.axis, _axisOptions);
axisConfig.joystick = EditorGUILayout.Popup("Joystick", axisConfig.joystick, _joystickOptions);
if(EditorApplication.isPlaying)
{
EditorGUILayout.Space();
GUI.enabled = false;
EditorGUILayout.FloatField("Raw Axis", axisConfig.GetAxisRaw());
EditorGUILayout.FloatField("Axis", axisConfig.GetAxis());
EditorGUILayout.Toggle("Button", axisConfig.GetButton());
GUI.enabled = true;
}
GUILayout.EndScrollView();
GUILayout.EndArea();
}
private void ProcessKeyString(ref KeyCode key, ref bool isEditing)
{
if(isEditing && Event.current.type == EventType.KeyUp)
{
key = AxisConfiguration.StringToKey(_keyString);
if(key == KeyCode.None)
{
_keyString = string.Empty;
}
else
{
_keyString = key.ToString();
}
isEditing = false;
}
}
#endregion
#region [Static Interface]
public static bool IsOpen { get; private set; }
[MenuItem("Team Utility/Input Manager/Open Input Editor", false, 0)]
public static void OpenWindow()
{
if (!IsOpen)
{
if (UnityEngine.Object.FindObjectOfType(typeof(_InputManager)) == null)
{
bool create = EditorUtility.DisplayDialog("Warning", "There is no InputManager instance in the scene. Do you want to create one?", "Yes", "No");
if (create)
{
GameObject gameObject = new GameObject("InputManager");
gameObject.AddComponent<_InputManager>();
}
else
{
return;
}
}
EditorWindow.GetWindow<AdvancedInputEditor>("Input Editor");
}
}
public static void OpenWindow(_InputManager target)
{
if(!IsOpen)
{
var window = EditorWindow.GetWindow<AdvancedInputEditor>("Input Editor");
window._inputManager = target;
}
}
public static void CloseWindow()
{
if(IsOpen)
{
var window = EditorWindow.GetWindow<AdvancedInputEditor>("Input Editor");
window.Close();
}
}
#endregion
}
}
| |
#region Copyright and license information
// Copyright 2001-2009 Stephen Colebourne
// Copyright 2009-2011 Jon Skeet
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using NodaTime.Fields;
namespace NodaTime.Calendars
{
/// <summary>
/// Abstract implementation for calendar systems that use a typical day/month/year/leapYear model,
/// assuming a constant number of months. Most concrete calendars in Noda Time either derive from
/// this class or delegate to another instance of it.
/// </summary>
[Serializable]
internal abstract class BasicCalendarSystem : CalendarSystem
{
private static readonly FieldSet preciseFields = CreatePreciseFields();
private const int YearCacheSize = 1 << 10;
private const int YearCacheMask = YearCacheSize - 1;
private readonly YearInfo[] yearCache = new YearInfo[YearCacheSize];
private readonly int minDaysInFirstWeek;
/// <summary>
/// Returns the number of ticks from the start of the given year to the start of the given month.
/// TODO: We always add this to the ticks at the start of the year. Why not just do it?
/// </summary>
protected abstract long GetTotalTicksByYearMonth(int year, int month);
internal abstract long AverageTicksPerMonth { get; }
internal abstract long AverageTicksPerYear { get; }
internal abstract long AverageTicksPerYearDividedByTwo { get; }
internal abstract long ApproxTicksAtEpochDividedByTwo { get; }
protected abstract LocalInstant CalculateStartOfYear(int year);
protected internal abstract int GetMonthOfYear(LocalInstant localInstant, int year);
internal abstract int GetDaysInMonthMax(int month);
internal abstract long GetYearDifference(LocalInstant minuendInstant, LocalInstant subtrahendInstant);
internal abstract LocalInstant SetYear(LocalInstant localInstant, int year);
private static FieldSet CreatePreciseFields()
{
// First create the simple durations, then fill in date/time fields,
// which rely on the other properties
FieldSet.Builder builder = new FieldSet.Builder
{
Ticks = TicksDurationField.Instance,
Milliseconds = PreciseDurationField.Milliseconds,
Seconds = PreciseDurationField.Seconds,
Minutes = PreciseDurationField.Minutes,
Hours = PreciseDurationField.Hours,
HalfDays = PreciseDurationField.HalfDays,
Days = PreciseDurationField.Days,
Weeks = PreciseDurationField.Weeks
};
builder.TickOfSecond = new PreciseDateTimeField(DateTimeFieldType.TickOfSecond, builder.Ticks, builder.Seconds);
builder.TickOfMillisecond = new PreciseDateTimeField(DateTimeFieldType.TickOfMillisecond, builder.Ticks, builder.Milliseconds);
builder.TickOfDay = new PreciseDateTimeField(DateTimeFieldType.TickOfDay, builder.Ticks, builder.Days);
builder.MillisecondOfSecond = new PreciseDateTimeField(DateTimeFieldType.MillisecondOfSecond, builder.Milliseconds, builder.Seconds);
builder.MillisecondOfDay = new PreciseDateTimeField(DateTimeFieldType.MillisecondOfDay, builder.Milliseconds, builder.Days);
builder.SecondOfMinute = new PreciseDateTimeField(DateTimeFieldType.SecondOfMinute, builder.Seconds, builder.Minutes);
builder.SecondOfDay = new PreciseDateTimeField(DateTimeFieldType.SecondOfDay, builder.Seconds, builder.Days);
builder.MinuteOfHour = new PreciseDateTimeField(DateTimeFieldType.MinuteOfHour, builder.Minutes, builder.Hours);
builder.MinuteOfDay = new PreciseDateTimeField(DateTimeFieldType.MinuteOfDay, builder.Minutes, builder.Days);
builder.HourOfDay = new PreciseDateTimeField(DateTimeFieldType.HourOfDay, builder.Hours, builder.Days);
builder.HourOfHalfDay = new PreciseDateTimeField(DateTimeFieldType.HourOfHalfDay, builder.Hours, builder.HalfDays);
builder.ClockHourOfDay = new ZeroIsMaxDateTimeField(builder.HourOfDay, DateTimeFieldType.ClockHourOfDay);
builder.ClockHourOfHalfDay = new ZeroIsMaxDateTimeField(builder.HourOfHalfDay, DateTimeFieldType.ClockHourOfHalfDay);
// TODO: This was a separate subclass in Joda, for i18n purposes
builder.HalfDayOfDay = new PreciseDateTimeField(DateTimeFieldType.HalfDayOfDay, builder.HalfDays, builder.Days);
return builder.Build();
}
protected BasicCalendarSystem(string name, int minDaysInFirstWeek, FieldAssembler assembler, IEnumerable<Era> eras)
: base(name, AssembleFields + assembler, eras)
{
if (minDaysInFirstWeek < 1 || minDaysInFirstWeek > 7)
{
throw new ArgumentOutOfRangeException("minDaysInFirstWeek", "Minimum days in first week must be between 1 and 7 inclusive");
}
this.minDaysInFirstWeek = minDaysInFirstWeek;
// Effectively invalidate the first cache entry.
// Every other cache entry will automatically be invalid,
// by having year 0.
yearCache[0] = new YearInfo(1, LocalInstant.LocalUnixEpoch.Ticks);
}
private static void AssembleFields(FieldSet.Builder builder, CalendarSystem @this)
{
// None of the fields will call anything on the calendar system *yet*, so this is safe enough.
BasicCalendarSystem thisCalendar = (BasicCalendarSystem) @this;
// First copy the fields that are the same for all basic
// calendars
builder.WithSupportedFieldsFrom(preciseFields);
// Now create fields that have unique behavior for Gregorian and Julian
// calendars.
builder.Year = new BasicYearDateTimeField(thisCalendar);
builder.YearOfEra = new GJYearOfEraDateTimeField(builder.Year, thisCalendar);
// Define one-based centuryOfEra and yearOfCentury.
DateTimeField field = new OffsetDateTimeField(builder.YearOfEra, 99);
builder.CenturyOfEra = new DividedDateTimeField(field, DateTimeFieldType.CenturyOfEra, 100);
field = new RemainderDateTimeField((DividedDateTimeField)builder.CenturyOfEra);
builder.YearOfCentury = new OffsetDateTimeField(field, DateTimeFieldType.YearOfCentury, 1);
builder.Era = new GJEraDateTimeField(thisCalendar);
builder.DayOfWeek = new GJDayOfWeekDateTimeField(thisCalendar, builder.Days);
builder.DayOfMonth = new BasicDayOfMonthDateTimeField(thisCalendar, builder.Days);
builder.DayOfYear = new BasicDayOfYearDateTimeField(thisCalendar, builder.Days);
builder.MonthOfYear = new BasicMonthOfYearDateTimeField(thisCalendar, 2); // February is the leap month
builder.WeekYear = new BasicWeekYearDateTimeField(thisCalendar);
builder.WeekOfWeekYear = new BasicWeekOfWeekYearDateTimeField(thisCalendar, builder.Weeks);
field = new RemainderDateTimeField(builder.WeekYear, DateTimeFieldType.WeekYearOfCentury, 100);
builder.WeekYearOfCentury = new OffsetDateTimeField(field, DateTimeFieldType.WeekYearOfCentury, 1);
// The remaining (imprecise) durations are available from the newly
// created datetime fields.
builder.Years = builder.Year.DurationField;
builder.Centuries = builder.CenturyOfEra.DurationField;
builder.Months = builder.MonthOfYear.DurationField;
builder.WeekYears = builder.WeekYear.DurationField;
}
/// <summary>
/// Fetches the start of the year from the cache, or calculates
/// and caches it.
/// </summary>
internal long GetYearTicks(int year)
{
YearInfo info = yearCache[year & YearCacheMask];
if (info.Year != year)
{
info = new YearInfo(year, CalculateStartOfYear(year).Ticks);
// TODO: Check thread safety of this; write won't be atomic...
yearCache[year & YearCacheMask] = info;
}
return info.StartOfYearTicks;
}
internal int GetDayOfWeek(LocalInstant localInstant)
{
// 1970-01-01 is day of week 4, Thursday.
long daysSince19700101;
long ticks = localInstant.Ticks;
if (ticks >= 0)
{
daysSince19700101 = ticks / NodaConstants.TicksPerStandardDay;
}
else
{
daysSince19700101 = (ticks - (NodaConstants.TicksPerStandardDay - 1)) / NodaConstants.TicksPerStandardDay;
if (daysSince19700101 < -3)
{
return 7 + (int)((daysSince19700101 + 4) % 7);
}
}
return 1 + (int)((daysSince19700101 + 3) % 7);
}
internal virtual int GetDayOfMonth(LocalInstant localInstant)
{
int year = GetYear(localInstant);
int month = GetMonthOfYear(localInstant, year);
return GetDayOfMonth(localInstant, year, month);
}
internal int GetDayOfMonth(LocalInstant localInstant, int year)
{
int month = GetMonthOfYear(localInstant, year);
return GetDayOfMonth(localInstant, year, month);
}
internal int GetDayOfMonth(LocalInstant localInstant, int year, int month)
{
long dateTicks = GetYearTicks(year);
dateTicks += GetTotalTicksByYearMonth(year, month);
return (int)((localInstant.Ticks - dateTicks) / NodaConstants.TicksPerStandardDay) + 1;
}
internal virtual int GetMaxDaysInMonth()
{
return 31;
}
internal virtual int GetMonthOfYear(LocalInstant localInstant)
{
return GetMonthOfYear(localInstant, GetYear(localInstant));
}
internal int GetMaxDaysInMonth(LocalInstant localInstant)
{
int thisYear = GetYear(localInstant);
int thisMonth = GetMonthOfYear(localInstant, thisYear);
return GetDaysInMonth(thisYear, thisMonth);
}
internal virtual int GetYear(LocalInstant localInstant)
{
long ticks = localInstant.Ticks;
// Get an initial estimate of the year, and the millis value that
// represents the start of that year. Then verify estimate and fix if
// necessary.
// Initial estimate uses values divided by two to avoid overflow.
long unitTicks = AverageTicksPerYearDividedByTwo;
long i2 = (ticks >> 1) + ApproxTicksAtEpochDividedByTwo;
if (i2 < 0)
{
i2 = i2 - unitTicks + 1;
}
int year = (int)(i2 / unitTicks);
long yearStart = GetYearTicks(year);
long diff = ticks - yearStart;
if (diff < 0)
{
year--;
}
else if (diff >= NodaConstants.TicksPerStandardDay * 365L)
{
// One year may need to be added to fix estimate.
long oneYear = NodaConstants.TicksPerStandardDay * (IsLeapYear(year) ? 366L : 365L);
yearStart += oneYear;
if (yearStart <= localInstant.Ticks)
{
// Didn't go too far, so actually add one year.
year++;
}
}
return year;
}
internal virtual int GetDaysInYearMax()
{
return 366;
}
internal virtual int GetDaysInYear(int year)
{
return IsLeapYear(year) ? 366 : 365;
}
internal int GetDayOfYear(LocalInstant localInstant)
{
return GetDayOfYear(localInstant, GetYear(localInstant));
}
internal int GetDayOfYear(LocalInstant localInstant, int year)
{
long yearStart = GetYearTicks(year);
return (int)((localInstant.Ticks - yearStart) / NodaConstants.TicksPerStandardDay) + 1;
}
/// <summary>
/// All basic calendars have the same number of months regardless of the year.
/// (Different calendars can have a different number of months, but it doesn't vary by time.)
/// </summary>
public override int GetMaxMonth(int year)
{
return GetMaxMonth();
}
internal virtual int GetMaxMonth()
{
return 12;
}
internal long GetTickOfDay(LocalInstant localInstant)
{
long ticks = localInstant.Ticks;
return ticks >= 0 ? ticks % NodaConstants.TicksPerStandardDay : (NodaConstants.TicksPerStandardDay - 1) + ((ticks + 1) % NodaConstants.TicksPerStandardDay);
}
/// <summary>
/// Computes the ticks of the local instant at the start of the given year/month/day.
/// This assumes all parameters have been validated previously.
/// </summary>
internal long GetYearMonthDayTicks(int year, int month, int dayOfMonth)
{
long ticks = GetYearTicks(year);
ticks += GetTotalTicksByYearMonth(year, month);
return ticks + (dayOfMonth - 1) * NodaConstants.TicksPerStandardDay;
}
internal long GetYearMonthTicks(int year, int month)
{
long ticks = GetYearTicks(year);
ticks += GetTotalTicksByYearMonth(year, month);
return ticks;
}
/// <summary>
/// Immutable struct containing a year and the first tick of that year.
/// This is cached to avoid it being calculated more often than is necessary.
/// </summary>
private struct YearInfo
{
private readonly int year;
private readonly long startOfYear;
internal YearInfo(int year, long startOfYear)
{
this.year = year;
this.startOfYear = startOfYear;
}
internal int Year { get { return year; } }
internal long StartOfYearTicks { get { return startOfYear; } }
}
internal int GetWeekYear(LocalInstant localInstant)
{
int year = GetYear(localInstant);
int week = GetWeekOfWeekYear(localInstant, year);
if (week == 1)
{
return GetYear(localInstant + Duration.OneWeek);
}
else if (week > 51)
{
return GetYear(localInstant - Duration.FromStandardWeeks(2));
}
else
{
return year;
}
}
internal int GetWeekOfWeekYear(LocalInstant localInstant)
{
return GetWeekOfWeekYear(localInstant, GetYear(localInstant));
}
internal int GetWeekOfWeekYear(LocalInstant localInstant, int year)
{
long firstWeekTicks1 = GetFirstWeekOfYearTicks(year);
if (localInstant.Ticks < firstWeekTicks1)
{
return GetWeeksInYear(year - 1);
}
long firstWeekTicks2 = GetFirstWeekOfYearTicks(year + 1);
if (localInstant.Ticks >= firstWeekTicks2)
{
return 1;
}
return (int)((localInstant.Ticks - firstWeekTicks1) / NodaConstants.TicksPerStandardWeek) + 1;
}
internal int GetWeeksInYear(int year)
{
long firstWeekTicks1 = GetFirstWeekOfYearTicks(year);
long firstWeekTicks2 = GetFirstWeekOfYearTicks(year + 1);
return (int)((firstWeekTicks2 - firstWeekTicks1) / NodaConstants.TicksPerStandardWeek);
}
private long GetFirstWeekOfYearTicks(int year)
{
long jan1Millis = GetYearTicks(year);
int jan1DayOfWeek = GetDayOfWeek(new LocalInstant(jan1Millis));
if (jan1DayOfWeek > (8 - minDaysInFirstWeek))
{
// First week is end of previous year because it doesn't have enough days.
return jan1Millis + (8 - jan1DayOfWeek) * NodaConstants.TicksPerStandardDay;
}
else
{
// First week is start of this year because it has enough days.
return jan1Millis - (jan1DayOfWeek - 1) * NodaConstants.TicksPerStandardDay;
}
}
protected virtual long GetDateMidnightTicks(int year, int monthOfYear, int dayOfMonth)
{
FieldUtils.VerifyValueBounds(DateTimeFieldType.Year, year, MinYear, MaxYear);
FieldUtils.VerifyValueBounds(DateTimeFieldType.MonthOfYear, monthOfYear, 1, GetMaxMonth());
FieldUtils.VerifyValueBounds(DateTimeFieldType.DayOfMonth, dayOfMonth, 1, GetDaysInMonth(year, monthOfYear));
return GetYearMonthDayTicks(year, monthOfYear, dayOfMonth);
}
internal override LocalInstant GetLocalInstant(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour)
{
FieldUtils.VerifyValueBounds(DateTimeFieldType.HourOfDay, hourOfDay, 0, 23);
FieldUtils.VerifyValueBounds(DateTimeFieldType.MinuteOfHour, minuteOfHour, 0, 59);
return
new LocalInstant(GetDateMidnightTicks(year, monthOfYear, dayOfMonth) + hourOfDay * NodaConstants.TicksPerHour +
minuteOfHour * NodaConstants.TicksPerMinute);
}
internal override LocalInstant GetLocalInstant(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute)
{
FieldUtils.VerifyValueBounds(DateTimeFieldType.HourOfDay, hourOfDay, 0, 23);
FieldUtils.VerifyValueBounds(DateTimeFieldType.MinuteOfHour, minuteOfHour, 0, 59);
FieldUtils.VerifyValueBounds(DateTimeFieldType.SecondOfMinute, secondOfMinute, 0, 59);
return
new LocalInstant(GetDateMidnightTicks(year, monthOfYear, dayOfMonth) + hourOfDay * NodaConstants.TicksPerHour +
minuteOfHour * NodaConstants.TicksPerMinute + secondOfMinute * NodaConstants.TicksPerSecond);
}
internal override LocalInstant GetLocalInstant(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute,
int millisecondOfSecond, int tickOfMillisecond)
{
FieldUtils.VerifyValueBounds(DateTimeFieldType.HourOfDay, hourOfDay, 0, 23);
FieldUtils.VerifyValueBounds(DateTimeFieldType.MinuteOfHour, minuteOfHour, 0, 59);
FieldUtils.VerifyValueBounds(DateTimeFieldType.SecondOfMinute, secondOfMinute, 0, 59);
FieldUtils.VerifyValueBounds(DateTimeFieldType.MillisecondOfSecond, millisecondOfSecond, 0, 999);
FieldUtils.VerifyValueBounds(DateTimeFieldType.TickOfMillisecond, tickOfMillisecond, 0, NodaConstants.TicksPerMillisecond - 1);
return
new LocalInstant(GetDateMidnightTicks(year, monthOfYear, dayOfMonth) + hourOfDay * NodaConstants.TicksPerHour +
minuteOfHour * NodaConstants.TicksPerMinute + secondOfMinute * NodaConstants.TicksPerSecond +
millisecondOfSecond * NodaConstants.TicksPerMillisecond + tickOfMillisecond);
}
internal override LocalInstant GetLocalInstant(int year, int monthOfYear, int dayOfMonth, long tickOfDay)
{
// TODO: Report bug in Joda Time, which doesn't have the - 1 here.
FieldUtils.VerifyValueBounds(DateTimeFieldType.TickOfDay, tickOfDay, 0, NodaConstants.TicksPerStandardDay - 1);
return new LocalInstant(GetDateMidnightTicks(year, monthOfYear, dayOfMonth) + tickOfDay);
}
}
}
| |
using Lucene.Net.Documents;
using Lucene.Net.Support;
namespace Lucene.Net.Index
{
using NUnit.Framework;
using Directory = Lucene.Net.Store.Directory;
/*
* 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 Document = Documents.Document;
using Field = Field;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using StringField = StringField;
[TestFixture]
public class TestSizeBoundedForceMerge : LuceneTestCase
{
private void AddDocs(IndexWriter writer, int numDocs)
{
AddDocs(writer, numDocs, false);
}
private void AddDocs(IndexWriter writer, int numDocs, bool withID)
{
for (int i = 0; i < numDocs; i++)
{
Document doc = new Document();
if (withID)
{
doc.Add(new StringField("id", "" + i, Field.Store.NO));
}
writer.AddDocument(doc);
}
writer.Commit();
}
private IndexWriterConfig NewWriterConfig()
{
IndexWriterConfig conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, null);
conf.SetMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH);
conf.SetRAMBufferSizeMB(IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB);
// prevent any merges by default.
conf.SetMergePolicy(NoMergePolicy.COMPOUND_FILES);
return conf;
}
[Test]
public virtual void TestByteSizeLimit()
{
// tests that the max merge size constraint is applied during forceMerge.
Directory dir = new RAMDirectory();
// Prepare an index w/ several small segments and a large one.
IndexWriterConfig conf = NewWriterConfig();
IndexWriter writer = new IndexWriter(dir, conf);
const int numSegments = 15;
for (int i = 0; i < numSegments; i++)
{
int numDocs = i == 7 ? 30 : 1;
AddDocs(writer, numDocs);
}
writer.Dispose();
SegmentInfos sis = new SegmentInfos();
sis.Read(dir);
double min = sis.Info(0).GetSizeInBytes();
conf = NewWriterConfig();
LogByteSizeMergePolicy lmp = new LogByteSizeMergePolicy();
lmp.MaxMergeMBForForcedMerge = (min + 1) / (1 << 20);
conf.SetMergePolicy(lmp);
writer = new IndexWriter(dir, conf);
writer.ForceMerge(1);
writer.Dispose();
// Should only be 3 segments in the index, because one of them exceeds the size limit
sis = new SegmentInfos();
sis.Read(dir);
Assert.AreEqual(3, sis.Count);
}
[Test]
public virtual void TestNumDocsLimit()
{
// tests that the max merge docs constraint is applied during forceMerge.
Directory dir = new RAMDirectory();
// Prepare an index w/ several small segments and a large one.
IndexWriterConfig conf = NewWriterConfig();
IndexWriter writer = new IndexWriter(dir, conf);
AddDocs(writer, 3);
AddDocs(writer, 3);
AddDocs(writer, 5);
AddDocs(writer, 3);
AddDocs(writer, 3);
AddDocs(writer, 3);
AddDocs(writer, 3);
writer.Dispose();
conf = NewWriterConfig();
LogMergePolicy lmp = new LogDocMergePolicy();
lmp.MaxMergeDocs = 3;
conf.SetMergePolicy(lmp);
writer = new IndexWriter(dir, conf);
writer.ForceMerge(1);
writer.Dispose();
// Should only be 3 segments in the index, because one of them exceeds the size limit
SegmentInfos sis = new SegmentInfos();
sis.Read(dir);
Assert.AreEqual(3, sis.Count);
}
[Test]
public virtual void TestLastSegmentTooLarge()
{
Directory dir = new RAMDirectory();
IndexWriterConfig conf = NewWriterConfig();
IndexWriter writer = new IndexWriter(dir, conf);
AddDocs(writer, 3);
AddDocs(writer, 3);
AddDocs(writer, 3);
AddDocs(writer, 5);
writer.Dispose();
conf = NewWriterConfig();
LogMergePolicy lmp = new LogDocMergePolicy();
lmp.MaxMergeDocs = 3;
conf.SetMergePolicy(lmp);
writer = new IndexWriter(dir, conf);
writer.ForceMerge(1);
writer.Dispose();
SegmentInfos sis = new SegmentInfos();
sis.Read(dir);
Assert.AreEqual(2, sis.Count);
}
[Test]
public virtual void TestFirstSegmentTooLarge()
{
Directory dir = new RAMDirectory();
IndexWriterConfig conf = NewWriterConfig();
IndexWriter writer = new IndexWriter(dir, conf);
AddDocs(writer, 5);
AddDocs(writer, 3);
AddDocs(writer, 3);
AddDocs(writer, 3);
writer.Dispose();
conf = NewWriterConfig();
LogMergePolicy lmp = new LogDocMergePolicy();
lmp.MaxMergeDocs = 3;
conf.SetMergePolicy(lmp);
writer = new IndexWriter(dir, conf);
writer.ForceMerge(1);
writer.Dispose();
SegmentInfos sis = new SegmentInfos();
sis.Read(dir);
Assert.AreEqual(2, sis.Count);
}
[Test]
public virtual void TestAllSegmentsSmall()
{
Directory dir = new RAMDirectory();
IndexWriterConfig conf = NewWriterConfig();
IndexWriter writer = new IndexWriter(dir, conf);
AddDocs(writer, 3);
AddDocs(writer, 3);
AddDocs(writer, 3);
AddDocs(writer, 3);
writer.Dispose();
conf = NewWriterConfig();
LogMergePolicy lmp = new LogDocMergePolicy();
lmp.MaxMergeDocs = 3;
conf.SetMergePolicy(lmp);
writer = new IndexWriter(dir, conf);
writer.ForceMerge(1);
writer.Dispose();
SegmentInfos sis = new SegmentInfos();
sis.Read(dir);
Assert.AreEqual(1, sis.Count);
}
[Test]
public virtual void TestAllSegmentsLarge()
{
Directory dir = new RAMDirectory();
IndexWriterConfig conf = NewWriterConfig();
IndexWriter writer = new IndexWriter(dir, conf);
AddDocs(writer, 3);
AddDocs(writer, 3);
AddDocs(writer, 3);
writer.Dispose();
conf = NewWriterConfig();
LogMergePolicy lmp = new LogDocMergePolicy();
lmp.MaxMergeDocs = 2;
conf.SetMergePolicy(lmp);
writer = new IndexWriter(dir, conf);
writer.ForceMerge(1);
writer.Dispose();
SegmentInfos sis = new SegmentInfos();
sis.Read(dir);
Assert.AreEqual(3, sis.Count);
}
[Test]
public virtual void TestOneLargeOneSmall()
{
Directory dir = new RAMDirectory();
IndexWriterConfig conf = NewWriterConfig();
IndexWriter writer = new IndexWriter(dir, conf);
AddDocs(writer, 3);
AddDocs(writer, 5);
AddDocs(writer, 3);
AddDocs(writer, 5);
writer.Dispose();
conf = NewWriterConfig();
LogMergePolicy lmp = new LogDocMergePolicy();
lmp.MaxMergeDocs = 3;
conf.SetMergePolicy(lmp);
writer = new IndexWriter(dir, conf);
writer.ForceMerge(1);
writer.Dispose();
SegmentInfos sis = new SegmentInfos();
sis.Read(dir);
Assert.AreEqual(4, sis.Count);
}
[Test]
public virtual void TestMergeFactor()
{
Directory dir = new RAMDirectory();
IndexWriterConfig conf = NewWriterConfig();
IndexWriter writer = new IndexWriter(dir, conf);
AddDocs(writer, 3);
AddDocs(writer, 3);
AddDocs(writer, 3);
AddDocs(writer, 3);
AddDocs(writer, 5);
AddDocs(writer, 3);
AddDocs(writer, 3);
writer.Dispose();
conf = NewWriterConfig();
LogMergePolicy lmp = new LogDocMergePolicy();
lmp.MaxMergeDocs = 3;
lmp.MergeFactor = 2;
conf.SetMergePolicy(lmp);
writer = new IndexWriter(dir, conf);
writer.ForceMerge(1);
writer.Dispose();
// Should only be 4 segments in the index, because of the merge factor and
// max merge docs settings.
SegmentInfos sis = new SegmentInfos();
sis.Read(dir);
Assert.AreEqual(4, sis.Count);
}
[Test]
public virtual void TestSingleMergeableSegment()
{
Directory dir = new RAMDirectory();
IndexWriterConfig conf = NewWriterConfig();
IndexWriter writer = new IndexWriter(dir, conf);
AddDocs(writer, 3);
AddDocs(writer, 5);
AddDocs(writer, 3);
// delete the last document, so that the last segment is merged.
writer.DeleteDocuments(new Term("id", "10"));
writer.Dispose();
conf = NewWriterConfig();
LogMergePolicy lmp = new LogDocMergePolicy();
lmp.MaxMergeDocs = 3;
conf.SetMergePolicy(lmp);
writer = new IndexWriter(dir, conf);
writer.ForceMerge(1);
writer.Dispose();
// Verify that the last segment does not have deletions.
SegmentInfos sis = new SegmentInfos();
sis.Read(dir);
Assert.AreEqual(3, sis.Count);
Assert.IsFalse(sis.Info(2).HasDeletions);
}
[Test]
public virtual void TestSingleNonMergeableSegment()
{
Directory dir = new RAMDirectory();
IndexWriterConfig conf = NewWriterConfig();
IndexWriter writer = new IndexWriter(dir, conf);
AddDocs(writer, 3, true);
writer.Dispose();
conf = NewWriterConfig();
LogMergePolicy lmp = new LogDocMergePolicy();
lmp.MaxMergeDocs = 3;
conf.SetMergePolicy(lmp);
writer = new IndexWriter(dir, conf);
writer.ForceMerge(1);
writer.Dispose();
// Verify that the last segment does not have deletions.
SegmentInfos sis = new SegmentInfos();
sis.Read(dir);
Assert.AreEqual(1, sis.Count);
}
[Test]
public virtual void TestSingleMergeableTooLargeSegment()
{
Directory dir = new RAMDirectory();
IndexWriterConfig conf = NewWriterConfig();
IndexWriter writer = new IndexWriter(dir, conf);
AddDocs(writer, 5, true);
// delete the last document
writer.DeleteDocuments(new Term("id", "4"));
writer.Dispose();
conf = NewWriterConfig();
LogMergePolicy lmp = new LogDocMergePolicy();
lmp.MaxMergeDocs = 2;
conf.SetMergePolicy(lmp);
writer = new IndexWriter(dir, conf);
writer.ForceMerge(1);
writer.Dispose();
// Verify that the last segment does not have deletions.
SegmentInfos sis = new SegmentInfos();
sis.Read(dir);
Assert.AreEqual(1, sis.Count);
Assert.IsTrue(sis.Info(0).HasDeletions);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void BlendUInt1685()
{
var test = new ImmBinaryOpTest__BlendUInt1685();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__BlendUInt1685
{
private struct TestStruct
{
public Vector256<UInt16> _fld1;
public Vector256<UInt16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__BlendUInt1685 testClass)
{
var result = Avx2.Blend(_fld1, _fld2, 85);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static UInt16[] _data2 = new UInt16[Op2ElementCount];
private static Vector256<UInt16> _clsVar1;
private static Vector256<UInt16> _clsVar2;
private Vector256<UInt16> _fld1;
private Vector256<UInt16> _fld2;
private SimpleBinaryOpTest__DataTable<UInt16, UInt16, UInt16> _dataTable;
static ImmBinaryOpTest__BlendUInt1685()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
}
public ImmBinaryOpTest__BlendUInt1685()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt16, UInt16, UInt16>(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.Blend(
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr),
85
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.Blend(
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr)),
85
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.Blend(
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr)),
85
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr),
(byte)85
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr)),
(byte)85
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr)),
(byte)85
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.Blend(
_clsVar1,
_clsVar2,
85
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr);
var result = Avx2.Blend(left, right, 85);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.Blend(left, right, 85);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.Blend(left, right, 85);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__BlendUInt1685();
var result = Avx2.Blend(test._fld1, test._fld2, 85);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.Blend(_fld1, _fld2, 85);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.Blend(test._fld1, test._fld2, 85);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt16> left, Vector256<UInt16> right, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (((85 & (1 << 0)) == 0) ? left[0] : right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((i < 8) ? (((85 & (1 << i)) == 0) ? left[i] : right[i]) : (((85 & (1 << (i - 8))) == 0) ? left[i] : right[i])))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Blend)}<UInt16>(Vector256<UInt16>.85, Vector256<UInt16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/* Copyright 2012 James Tuley (jay+code@tuley.name)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.IO;
using Keyczar.Util;
namespace Keyczar
{
/// <summary>
/// Verifies a message with an attached signature.
/// </summary>
public class AttachedVerifier:KeyczarBase
{
private HelperAttachedVerify _verifier;
/// <summary>
/// Initializes a new instance of the <see cref="AttachedSigner"/> class.
/// </summary>
/// <param name="keySetLocation">The key set location.</param>
public AttachedVerifier(string keySetLocation)
: this(new FileSystemKeySet(keySetLocation))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AttachedSigner" /> class.
/// </summary>
/// <param name="keySet">The key set.</param>
/// <exception cref="InvalidKeySetException">This key set can not be used for verifying signatures.</exception>
public AttachedVerifier(IKeySet keySet) : base(keySet)
{
if (keySet.Metadata.Purpose != KeyPurpose.Verify
&& keySet.Metadata.Purpose != KeyPurpose.SignAndVerify)
{
throw new InvalidKeySetException("This key set can not be used for verifying signatures.");
}
_verifier = new HelperAttachedVerify(keySet, this);
}
/// <summary>
/// Verifies the specified message.
/// </summary>
/// <param name="signedMessage">The signed message.</param>
/// <param name="hidden">Optional hidden data used to generate the digest signature.</param>
/// <returns></returns>
public bool Verify(WebBase64 signedMessage, byte[] hidden =null) =>
Verify(signedMessage.ToBytes(), hidden);
/// <summary>
/// Verifies the specified message.
/// </summary>
/// <param name="signedMessage">The signed message.</param>
/// <param name="hidden">Optional hidden data used to generate the digest signature.</param>
/// <returns></returns>
public bool Verify(byte[] signedMessage, byte[] hidden =null){
using (var memstream = new MemoryStream(signedMessage))
{
return Verify(memstream, hidden);
}
}
/// <summary>
/// Verifies the specified message.
/// </summary>
/// <param name="input">The input.</param>
/// <param name="hidden">Optional hidden data used to generate the digest signature.</param>
/// <param name="inputLength">(optional) Length of the input.</param>
/// <returns></returns>
public bool Verify(Stream input, byte[] hidden =null, long inputLength=-1)
=> _verifier.VerifyHidden(input, null, hidden, inputLength);
/// <summary>
/// Gets Verified message from signed message
/// </summary>
/// <param name="rawData">The raw data.</param>
/// <param name="hidden">Optional hidden data used to generate the digest signature.</param>
/// <returns></returns>
/// <exception cref="InvalidCryptoDataException">Data Doesn't Match Signature!</exception>
public string VerifiedMessage(WebBase64 rawData, byte[] hidden = null)
=> Config.RawStringEncoding.GetString(VerifiedMessage(rawData.ToBytes(), hidden));
/// <summary>
/// Gets Verified message from signed message
/// </summary>
/// <param name="data">The data.</param>
/// <param name="hidden">Optional hidden data used to generate the digest signature.</param>
/// <returns></returns>
/// <exception cref="InvalidCryptoDataException">Data Doesn't Match Signature!</exception>
public byte[] VerifiedMessage(byte[] data, byte[] hidden = null)
{
using (var output = new MemoryStream())
using (var memstream = new MemoryStream(data))
{
VerifiedMessage(memstream,output, hidden);
return output.ToArray();
}
}
/// <summary>
/// Gets Verified message from signed message
/// </summary>
/// <param name="input">The input.</param>
/// <param name="verifiedMessage">The output message.</param>
/// <param name="hidden">The hidden.</param>
/// <param name="inputLength">Length of the input.</param>
/// <exception cref="InvalidCryptoDataException">Data Doesn't Match Signature!</exception>
public void VerifiedMessage(Stream input, Stream verifiedMessage, byte[] hidden = null, long inputLength=-1)
{
if (!TryGetVerifiedMessage(input, verifiedMessage, hidden, inputLength))
{
throw new InvalidCryptoDataException("Data Doesn't Match Signature!");
}
}
/// <summary>
/// Tries to get the verified message.
/// </summary>
/// <param name="signedMessage">The signed message.</param>
/// <param name="verifiedMessage">The verified message.</param>
/// <param name="hidden">The hidden.</param>
/// <returns>false if signature is not correct</returns>
public bool TryGetVerifiedMessage(WebBase64 signedMessage, out string verifiedMessage, byte[] hidden = null)
{
byte[] output;
var verified = TryGetVerifiedMessage(signedMessage.ToBytes(), out output, hidden);
verifiedMessage = Config.RawStringEncoding.GetString(output);
return verified;
}
/// <summary>
/// Tries to get the verified message.
/// </summary>
/// <param name="signedMessage">The signed message.</param>
/// <param name="verifiedMessage">The verified message.</param>
/// <param name="hidden">The hidden.</param>
/// <returns>false if signature is not correct</returns>
public bool TryGetVerifiedMessage(byte[] signedMessage, out byte[] verifiedMessage, byte[] hidden = null)
{
try
{
using (var output = new MemoryStream())
using (var memstream = new MemoryStream(signedMessage))
{
var verified = TryGetVerifiedMessage(memstream, output, hidden);
verifiedMessage = output.ToArray();
return verified;
}
}
catch (InvalidCryptoDataException)
{
verifiedMessage = null;
return false;
}
}
/// <summary>
/// Tries to get the verified message.
/// </summary>
/// <param name="input">The input.</param>
/// <param name="verifiedMessage">The verified message.</param>
/// <param name="hiddden">The hiddden.</param>
/// <param name="inputLength">(optional) Length of the input.</param>
/// <returns>
/// false if signature is not correct
/// </returns>
public bool TryGetVerifiedMessage(Stream input, Stream verifiedMessage, byte[] hiddden = null, long inputLength=-1)
=> _verifier.VerifyHidden(input, verifiedMessage, hiddden, inputLength);
/// <summary>
/// Does the attache verify work.
/// </summary>
protected class HelperAttachedVerify:Verifier
{
private KeyczarBase _parent;
private KeyczarConfig _config1;
/// <summary>
/// Initializes a new instance of the <see cref="HelperAttachedVerify"/> class.
/// </summary>
/// <param name="keySet">The key set.</param>
public HelperAttachedVerify(IKeySet keySet, KeyczarBase parent) : base(keySet)
{
_parent = parent;
}
public override KeyczarConfig Config
{
get => _config1 ?? _parent.Config;
set => _config1 = value;
}
/// <summary>
/// Verifies the specified signed message.
/// </summary>
/// <param name="input">The signed message.</param>
/// <param name="verifiedMessage">The verified message.</param>
/// <param name="hidden">The hidden data used to generate the digest signature.</param>
/// <param name="inputLength">(optional) Length of the input.</param>
/// <returns></returns>
/// <exception cref="InvalidCryptoDataException">Data doesn't appear to have signatures attached!</exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
public bool VerifyHidden(Stream input, Stream verifiedMessage, byte[] hidden, long inputLength)
{
var fullLength = inputLength < 0 ? input.Length : inputLength + input.Position;
using (var reader = new NondestructiveBinaryReader(input))
{
var header = reader.ReadBytes(KeyczarConst.HeaderLength);
var length = Utility.ToInt32(reader.ReadBytes(4));
if (fullLength < input.Position + length)
{
throw new InvalidCryptoDataException("Data doesn't appear to have signatures attached!");
}
using(var sigStream = new MemoryStream())
{
using (Utility.ResetStreamWhenFinished(input))
{
sigStream.Write(header, 0, header.Length);
input.Seek(length, SeekOrigin.Current);
while (reader.Peek() != -1 && input.Position < fullLength)
{
var adjustedBufferSize = (int)Math.Min(BufferSize, (fullLength - input.Position));
var buffer = reader.ReadBytes(adjustedBufferSize);
sigStream.Write(buffer, 0, buffer.Length);
}
sigStream.Flush();
}
using (var signedMessageLimtedLength = new NondestructivePositionLengthLimitingStream(input))
{
signedMessageLimtedLength.SetLength(length);
if (verifiedMessage != null)
{
using (Utility.ResetStreamWhenFinished(input))
{
signedMessageLimtedLength.CopyTo(verifiedMessage);
}
}
var verified= Verify(signedMessageLimtedLength, sigStream.ToArray(), prefixData: null, postfixData: hidden, inputLength: inputLength);
input.Seek(fullLength, SeekOrigin.Begin);
return verified;
}
}
}
}
/// <summary>
/// Postfixes data before verifying.
/// </summary>
/// <param name="verifyingStream">The verifying stream.</param>
/// <param name="extra">The extra data passed by postFixData</param>
protected override void PostfixDataVerify(Crypto.Streams.VerifyingStream verifyingStream, object extra)
{
var bytes = extra as byte[] ?? new byte[0];
var len = Utility.GetBytes(bytes.Length);
verifyingStream.Write(len, 0, len.Length);
verifyingStream.Write(bytes, 0, bytes.Length);
base.PostfixDataVerify(verifyingStream, extra: null);
}
}
}
}
| |
using System;
using System.Web;
using Fluid;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using OrchardCore.Admin;
using OrchardCore.Data.Migration;
using OrchardCore.Deployment;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.Handlers;
using OrchardCore.DisplayManagement.Theming;
using OrchardCore.Environment.Commands;
using OrchardCore.Environment.Shell;
using OrchardCore.Environment.Shell.Configuration;
using OrchardCore.Environment.Shell.Scope;
using OrchardCore.Liquid;
using OrchardCore.Modules;
using OrchardCore.Mvc.Core.Utilities;
using OrchardCore.Navigation;
using OrchardCore.Security;
using OrchardCore.Security.Permissions;
using OrchardCore.Settings;
using OrchardCore.Settings.Deployment;
using OrchardCore.Setup.Events;
using OrchardCore.Users.Commands;
using OrchardCore.Users.Controllers;
using OrchardCore.Users.Drivers;
using OrchardCore.Users.Indexes;
using OrchardCore.Users.Liquid;
using OrchardCore.Users.Models;
using OrchardCore.Users.Services;
using OrchardCore.Users.ViewModels;
using YesSql.Indexes;
namespace OrchardCore.Users
{
public class Startup : StartupBase
{
private readonly AdminOptions _adminOptions;
private readonly string _tenantName;
public Startup(IOptions<AdminOptions> adminOptions, ShellSettings shellSettings)
{
_adminOptions = adminOptions.Value;
_tenantName = shellSettings.Name;
}
public override void Configure(IApplicationBuilder builder, IEndpointRouteBuilder routes, IServiceProvider serviceProvider)
{
var userOptions = serviceProvider.GetRequiredService<IOptions<UserOptions>>().Value;
var accountControllerName = typeof(AccountController).ControllerName();
routes.MapAreaControllerRoute(
name: "Login",
areaName: "OrchardCore.Users",
pattern: userOptions.LoginPath,
defaults: new { controller = accountControllerName, action = nameof(AccountController.Login) }
);
routes.MapAreaControllerRoute(
name: "ChangePassword",
areaName: "OrchardCore.Users",
pattern: userOptions.ChangePasswordUrl,
defaults: new { controller = accountControllerName, action = nameof(AccountController.ChangePassword) }
);
routes.MapAreaControllerRoute(
name: "UsersLogOff",
areaName: "OrchardCore.Users",
pattern: userOptions.LogoffPath,
defaults: new { controller = accountControllerName, action = nameof(AccountController.LogOff) }
);
routes.MapAreaControllerRoute(
name: "ExternalLogins",
areaName: "OrchardCore.Users",
pattern: userOptions.ExternalLoginsUrl,
defaults: new { controller = accountControllerName, action = nameof(AccountController.ExternalLogins) }
);
var adminControllerName = typeof(AdminController).ControllerName();
routes.MapAreaControllerRoute(
name: "UsersIndex",
areaName: "OrchardCore.Users",
pattern: _adminOptions.AdminUrlPrefix + "/Users/Index",
defaults: new { controller = adminControllerName, action = nameof(AdminController.Index) }
);
routes.MapAreaControllerRoute(
name: "UsersCreate",
areaName: "OrchardCore.Users",
pattern: _adminOptions.AdminUrlPrefix + "/Users/Create",
defaults: new { controller = adminControllerName, action = nameof(AdminController.Create) }
);
routes.MapAreaControllerRoute(
name: "UsersDelete",
areaName: "OrchardCore.Users",
pattern: _adminOptions.AdminUrlPrefix + "/Users/Delete/{id}",
defaults: new { controller = adminControllerName, action = nameof(AdminController.Delete) }
);
routes.MapAreaControllerRoute(
name: "UsersEdit",
areaName: "OrchardCore.Users",
pattern: _adminOptions.AdminUrlPrefix + "/Users/Edit/{id}",
defaults: new { controller = adminControllerName, action = nameof(AdminController.Edit) }
);
routes.MapAreaControllerRoute(
name: "UsersEditPassword",
areaName: "OrchardCore.Users",
pattern: _adminOptions.AdminUrlPrefix + "/Users/EditPassword/{id}",
defaults: new { controller = adminControllerName, action = nameof(AdminController.EditPassword) }
);
builder.UseAuthorization();
}
public override void ConfigureServices(IServiceCollection services)
{
services.Configure<UserOptions>(userOptions =>
{
var configuration = ShellScope.Services.GetRequiredService<IShellConfiguration>();
configuration.GetSection("OrchardCore_Users").Bind(userOptions);
});
services.AddSecurity();
// Add ILookupNormalizer as Singleton because it is needed by UserIndexProvider
services.TryAddSingleton<ILookupNormalizer, UpperInvariantLookupNormalizer>();
// Adds the default token providers used to generate tokens for reset passwords, change email
// and change telephone number operations, and for two factor authentication token generation.
services.AddIdentity<IUser, IRole>().AddDefaultTokenProviders();
// Configure the authentication options to use the application cookie scheme as the default sign-out handler.
// This is required for security modules like the OpenID module (that uses SignOutAsync()) to work correctly.
services.AddAuthentication(options => options.DefaultSignOutScheme = IdentityConstants.ApplicationScheme);
services.TryAddScoped<UserStore>();
services.TryAddScoped<IUserStore<IUser>>(sp => sp.GetRequiredService<UserStore>());
services.TryAddScoped<IUserRoleStore<IUser>>(sp => sp.GetRequiredService<UserStore>());
services.TryAddScoped<IUserPasswordStore<IUser>>(sp => sp.GetRequiredService<UserStore>());
services.TryAddScoped<IUserEmailStore<IUser>>(sp => sp.GetRequiredService<UserStore>());
services.TryAddScoped<IUserSecurityStampStore<IUser>>(sp => sp.GetRequiredService<UserStore>());
services.TryAddScoped<IUserLoginStore<IUser>>(sp => sp.GetRequiredService<UserStore>());
services.TryAddScoped<IUserClaimStore<IUser>>(sp => sp.GetRequiredService<UserStore>());
services.TryAddScoped<IUserAuthenticationTokenStore<IUser>>(sp => sp.GetRequiredService<UserStore>());
services.ConfigureApplicationCookie(options =>
{
var userOptions = ShellScope.Services.GetRequiredService<IOptions<UserOptions>>();
options.Cookie.Name = "orchauth_" + HttpUtility.UrlEncode(_tenantName);
// Don't set the cookie builder 'Path' so that it uses the 'IAuthenticationFeature' value
// set by the pipeline and comming from the request 'PathBase' which already ends with the
// tenant prefix but may also start by a path related e.g to a virtual folder.
options.LoginPath = "/" + userOptions.Value.LoginPath;
options.AccessDeniedPath = "/Error/403";
});
services.AddSingleton<IIndexProvider, UserIndexProvider>();
services.AddSingleton<IIndexProvider, UserByRoleNameIndexProvider>();
services.AddSingleton<IIndexProvider, UserByLoginInfoIndexProvider>();
services.AddSingleton<IIndexProvider, UserByClaimIndexProvider>();
services.AddScoped<IDataMigration, Migrations>();
services.AddScoped<IUserService, UserService>();
services.AddScoped<IUserClaimsPrincipalFactory<IUser>, DefaultUserClaimsPrincipalFactory>();
services.AddScoped<IMembershipService, MembershipService>();
services.AddScoped<ISetupEventHandler, SetupEventHandler>();
services.AddScoped<ICommandHandler, UserCommands>();
services.AddScoped<IRoleRemovedEventHandler, UserRoleRemovedEventHandler>();
services.AddScoped<IPermissionProvider, Permissions>();
services.AddScoped<INavigationProvider, AdminMenu>();
services.AddScoped<IDisplayDriver<ISite>, LoginSettingsDisplayDriver>();
services.AddScoped<ILiquidTemplateEventHandler, UserLiquidTemplateEventHandler>();
services.AddScoped<IDisplayManager<User>, DisplayManager<User>>();
services.AddScoped<IDisplayDriver<User>, UserDisplayDriver>();
services.AddScoped<IDisplayDriver<User>, UserButtonsDisplayDriver>();
services.AddScoped<IThemeSelector, UsersThemeSelector>();
}
}
[RequireFeatures("OrchardCore.Liquid")]
public class LiquidStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ILiquidTemplateEventHandler, UserLiquidTemplateEventHandler>();
services.AddLiquidFilter<HasPermissionFilter>("has_permission");
services.AddLiquidFilter<HasClaimFilter>("has_claim");
services.AddLiquidFilter<IsInRoleFilter>("is_in_role");
services.AddLiquidFilter<UserEmailFilter>("user_email");
}
}
[RequireFeatures("OrchardCore.Deployment")]
public class LoginDeploymentStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IDeploymentSource, SiteSettingsPropertyDeploymentSource<LoginSettings>>();
services.AddScoped<IDisplayDriver<DeploymentStep>>(sp =>
{
var S = sp.GetService<IStringLocalizer<LoginDeploymentStartup>>();
return new SiteSettingsPropertyDeploymentStepDriver<LoginSettings>(S["Login settings"], S["Exports the Login settings."]);
});
services.AddSingleton<IDeploymentStepFactory>(new SiteSettingsPropertyDeploymentStepFactory<LoginSettings>());
}
}
[Feature("OrchardCore.Users.ChangeEmail")]
public class ChangeEmailStartup : StartupBase
{
private const string ChangeEmailPath = "ChangeEmail";
private const string ChangeEmailConfirmationPath = "ChangeEmailConfirmation";
static ChangeEmailStartup()
{
TemplateContext.GlobalMemberAccessStrategy.Register<ChangeEmailViewModel>();
}
public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider)
{
routes.MapAreaControllerRoute(
name: "ChangeEmail",
areaName: "OrchardCore.Users",
pattern: ChangeEmailPath,
defaults: new { controller = "ChangeEmail", action = "Index" }
);
routes.MapAreaControllerRoute(
name: "ChangeEmailConfirmation",
areaName: "OrchardCore.Users",
pattern: ChangeEmailConfirmationPath,
defaults: new { controller = "ChangeEmail", action = "ChangeEmailConfirmation" }
);
}
public override void ConfigureServices(IServiceCollection services)
{
services.AddScoped<INavigationProvider, ChangeEmailAdminMenu>();
services.AddScoped<IDisplayDriver<ISite>, ChangeEmailSettingsDisplayDriver>();
}
}
[Feature("OrchardCore.Users.ChangeEmail")]
[RequireFeatures("OrchardCore.Deployment")]
public class ChangeEmailDeploymentStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IDeploymentSource, SiteSettingsPropertyDeploymentSource<ChangeEmailSettings>>();
services.AddScoped<IDisplayDriver<DeploymentStep>>(sp =>
{
var S = sp.GetService<IStringLocalizer<ChangeEmailDeploymentStartup>>();
return new SiteSettingsPropertyDeploymentStepDriver<ChangeEmailSettings>(S["Change Email settings"], S["Exports the Change Email settings."]);
});
services.AddSingleton<IDeploymentStepFactory>(new SiteSettingsPropertyDeploymentStepFactory<ChangeEmailSettings>());
}
}
[Feature("OrchardCore.Users.Registration")]
public class RegistrationStartup : StartupBase
{
private const string RegisterPath = "Register";
static RegistrationStartup()
{
TemplateContext.GlobalMemberAccessStrategy.Register<ConfirmEmailViewModel>();
}
public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider)
{
routes.MapAreaControllerRoute(
name: "Register",
areaName: "OrchardCore.Users",
pattern: RegisterPath,
defaults: new { controller = "Registration", action = "Register" }
);
}
public override void ConfigureServices(IServiceCollection services)
{
services.AddScoped<INavigationProvider, RegistrationAdminMenu>();
services.AddScoped<IDisplayDriver<ISite>, RegistrationSettingsDisplayDriver>();
}
}
[Feature("OrchardCore.Users.Registration")]
[RequireFeatures("OrchardCore.Deployment")]
public class RegistrationDeploymentStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IDeploymentSource, SiteSettingsPropertyDeploymentSource<RegistrationSettings>>();
services.AddScoped<IDisplayDriver<DeploymentStep>>(sp =>
{
var S = sp.GetService<IStringLocalizer<RegistrationDeploymentStartup>>();
return new SiteSettingsPropertyDeploymentStepDriver<RegistrationSettings>(S["Registration settings"], S["Exports the Registration settings."]);
});
services.AddSingleton<IDeploymentStepFactory>(new SiteSettingsPropertyDeploymentStepFactory<RegistrationSettings>());
}
}
[Feature("OrchardCore.Users.ResetPassword")]
public class ResetPasswordStartup : StartupBase
{
private const string ForgotPasswordPath = "ForgotPassword";
private const string ForgotPasswordConfirmationPath = "ForgotPasswordConfirmation";
private const string ResetPasswordPath = "ResetPassword";
private const string ResetPasswordConfirmationPath = "ResetPasswordConfirmation";
static ResetPasswordStartup()
{
TemplateContext.GlobalMemberAccessStrategy.Register<LostPasswordViewModel>();
}
public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider)
{
routes.MapAreaControllerRoute(
name: "ForgotPassword",
areaName: "OrchardCore.Users",
pattern: ForgotPasswordPath,
defaults: new { controller = "ResetPassword", action = "ForgotPassword" }
);
routes.MapAreaControllerRoute(
name: "ForgotPasswordConfirmation",
areaName: "OrchardCore.Users",
pattern: ForgotPasswordConfirmationPath,
defaults: new { controller = "ResetPassword", action = "ForgotPasswordConfirmation" }
);
routes.MapAreaControllerRoute(
name: "ResetPassword",
areaName: "OrchardCore.Users",
pattern: ResetPasswordPath,
defaults: new { controller = "ResetPassword", action = "ResetPassword" }
);
routes.MapAreaControllerRoute(
name: "ResetPasswordConfirmation",
areaName: "OrchardCore.Users",
pattern: ResetPasswordConfirmationPath,
defaults: new { controller = "ResetPassword", action = "ResetPasswordConfirmation" }
);
}
public override void ConfigureServices(IServiceCollection services)
{
services.AddScoped<INavigationProvider, ResetPasswordAdminMenu>();
services.AddScoped<IDisplayDriver<ISite>, ResetPasswordSettingsDisplayDriver>();
}
}
[Feature("OrchardCore.Users.ResetPassword")]
[RequireFeatures("OrchardCore.Deployment")]
public class ResetPasswordDeploymentStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IDeploymentSource, SiteSettingsPropertyDeploymentSource<ResetPasswordSettings>>();
services.AddScoped<IDisplayDriver<DeploymentStep>>(sp =>
{
var S = sp.GetService<IStringLocalizer<ResetPasswordDeploymentStartup>>();
return new SiteSettingsPropertyDeploymentStepDriver<ResetPasswordSettings>(S["Reset Password settings"], S["Exports the Reset Password settings."]);
});
services.AddSingleton<IDeploymentStepFactory>(new SiteSettingsPropertyDeploymentStepFactory<ResetPasswordSettings>());
}
}
}
| |
// ****************************************************************
// Copyright 2007, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
using System;
using System.IO;
using System.Collections;
#if NET_2_0
using System.Collections.Generic;
#endif
namespace NAssert.Constraints
{
/// <summary>
/// EqualConstraint is able to compare an actual value with the
/// expected value provided in its constructor. Two objects are
/// considered equal if both are null, or if both have the same
/// value. NUnit has special semantics for some object types.
/// </summary>
public class EqualConstraint : Constraint
{
#region Static and Instance Fields
private readonly object expected;
/// <summary>
/// If true, strings in error messages will be clipped
/// </summary>
private bool clipStrings = true;
/// <summary>
/// NUnitEqualityComparer used to test equality.
/// </summary>
private NUnitEqualityComparer comparer = new NUnitEqualityComparer();
#region Message Strings
private static readonly string StringsDiffer_1 =
"String lengths are both {0}. Strings differ at index {1}.";
private static readonly string StringsDiffer_2 =
"Expected string length {0} but was {1}. Strings differ at index {2}.";
private static readonly string StreamsDiffer_1 =
"Stream lengths are both {0}. Streams differ at offset {1}.";
private static readonly string StreamsDiffer_2 =
"Expected Stream length {0} but was {1}.";// Streams differ at offset {2}.";
private static readonly string CollectionType_1 =
"Expected and actual are both {0}";
private static readonly string CollectionType_2 =
"Expected is {0}, actual is {1}";
private static readonly string ValuesDiffer_1 =
"Values differ at index {0}";
private static readonly string ValuesDiffer_2 =
"Values differ at expected index {0}, actual index {1}";
#endregion
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="EqualConstraint"/> class.
/// </summary>
/// <param name="expected">The expected value.</param>
public EqualConstraint(object expected) : base(expected)
{
this.expected = expected;
}
#endregion
#region Constraint Modifiers
/// <summary>
/// Flag the constraint to ignore case and return self.
/// </summary>
public EqualConstraint IgnoreCase
{
get
{
comparer.IgnoreCase = true;
return this;
}
}
/// <summary>
/// Flag the constraint to suppress string clipping
/// and return self.
/// </summary>
public EqualConstraint NoClip
{
get
{
clipStrings = false;
return this;
}
}
/// <summary>
/// Flag the constraint to compare arrays as collections
/// and return self.
/// </summary>
public EqualConstraint AsCollection
{
get
{
comparer.CompareAsCollection = true;
return this;
}
}
/// <summary>
/// Flag the constraint to use a tolerance when determining equality.
/// </summary>
/// <param name="amount">Tolerance value to be used</param>
/// <returns>Self.</returns>
public EqualConstraint Within(object amount)
{
if (!comparer.Tolerance.IsEmpty)
throw new InvalidOperationException("Within modifier may appear only once in a constraint expression");
comparer.Tolerance = new Tolerance(amount);
return this;
}
/// <summary>
/// Switches the .Within() modifier to interpret its tolerance as
/// a distance in representable values (see remarks).
/// </summary>
/// <returns>Self.</returns>
/// <remarks>
/// Ulp stands for "unit in the last place" and describes the minimum
/// amount a given value can change. For any integers, an ulp is 1 whole
/// digit. For floating point values, the accuracy of which is better
/// for smaller numbers and worse for larger numbers, an ulp depends
/// on the size of the number. Using ulps for comparison of floating
/// point results instead of fixed tolerances is safer because it will
/// automatically compensate for the added inaccuracy of larger numbers.
/// </remarks>
public EqualConstraint Ulps
{
get
{
comparer.Tolerance = comparer.Tolerance.Ulps;
return this;
}
}
/// <summary>
/// Switches the .Within() modifier to interpret its tolerance as
/// a percentage that the actual values is allowed to deviate from
/// the expected value.
/// </summary>
/// <returns>Self</returns>
public EqualConstraint Percent
{
get
{
comparer.Tolerance = comparer.Tolerance.Percent;
return this;
}
}
/// <summary>
/// Causes the tolerance to be interpreted as a TimeSpan in days.
/// </summary>
/// <returns>Self</returns>
public EqualConstraint Days
{
get
{
comparer.Tolerance = comparer.Tolerance.Days;
return this;
}
}
/// <summary>
/// Causes the tolerance to be interpreted as a TimeSpan in hours.
/// </summary>
/// <returns>Self</returns>
public EqualConstraint Hours
{
get
{
comparer.Tolerance = comparer.Tolerance.Hours;
return this;
}
}
/// <summary>
/// Causes the tolerance to be interpreted as a TimeSpan in minutes.
/// </summary>
/// <returns>Self</returns>
public EqualConstraint Minutes
{
get
{
comparer.Tolerance = comparer.Tolerance.Minutes;
return this;
}
}
/// <summary>
/// Causes the tolerance to be interpreted as a TimeSpan in seconds.
/// </summary>
/// <returns>Self</returns>
public EqualConstraint Seconds
{
get
{
comparer.Tolerance = comparer.Tolerance.Seconds;
return this;
}
}
/// <summary>
/// Causes the tolerance to be interpreted as a TimeSpan in milliseconds.
/// </summary>
/// <returns>Self</returns>
public EqualConstraint Milliseconds
{
get
{
comparer.Tolerance = comparer.Tolerance.Milliseconds;
return this;
}
}
/// <summary>
/// Causes the tolerance to be interpreted as a TimeSpan in clock ticks.
/// </summary>
/// <returns>Self</returns>
public EqualConstraint Ticks
{
get
{
comparer.Tolerance = comparer.Tolerance.Ticks;
return this;
}
}
/// <summary>
/// Flag the constraint to use the supplied IComparer object.
/// </summary>
/// <param name="comparer">The IComparer object to use.</param>
/// <returns>Self.</returns>
[Obsolete("Replace with 'Using'")]
public EqualConstraint Comparer(IComparer comparer)
{
return Using(comparer);
}
/// <summary>
/// Flag the constraint to use the supplied IComparer object.
/// </summary>
/// <param name="comparer">The IComparer object to use.</param>
/// <returns>Self.</returns>
public EqualConstraint Using(IComparer comparer)
{
this.comparer.ExternalComparer = EqualityAdapter.For(comparer);
return this;
}
#if NET_2_0
/// <summary>
/// Flag the constraint to use the supplied IComparer object.
/// </summary>
/// <param name="comparer">The IComparer object to use.</param>
/// <returns>Self.</returns>
public EqualConstraint Using<T>(IComparer<T> comparer)
{
this.comparer.ExternalComparer = EqualityAdapter.For( comparer );
return this;
}
/// <summary>
/// Flag the constraint to use the supplied Comparison object.
/// </summary>
/// <param name="comparer">The IComparer object to use.</param>
/// <returns>Self.</returns>
public EqualConstraint Using<T>(Comparison<T> comparer)
{
this.comparer.ExternalComparer = EqualityAdapter.For( comparer );
return this;
}
/// <summary>
/// Flag the constraint to use the supplied IEqualityComparer object.
/// </summary>
/// <param name="comparer">The IComparer object to use.</param>
/// <returns>Self.</returns>
public EqualConstraint Using(IEqualityComparer comparer)
{
this.comparer.ExternalComparer = EqualityAdapter.For(comparer);
return this;
}
/// <summary>
/// Flag the constraint to use the supplied IEqualityComparer object.
/// </summary>
/// <param name="comparer">The IComparer object to use.</param>
/// <returns>Self.</returns>
public EqualConstraint Using<T>(IEqualityComparer<T> comparer)
{
this.comparer.ExternalComparer = EqualityAdapter.For(comparer);
return this;
}
#endif
#endregion
#region Public Methods
/// <summary>
/// Test whether the constraint is satisfied by a given value
/// </summary>
/// <param name="actual">The value to be tested</param>
/// <returns>True for success, false for failure</returns>
public override bool Matches(object actual)
{
this.actual = actual;
return comparer.ObjectsEqual(expected, actual);
}
/// <summary>
/// Write a failure message. Overridden to provide custom
/// failure messages for EqualConstraint.
/// </summary>
/// <param name="writer">The MessageWriter to write to</param>
public override void WriteMessageTo(MessageWriter writer)
{
DisplayDifferences(writer, expected, actual, 0);
}
/// <summary>
/// Write description of this constraint
/// </summary>
/// <param name="writer">The MessageWriter to write to</param>
public override void WriteDescriptionTo(MessageWriter writer)
{
writer.WriteExpectedValue( expected );
if (comparer.Tolerance != null && !comparer.Tolerance.IsEmpty)
{
writer.WriteConnector("+/-");
writer.WriteExpectedValue(comparer.Tolerance.Value);
}
if ( comparer.IgnoreCase )
writer.WriteModifier("ignoring case");
}
private void DisplayDifferences(MessageWriter writer, object expected, object actual, int depth)
{
if (expected is string && actual is string)
DisplayStringDifferences(writer, (string)expected, (string)actual);
else if (expected is ICollection && actual is ICollection)
DisplayCollectionDifferences(writer, (ICollection)expected, (ICollection)actual, depth);
else if (expected is Stream && actual is Stream)
DisplayStreamDifferences(writer, (Stream)expected, (Stream)actual, depth);
else if (comparer.Tolerance != null)
writer.DisplayDifferences(expected, actual, comparer.Tolerance);
else
writer.DisplayDifferences(expected, actual);
}
#endregion
#region DisplayStringDifferences
private void DisplayStringDifferences(MessageWriter writer, string expected, string actual)
{
int mismatch = MsgUtils.FindMismatchPosition(expected, actual, 0, comparer.IgnoreCase);
if (expected.Length == actual.Length)
writer.WriteMessageLine(StringsDiffer_1, expected.Length, mismatch);
else
writer.WriteMessageLine(StringsDiffer_2, expected.Length, actual.Length, mismatch);
writer.DisplayStringDifferences(expected, actual, mismatch, comparer.IgnoreCase, clipStrings);
}
#endregion
#region DisplayStreamDifferences
private void DisplayStreamDifferences(MessageWriter writer, Stream expected, Stream actual, int depth)
{
if ( expected.Length == actual.Length )
{
long offset = (long)comparer.FailurePoints[depth];
writer.WriteMessageLine(StreamsDiffer_1, expected.Length, offset);
}
else
writer.WriteMessageLine(StreamsDiffer_2, expected.Length, actual.Length);
}
#endregion
#region DisplayCollectionDifferences
/// <summary>
/// Display the failure information for two collections that did not match.
/// </summary>
/// <param name="writer">The MessageWriter on which to display</param>
/// <param name="expected">The expected collection.</param>
/// <param name="actual">The actual collection</param>
/// <param name="depth">The depth of this failure in a set of nested collections</param>
private void DisplayCollectionDifferences(MessageWriter writer, ICollection expected, ICollection actual, int depth)
{
int failurePoint = comparer.FailurePoints.Count > depth ? (int)comparer.FailurePoints[depth] : -1;
DisplayCollectionTypesAndSizes(writer, expected, actual, depth);
if (failurePoint >= 0)
{
DisplayFailurePoint(writer, expected, actual, failurePoint, depth);
if (failurePoint < expected.Count && failurePoint < actual.Count)
DisplayDifferences(
writer,
GetValueFromCollection(expected, failurePoint),
GetValueFromCollection(actual, failurePoint),
++depth);
else if (expected.Count < actual.Count)
{
writer.Write( " Extra: " );
writer.WriteCollectionElements( actual, failurePoint, 3 );
}
else
{
writer.Write( " Missing: " );
writer.WriteCollectionElements( expected, failurePoint, 3 );
}
}
}
/// <summary>
/// Displays a single line showing the types and sizes of the expected
/// and actual collections or arrays. If both are identical, the value is
/// only shown once.
/// </summary>
/// <param name="writer">The MessageWriter on which to display</param>
/// <param name="expected">The expected collection or array</param>
/// <param name="actual">The actual collection or array</param>
/// <param name="indent">The indentation level for the message line</param>
private void DisplayCollectionTypesAndSizes(MessageWriter writer, ICollection expected, ICollection actual, int indent)
{
string sExpected = MsgUtils.GetTypeRepresentation(expected);
if (!(expected is Array))
sExpected += string.Format(" with {0} elements", expected.Count);
string sActual = MsgUtils.GetTypeRepresentation(actual);
if (!(actual is Array))
sActual += string.Format(" with {0} elements", actual.Count);
if (sExpected == sActual)
writer.WriteMessageLine(indent, CollectionType_1, sExpected);
else
writer.WriteMessageLine(indent, CollectionType_2, sExpected, sActual);
}
/// <summary>
/// Displays a single line showing the point in the expected and actual
/// arrays at which the comparison failed. If the arrays have different
/// structures or dimensions, both values are shown.
/// </summary>
/// <param name="writer">The MessageWriter on which to display</param>
/// <param name="expected">The expected array</param>
/// <param name="actual">The actual array</param>
/// <param name="failurePoint">Index of the failure point in the underlying collections</param>
/// <param name="indent">The indentation level for the message line</param>
private void DisplayFailurePoint(MessageWriter writer, ICollection expected, ICollection actual, int failurePoint, int indent)
{
Array expectedArray = expected as Array;
Array actualArray = actual as Array;
int expectedRank = expectedArray != null ? expectedArray.Rank : 1;
int actualRank = actualArray != null ? actualArray.Rank : 1;
bool useOneIndex = expectedRank == actualRank;
if (expectedArray != null && actualArray != null)
for (int r = 1; r < expectedRank && useOneIndex; r++)
if (expectedArray.GetLength(r) != actualArray.GetLength(r))
useOneIndex = false;
int[] expectedIndices = MsgUtils.GetArrayIndicesFromCollectionIndex(expected, failurePoint);
if (useOneIndex)
{
writer.WriteMessageLine(indent, ValuesDiffer_1, MsgUtils.GetArrayIndicesAsString(expectedIndices));
}
else
{
int[] actualIndices = MsgUtils.GetArrayIndicesFromCollectionIndex(actual, failurePoint);
writer.WriteMessageLine(indent, ValuesDiffer_2,
MsgUtils.GetArrayIndicesAsString(expectedIndices), MsgUtils.GetArrayIndicesAsString(actualIndices));
}
}
private static object GetValueFromCollection(ICollection collection, int index)
{
Array array = collection as Array;
if (array != null && array.Rank > 1)
return array.GetValue(MsgUtils.GetArrayIndicesFromCollectionIndex(array, index));
if (collection is IList)
return ((IList)collection)[index];
foreach (object obj in collection)
if (--index < 0)
return obj;
return null;
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.